992902d6f6eb18b07c0f95cb2dded8794515934a
[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     // Set the correct calling convention for ARMv7k WatchOS. It's just
247     // AAPCS_VFP for functions as simple as libcalls.
248     if (Subtarget->isTargetWatchOS()) {
249       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
250         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, nullptr);
256   setLibcallName(RTLIB::SRL_I128, nullptr);
257   setLibcallName(RTLIB::SRA_I128, nullptr);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
260       !Subtarget->isTargetWindows()) {
261     static const struct {
262       const RTLIB::Libcall Op;
263       const char * const Name;
264       const CallingConv::ID CC;
265       const ISD::CondCode Cond;
266     } LibraryCalls[] = {
267       // Double-precision floating-point arithmetic helper functions
268       // RTABI chapter 4.1.2, Table 2
269       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273
274       // Double-precision floating-point comparison helper functions
275       // RTABI chapter 4.1.2, Table 3
276       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
278       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
284
285       // Single-precision floating-point arithmetic helper functions
286       // RTABI chapter 4.1.2, Table 4
287       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291
292       // Single-precision floating-point comparison helper functions
293       // RTABI chapter 4.1.2, Table 5
294       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
296       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
300       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
301       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
302
303       // Floating-point to integer conversions.
304       // RTABI chapter 4.1.2, Table 6
305       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313
314       // Conversions between floating types.
315       // RTABI chapter 4.1.2, Table 7
316       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319
320       // Integer to floating-point conversions.
321       // RTABI chapter 4.1.2, Table 8
322       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Long long helper functions
332       // RTABI chapter 4.2, Table 9
333       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337
338       // Integer division functions
339       // RTABI chapter 4.3.1
340       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348
349       // Memory operations
350       // RTABI chapter 4.3.4
351       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354     };
355
356     for (const auto &LC : LibraryCalls) {
357       setLibcallName(LC.Op, LC.Name);
358       setLibcallCallingConv(LC.Op, LC.CC);
359       if (LC.Cond != ISD::SETCC_INVALID)
360         setCmpLibcallCC(LC.Op, LC.Cond);
361     }
362   }
363
364   if (Subtarget->isTargetWindows()) {
365     static const struct {
366       const RTLIB::Libcall Op;
367       const char * const Name;
368       const CallingConv::ID CC;
369     } LibraryCalls[] = {
370       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
376       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
377       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
378     };
379
380     for (const auto &LC : LibraryCalls) {
381       setLibcallName(LC.Op, LC.Name);
382       setLibcallCallingConv(LC.Op, LC.CC);
383     }
384   }
385
386   // Use divmod compiler-rt calls for iOS 5.0 and later.
387   if (Subtarget->isTargetWatchOS() ||
388       (Subtarget->isTargetIOS() &&
389        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
390     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
391     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
392   }
393
394   // The half <-> float conversion functions are always soft-float, but are
395   // needed for some targets which use a hard-float calling convention by
396   // default.
397   if (Subtarget->isAAPCS_ABI()) {
398     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
399     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
400     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
401   } else {
402     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
403     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
404     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
405   }
406
407   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
408   // a __gnu_ prefix (which is the default).
409   if (Subtarget->isTargetAEABI()) {
410     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
411     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
412     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
413   }
414
415   if (Subtarget->isThumb1Only())
416     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
417   else
418     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
419   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
420       !Subtarget->isThumb1Only()) {
421     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
422     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
423   }
424
425   for (MVT VT : MVT::vector_valuetypes()) {
426     for (MVT InnerVT : MVT::vector_valuetypes()) {
427       setTruncStoreAction(VT, InnerVT, Expand);
428       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
429       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
430       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
431     }
432
433     setOperationAction(ISD::MULHS, VT, Expand);
434     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
435     setOperationAction(ISD::MULHU, VT, Expand);
436     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
437
438     setOperationAction(ISD::BSWAP, VT, Expand);
439   }
440
441   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
442   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
443
444   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
445   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
446
447   if (Subtarget->hasNEON()) {
448     addDRTypeForNEON(MVT::v2f32);
449     addDRTypeForNEON(MVT::v8i8);
450     addDRTypeForNEON(MVT::v4i16);
451     addDRTypeForNEON(MVT::v2i32);
452     addDRTypeForNEON(MVT::v1i64);
453
454     addQRTypeForNEON(MVT::v4f32);
455     addQRTypeForNEON(MVT::v2f64);
456     addQRTypeForNEON(MVT::v16i8);
457     addQRTypeForNEON(MVT::v8i16);
458     addQRTypeForNEON(MVT::v4i32);
459     addQRTypeForNEON(MVT::v2i64);
460
461     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
462     // neither Neon nor VFP support any arithmetic operations on it.
463     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
464     // supported for v4f32.
465     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
466     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
467     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
468     // FIXME: Code duplication: FDIV and FREM are expanded always, see
469     // ARMTargetLowering::addTypeForNEON method for details.
470     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
471     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
472     // FIXME: Create unittest.
473     // In another words, find a way when "copysign" appears in DAG with vector
474     // operands.
475     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
476     // FIXME: Code duplication: SETCC has custom operation action, see
477     // ARMTargetLowering::addTypeForNEON method for details.
478     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
479     // FIXME: Create unittest for FNEG and for FABS.
480     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
481     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
482     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
483     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
484     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
485     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
486     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
487     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
488     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
489     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
490     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
491     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
492     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
493     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
494     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
495     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
496     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
497     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
498     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
499
500     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
501     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
502     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
503     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
504     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
505     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
506     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
507     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
508     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
509     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
510     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
511     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
512     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
514     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
515
516     // Mark v2f32 intrinsics.
517     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
518     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
519     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
520     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
521     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
522     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
523     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
524     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
525     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
526     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
527     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
528     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
529     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
530     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
531     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
532
533     // Neon does not support some operations on v1i64 and v2i64 types.
534     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
535     // Custom handling for some quad-vector types to detect VMULL.
536     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
537     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
538     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
539     // Custom handling for some vector types to avoid expensive expansions
540     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
541     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
542     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
543     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
544     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
545     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
546     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
547     // a destination type that is wider than the source, and nor does
548     // it have a FP_TO_[SU]INT instruction with a narrower destination than
549     // source.
550     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
551     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
552     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
553     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
554
555     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
556     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
557
558     // NEON does not have single instruction CTPOP for vectors with element
559     // types wider than 8-bits.  However, custom lowering can leverage the
560     // v8i8/v16i8 vcnt instruction.
561     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
562     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
563     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
564     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
565
566     // NEON does not have single instruction CTTZ for vectors.
567     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
568     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
569     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
570     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
571
572     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
573     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
574     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
575     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
576
577     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
578     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
579     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
580     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
581
582     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
583     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
584     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
585     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
586
587     // NEON only has FMA instructions as of VFP4.
588     if (!Subtarget->hasVFP4()) {
589       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
590       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
591     }
592
593     setTargetDAGCombine(ISD::INTRINSIC_VOID);
594     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
595     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
596     setTargetDAGCombine(ISD::SHL);
597     setTargetDAGCombine(ISD::SRL);
598     setTargetDAGCombine(ISD::SRA);
599     setTargetDAGCombine(ISD::SIGN_EXTEND);
600     setTargetDAGCombine(ISD::ZERO_EXTEND);
601     setTargetDAGCombine(ISD::ANY_EXTEND);
602     setTargetDAGCombine(ISD::BUILD_VECTOR);
603     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
604     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
605     setTargetDAGCombine(ISD::STORE);
606     setTargetDAGCombine(ISD::FP_TO_SINT);
607     setTargetDAGCombine(ISD::FP_TO_UINT);
608     setTargetDAGCombine(ISD::FDIV);
609     setTargetDAGCombine(ISD::LOAD);
610
611     // It is legal to extload from v4i8 to v4i16 or v4i32.
612     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
613                    MVT::v2i32}) {
614       for (MVT VT : MVT::integer_vector_valuetypes()) {
615         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
616         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
617         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
618       }
619     }
620   }
621
622   // ARM and Thumb2 support UMLAL/SMLAL.
623   if (!Subtarget->isThumb1Only())
624     setTargetDAGCombine(ISD::ADDC);
625
626   if (Subtarget->isFPOnlySP()) {
627     // When targeting a floating-point unit with only single-precision
628     // operations, f64 is legal for the few double-precision instructions which
629     // are present However, no double-precision operations other than moves,
630     // loads and stores are provided by the hardware.
631     setOperationAction(ISD::FADD,       MVT::f64, Expand);
632     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
633     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
634     setOperationAction(ISD::FMA,        MVT::f64, Expand);
635     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
636     setOperationAction(ISD::FREM,       MVT::f64, Expand);
637     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
638     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
639     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
640     setOperationAction(ISD::FABS,       MVT::f64, Expand);
641     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
642     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
643     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
644     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
645     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
646     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
647     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
648     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
649     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
650     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
651     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
652     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
653     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
654     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
655     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
656     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
657     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
658     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
659     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
660     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
661     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
662     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
663     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
664   }
665
666   computeRegisterProperties(Subtarget->getRegisterInfo());
667
668   // ARM does not have floating-point extending loads.
669   for (MVT VT : MVT::fp_valuetypes()) {
670     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
671     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
672   }
673
674   // ... or truncating stores
675   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
676   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
677   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
678
679   // ARM does not have i1 sign extending load.
680   for (MVT VT : MVT::integer_valuetypes())
681     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
682
683   // ARM supports all 4 flavors of integer indexed load / store.
684   if (!Subtarget->isThumb1Only()) {
685     for (unsigned im = (unsigned)ISD::PRE_INC;
686          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
687       setIndexedLoadAction(im,  MVT::i1,  Legal);
688       setIndexedLoadAction(im,  MVT::i8,  Legal);
689       setIndexedLoadAction(im,  MVT::i16, Legal);
690       setIndexedLoadAction(im,  MVT::i32, Legal);
691       setIndexedStoreAction(im, MVT::i1,  Legal);
692       setIndexedStoreAction(im, MVT::i8,  Legal);
693       setIndexedStoreAction(im, MVT::i16, Legal);
694       setIndexedStoreAction(im, MVT::i32, Legal);
695     }
696   }
697
698   setOperationAction(ISD::SADDO, MVT::i32, Custom);
699   setOperationAction(ISD::UADDO, MVT::i32, Custom);
700   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
701   setOperationAction(ISD::USUBO, MVT::i32, Custom);
702
703   // i64 operation support.
704   setOperationAction(ISD::MUL,     MVT::i64, Expand);
705   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
706   if (Subtarget->isThumb1Only()) {
707     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
708     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
709   }
710   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
711       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
712     setOperationAction(ISD::MULHS, MVT::i32, Expand);
713
714   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
715   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
716   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
717   setOperationAction(ISD::SRL,       MVT::i64, Custom);
718   setOperationAction(ISD::SRA,       MVT::i64, Custom);
719
720   if (!Subtarget->isThumb1Only()) {
721     // FIXME: We should do this for Thumb1 as well.
722     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
723     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
724     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
725     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
726   }
727
728   // ARM does not have ROTL.
729   setOperationAction(ISD::ROTL, MVT::i32, Expand);
730   for (MVT VT : MVT::vector_valuetypes()) {
731     setOperationAction(ISD::ROTL, VT, Expand);
732     setOperationAction(ISD::ROTR, VT, Expand);
733   }
734   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
735   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
736   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
737     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
738
739   // These just redirect to CTTZ and CTLZ on ARM.
740   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
741   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
742
743   // @llvm.readcyclecounter requires the Performance Monitors extension.
744   // Default to the 0 expansion on unsupported platforms.
745   // FIXME: Technically there are older ARM CPUs that have
746   // implementation-specific ways of obtaining this information.
747   if (Subtarget->hasPerfMon())
748     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
749
750   // Only ARMv6 has BSWAP.
751   if (!Subtarget->hasV6Ops())
752     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
753
754   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
755       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
756     // These are expanded into libcalls if the cpu doesn't have HW divider.
757     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
758     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
759   }
760
761   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
762     setOperationAction(ISD::SDIV, MVT::i32, Custom);
763     setOperationAction(ISD::UDIV, MVT::i32, Custom);
764
765     setOperationAction(ISD::SDIV, MVT::i64, Custom);
766     setOperationAction(ISD::UDIV, MVT::i64, Custom);
767   }
768
769   setOperationAction(ISD::SREM,  MVT::i32, Expand);
770   setOperationAction(ISD::UREM,  MVT::i32, Expand);
771   // Register based DivRem for AEABI (RTABI 4.2)
772   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
773     setOperationAction(ISD::SREM, MVT::i64, Custom);
774     setOperationAction(ISD::UREM, MVT::i64, Custom);
775
776     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
777     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
778     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
779     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
780     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
781     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
782     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
783     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
784
785     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
786     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
787     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
788     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
789     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
790     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
791     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
792     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
793
794     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
795     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
796   } else {
797     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
798     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
799   }
800
801   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
802   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
803   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
804   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
805
806   setOperationAction(ISD::TRAP, MVT::Other, Legal);
807
808   // Use the default implementation.
809   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
810   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
811   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
812   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
813   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
814   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
815
816   if (!Subtarget->useSjLjEH()) {
817     // Platforms which do not use SjLj EH may return values in these registers
818     // via the personality function.
819     setExceptionPointerRegister(ARM::R0);
820     setExceptionSelectorRegister(ARM::R1);
821   }
822
823   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
824     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
825   else
826     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
827
828   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
829   // the default expansion. If we are targeting a single threaded system,
830   // then set them all for expand so we can lower them later into their
831   // non-atomic form.
832   if (TM.Options.ThreadModel == ThreadModel::Single)
833     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
834   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
835     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
836     // to ldrex/strex loops already.
837     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
838
839     // On v8, we have particularly efficient implementations of atomic fences
840     // if they can be combined with nearby atomic loads and stores.
841     if (!Subtarget->hasV8Ops()) {
842       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
843       setInsertFencesForAtomic(true);
844     }
845   } else {
846     // If there's anything we can use as a barrier, go through custom lowering
847     // for ATOMIC_FENCE.
848     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
849                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
850
851     // Set them all for expansion, which will force libcalls.
852     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
853     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
854     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
855     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
856     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
857     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
858     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
859     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
860     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
861     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
862     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
863     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
864     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
865     // Unordered/Monotonic case.
866     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
867     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
868   }
869
870   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
871
872   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
873   if (!Subtarget->hasV6Ops()) {
874     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
875     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
876   }
877   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
878
879   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
880       !Subtarget->isThumb1Only()) {
881     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
882     // iff target supports vfp2.
883     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
884     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
885   }
886
887   // We want to custom lower some of our intrinsics.
888   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
889   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
890   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
891   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
892   if (Subtarget->useSjLjEH())
893     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
894
895   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
896   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
897   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
898   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
899   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
900   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
901   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
902   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
903   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
904
905   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
906   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
907   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
908   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
909   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
910
911   // We don't support sin/cos/fmod/copysign/pow
912   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
913   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
914   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
915   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
916   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
917   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
918   setOperationAction(ISD::FREM,      MVT::f64, Expand);
919   setOperationAction(ISD::FREM,      MVT::f32, Expand);
920   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
921       !Subtarget->isThumb1Only()) {
922     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
923     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
924   }
925   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
926   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
927
928   if (!Subtarget->hasVFP4()) {
929     setOperationAction(ISD::FMA, MVT::f64, Expand);
930     setOperationAction(ISD::FMA, MVT::f32, Expand);
931   }
932
933   // Various VFP goodness
934   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
935     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
936     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
937       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
938       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
939     }
940
941     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
942     if (!Subtarget->hasFP16()) {
943       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
944       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
945     }
946   }
947
948   // Combine sin / cos into one node or libcall if possible.
949   if (Subtarget->hasSinCos()) {
950     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
951     setLibcallName(RTLIB::SINCOS_F64, "sincos");
952     if (Subtarget->isTargetWatchOS()) {
953       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
954       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
955     }
956     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
957       // For iOS, we don't want to the normal expansion of a libcall to
958       // sincos. We want to issue a libcall to __sincos_stret.
959       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
960       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
961     }
962   }
963
964   // FP-ARMv8 implements a lot of rounding-like FP operations.
965   if (Subtarget->hasFPARMv8()) {
966     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
967     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
968     setOperationAction(ISD::FROUND, MVT::f32, Legal);
969     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
970     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
971     setOperationAction(ISD::FRINT, MVT::f32, Legal);
972     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
973     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
974     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
975     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
976     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
977     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
978
979     if (!Subtarget->isFPOnlySP()) {
980       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
981       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
982       setOperationAction(ISD::FROUND, MVT::f64, Legal);
983       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
984       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
985       setOperationAction(ISD::FRINT, MVT::f64, Legal);
986       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
987       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
988     }
989   }
990
991   if (Subtarget->hasNEON()) {
992     // vmin and vmax aren't available in a scalar form, so we use
993     // a NEON instruction with an undef lane instead.
994     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
995     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
996     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
997     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
998     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
999     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1000   }
1001
1002   // We have target-specific dag combine patterns for the following nodes:
1003   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1004   setTargetDAGCombine(ISD::ADD);
1005   setTargetDAGCombine(ISD::SUB);
1006   setTargetDAGCombine(ISD::MUL);
1007   setTargetDAGCombine(ISD::AND);
1008   setTargetDAGCombine(ISD::OR);
1009   setTargetDAGCombine(ISD::XOR);
1010
1011   if (Subtarget->hasV6Ops())
1012     setTargetDAGCombine(ISD::SRL);
1013
1014   setStackPointerRegisterToSaveRestore(ARM::SP);
1015
1016   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1017       !Subtarget->hasVFP2())
1018     setSchedulingPreference(Sched::RegPressure);
1019   else
1020     setSchedulingPreference(Sched::Hybrid);
1021
1022   //// temporary - rewrite interface to use type
1023   MaxStoresPerMemset = 8;
1024   MaxStoresPerMemsetOptSize = 4;
1025   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1026   MaxStoresPerMemcpyOptSize = 2;
1027   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1028   MaxStoresPerMemmoveOptSize = 2;
1029
1030   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1031   // are at least 4 bytes aligned.
1032   setMinStackArgumentAlignment(4);
1033
1034   // Prefer likely predicted branches to selects on out-of-order cores.
1035   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1036
1037   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1038 }
1039
1040 bool ARMTargetLowering::useSoftFloat() const {
1041   return Subtarget->useSoftFloat();
1042 }
1043
1044 // FIXME: It might make sense to define the representative register class as the
1045 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1046 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1047 // SPR's representative would be DPR_VFP2. This should work well if register
1048 // pressure tracking were modified such that a register use would increment the
1049 // pressure of the register class's representative and all of it's super
1050 // classes' representatives transitively. We have not implemented this because
1051 // of the difficulty prior to coalescing of modeling operand register classes
1052 // due to the common occurrence of cross class copies and subregister insertions
1053 // and extractions.
1054 std::pair<const TargetRegisterClass *, uint8_t>
1055 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1056                                            MVT VT) const {
1057   const TargetRegisterClass *RRC = nullptr;
1058   uint8_t Cost = 1;
1059   switch (VT.SimpleTy) {
1060   default:
1061     return TargetLowering::findRepresentativeClass(TRI, VT);
1062   // Use DPR as representative register class for all floating point
1063   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1064   // the cost is 1 for both f32 and f64.
1065   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1066   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1067     RRC = &ARM::DPRRegClass;
1068     // When NEON is used for SP, only half of the register file is available
1069     // because operations that define both SP and DP results will be constrained
1070     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1071     // coalescing by double-counting the SP regs. See the FIXME above.
1072     if (Subtarget->useNEONForSinglePrecisionFP())
1073       Cost = 2;
1074     break;
1075   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1076   case MVT::v4f32: case MVT::v2f64:
1077     RRC = &ARM::DPRRegClass;
1078     Cost = 2;
1079     break;
1080   case MVT::v4i64:
1081     RRC = &ARM::DPRRegClass;
1082     Cost = 4;
1083     break;
1084   case MVT::v8i64:
1085     RRC = &ARM::DPRRegClass;
1086     Cost = 8;
1087     break;
1088   }
1089   return std::make_pair(RRC, Cost);
1090 }
1091
1092 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1093   switch ((ARMISD::NodeType)Opcode) {
1094   case ARMISD::FIRST_NUMBER:  break;
1095   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1096   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1097   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1098   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1099   case ARMISD::CALL:          return "ARMISD::CALL";
1100   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1101   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1102   case ARMISD::tCALL:         return "ARMISD::tCALL";
1103   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1104   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1105   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1106   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1107   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1108   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1109   case ARMISD::CMP:           return "ARMISD::CMP";
1110   case ARMISD::CMN:           return "ARMISD::CMN";
1111   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1112   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1113   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1114   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1115   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1116
1117   case ARMISD::CMOV:          return "ARMISD::CMOV";
1118
1119   case ARMISD::RBIT:          return "ARMISD::RBIT";
1120
1121   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1122   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1123   case ARMISD::RRX:           return "ARMISD::RRX";
1124
1125   case ARMISD::ADDC:          return "ARMISD::ADDC";
1126   case ARMISD::ADDE:          return "ARMISD::ADDE";
1127   case ARMISD::SUBC:          return "ARMISD::SUBC";
1128   case ARMISD::SUBE:          return "ARMISD::SUBE";
1129
1130   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1131   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1132
1133   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1134   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1135   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1136
1137   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1138
1139   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1140
1141   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1142
1143   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1144
1145   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1146
1147   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1148   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1149
1150   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1151   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1152   case ARMISD::VCGE:          return "ARMISD::VCGE";
1153   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1154   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1155   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1156   case ARMISD::VCGT:          return "ARMISD::VCGT";
1157   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1158   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1159   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1160   case ARMISD::VTST:          return "ARMISD::VTST";
1161
1162   case ARMISD::VSHL:          return "ARMISD::VSHL";
1163   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1164   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1165   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1166   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1167   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1168   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1169   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1170   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1171   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1172   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1173   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1174   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1175   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1176   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1177   case ARMISD::VSLI:          return "ARMISD::VSLI";
1178   case ARMISD::VSRI:          return "ARMISD::VSRI";
1179   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1180   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1181   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1182   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1183   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1184   case ARMISD::VDUP:          return "ARMISD::VDUP";
1185   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1186   case ARMISD::VEXT:          return "ARMISD::VEXT";
1187   case ARMISD::VREV64:        return "ARMISD::VREV64";
1188   case ARMISD::VREV32:        return "ARMISD::VREV32";
1189   case ARMISD::VREV16:        return "ARMISD::VREV16";
1190   case ARMISD::VZIP:          return "ARMISD::VZIP";
1191   case ARMISD::VUZP:          return "ARMISD::VUZP";
1192   case ARMISD::VTRN:          return "ARMISD::VTRN";
1193   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1194   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1195   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1196   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1197   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1198   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1199   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1200   case ARMISD::BFI:           return "ARMISD::BFI";
1201   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1202   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1203   case ARMISD::VBSL:          return "ARMISD::VBSL";
1204   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1205   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1206   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1207   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1208   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1209   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1210   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1211   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1212   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1213   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1214   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1215   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1216   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1217   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1218   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1219   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1220   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1221   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1222   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1223   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1224   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1225   }
1226   return nullptr;
1227 }
1228
1229 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1230                                           EVT VT) const {
1231   if (!VT.isVector())
1232     return getPointerTy(DL);
1233   return VT.changeVectorElementTypeToInteger();
1234 }
1235
1236 /// getRegClassFor - Return the register class that should be used for the
1237 /// specified value type.
1238 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1239   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1240   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1241   // load / store 4 to 8 consecutive D registers.
1242   if (Subtarget->hasNEON()) {
1243     if (VT == MVT::v4i64)
1244       return &ARM::QQPRRegClass;
1245     if (VT == MVT::v8i64)
1246       return &ARM::QQQQPRRegClass;
1247   }
1248   return TargetLowering::getRegClassFor(VT);
1249 }
1250
1251 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1252 // source/dest is aligned and the copy size is large enough. We therefore want
1253 // to align such objects passed to memory intrinsics.
1254 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1255                                                unsigned &PrefAlign) const {
1256   if (!isa<MemIntrinsic>(CI))
1257     return false;
1258   MinSize = 8;
1259   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1260   // cycle faster than 4-byte aligned LDM.
1261   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1262   return true;
1263 }
1264
1265 // Create a fast isel object.
1266 FastISel *
1267 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1268                                   const TargetLibraryInfo *libInfo) const {
1269   return ARM::createFastISel(funcInfo, libInfo);
1270 }
1271
1272 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1273   unsigned NumVals = N->getNumValues();
1274   if (!NumVals)
1275     return Sched::RegPressure;
1276
1277   for (unsigned i = 0; i != NumVals; ++i) {
1278     EVT VT = N->getValueType(i);
1279     if (VT == MVT::Glue || VT == MVT::Other)
1280       continue;
1281     if (VT.isFloatingPoint() || VT.isVector())
1282       return Sched::ILP;
1283   }
1284
1285   if (!N->isMachineOpcode())
1286     return Sched::RegPressure;
1287
1288   // Load are scheduled for latency even if there instruction itinerary
1289   // is not available.
1290   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1291   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1292
1293   if (MCID.getNumDefs() == 0)
1294     return Sched::RegPressure;
1295   if (!Itins->isEmpty() &&
1296       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1297     return Sched::ILP;
1298
1299   return Sched::RegPressure;
1300 }
1301
1302 //===----------------------------------------------------------------------===//
1303 // Lowering Code
1304 //===----------------------------------------------------------------------===//
1305
1306 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1307 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1308   switch (CC) {
1309   default: llvm_unreachable("Unknown condition code!");
1310   case ISD::SETNE:  return ARMCC::NE;
1311   case ISD::SETEQ:  return ARMCC::EQ;
1312   case ISD::SETGT:  return ARMCC::GT;
1313   case ISD::SETGE:  return ARMCC::GE;
1314   case ISD::SETLT:  return ARMCC::LT;
1315   case ISD::SETLE:  return ARMCC::LE;
1316   case ISD::SETUGT: return ARMCC::HI;
1317   case ISD::SETUGE: return ARMCC::HS;
1318   case ISD::SETULT: return ARMCC::LO;
1319   case ISD::SETULE: return ARMCC::LS;
1320   }
1321 }
1322
1323 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1324 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1325                         ARMCC::CondCodes &CondCode2) {
1326   CondCode2 = ARMCC::AL;
1327   switch (CC) {
1328   default: llvm_unreachable("Unknown FP condition!");
1329   case ISD::SETEQ:
1330   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1331   case ISD::SETGT:
1332   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1333   case ISD::SETGE:
1334   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1335   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1336   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1337   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1338   case ISD::SETO:   CondCode = ARMCC::VC; break;
1339   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1340   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1341   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1342   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1343   case ISD::SETLT:
1344   case ISD::SETULT: CondCode = ARMCC::LT; break;
1345   case ISD::SETLE:
1346   case ISD::SETULE: CondCode = ARMCC::LE; break;
1347   case ISD::SETNE:
1348   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1349   }
1350 }
1351
1352 //===----------------------------------------------------------------------===//
1353 //                      Calling Convention Implementation
1354 //===----------------------------------------------------------------------===//
1355
1356 #include "ARMGenCallingConv.inc"
1357
1358 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1359 /// account presence of floating point hardware and calling convention
1360 /// limitations, such as support for variadic functions.
1361 CallingConv::ID
1362 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1363                                            bool isVarArg) const {
1364   switch (CC) {
1365   default:
1366     llvm_unreachable("Unsupported calling convention");
1367   case CallingConv::ARM_AAPCS:
1368   case CallingConv::ARM_APCS:
1369   case CallingConv::GHC:
1370     return CC;
1371   case CallingConv::ARM_AAPCS_VFP:
1372     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1373   case CallingConv::C:
1374     if (!Subtarget->isAAPCS_ABI())
1375       return CallingConv::ARM_APCS;
1376     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1377              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1378              !isVarArg)
1379       return CallingConv::ARM_AAPCS_VFP;
1380     else
1381       return CallingConv::ARM_AAPCS;
1382   case CallingConv::Fast:
1383     if (!Subtarget->isAAPCS_ABI()) {
1384       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1385         return CallingConv::Fast;
1386       return CallingConv::ARM_APCS;
1387     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1388       return CallingConv::ARM_AAPCS_VFP;
1389     else
1390       return CallingConv::ARM_AAPCS;
1391   }
1392 }
1393
1394 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1395 /// CallingConvention.
1396 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1397                                                  bool Return,
1398                                                  bool isVarArg) const {
1399   switch (getEffectiveCallingConv(CC, isVarArg)) {
1400   default:
1401     llvm_unreachable("Unsupported calling convention");
1402   case CallingConv::ARM_APCS:
1403     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1404   case CallingConv::ARM_AAPCS:
1405     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1406   case CallingConv::ARM_AAPCS_VFP:
1407     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1408   case CallingConv::Fast:
1409     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1410   case CallingConv::GHC:
1411     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1412   }
1413 }
1414
1415 /// LowerCallResult - Lower the result values of a call into the
1416 /// appropriate copies out of appropriate physical registers.
1417 SDValue
1418 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1419                                    CallingConv::ID CallConv, bool isVarArg,
1420                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1421                                    SDLoc dl, SelectionDAG &DAG,
1422                                    SmallVectorImpl<SDValue> &InVals,
1423                                    bool isThisReturn, SDValue ThisVal) const {
1424
1425   // Assign locations to each value returned by this call.
1426   SmallVector<CCValAssign, 16> RVLocs;
1427   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1428                     *DAG.getContext(), Call);
1429   CCInfo.AnalyzeCallResult(Ins,
1430                            CCAssignFnForNode(CallConv, /* Return*/ true,
1431                                              isVarArg));
1432
1433   // Copy all of the result registers out of their specified physreg.
1434   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1435     CCValAssign VA = RVLocs[i];
1436
1437     // Pass 'this' value directly from the argument to return value, to avoid
1438     // reg unit interference
1439     if (i == 0 && isThisReturn) {
1440       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1441              "unexpected return calling convention register assignment");
1442       InVals.push_back(ThisVal);
1443       continue;
1444     }
1445
1446     SDValue Val;
1447     if (VA.needsCustom()) {
1448       // Handle f64 or half of a v2f64.
1449       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1450                                       InFlag);
1451       Chain = Lo.getValue(1);
1452       InFlag = Lo.getValue(2);
1453       VA = RVLocs[++i]; // skip ahead to next loc
1454       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1455                                       InFlag);
1456       Chain = Hi.getValue(1);
1457       InFlag = Hi.getValue(2);
1458       if (!Subtarget->isLittle())
1459         std::swap (Lo, Hi);
1460       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1461
1462       if (VA.getLocVT() == MVT::v2f64) {
1463         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1464         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1465                           DAG.getConstant(0, dl, MVT::i32));
1466
1467         VA = RVLocs[++i]; // skip ahead to next loc
1468         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1469         Chain = Lo.getValue(1);
1470         InFlag = Lo.getValue(2);
1471         VA = RVLocs[++i]; // skip ahead to next loc
1472         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1473         Chain = Hi.getValue(1);
1474         InFlag = Hi.getValue(2);
1475         if (!Subtarget->isLittle())
1476           std::swap (Lo, Hi);
1477         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1478         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1479                           DAG.getConstant(1, dl, MVT::i32));
1480       }
1481     } else {
1482       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1483                                InFlag);
1484       Chain = Val.getValue(1);
1485       InFlag = Val.getValue(2);
1486     }
1487
1488     switch (VA.getLocInfo()) {
1489     default: llvm_unreachable("Unknown loc info!");
1490     case CCValAssign::Full: break;
1491     case CCValAssign::BCvt:
1492       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1493       break;
1494     }
1495
1496     InVals.push_back(Val);
1497   }
1498
1499   return Chain;
1500 }
1501
1502 /// LowerMemOpCallTo - Store the argument to the stack.
1503 SDValue
1504 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1505                                     SDValue StackPtr, SDValue Arg,
1506                                     SDLoc dl, SelectionDAG &DAG,
1507                                     const CCValAssign &VA,
1508                                     ISD::ArgFlagsTy Flags) const {
1509   unsigned LocMemOffset = VA.getLocMemOffset();
1510   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1511   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1512                        StackPtr, PtrOff);
1513   return DAG.getStore(
1514       Chain, dl, Arg, PtrOff,
1515       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1516       false, false, 0);
1517 }
1518
1519 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1520                                          SDValue Chain, SDValue &Arg,
1521                                          RegsToPassVector &RegsToPass,
1522                                          CCValAssign &VA, CCValAssign &NextVA,
1523                                          SDValue &StackPtr,
1524                                          SmallVectorImpl<SDValue> &MemOpChains,
1525                                          ISD::ArgFlagsTy Flags) const {
1526
1527   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1528                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1529   unsigned id = Subtarget->isLittle() ? 0 : 1;
1530   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1531
1532   if (NextVA.isRegLoc())
1533     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1534   else {
1535     assert(NextVA.isMemLoc());
1536     if (!StackPtr.getNode())
1537       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1538                                     getPointerTy(DAG.getDataLayout()));
1539
1540     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1541                                            dl, DAG, NextVA,
1542                                            Flags));
1543   }
1544 }
1545
1546 /// LowerCall - Lowering a call into a callseq_start <-
1547 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1548 /// nodes.
1549 SDValue
1550 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1551                              SmallVectorImpl<SDValue> &InVals) const {
1552   SelectionDAG &DAG                     = CLI.DAG;
1553   SDLoc &dl                             = CLI.DL;
1554   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1555   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1556   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1557   SDValue Chain                         = CLI.Chain;
1558   SDValue Callee                        = CLI.Callee;
1559   bool &isTailCall                      = CLI.IsTailCall;
1560   CallingConv::ID CallConv              = CLI.CallConv;
1561   bool doesNotRet                       = CLI.DoesNotReturn;
1562   bool isVarArg                         = CLI.IsVarArg;
1563
1564   MachineFunction &MF = DAG.getMachineFunction();
1565   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1566   bool isThisReturn   = false;
1567   bool isSibCall      = false;
1568   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1569
1570   // Disable tail calls if they're not supported.
1571   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1572     isTailCall = false;
1573
1574   if (isTailCall) {
1575     // Check if it's really possible to do a tail call.
1576     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1577                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1578                                                    Outs, OutVals, Ins, DAG);
1579     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1580       report_fatal_error("failed to perform tail call elimination on a call "
1581                          "site marked musttail");
1582     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1583     // detected sibcalls.
1584     if (isTailCall) {
1585       ++NumTailCalls;
1586       isSibCall = true;
1587     }
1588   }
1589
1590   // Analyze operands of the call, assigning locations to each operand.
1591   SmallVector<CCValAssign, 16> ArgLocs;
1592   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1593                     *DAG.getContext(), Call);
1594   CCInfo.AnalyzeCallOperands(Outs,
1595                              CCAssignFnForNode(CallConv, /* Return*/ false,
1596                                                isVarArg));
1597
1598   // Get a count of how many bytes are to be pushed on the stack.
1599   unsigned NumBytes = CCInfo.getNextStackOffset();
1600
1601   // For tail calls, memory operands are available in our caller's stack.
1602   if (isSibCall)
1603     NumBytes = 0;
1604
1605   // Adjust the stack pointer for the new arguments...
1606   // These operations are automatically eliminated by the prolog/epilog pass
1607   if (!isSibCall)
1608     Chain = DAG.getCALLSEQ_START(Chain,
1609                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1610
1611   SDValue StackPtr =
1612       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1613
1614   RegsToPassVector RegsToPass;
1615   SmallVector<SDValue, 8> MemOpChains;
1616
1617   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1618   // of tail call optimization, arguments are handled later.
1619   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1620        i != e;
1621        ++i, ++realArgIdx) {
1622     CCValAssign &VA = ArgLocs[i];
1623     SDValue Arg = OutVals[realArgIdx];
1624     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1625     bool isByVal = Flags.isByVal();
1626
1627     // Promote the value if needed.
1628     switch (VA.getLocInfo()) {
1629     default: llvm_unreachable("Unknown loc info!");
1630     case CCValAssign::Full: break;
1631     case CCValAssign::SExt:
1632       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1633       break;
1634     case CCValAssign::ZExt:
1635       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1636       break;
1637     case CCValAssign::AExt:
1638       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1639       break;
1640     case CCValAssign::BCvt:
1641       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1642       break;
1643     }
1644
1645     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1646     if (VA.needsCustom()) {
1647       if (VA.getLocVT() == MVT::v2f64) {
1648         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1649                                   DAG.getConstant(0, dl, MVT::i32));
1650         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1651                                   DAG.getConstant(1, dl, MVT::i32));
1652
1653         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1654                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1655
1656         VA = ArgLocs[++i]; // skip ahead to next loc
1657         if (VA.isRegLoc()) {
1658           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1659                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1660         } else {
1661           assert(VA.isMemLoc());
1662
1663           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1664                                                  dl, DAG, VA, Flags));
1665         }
1666       } else {
1667         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1668                          StackPtr, MemOpChains, Flags);
1669       }
1670     } else if (VA.isRegLoc()) {
1671       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1672         assert(VA.getLocVT() == MVT::i32 &&
1673                "unexpected calling convention register assignment");
1674         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1675                "unexpected use of 'returned'");
1676         isThisReturn = true;
1677       }
1678       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1679     } else if (isByVal) {
1680       assert(VA.isMemLoc());
1681       unsigned offset = 0;
1682
1683       // True if this byval aggregate will be split between registers
1684       // and memory.
1685       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1686       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1687
1688       if (CurByValIdx < ByValArgsCount) {
1689
1690         unsigned RegBegin, RegEnd;
1691         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1692
1693         EVT PtrVT =
1694             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1695         unsigned int i, j;
1696         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1697           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1698           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1699           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1700                                      MachinePointerInfo(),
1701                                      false, false, false,
1702                                      DAG.InferPtrAlignment(AddArg));
1703           MemOpChains.push_back(Load.getValue(1));
1704           RegsToPass.push_back(std::make_pair(j, Load));
1705         }
1706
1707         // If parameter size outsides register area, "offset" value
1708         // helps us to calculate stack slot for remained part properly.
1709         offset = RegEnd - RegBegin;
1710
1711         CCInfo.nextInRegsParam();
1712       }
1713
1714       if (Flags.getByValSize() > 4*offset) {
1715         auto PtrVT = getPointerTy(DAG.getDataLayout());
1716         unsigned LocMemOffset = VA.getLocMemOffset();
1717         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1718         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1719         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1720         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1721         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1722                                            MVT::i32);
1723         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1724                                             MVT::i32);
1725
1726         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1727         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1728         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1729                                           Ops));
1730       }
1731     } else if (!isSibCall) {
1732       assert(VA.isMemLoc());
1733
1734       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1735                                              dl, DAG, VA, Flags));
1736     }
1737   }
1738
1739   if (!MemOpChains.empty())
1740     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1741
1742   // Build a sequence of copy-to-reg nodes chained together with token chain
1743   // and flag operands which copy the outgoing args into the appropriate regs.
1744   SDValue InFlag;
1745   // Tail call byval lowering might overwrite argument registers so in case of
1746   // tail call optimization the copies to registers are lowered later.
1747   if (!isTailCall)
1748     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1749       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1750                                RegsToPass[i].second, InFlag);
1751       InFlag = Chain.getValue(1);
1752     }
1753
1754   // For tail calls lower the arguments to the 'real' stack slot.
1755   if (isTailCall) {
1756     // Force all the incoming stack arguments to be loaded from the stack
1757     // before any new outgoing arguments are stored to the stack, because the
1758     // outgoing stack slots may alias the incoming argument stack slots, and
1759     // the alias isn't otherwise explicit. This is slightly more conservative
1760     // than necessary, because it means that each store effectively depends
1761     // on every argument instead of just those arguments it would clobber.
1762
1763     // Do not flag preceding copytoreg stuff together with the following stuff.
1764     InFlag = SDValue();
1765     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1766       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1767                                RegsToPass[i].second, InFlag);
1768       InFlag = Chain.getValue(1);
1769     }
1770     InFlag = SDValue();
1771   }
1772
1773   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1774   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1775   // node so that legalize doesn't hack it.
1776   bool isDirect = false;
1777   bool isARMFunc = false;
1778   bool isLocalARMFunc = false;
1779   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1780   auto PtrVt = getPointerTy(DAG.getDataLayout());
1781
1782   if (Subtarget->genLongCalls()) {
1783     assert((Subtarget->isTargetWindows() ||
1784             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1785            "long-calls with non-static relocation model!");
1786     // Handle a global address or an external symbol. If it's not one of
1787     // those, the target's already in a register, so we don't need to do
1788     // anything extra.
1789     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1790       const GlobalValue *GV = G->getGlobal();
1791       // Create a constant pool entry for the callee address
1792       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1793       ARMConstantPoolValue *CPV =
1794         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1795
1796       // Get the address of the callee into a register
1797       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1798       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1799       Callee = DAG.getLoad(
1800           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1801           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1802           false, false, 0);
1803     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1804       const char *Sym = S->getSymbol();
1805
1806       // Create a constant pool entry for the callee address
1807       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1808       ARMConstantPoolValue *CPV =
1809         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1810                                       ARMPCLabelIndex, 0);
1811       // Get the address of the callee into a register
1812       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1813       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1814       Callee = DAG.getLoad(
1815           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1816           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1817           false, false, 0);
1818     }
1819   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1820     const GlobalValue *GV = G->getGlobal();
1821     isDirect = true;
1822     bool isDef = GV->isStrongDefinitionForLinker();
1823     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1824                    getTargetMachine().getRelocationModel() != Reloc::Static;
1825     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1826     // ARM call to a local ARM function is predicable.
1827     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1828     // tBX takes a register source operand.
1829     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1830       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1831       Callee = DAG.getNode(
1832           ARMISD::WrapperPIC, dl, PtrVt,
1833           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1834       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1835                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1836                            false, false, true, 0);
1837     } else if (Subtarget->isTargetCOFF()) {
1838       assert(Subtarget->isTargetWindows() &&
1839              "Windows is the only supported COFF target");
1840       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1841                                  ? ARMII::MO_DLLIMPORT
1842                                  : ARMII::MO_NO_FLAG;
1843       Callee =
1844           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1845       if (GV->hasDLLImportStorageClass())
1846         Callee =
1847             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1848                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1849                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1850                         false, false, false, 0);
1851     } else {
1852       // On ELF targets for PIC code, direct calls should go through the PLT
1853       unsigned OpFlags = 0;
1854       if (Subtarget->isTargetELF() &&
1855           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1856         OpFlags = ARMII::MO_PLT;
1857       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1858     }
1859   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1860     isDirect = true;
1861     bool isStub = Subtarget->isTargetMachO() &&
1862                   getTargetMachine().getRelocationModel() != Reloc::Static;
1863     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1864     // tBX takes a register source operand.
1865     const char *Sym = S->getSymbol();
1866     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1867       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1868       ARMConstantPoolValue *CPV =
1869         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1870                                       ARMPCLabelIndex, 4);
1871       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1872       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1873       Callee = DAG.getLoad(
1874           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1875           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1876           false, false, 0);
1877       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1878       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1879     } else {
1880       unsigned OpFlags = 0;
1881       // On ELF targets for PIC code, direct calls should go through the PLT
1882       if (Subtarget->isTargetELF() &&
1883                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1884         OpFlags = ARMII::MO_PLT;
1885       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1886     }
1887   }
1888
1889   // FIXME: handle tail calls differently.
1890   unsigned CallOpc;
1891   if (Subtarget->isThumb()) {
1892     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1893       CallOpc = ARMISD::CALL_NOLINK;
1894     else
1895       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1896   } else {
1897     if (!isDirect && !Subtarget->hasV5TOps())
1898       CallOpc = ARMISD::CALL_NOLINK;
1899     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1900              // Emit regular call when code size is the priority
1901              !MF.getFunction()->optForMinSize())
1902       // "mov lr, pc; b _foo" to avoid confusing the RSP
1903       CallOpc = ARMISD::CALL_NOLINK;
1904     else
1905       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1906   }
1907
1908   std::vector<SDValue> Ops;
1909   Ops.push_back(Chain);
1910   Ops.push_back(Callee);
1911
1912   // Add argument registers to the end of the list so that they are known live
1913   // into the call.
1914   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1915     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1916                                   RegsToPass[i].second.getValueType()));
1917
1918   // Add a register mask operand representing the call-preserved registers.
1919   if (!isTailCall) {
1920     const uint32_t *Mask;
1921     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1922     if (isThisReturn) {
1923       // For 'this' returns, use the R0-preserving mask if applicable
1924       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1925       if (!Mask) {
1926         // Set isThisReturn to false if the calling convention is not one that
1927         // allows 'returned' to be modeled in this way, so LowerCallResult does
1928         // not try to pass 'this' straight through
1929         isThisReturn = false;
1930         Mask = ARI->getCallPreservedMask(MF, CallConv);
1931       }
1932     } else
1933       Mask = ARI->getCallPreservedMask(MF, CallConv);
1934
1935     assert(Mask && "Missing call preserved mask for calling convention");
1936     Ops.push_back(DAG.getRegisterMask(Mask));
1937   }
1938
1939   if (InFlag.getNode())
1940     Ops.push_back(InFlag);
1941
1942   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1943   if (isTailCall) {
1944     MF.getFrameInfo()->setHasTailCall();
1945     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1946   }
1947
1948   // Returns a chain and a flag for retval copy to use.
1949   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1950   InFlag = Chain.getValue(1);
1951
1952   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1953                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1954   if (!Ins.empty())
1955     InFlag = Chain.getValue(1);
1956
1957   // Handle result values, copying them out of physregs into vregs that we
1958   // return.
1959   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1960                          InVals, isThisReturn,
1961                          isThisReturn ? OutVals[0] : SDValue());
1962 }
1963
1964 /// HandleByVal - Every parameter *after* a byval parameter is passed
1965 /// on the stack.  Remember the next parameter register to allocate,
1966 /// and then confiscate the rest of the parameter registers to insure
1967 /// this.
1968 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1969                                     unsigned Align) const {
1970   assert((State->getCallOrPrologue() == Prologue ||
1971           State->getCallOrPrologue() == Call) &&
1972          "unhandled ParmContext");
1973
1974   // Byval (as with any stack) slots are always at least 4 byte aligned.
1975   Align = std::max(Align, 4U);
1976
1977   unsigned Reg = State->AllocateReg(GPRArgRegs);
1978   if (!Reg)
1979     return;
1980
1981   unsigned AlignInRegs = Align / 4;
1982   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1983   for (unsigned i = 0; i < Waste; ++i)
1984     Reg = State->AllocateReg(GPRArgRegs);
1985
1986   if (!Reg)
1987     return;
1988
1989   unsigned Excess = 4 * (ARM::R4 - Reg);
1990
1991   // Special case when NSAA != SP and parameter size greater than size of
1992   // all remained GPR regs. In that case we can't split parameter, we must
1993   // send it to stack. We also must set NCRN to R4, so waste all
1994   // remained registers.
1995   const unsigned NSAAOffset = State->getNextStackOffset();
1996   if (NSAAOffset != 0 && Size > Excess) {
1997     while (State->AllocateReg(GPRArgRegs))
1998       ;
1999     return;
2000   }
2001
2002   // First register for byval parameter is the first register that wasn't
2003   // allocated before this method call, so it would be "reg".
2004   // If parameter is small enough to be saved in range [reg, r4), then
2005   // the end (first after last) register would be reg + param-size-in-regs,
2006   // else parameter would be splitted between registers and stack,
2007   // end register would be r4 in this case.
2008   unsigned ByValRegBegin = Reg;
2009   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2010   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2011   // Note, first register is allocated in the beginning of function already,
2012   // allocate remained amount of registers we need.
2013   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2014     State->AllocateReg(GPRArgRegs);
2015   // A byval parameter that is split between registers and memory needs its
2016   // size truncated here.
2017   // In the case where the entire structure fits in registers, we set the
2018   // size in memory to zero.
2019   Size = std::max<int>(Size - Excess, 0);
2020 }
2021
2022 /// MatchingStackOffset - Return true if the given stack call argument is
2023 /// already available in the same position (relatively) of the caller's
2024 /// incoming argument stack.
2025 static
2026 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2027                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2028                          const TargetInstrInfo *TII) {
2029   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2030   int FI = INT_MAX;
2031   if (Arg.getOpcode() == ISD::CopyFromReg) {
2032     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2033     if (!TargetRegisterInfo::isVirtualRegister(VR))
2034       return false;
2035     MachineInstr *Def = MRI->getVRegDef(VR);
2036     if (!Def)
2037       return false;
2038     if (!Flags.isByVal()) {
2039       if (!TII->isLoadFromStackSlot(Def, FI))
2040         return false;
2041     } else {
2042       return false;
2043     }
2044   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2045     if (Flags.isByVal())
2046       // ByVal argument is passed in as a pointer but it's now being
2047       // dereferenced. e.g.
2048       // define @foo(%struct.X* %A) {
2049       //   tail call @bar(%struct.X* byval %A)
2050       // }
2051       return false;
2052     SDValue Ptr = Ld->getBasePtr();
2053     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2054     if (!FINode)
2055       return false;
2056     FI = FINode->getIndex();
2057   } else
2058     return false;
2059
2060   assert(FI != INT_MAX);
2061   if (!MFI->isFixedObjectIndex(FI))
2062     return false;
2063   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2064 }
2065
2066 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2067 /// for tail call optimization. Targets which want to do tail call
2068 /// optimization should implement this function.
2069 bool
2070 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2071                                                      CallingConv::ID CalleeCC,
2072                                                      bool isVarArg,
2073                                                      bool isCalleeStructRet,
2074                                                      bool isCallerStructRet,
2075                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2076                                     const SmallVectorImpl<SDValue> &OutVals,
2077                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2078                                                      SelectionDAG& DAG) const {
2079   const Function *CallerF = DAG.getMachineFunction().getFunction();
2080   CallingConv::ID CallerCC = CallerF->getCallingConv();
2081   bool CCMatch = CallerCC == CalleeCC;
2082
2083   assert(Subtarget->supportsTailCall());
2084
2085   // Look for obvious safe cases to perform tail call optimization that do not
2086   // require ABI changes. This is what gcc calls sibcall.
2087
2088   // Do not sibcall optimize vararg calls unless the call site is not passing
2089   // any arguments.
2090   if (isVarArg && !Outs.empty())
2091     return false;
2092
2093   // Exception-handling functions need a special set of instructions to indicate
2094   // a return to the hardware. Tail-calling another function would probably
2095   // break this.
2096   if (CallerF->hasFnAttribute("interrupt"))
2097     return false;
2098
2099   // Also avoid sibcall optimization if either caller or callee uses struct
2100   // return semantics.
2101   if (isCalleeStructRet || isCallerStructRet)
2102     return false;
2103
2104   // Externally-defined functions with weak linkage should not be
2105   // tail-called on ARM when the OS does not support dynamic
2106   // pre-emption of symbols, as the AAELF spec requires normal calls
2107   // to undefined weak functions to be replaced with a NOP or jump to the
2108   // next instruction. The behaviour of branch instructions in this
2109   // situation (as used for tail calls) is implementation-defined, so we
2110   // cannot rely on the linker replacing the tail call with a return.
2111   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2112     const GlobalValue *GV = G->getGlobal();
2113     const Triple &TT = getTargetMachine().getTargetTriple();
2114     if (GV->hasExternalWeakLinkage() &&
2115         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2116       return false;
2117   }
2118
2119   // If the calling conventions do not match, then we'd better make sure the
2120   // results are returned in the same way as what the caller expects.
2121   if (!CCMatch) {
2122     SmallVector<CCValAssign, 16> RVLocs1;
2123     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2124                        *DAG.getContext(), Call);
2125     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2126
2127     SmallVector<CCValAssign, 16> RVLocs2;
2128     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2129                        *DAG.getContext(), Call);
2130     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2131
2132     if (RVLocs1.size() != RVLocs2.size())
2133       return false;
2134     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2135       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2136         return false;
2137       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2138         return false;
2139       if (RVLocs1[i].isRegLoc()) {
2140         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2141           return false;
2142       } else {
2143         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2144           return false;
2145       }
2146     }
2147   }
2148
2149   // If Caller's vararg or byval argument has been split between registers and
2150   // stack, do not perform tail call, since part of the argument is in caller's
2151   // local frame.
2152   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2153                                       getInfo<ARMFunctionInfo>();
2154   if (AFI_Caller->getArgRegsSaveSize())
2155     return false;
2156
2157   // If the callee takes no arguments then go on to check the results of the
2158   // call.
2159   if (!Outs.empty()) {
2160     // Check if stack adjustment is needed. For now, do not do this if any
2161     // argument is passed on the stack.
2162     SmallVector<CCValAssign, 16> ArgLocs;
2163     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2164                       *DAG.getContext(), Call);
2165     CCInfo.AnalyzeCallOperands(Outs,
2166                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2167     if (CCInfo.getNextStackOffset()) {
2168       MachineFunction &MF = DAG.getMachineFunction();
2169
2170       // Check if the arguments are already laid out in the right way as
2171       // the caller's fixed stack objects.
2172       MachineFrameInfo *MFI = MF.getFrameInfo();
2173       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2174       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2175       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2176            i != e;
2177            ++i, ++realArgIdx) {
2178         CCValAssign &VA = ArgLocs[i];
2179         EVT RegVT = VA.getLocVT();
2180         SDValue Arg = OutVals[realArgIdx];
2181         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2182         if (VA.getLocInfo() == CCValAssign::Indirect)
2183           return false;
2184         if (VA.needsCustom()) {
2185           // f64 and vector types are split into multiple registers or
2186           // register/stack-slot combinations.  The types will not match
2187           // the registers; give up on memory f64 refs until we figure
2188           // out what to do about this.
2189           if (!VA.isRegLoc())
2190             return false;
2191           if (!ArgLocs[++i].isRegLoc())
2192             return false;
2193           if (RegVT == MVT::v2f64) {
2194             if (!ArgLocs[++i].isRegLoc())
2195               return false;
2196             if (!ArgLocs[++i].isRegLoc())
2197               return false;
2198           }
2199         } else if (!VA.isRegLoc()) {
2200           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2201                                    MFI, MRI, TII))
2202             return false;
2203         }
2204       }
2205     }
2206   }
2207
2208   return true;
2209 }
2210
2211 bool
2212 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2213                                   MachineFunction &MF, bool isVarArg,
2214                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2215                                   LLVMContext &Context) const {
2216   SmallVector<CCValAssign, 16> RVLocs;
2217   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2218   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2219                                                     isVarArg));
2220 }
2221
2222 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2223                                     SDLoc DL, SelectionDAG &DAG) {
2224   const MachineFunction &MF = DAG.getMachineFunction();
2225   const Function *F = MF.getFunction();
2226
2227   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2228
2229   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2230   // version of the "preferred return address". These offsets affect the return
2231   // instruction if this is a return from PL1 without hypervisor extensions.
2232   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2233   //    SWI:     0      "subs pc, lr, #0"
2234   //    ABORT:   +4     "subs pc, lr, #4"
2235   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2236   // UNDEF varies depending on where the exception came from ARM or Thumb
2237   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2238
2239   int64_t LROffset;
2240   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2241       IntKind == "ABORT")
2242     LROffset = 4;
2243   else if (IntKind == "SWI" || IntKind == "UNDEF")
2244     LROffset = 0;
2245   else
2246     report_fatal_error("Unsupported interrupt attribute. If present, value "
2247                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2248
2249   RetOps.insert(RetOps.begin() + 1,
2250                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2251
2252   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2253 }
2254
2255 SDValue
2256 ARMTargetLowering::LowerReturn(SDValue Chain,
2257                                CallingConv::ID CallConv, bool isVarArg,
2258                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2259                                const SmallVectorImpl<SDValue> &OutVals,
2260                                SDLoc dl, SelectionDAG &DAG) const {
2261
2262   // CCValAssign - represent the assignment of the return value to a location.
2263   SmallVector<CCValAssign, 16> RVLocs;
2264
2265   // CCState - Info about the registers and stack slots.
2266   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2267                     *DAG.getContext(), Call);
2268
2269   // Analyze outgoing return values.
2270   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2271                                                isVarArg));
2272
2273   SDValue Flag;
2274   SmallVector<SDValue, 4> RetOps;
2275   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2276   bool isLittleEndian = Subtarget->isLittle();
2277
2278   MachineFunction &MF = DAG.getMachineFunction();
2279   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2280   AFI->setReturnRegsCount(RVLocs.size());
2281
2282   // Copy the result values into the output registers.
2283   for (unsigned i = 0, realRVLocIdx = 0;
2284        i != RVLocs.size();
2285        ++i, ++realRVLocIdx) {
2286     CCValAssign &VA = RVLocs[i];
2287     assert(VA.isRegLoc() && "Can only return in registers!");
2288
2289     SDValue Arg = OutVals[realRVLocIdx];
2290
2291     switch (VA.getLocInfo()) {
2292     default: llvm_unreachable("Unknown loc info!");
2293     case CCValAssign::Full: break;
2294     case CCValAssign::BCvt:
2295       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2296       break;
2297     }
2298
2299     if (VA.needsCustom()) {
2300       if (VA.getLocVT() == MVT::v2f64) {
2301         // Extract the first half and return it in two registers.
2302         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2303                                    DAG.getConstant(0, dl, MVT::i32));
2304         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2305                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2306
2307         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2308                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2309                                  Flag);
2310         Flag = Chain.getValue(1);
2311         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2312         VA = RVLocs[++i]; // skip ahead to next loc
2313         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2314                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2315                                  Flag);
2316         Flag = Chain.getValue(1);
2317         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2318         VA = RVLocs[++i]; // skip ahead to next loc
2319
2320         // Extract the 2nd half and fall through to handle it as an f64 value.
2321         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2322                           DAG.getConstant(1, dl, MVT::i32));
2323       }
2324       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2325       // available.
2326       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2327                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2328       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2329                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2330                                Flag);
2331       Flag = Chain.getValue(1);
2332       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2333       VA = RVLocs[++i]; // skip ahead to next loc
2334       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2335                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2336                                Flag);
2337     } else
2338       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2339
2340     // Guarantee that all emitted copies are
2341     // stuck together, avoiding something bad.
2342     Flag = Chain.getValue(1);
2343     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2344   }
2345
2346   // Update chain and glue.
2347   RetOps[0] = Chain;
2348   if (Flag.getNode())
2349     RetOps.push_back(Flag);
2350
2351   // CPUs which aren't M-class use a special sequence to return from
2352   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2353   // though we use "subs pc, lr, #N").
2354   //
2355   // M-class CPUs actually use a normal return sequence with a special
2356   // (hardware-provided) value in LR, so the normal code path works.
2357   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2358       !Subtarget->isMClass()) {
2359     if (Subtarget->isThumb1Only())
2360       report_fatal_error("interrupt attribute is not supported in Thumb1");
2361     return LowerInterruptReturn(RetOps, dl, DAG);
2362   }
2363
2364   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2365 }
2366
2367 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2368   if (N->getNumValues() != 1)
2369     return false;
2370   if (!N->hasNUsesOfValue(1, 0))
2371     return false;
2372
2373   SDValue TCChain = Chain;
2374   SDNode *Copy = *N->use_begin();
2375   if (Copy->getOpcode() == ISD::CopyToReg) {
2376     // If the copy has a glue operand, we conservatively assume it isn't safe to
2377     // perform a tail call.
2378     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2379       return false;
2380     TCChain = Copy->getOperand(0);
2381   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2382     SDNode *VMov = Copy;
2383     // f64 returned in a pair of GPRs.
2384     SmallPtrSet<SDNode*, 2> Copies;
2385     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2386          UI != UE; ++UI) {
2387       if (UI->getOpcode() != ISD::CopyToReg)
2388         return false;
2389       Copies.insert(*UI);
2390     }
2391     if (Copies.size() > 2)
2392       return false;
2393
2394     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2395          UI != UE; ++UI) {
2396       SDValue UseChain = UI->getOperand(0);
2397       if (Copies.count(UseChain.getNode()))
2398         // Second CopyToReg
2399         Copy = *UI;
2400       else {
2401         // We are at the top of this chain.
2402         // If the copy has a glue operand, we conservatively assume it
2403         // isn't safe to perform a tail call.
2404         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2405           return false;
2406         // First CopyToReg
2407         TCChain = UseChain;
2408       }
2409     }
2410   } else if (Copy->getOpcode() == ISD::BITCAST) {
2411     // f32 returned in a single GPR.
2412     if (!Copy->hasOneUse())
2413       return false;
2414     Copy = *Copy->use_begin();
2415     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2416       return false;
2417     // If the copy has a glue operand, we conservatively assume it isn't safe to
2418     // perform a tail call.
2419     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2420       return false;
2421     TCChain = Copy->getOperand(0);
2422   } else {
2423     return false;
2424   }
2425
2426   bool HasRet = false;
2427   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2428        UI != UE; ++UI) {
2429     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2430         UI->getOpcode() != ARMISD::INTRET_FLAG)
2431       return false;
2432     HasRet = true;
2433   }
2434
2435   if (!HasRet)
2436     return false;
2437
2438   Chain = TCChain;
2439   return true;
2440 }
2441
2442 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2443   if (!Subtarget->supportsTailCall())
2444     return false;
2445
2446   auto Attr =
2447       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2448   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2449     return false;
2450
2451   return true;
2452 }
2453
2454 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2455 // and pass the lower and high parts through.
2456 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2457   SDLoc DL(Op);
2458   SDValue WriteValue = Op->getOperand(2);
2459
2460   // This function is only supposed to be called for i64 type argument.
2461   assert(WriteValue.getValueType() == MVT::i64
2462           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2463
2464   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2465                            DAG.getConstant(0, DL, MVT::i32));
2466   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2467                            DAG.getConstant(1, DL, MVT::i32));
2468   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2469   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2470 }
2471
2472 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2473 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2474 // one of the above mentioned nodes. It has to be wrapped because otherwise
2475 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2476 // be used to form addressing mode. These wrapped nodes will be selected
2477 // into MOVi.
2478 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2479   EVT PtrVT = Op.getValueType();
2480   // FIXME there is no actual debug info here
2481   SDLoc dl(Op);
2482   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2483   SDValue Res;
2484   if (CP->isMachineConstantPoolEntry())
2485     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2486                                     CP->getAlignment());
2487   else
2488     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2489                                     CP->getAlignment());
2490   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2491 }
2492
2493 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2494   return MachineJumpTableInfo::EK_Inline;
2495 }
2496
2497 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2498                                              SelectionDAG &DAG) const {
2499   MachineFunction &MF = DAG.getMachineFunction();
2500   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2501   unsigned ARMPCLabelIndex = 0;
2502   SDLoc DL(Op);
2503   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2504   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2505   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2506   SDValue CPAddr;
2507   if (RelocM == Reloc::Static) {
2508     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2509   } else {
2510     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2511     ARMPCLabelIndex = AFI->createPICLabelUId();
2512     ARMConstantPoolValue *CPV =
2513       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2514                                       ARMCP::CPBlockAddress, PCAdj);
2515     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2516   }
2517   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2518   SDValue Result =
2519       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2520                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2521                   false, false, false, 0);
2522   if (RelocM == Reloc::Static)
2523     return Result;
2524   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2525   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2526 }
2527
2528 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2529 SDValue
2530 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2531                                                  SelectionDAG &DAG) const {
2532   SDLoc dl(GA);
2533   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2534   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2535   MachineFunction &MF = DAG.getMachineFunction();
2536   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2537   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2538   ARMConstantPoolValue *CPV =
2539     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2540                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2541   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2542   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2543   Argument =
2544       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2545                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2546                   false, false, false, 0);
2547   SDValue Chain = Argument.getValue(1);
2548
2549   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2550   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2551
2552   // call __tls_get_addr.
2553   ArgListTy Args;
2554   ArgListEntry Entry;
2555   Entry.Node = Argument;
2556   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2557   Args.push_back(Entry);
2558
2559   // FIXME: is there useful debug info available here?
2560   TargetLowering::CallLoweringInfo CLI(DAG);
2561   CLI.setDebugLoc(dl).setChain(Chain)
2562     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2563                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2564                0);
2565
2566   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2567   return CallResult.first;
2568 }
2569
2570 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2571 // "local exec" model.
2572 SDValue
2573 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2574                                         SelectionDAG &DAG,
2575                                         TLSModel::Model model) const {
2576   const GlobalValue *GV = GA->getGlobal();
2577   SDLoc dl(GA);
2578   SDValue Offset;
2579   SDValue Chain = DAG.getEntryNode();
2580   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2581   // Get the Thread Pointer
2582   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2583
2584   if (model == TLSModel::InitialExec) {
2585     MachineFunction &MF = DAG.getMachineFunction();
2586     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2587     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2588     // Initial exec model.
2589     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2590     ARMConstantPoolValue *CPV =
2591       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2592                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2593                                       true);
2594     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2595     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2596     Offset = DAG.getLoad(
2597         PtrVT, dl, Chain, Offset,
2598         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2599         false, false, 0);
2600     Chain = Offset.getValue(1);
2601
2602     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2603     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2604
2605     Offset = DAG.getLoad(
2606         PtrVT, dl, Chain, Offset,
2607         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2608         false, false, 0);
2609   } else {
2610     // local exec model
2611     assert(model == TLSModel::LocalExec);
2612     ARMConstantPoolValue *CPV =
2613       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2614     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2615     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2616     Offset = DAG.getLoad(
2617         PtrVT, dl, Chain, Offset,
2618         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2619         false, false, 0);
2620   }
2621
2622   // The address of the thread local variable is the add of the thread
2623   // pointer with the offset of the variable.
2624   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2625 }
2626
2627 SDValue
2628 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2629   // TODO: implement the "local dynamic" model
2630   assert(Subtarget->isTargetELF() &&
2631          "TLS not implemented for non-ELF targets");
2632   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2633   if (DAG.getTarget().Options.EmulatedTLS)
2634     return LowerToTLSEmulatedModel(GA, DAG);
2635
2636   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2637
2638   switch (model) {
2639     case TLSModel::GeneralDynamic:
2640     case TLSModel::LocalDynamic:
2641       return LowerToTLSGeneralDynamicModel(GA, DAG);
2642     case TLSModel::InitialExec:
2643     case TLSModel::LocalExec:
2644       return LowerToTLSExecModels(GA, DAG, model);
2645   }
2646   llvm_unreachable("bogus TLS model");
2647 }
2648
2649 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2650                                                  SelectionDAG &DAG) const {
2651   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2652   SDLoc dl(Op);
2653   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2654   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2655     bool UseGOT_PREL =
2656         !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2657
2658     MachineFunction &MF = DAG.getMachineFunction();
2659     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2660     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2661     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2662     SDLoc dl(Op);
2663     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2664     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2665         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2666         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2667         /*AddCurrentAddress=*/UseGOT_PREL);
2668     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2669     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2670     SDValue Result = DAG.getLoad(
2671         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2672         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2673         false, false, 0);
2674     SDValue Chain = Result.getValue(1);
2675     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2676     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2677     if (UseGOT_PREL)
2678       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2679                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2680                            false, false, false, 0);
2681     return Result;
2682   }
2683
2684   // If we have T2 ops, we can materialize the address directly via movt/movw
2685   // pair. This is always cheaper.
2686   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2687     ++NumMovwMovt;
2688     // FIXME: Once remat is capable of dealing with instructions with register
2689     // operands, expand this into two nodes.
2690     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2691                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2692   } else {
2693     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2694     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2695     return DAG.getLoad(
2696         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2697         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2698         false, false, 0);
2699   }
2700 }
2701
2702 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2703                                                     SelectionDAG &DAG) const {
2704   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2705   SDLoc dl(Op);
2706   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2707   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2708
2709   if (Subtarget->useMovt(DAG.getMachineFunction()))
2710     ++NumMovwMovt;
2711
2712   // FIXME: Once remat is capable of dealing with instructions with register
2713   // operands, expand this into multiple nodes
2714   unsigned Wrapper =
2715       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2716
2717   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2718   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2719
2720   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2721     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2722                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2723                          false, false, false, 0);
2724   return Result;
2725 }
2726
2727 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2728                                                      SelectionDAG &DAG) const {
2729   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2730   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2731          "Windows on ARM expects to use movw/movt");
2732
2733   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2734   const ARMII::TOF TargetFlags =
2735     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2736   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2737   SDValue Result;
2738   SDLoc DL(Op);
2739
2740   ++NumMovwMovt;
2741
2742   // FIXME: Once remat is capable of dealing with instructions with register
2743   // operands, expand this into two nodes.
2744   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2745                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2746                                                   TargetFlags));
2747   if (GV->hasDLLImportStorageClass())
2748     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2749                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2750                          false, false, false, 0);
2751   return Result;
2752 }
2753
2754 SDValue
2755 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2756   SDLoc dl(Op);
2757   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2758   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2759                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2760                      Op.getOperand(1), Val);
2761 }
2762
2763 SDValue
2764 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2765   SDLoc dl(Op);
2766   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2767                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2768 }
2769
2770 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2771                                                       SelectionDAG &DAG) const {
2772   SDLoc dl(Op);
2773   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2774                      Op.getOperand(0));
2775 }
2776
2777 SDValue
2778 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2779                                           const ARMSubtarget *Subtarget) const {
2780   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2781   SDLoc dl(Op);
2782   switch (IntNo) {
2783   default: return SDValue();    // Don't custom lower most intrinsics.
2784   case Intrinsic::arm_rbit: {
2785     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2786            "RBIT intrinsic must have i32 type!");
2787     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2788   }
2789   case Intrinsic::arm_thread_pointer: {
2790     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2791     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2792   }
2793   case Intrinsic::eh_sjlj_lsda: {
2794     MachineFunction &MF = DAG.getMachineFunction();
2795     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2796     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2797     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2798     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2799     SDValue CPAddr;
2800     unsigned PCAdj = (RelocM != Reloc::PIC_)
2801       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2802     ARMConstantPoolValue *CPV =
2803       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2804                                       ARMCP::CPLSDA, PCAdj);
2805     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2806     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2807     SDValue Result = DAG.getLoad(
2808         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2809         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2810         false, false, 0);
2811
2812     if (RelocM == Reloc::PIC_) {
2813       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2814       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2815     }
2816     return Result;
2817   }
2818   case Intrinsic::arm_neon_vmulls:
2819   case Intrinsic::arm_neon_vmullu: {
2820     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2821       ? ARMISD::VMULLs : ARMISD::VMULLu;
2822     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2823                        Op.getOperand(1), Op.getOperand(2));
2824   }
2825   case Intrinsic::arm_neon_vminnm:
2826   case Intrinsic::arm_neon_vmaxnm: {
2827     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2828       ? ISD::FMINNUM : ISD::FMAXNUM;
2829     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2830                        Op.getOperand(1), Op.getOperand(2));
2831   }
2832   case Intrinsic::arm_neon_vminu:
2833   case Intrinsic::arm_neon_vmaxu: {
2834     if (Op.getValueType().isFloatingPoint())
2835       return SDValue();
2836     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2837       ? ISD::UMIN : ISD::UMAX;
2838     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2839                          Op.getOperand(1), Op.getOperand(2));
2840   }
2841   case Intrinsic::arm_neon_vmins:
2842   case Intrinsic::arm_neon_vmaxs: {
2843     // v{min,max}s is overloaded between signed integers and floats.
2844     if (!Op.getValueType().isFloatingPoint()) {
2845       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2846         ? ISD::SMIN : ISD::SMAX;
2847       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2848                          Op.getOperand(1), Op.getOperand(2));
2849     }
2850     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2851       ? ISD::FMINNAN : ISD::FMAXNAN;
2852     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2853                        Op.getOperand(1), Op.getOperand(2));
2854   }
2855   }
2856 }
2857
2858 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2859                                  const ARMSubtarget *Subtarget) {
2860   // FIXME: handle "fence singlethread" more efficiently.
2861   SDLoc dl(Op);
2862   if (!Subtarget->hasDataBarrier()) {
2863     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2864     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2865     // here.
2866     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2867            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2868     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2869                        DAG.getConstant(0, dl, MVT::i32));
2870   }
2871
2872   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2873   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2874   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2875   if (Subtarget->isMClass()) {
2876     // Only a full system barrier exists in the M-class architectures.
2877     Domain = ARM_MB::SY;
2878   } else if (Subtarget->isSwift() && Ord == Release) {
2879     // Swift happens to implement ISHST barriers in a way that's compatible with
2880     // Release semantics but weaker than ISH so we'd be fools not to use
2881     // it. Beware: other processors probably don't!
2882     Domain = ARM_MB::ISHST;
2883   }
2884
2885   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2886                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2887                      DAG.getConstant(Domain, dl, MVT::i32));
2888 }
2889
2890 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2891                              const ARMSubtarget *Subtarget) {
2892   // ARM pre v5TE and Thumb1 does not have preload instructions.
2893   if (!(Subtarget->isThumb2() ||
2894         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2895     // Just preserve the chain.
2896     return Op.getOperand(0);
2897
2898   SDLoc dl(Op);
2899   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2900   if (!isRead &&
2901       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2902     // ARMv7 with MP extension has PLDW.
2903     return Op.getOperand(0);
2904
2905   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2906   if (Subtarget->isThumb()) {
2907     // Invert the bits.
2908     isRead = ~isRead & 1;
2909     isData = ~isData & 1;
2910   }
2911
2912   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2913                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2914                      DAG.getConstant(isData, dl, MVT::i32));
2915 }
2916
2917 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2918   MachineFunction &MF = DAG.getMachineFunction();
2919   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2920
2921   // vastart just stores the address of the VarArgsFrameIndex slot into the
2922   // memory location argument.
2923   SDLoc dl(Op);
2924   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2925   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2926   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2927   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2928                       MachinePointerInfo(SV), false, false, 0);
2929 }
2930
2931 SDValue
2932 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2933                                         SDValue &Root, SelectionDAG &DAG,
2934                                         SDLoc dl) const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2937
2938   const TargetRegisterClass *RC;
2939   if (AFI->isThumb1OnlyFunction())
2940     RC = &ARM::tGPRRegClass;
2941   else
2942     RC = &ARM::GPRRegClass;
2943
2944   // Transform the arguments stored in physical registers into virtual ones.
2945   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2946   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2947
2948   SDValue ArgValue2;
2949   if (NextVA.isMemLoc()) {
2950     MachineFrameInfo *MFI = MF.getFrameInfo();
2951     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2952
2953     // Create load node to retrieve arguments from the stack.
2954     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2955     ArgValue2 = DAG.getLoad(
2956         MVT::i32, dl, Root, FIN,
2957         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2958         false, false, 0);
2959   } else {
2960     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2961     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2962   }
2963   if (!Subtarget->isLittle())
2964     std::swap (ArgValue, ArgValue2);
2965   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2966 }
2967
2968 // The remaining GPRs hold either the beginning of variable-argument
2969 // data, or the beginning of an aggregate passed by value (usually
2970 // byval).  Either way, we allocate stack slots adjacent to the data
2971 // provided by our caller, and store the unallocated registers there.
2972 // If this is a variadic function, the va_list pointer will begin with
2973 // these values; otherwise, this reassembles a (byval) structure that
2974 // was split between registers and memory.
2975 // Return: The frame index registers were stored into.
2976 int
2977 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2978                                   SDLoc dl, SDValue &Chain,
2979                                   const Value *OrigArg,
2980                                   unsigned InRegsParamRecordIdx,
2981                                   int ArgOffset,
2982                                   unsigned ArgSize) const {
2983   // Currently, two use-cases possible:
2984   // Case #1. Non-var-args function, and we meet first byval parameter.
2985   //          Setup first unallocated register as first byval register;
2986   //          eat all remained registers
2987   //          (these two actions are performed by HandleByVal method).
2988   //          Then, here, we initialize stack frame with
2989   //          "store-reg" instructions.
2990   // Case #2. Var-args function, that doesn't contain byval parameters.
2991   //          The same: eat all remained unallocated registers,
2992   //          initialize stack frame.
2993
2994   MachineFunction &MF = DAG.getMachineFunction();
2995   MachineFrameInfo *MFI = MF.getFrameInfo();
2996   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2997   unsigned RBegin, REnd;
2998   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2999     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3000   } else {
3001     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3002     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3003     REnd = ARM::R4;
3004   }
3005
3006   if (REnd != RBegin)
3007     ArgOffset = -4 * (ARM::R4 - RBegin);
3008
3009   auto PtrVT = getPointerTy(DAG.getDataLayout());
3010   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3011   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3012
3013   SmallVector<SDValue, 4> MemOps;
3014   const TargetRegisterClass *RC =
3015       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3016
3017   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3018     unsigned VReg = MF.addLiveIn(Reg, RC);
3019     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3020     SDValue Store =
3021         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3022                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3023     MemOps.push_back(Store);
3024     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3025   }
3026
3027   if (!MemOps.empty())
3028     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3029   return FrameIndex;
3030 }
3031
3032 // Setup stack frame, the va_list pointer will start from.
3033 void
3034 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3035                                         SDLoc dl, SDValue &Chain,
3036                                         unsigned ArgOffset,
3037                                         unsigned TotalArgRegsSaveSize,
3038                                         bool ForceMutable) const {
3039   MachineFunction &MF = DAG.getMachineFunction();
3040   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3041
3042   // Try to store any remaining integer argument regs
3043   // to their spots on the stack so that they may be loaded by deferencing
3044   // the result of va_next.
3045   // If there is no regs to be stored, just point address after last
3046   // argument passed via stack.
3047   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3048                                   CCInfo.getInRegsParamsCount(),
3049                                   CCInfo.getNextStackOffset(), 4);
3050   AFI->setVarArgsFrameIndex(FrameIndex);
3051 }
3052
3053 SDValue
3054 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3055                                         CallingConv::ID CallConv, bool isVarArg,
3056                                         const SmallVectorImpl<ISD::InputArg>
3057                                           &Ins,
3058                                         SDLoc dl, SelectionDAG &DAG,
3059                                         SmallVectorImpl<SDValue> &InVals)
3060                                           const {
3061   MachineFunction &MF = DAG.getMachineFunction();
3062   MachineFrameInfo *MFI = MF.getFrameInfo();
3063
3064   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3065
3066   // Assign locations to all of the incoming arguments.
3067   SmallVector<CCValAssign, 16> ArgLocs;
3068   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3069                     *DAG.getContext(), Prologue);
3070   CCInfo.AnalyzeFormalArguments(Ins,
3071                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3072                                                   isVarArg));
3073
3074   SmallVector<SDValue, 16> ArgValues;
3075   SDValue ArgValue;
3076   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3077   unsigned CurArgIdx = 0;
3078
3079   // Initially ArgRegsSaveSize is zero.
3080   // Then we increase this value each time we meet byval parameter.
3081   // We also increase this value in case of varargs function.
3082   AFI->setArgRegsSaveSize(0);
3083
3084   // Calculate the amount of stack space that we need to allocate to store
3085   // byval and variadic arguments that are passed in registers.
3086   // We need to know this before we allocate the first byval or variadic
3087   // argument, as they will be allocated a stack slot below the CFA (Canonical
3088   // Frame Address, the stack pointer at entry to the function).
3089   unsigned ArgRegBegin = ARM::R4;
3090   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3091     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3092       break;
3093
3094     CCValAssign &VA = ArgLocs[i];
3095     unsigned Index = VA.getValNo();
3096     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3097     if (!Flags.isByVal())
3098       continue;
3099
3100     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3101     unsigned RBegin, REnd;
3102     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3103     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3104
3105     CCInfo.nextInRegsParam();
3106   }
3107   CCInfo.rewindByValRegsInfo();
3108
3109   int lastInsIndex = -1;
3110   if (isVarArg && MFI->hasVAStart()) {
3111     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3112     if (RegIdx != array_lengthof(GPRArgRegs))
3113       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3114   }
3115
3116   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3117   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3118   auto PtrVT = getPointerTy(DAG.getDataLayout());
3119
3120   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3121     CCValAssign &VA = ArgLocs[i];
3122     if (Ins[VA.getValNo()].isOrigArg()) {
3123       std::advance(CurOrigArg,
3124                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3125       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3126     }
3127     // Arguments stored in registers.
3128     if (VA.isRegLoc()) {
3129       EVT RegVT = VA.getLocVT();
3130
3131       if (VA.needsCustom()) {
3132         // f64 and vector types are split up into multiple registers or
3133         // combinations of registers and stack slots.
3134         if (VA.getLocVT() == MVT::v2f64) {
3135           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3136                                                    Chain, DAG, dl);
3137           VA = ArgLocs[++i]; // skip ahead to next loc
3138           SDValue ArgValue2;
3139           if (VA.isMemLoc()) {
3140             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3141             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3142             ArgValue2 = DAG.getLoad(
3143                 MVT::f64, dl, Chain, FIN,
3144                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3145                 false, false, false, 0);
3146           } else {
3147             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3148                                              Chain, DAG, dl);
3149           }
3150           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3151           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3152                                  ArgValue, ArgValue1,
3153                                  DAG.getIntPtrConstant(0, dl));
3154           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3155                                  ArgValue, ArgValue2,
3156                                  DAG.getIntPtrConstant(1, dl));
3157         } else
3158           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3159
3160       } else {
3161         const TargetRegisterClass *RC;
3162
3163         if (RegVT == MVT::f32)
3164           RC = &ARM::SPRRegClass;
3165         else if (RegVT == MVT::f64)
3166           RC = &ARM::DPRRegClass;
3167         else if (RegVT == MVT::v2f64)
3168           RC = &ARM::QPRRegClass;
3169         else if (RegVT == MVT::i32)
3170           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3171                                            : &ARM::GPRRegClass;
3172         else
3173           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3174
3175         // Transform the arguments in physical registers into virtual ones.
3176         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3177         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3178       }
3179
3180       // If this is an 8 or 16-bit value, it is really passed promoted
3181       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3182       // truncate to the right size.
3183       switch (VA.getLocInfo()) {
3184       default: llvm_unreachable("Unknown loc info!");
3185       case CCValAssign::Full: break;
3186       case CCValAssign::BCvt:
3187         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3188         break;
3189       case CCValAssign::SExt:
3190         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3191                                DAG.getValueType(VA.getValVT()));
3192         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3193         break;
3194       case CCValAssign::ZExt:
3195         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3196                                DAG.getValueType(VA.getValVT()));
3197         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3198         break;
3199       }
3200
3201       InVals.push_back(ArgValue);
3202
3203     } else { // VA.isRegLoc()
3204
3205       // sanity check
3206       assert(VA.isMemLoc());
3207       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3208
3209       int index = VA.getValNo();
3210
3211       // Some Ins[] entries become multiple ArgLoc[] entries.
3212       // Process them only once.
3213       if (index != lastInsIndex)
3214         {
3215           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3216           // FIXME: For now, all byval parameter objects are marked mutable.
3217           // This can be changed with more analysis.
3218           // In case of tail call optimization mark all arguments mutable.
3219           // Since they could be overwritten by lowering of arguments in case of
3220           // a tail call.
3221           if (Flags.isByVal()) {
3222             assert(Ins[index].isOrigArg() &&
3223                    "Byval arguments cannot be implicit");
3224             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3225
3226             int FrameIndex = StoreByValRegs(
3227                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3228                 VA.getLocMemOffset(), Flags.getByValSize());
3229             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3230             CCInfo.nextInRegsParam();
3231           } else {
3232             unsigned FIOffset = VA.getLocMemOffset();
3233             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3234                                             FIOffset, true);
3235
3236             // Create load nodes to retrieve arguments from the stack.
3237             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3238             InVals.push_back(DAG.getLoad(
3239                 VA.getValVT(), dl, Chain, FIN,
3240                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3241                 false, false, false, 0));
3242           }
3243           lastInsIndex = index;
3244         }
3245     }
3246   }
3247
3248   // varargs
3249   if (isVarArg && MFI->hasVAStart())
3250     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3251                          CCInfo.getNextStackOffset(),
3252                          TotalArgRegsSaveSize);
3253
3254   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3255
3256   return Chain;
3257 }
3258
3259 /// isFloatingPointZero - Return true if this is +0.0.
3260 static bool isFloatingPointZero(SDValue Op) {
3261   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3262     return CFP->getValueAPF().isPosZero();
3263   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3264     // Maybe this has already been legalized into the constant pool?
3265     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3266       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3267       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3268         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3269           return CFP->getValueAPF().isPosZero();
3270     }
3271   } else if (Op->getOpcode() == ISD::BITCAST &&
3272              Op->getValueType(0) == MVT::f64) {
3273     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3274     // created by LowerConstantFP().
3275     SDValue BitcastOp = Op->getOperand(0);
3276     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3277       SDValue MoveOp = BitcastOp->getOperand(0);
3278       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3279           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3280         return true;
3281       }
3282     }
3283   }
3284   return false;
3285 }
3286
3287 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3288 /// the given operands.
3289 SDValue
3290 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3291                              SDValue &ARMcc, SelectionDAG &DAG,
3292                              SDLoc dl) const {
3293   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3294     unsigned C = RHSC->getZExtValue();
3295     if (!isLegalICmpImmediate(C)) {
3296       // Constant does not fit, try adjusting it by one?
3297       switch (CC) {
3298       default: break;
3299       case ISD::SETLT:
3300       case ISD::SETGE:
3301         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3302           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3303           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3304         }
3305         break;
3306       case ISD::SETULT:
3307       case ISD::SETUGE:
3308         if (C != 0 && isLegalICmpImmediate(C-1)) {
3309           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3310           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3311         }
3312         break;
3313       case ISD::SETLE:
3314       case ISD::SETGT:
3315         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3316           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3317           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3318         }
3319         break;
3320       case ISD::SETULE:
3321       case ISD::SETUGT:
3322         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3323           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3324           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3325         }
3326         break;
3327       }
3328     }
3329   }
3330
3331   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3332   ARMISD::NodeType CompareType;
3333   switch (CondCode) {
3334   default:
3335     CompareType = ARMISD::CMP;
3336     break;
3337   case ARMCC::EQ:
3338   case ARMCC::NE:
3339     // Uses only Z Flag
3340     CompareType = ARMISD::CMPZ;
3341     break;
3342   }
3343   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3344   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3345 }
3346
3347 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3348 SDValue
3349 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3350                              SDLoc dl) const {
3351   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3352   SDValue Cmp;
3353   if (!isFloatingPointZero(RHS))
3354     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3355   else
3356     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3357   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3358 }
3359
3360 /// duplicateCmp - Glue values can have only one use, so this function
3361 /// duplicates a comparison node.
3362 SDValue
3363 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3364   unsigned Opc = Cmp.getOpcode();
3365   SDLoc DL(Cmp);
3366   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3367     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3368
3369   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3370   Cmp = Cmp.getOperand(0);
3371   Opc = Cmp.getOpcode();
3372   if (Opc == ARMISD::CMPFP)
3373     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3374   else {
3375     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3376     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3377   }
3378   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3379 }
3380
3381 std::pair<SDValue, SDValue>
3382 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3383                                  SDValue &ARMcc) const {
3384   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3385
3386   SDValue Value, OverflowCmp;
3387   SDValue LHS = Op.getOperand(0);
3388   SDValue RHS = Op.getOperand(1);
3389   SDLoc dl(Op);
3390
3391   // FIXME: We are currently always generating CMPs because we don't support
3392   // generating CMN through the backend. This is not as good as the natural
3393   // CMP case because it causes a register dependency and cannot be folded
3394   // later.
3395
3396   switch (Op.getOpcode()) {
3397   default:
3398     llvm_unreachable("Unknown overflow instruction!");
3399   case ISD::SADDO:
3400     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3401     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3402     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3403     break;
3404   case ISD::UADDO:
3405     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3406     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3407     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3408     break;
3409   case ISD::SSUBO:
3410     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3411     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3412     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3413     break;
3414   case ISD::USUBO:
3415     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3416     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3417     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3418     break;
3419   } // switch (...)
3420
3421   return std::make_pair(Value, OverflowCmp);
3422 }
3423
3424
3425 SDValue
3426 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3427   // Let legalize expand this if it isn't a legal type yet.
3428   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3429     return SDValue();
3430
3431   SDValue Value, OverflowCmp;
3432   SDValue ARMcc;
3433   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3434   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3435   SDLoc dl(Op);
3436   // We use 0 and 1 as false and true values.
3437   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3438   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3439   EVT VT = Op.getValueType();
3440
3441   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3442                                  ARMcc, CCR, OverflowCmp);
3443
3444   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3445   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3446 }
3447
3448
3449 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3450   SDValue Cond = Op.getOperand(0);
3451   SDValue SelectTrue = Op.getOperand(1);
3452   SDValue SelectFalse = Op.getOperand(2);
3453   SDLoc dl(Op);
3454   unsigned Opc = Cond.getOpcode();
3455
3456   if (Cond.getResNo() == 1 &&
3457       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3458        Opc == ISD::USUBO)) {
3459     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3460       return SDValue();
3461
3462     SDValue Value, OverflowCmp;
3463     SDValue ARMcc;
3464     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3465     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3466     EVT VT = Op.getValueType();
3467
3468     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3469                    OverflowCmp, DAG);
3470   }
3471
3472   // Convert:
3473   //
3474   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3475   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3476   //
3477   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3478     const ConstantSDNode *CMOVTrue =
3479       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3480     const ConstantSDNode *CMOVFalse =
3481       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3482
3483     if (CMOVTrue && CMOVFalse) {
3484       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3485       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3486
3487       SDValue True;
3488       SDValue False;
3489       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3490         True = SelectTrue;
3491         False = SelectFalse;
3492       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3493         True = SelectFalse;
3494         False = SelectTrue;
3495       }
3496
3497       if (True.getNode() && False.getNode()) {
3498         EVT VT = Op.getValueType();
3499         SDValue ARMcc = Cond.getOperand(2);
3500         SDValue CCR = Cond.getOperand(3);
3501         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3502         assert(True.getValueType() == VT);
3503         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3504       }
3505     }
3506   }
3507
3508   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3509   // undefined bits before doing a full-word comparison with zero.
3510   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3511                      DAG.getConstant(1, dl, Cond.getValueType()));
3512
3513   return DAG.getSelectCC(dl, Cond,
3514                          DAG.getConstant(0, dl, Cond.getValueType()),
3515                          SelectTrue, SelectFalse, ISD::SETNE);
3516 }
3517
3518 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3519                                  bool &swpCmpOps, bool &swpVselOps) {
3520   // Start by selecting the GE condition code for opcodes that return true for
3521   // 'equality'
3522   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3523       CC == ISD::SETULE)
3524     CondCode = ARMCC::GE;
3525
3526   // and GT for opcodes that return false for 'equality'.
3527   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3528            CC == ISD::SETULT)
3529     CondCode = ARMCC::GT;
3530
3531   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3532   // to swap the compare operands.
3533   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3534       CC == ISD::SETULT)
3535     swpCmpOps = true;
3536
3537   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3538   // If we have an unordered opcode, we need to swap the operands to the VSEL
3539   // instruction (effectively negating the condition).
3540   //
3541   // This also has the effect of swapping which one of 'less' or 'greater'
3542   // returns true, so we also swap the compare operands. It also switches
3543   // whether we return true for 'equality', so we compensate by picking the
3544   // opposite condition code to our original choice.
3545   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3546       CC == ISD::SETUGT) {
3547     swpCmpOps = !swpCmpOps;
3548     swpVselOps = !swpVselOps;
3549     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3550   }
3551
3552   // 'ordered' is 'anything but unordered', so use the VS condition code and
3553   // swap the VSEL operands.
3554   if (CC == ISD::SETO) {
3555     CondCode = ARMCC::VS;
3556     swpVselOps = true;
3557   }
3558
3559   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3560   // code and swap the VSEL operands.
3561   if (CC == ISD::SETUNE) {
3562     CondCode = ARMCC::EQ;
3563     swpVselOps = true;
3564   }
3565 }
3566
3567 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3568                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3569                                    SDValue Cmp, SelectionDAG &DAG) const {
3570   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3571     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3572                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3573     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3574                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3575
3576     SDValue TrueLow = TrueVal.getValue(0);
3577     SDValue TrueHigh = TrueVal.getValue(1);
3578     SDValue FalseLow = FalseVal.getValue(0);
3579     SDValue FalseHigh = FalseVal.getValue(1);
3580
3581     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3582                               ARMcc, CCR, Cmp);
3583     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3584                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3585
3586     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3587   } else {
3588     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3589                        Cmp);
3590   }
3591 }
3592
3593 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3594   EVT VT = Op.getValueType();
3595   SDValue LHS = Op.getOperand(0);
3596   SDValue RHS = Op.getOperand(1);
3597   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3598   SDValue TrueVal = Op.getOperand(2);
3599   SDValue FalseVal = Op.getOperand(3);
3600   SDLoc dl(Op);
3601
3602   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3603     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3604                                                     dl);
3605
3606     // If softenSetCCOperands only returned one value, we should compare it to
3607     // zero.
3608     if (!RHS.getNode()) {
3609       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3610       CC = ISD::SETNE;
3611     }
3612   }
3613
3614   if (LHS.getValueType() == MVT::i32) {
3615     // Try to generate VSEL on ARMv8.
3616     // The VSEL instruction can't use all the usual ARM condition
3617     // codes: it only has two bits to select the condition code, so it's
3618     // constrained to use only GE, GT, VS and EQ.
3619     //
3620     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3621     // swap the operands of the previous compare instruction (effectively
3622     // inverting the compare condition, swapping 'less' and 'greater') and
3623     // sometimes need to swap the operands to the VSEL (which inverts the
3624     // condition in the sense of firing whenever the previous condition didn't)
3625     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3626                                     TrueVal.getValueType() == MVT::f64)) {
3627       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3628       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3629           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3630         CC = ISD::getSetCCInverse(CC, true);
3631         std::swap(TrueVal, FalseVal);
3632       }
3633     }
3634
3635     SDValue ARMcc;
3636     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3637     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3638     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3639   }
3640
3641   ARMCC::CondCodes CondCode, CondCode2;
3642   FPCCToARMCC(CC, CondCode, CondCode2);
3643
3644   // Try to generate VMAXNM/VMINNM on ARMv8.
3645   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3646                                   TrueVal.getValueType() == MVT::f64)) {
3647     bool swpCmpOps = false;
3648     bool swpVselOps = false;
3649     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3650
3651     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3652         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3653       if (swpCmpOps)
3654         std::swap(LHS, RHS);
3655       if (swpVselOps)
3656         std::swap(TrueVal, FalseVal);
3657     }
3658   }
3659
3660   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3661   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3662   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3663   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3664   if (CondCode2 != ARMCC::AL) {
3665     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3666     // FIXME: Needs another CMP because flag can have but one use.
3667     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3668     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3669   }
3670   return Result;
3671 }
3672
3673 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3674 /// to morph to an integer compare sequence.
3675 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3676                            const ARMSubtarget *Subtarget) {
3677   SDNode *N = Op.getNode();
3678   if (!N->hasOneUse())
3679     // Otherwise it requires moving the value from fp to integer registers.
3680     return false;
3681   if (!N->getNumValues())
3682     return false;
3683   EVT VT = Op.getValueType();
3684   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3685     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3686     // vmrs are very slow, e.g. cortex-a8.
3687     return false;
3688
3689   if (isFloatingPointZero(Op)) {
3690     SeenZero = true;
3691     return true;
3692   }
3693   return ISD::isNormalLoad(N);
3694 }
3695
3696 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3697   if (isFloatingPointZero(Op))
3698     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3699
3700   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3701     return DAG.getLoad(MVT::i32, SDLoc(Op),
3702                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3703                        Ld->isVolatile(), Ld->isNonTemporal(),
3704                        Ld->isInvariant(), Ld->getAlignment());
3705
3706   llvm_unreachable("Unknown VFP cmp argument!");
3707 }
3708
3709 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3710                            SDValue &RetVal1, SDValue &RetVal2) {
3711   SDLoc dl(Op);
3712
3713   if (isFloatingPointZero(Op)) {
3714     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3715     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3716     return;
3717   }
3718
3719   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3720     SDValue Ptr = Ld->getBasePtr();
3721     RetVal1 = DAG.getLoad(MVT::i32, dl,
3722                           Ld->getChain(), Ptr,
3723                           Ld->getPointerInfo(),
3724                           Ld->isVolatile(), Ld->isNonTemporal(),
3725                           Ld->isInvariant(), Ld->getAlignment());
3726
3727     EVT PtrType = Ptr.getValueType();
3728     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3729     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3730                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3731     RetVal2 = DAG.getLoad(MVT::i32, dl,
3732                           Ld->getChain(), NewPtr,
3733                           Ld->getPointerInfo().getWithOffset(4),
3734                           Ld->isVolatile(), Ld->isNonTemporal(),
3735                           Ld->isInvariant(), NewAlign);
3736     return;
3737   }
3738
3739   llvm_unreachable("Unknown VFP cmp argument!");
3740 }
3741
3742 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3743 /// f32 and even f64 comparisons to integer ones.
3744 SDValue
3745 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3746   SDValue Chain = Op.getOperand(0);
3747   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3748   SDValue LHS = Op.getOperand(2);
3749   SDValue RHS = Op.getOperand(3);
3750   SDValue Dest = Op.getOperand(4);
3751   SDLoc dl(Op);
3752
3753   bool LHSSeenZero = false;
3754   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3755   bool RHSSeenZero = false;
3756   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3757   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3758     // If unsafe fp math optimization is enabled and there are no other uses of
3759     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3760     // to an integer comparison.
3761     if (CC == ISD::SETOEQ)
3762       CC = ISD::SETEQ;
3763     else if (CC == ISD::SETUNE)
3764       CC = ISD::SETNE;
3765
3766     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3767     SDValue ARMcc;
3768     if (LHS.getValueType() == MVT::f32) {
3769       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3770                         bitcastf32Toi32(LHS, DAG), Mask);
3771       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3772                         bitcastf32Toi32(RHS, DAG), Mask);
3773       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3774       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3775       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3776                          Chain, Dest, ARMcc, CCR, Cmp);
3777     }
3778
3779     SDValue LHS1, LHS2;
3780     SDValue RHS1, RHS2;
3781     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3782     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3783     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3784     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3785     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3786     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3787     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3788     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3789     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3790   }
3791
3792   return SDValue();
3793 }
3794
3795 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3796   SDValue Chain = Op.getOperand(0);
3797   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3798   SDValue LHS = Op.getOperand(2);
3799   SDValue RHS = Op.getOperand(3);
3800   SDValue Dest = Op.getOperand(4);
3801   SDLoc dl(Op);
3802
3803   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3804     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3805                                                     dl);
3806
3807     // If softenSetCCOperands only returned one value, we should compare it to
3808     // zero.
3809     if (!RHS.getNode()) {
3810       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3811       CC = ISD::SETNE;
3812     }
3813   }
3814
3815   if (LHS.getValueType() == MVT::i32) {
3816     SDValue ARMcc;
3817     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3818     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3819     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3820                        Chain, Dest, ARMcc, CCR, Cmp);
3821   }
3822
3823   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3824
3825   if (getTargetMachine().Options.UnsafeFPMath &&
3826       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3827        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3828     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3829     if (Result.getNode())
3830       return Result;
3831   }
3832
3833   ARMCC::CondCodes CondCode, CondCode2;
3834   FPCCToARMCC(CC, CondCode, CondCode2);
3835
3836   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3837   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3838   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3839   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3840   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3841   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3842   if (CondCode2 != ARMCC::AL) {
3843     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3844     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3845     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3846   }
3847   return Res;
3848 }
3849
3850 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3851   SDValue Chain = Op.getOperand(0);
3852   SDValue Table = Op.getOperand(1);
3853   SDValue Index = Op.getOperand(2);
3854   SDLoc dl(Op);
3855
3856   EVT PTy = getPointerTy(DAG.getDataLayout());
3857   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3858   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3859   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3860   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3861   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3862   if (Subtarget->isThumb2()) {
3863     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3864     // which does another jump to the destination. This also makes it easier
3865     // to translate it to TBB / TBH later.
3866     // FIXME: This might not work if the function is extremely large.
3867     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3868                        Addr, Op.getOperand(2), JTI);
3869   }
3870   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3871     Addr =
3872         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3873                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3874                     false, false, false, 0);
3875     Chain = Addr.getValue(1);
3876     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3877     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3878   } else {
3879     Addr =
3880         DAG.getLoad(PTy, dl, Chain, Addr,
3881                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3882                     false, false, false, 0);
3883     Chain = Addr.getValue(1);
3884     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3885   }
3886 }
3887
3888 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3889   EVT VT = Op.getValueType();
3890   SDLoc dl(Op);
3891
3892   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3893     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3894       return Op;
3895     return DAG.UnrollVectorOp(Op.getNode());
3896   }
3897
3898   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3899          "Invalid type for custom lowering!");
3900   if (VT != MVT::v4i16)
3901     return DAG.UnrollVectorOp(Op.getNode());
3902
3903   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3904   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3905 }
3906
3907 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3908   EVT VT = Op.getValueType();
3909   if (VT.isVector())
3910     return LowerVectorFP_TO_INT(Op, DAG);
3911   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3912     RTLIB::Libcall LC;
3913     if (Op.getOpcode() == ISD::FP_TO_SINT)
3914       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3915                               Op.getValueType());
3916     else
3917       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3918                               Op.getValueType());
3919     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3920                        /*isSigned*/ false, SDLoc(Op)).first;
3921   }
3922
3923   return Op;
3924 }
3925
3926 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3927   EVT VT = Op.getValueType();
3928   SDLoc dl(Op);
3929
3930   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3931     if (VT.getVectorElementType() == MVT::f32)
3932       return Op;
3933     return DAG.UnrollVectorOp(Op.getNode());
3934   }
3935
3936   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3937          "Invalid type for custom lowering!");
3938   if (VT != MVT::v4f32)
3939     return DAG.UnrollVectorOp(Op.getNode());
3940
3941   unsigned CastOpc;
3942   unsigned Opc;
3943   switch (Op.getOpcode()) {
3944   default: llvm_unreachable("Invalid opcode!");
3945   case ISD::SINT_TO_FP:
3946     CastOpc = ISD::SIGN_EXTEND;
3947     Opc = ISD::SINT_TO_FP;
3948     break;
3949   case ISD::UINT_TO_FP:
3950     CastOpc = ISD::ZERO_EXTEND;
3951     Opc = ISD::UINT_TO_FP;
3952     break;
3953   }
3954
3955   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3956   return DAG.getNode(Opc, dl, VT, Op);
3957 }
3958
3959 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3960   EVT VT = Op.getValueType();
3961   if (VT.isVector())
3962     return LowerVectorINT_TO_FP(Op, DAG);
3963   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3964     RTLIB::Libcall LC;
3965     if (Op.getOpcode() == ISD::SINT_TO_FP)
3966       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3967                               Op.getValueType());
3968     else
3969       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3970                               Op.getValueType());
3971     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3972                        /*isSigned*/ false, SDLoc(Op)).first;
3973   }
3974
3975   return Op;
3976 }
3977
3978 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3979   // Implement fcopysign with a fabs and a conditional fneg.
3980   SDValue Tmp0 = Op.getOperand(0);
3981   SDValue Tmp1 = Op.getOperand(1);
3982   SDLoc dl(Op);
3983   EVT VT = Op.getValueType();
3984   EVT SrcVT = Tmp1.getValueType();
3985   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3986     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3987   bool UseNEON = !InGPR && Subtarget->hasNEON();
3988
3989   if (UseNEON) {
3990     // Use VBSL to copy the sign bit.
3991     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3992     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3993                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3994     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3995     if (VT == MVT::f64)
3996       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3997                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3998                          DAG.getConstant(32, dl, MVT::i32));
3999     else /*if (VT == MVT::f32)*/
4000       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4001     if (SrcVT == MVT::f32) {
4002       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4003       if (VT == MVT::f64)
4004         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4005                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4006                            DAG.getConstant(32, dl, MVT::i32));
4007     } else if (VT == MVT::f32)
4008       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4009                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4010                          DAG.getConstant(32, dl, MVT::i32));
4011     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4012     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4013
4014     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4015                                             dl, MVT::i32);
4016     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4017     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4018                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4019
4020     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4021                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4022                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4023     if (VT == MVT::f32) {
4024       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4025       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4026                         DAG.getConstant(0, dl, MVT::i32));
4027     } else {
4028       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4029     }
4030
4031     return Res;
4032   }
4033
4034   // Bitcast operand 1 to i32.
4035   if (SrcVT == MVT::f64)
4036     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4037                        Tmp1).getValue(1);
4038   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4039
4040   // Or in the signbit with integer operations.
4041   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4042   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4043   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4044   if (VT == MVT::f32) {
4045     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4046                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4047     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4048                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4049   }
4050
4051   // f64: Or the high part with signbit and then combine two parts.
4052   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4053                      Tmp0);
4054   SDValue Lo = Tmp0.getValue(0);
4055   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4056   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4057   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4058 }
4059
4060 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4061   MachineFunction &MF = DAG.getMachineFunction();
4062   MachineFrameInfo *MFI = MF.getFrameInfo();
4063   MFI->setReturnAddressIsTaken(true);
4064
4065   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4066     return SDValue();
4067
4068   EVT VT = Op.getValueType();
4069   SDLoc dl(Op);
4070   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4071   if (Depth) {
4072     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4073     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4074     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4075                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4076                        MachinePointerInfo(), false, false, false, 0);
4077   }
4078
4079   // Return LR, which contains the return address. Mark it an implicit live-in.
4080   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4081   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4082 }
4083
4084 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4085   const ARMBaseRegisterInfo &ARI =
4086     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4087   MachineFunction &MF = DAG.getMachineFunction();
4088   MachineFrameInfo *MFI = MF.getFrameInfo();
4089   MFI->setFrameAddressIsTaken(true);
4090
4091   EVT VT = Op.getValueType();
4092   SDLoc dl(Op);  // FIXME probably not meaningful
4093   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4094   unsigned FrameReg = ARI.getFrameRegister(MF);
4095   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4096   while (Depth--)
4097     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4098                             MachinePointerInfo(),
4099                             false, false, false, 0);
4100   return FrameAddr;
4101 }
4102
4103 // FIXME? Maybe this could be a TableGen attribute on some registers and
4104 // this table could be generated automatically from RegInfo.
4105 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4106                                               SelectionDAG &DAG) const {
4107   unsigned Reg = StringSwitch<unsigned>(RegName)
4108                        .Case("sp", ARM::SP)
4109                        .Default(0);
4110   if (Reg)
4111     return Reg;
4112   report_fatal_error(Twine("Invalid register name \""
4113                               + StringRef(RegName)  + "\"."));
4114 }
4115
4116 // Result is 64 bit value so split into two 32 bit values and return as a
4117 // pair of values.
4118 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4119                                 SelectionDAG &DAG) {
4120   SDLoc DL(N);
4121
4122   // This function is only supposed to be called for i64 type destination.
4123   assert(N->getValueType(0) == MVT::i64
4124           && "ExpandREAD_REGISTER called for non-i64 type result.");
4125
4126   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4127                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4128                              N->getOperand(0),
4129                              N->getOperand(1));
4130
4131   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4132                     Read.getValue(1)));
4133   Results.push_back(Read.getOperand(0));
4134 }
4135
4136 /// ExpandBITCAST - If the target supports VFP, this function is called to
4137 /// expand a bit convert where either the source or destination type is i64 to
4138 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4139 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4140 /// vectors), since the legalizer won't know what to do with that.
4141 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4143   SDLoc dl(N);
4144   SDValue Op = N->getOperand(0);
4145
4146   // This function is only supposed to be called for i64 types, either as the
4147   // source or destination of the bit convert.
4148   EVT SrcVT = Op.getValueType();
4149   EVT DstVT = N->getValueType(0);
4150   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4151          "ExpandBITCAST called for non-i64 type");
4152
4153   // Turn i64->f64 into VMOVDRR.
4154   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4155     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4156                              DAG.getConstant(0, dl, MVT::i32));
4157     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4158                              DAG.getConstant(1, dl, MVT::i32));
4159     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4160                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4161   }
4162
4163   // Turn f64->i64 into VMOVRRD.
4164   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4165     SDValue Cvt;
4166     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4167         SrcVT.getVectorNumElements() > 1)
4168       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4169                         DAG.getVTList(MVT::i32, MVT::i32),
4170                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4171     else
4172       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4173                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4174     // Merge the pieces into a single i64 value.
4175     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4176   }
4177
4178   return SDValue();
4179 }
4180
4181 /// getZeroVector - Returns a vector of specified type with all zero elements.
4182 /// Zero vectors are used to represent vector negation and in those cases
4183 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4184 /// not support i64 elements, so sometimes the zero vectors will need to be
4185 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4186 /// zero vector.
4187 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4188   assert(VT.isVector() && "Expected a vector type");
4189   // The canonical modified immediate encoding of a zero vector is....0!
4190   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4191   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4192   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4193   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4194 }
4195
4196 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4197 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4198 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4199                                                 SelectionDAG &DAG) const {
4200   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4201   EVT VT = Op.getValueType();
4202   unsigned VTBits = VT.getSizeInBits();
4203   SDLoc dl(Op);
4204   SDValue ShOpLo = Op.getOperand(0);
4205   SDValue ShOpHi = Op.getOperand(1);
4206   SDValue ShAmt  = Op.getOperand(2);
4207   SDValue ARMcc;
4208   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4209
4210   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4211
4212   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4213                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4214   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4215   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4216                                    DAG.getConstant(VTBits, dl, MVT::i32));
4217   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4218   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4219   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4220
4221   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4222   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4223                           ISD::SETGE, ARMcc, DAG, dl);
4224   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4225   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4226                            CCR, Cmp);
4227
4228   SDValue Ops[2] = { Lo, Hi };
4229   return DAG.getMergeValues(Ops, dl);
4230 }
4231
4232 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4233 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4234 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4235                                                SelectionDAG &DAG) const {
4236   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4237   EVT VT = Op.getValueType();
4238   unsigned VTBits = VT.getSizeInBits();
4239   SDLoc dl(Op);
4240   SDValue ShOpLo = Op.getOperand(0);
4241   SDValue ShOpHi = Op.getOperand(1);
4242   SDValue ShAmt  = Op.getOperand(2);
4243   SDValue ARMcc;
4244
4245   assert(Op.getOpcode() == ISD::SHL_PARTS);
4246   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4247                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4248   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4249   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4250                                    DAG.getConstant(VTBits, dl, MVT::i32));
4251   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4252   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4253
4254   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4255   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4256   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4257                           ISD::SETGE, ARMcc, DAG, dl);
4258   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4259   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4260                            CCR, Cmp);
4261
4262   SDValue Ops[2] = { Lo, Hi };
4263   return DAG.getMergeValues(Ops, dl);
4264 }
4265
4266 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4267                                             SelectionDAG &DAG) const {
4268   // The rounding mode is in bits 23:22 of the FPSCR.
4269   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4270   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4271   // so that the shift + and get folded into a bitfield extract.
4272   SDLoc dl(Op);
4273   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4274                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4275                                               MVT::i32));
4276   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4277                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4278   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4279                               DAG.getConstant(22, dl, MVT::i32));
4280   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4281                      DAG.getConstant(3, dl, MVT::i32));
4282 }
4283
4284 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4285                          const ARMSubtarget *ST) {
4286   SDLoc dl(N);
4287   EVT VT = N->getValueType(0);
4288   if (VT.isVector()) {
4289     assert(ST->hasNEON());
4290
4291     // Compute the least significant set bit: LSB = X & -X
4292     SDValue X = N->getOperand(0);
4293     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4294     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4295
4296     EVT ElemTy = VT.getVectorElementType();
4297
4298     if (ElemTy == MVT::i8) {
4299       // Compute with: cttz(x) = ctpop(lsb - 1)
4300       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4301                                 DAG.getTargetConstant(1, dl, ElemTy));
4302       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4303       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4304     }
4305
4306     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4307         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4308       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4309       unsigned NumBits = ElemTy.getSizeInBits();
4310       SDValue WidthMinus1 =
4311           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4312                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4313       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4314       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4315     }
4316
4317     // Compute with: cttz(x) = ctpop(lsb - 1)
4318
4319     // Since we can only compute the number of bits in a byte with vcnt.8, we
4320     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4321     // and i64.
4322
4323     // Compute LSB - 1.
4324     SDValue Bits;
4325     if (ElemTy == MVT::i64) {
4326       // Load constant 0xffff'ffff'ffff'ffff to register.
4327       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4328                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4329       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4330     } else {
4331       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4332                                 DAG.getTargetConstant(1, dl, ElemTy));
4333       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4334     }
4335
4336     // Count #bits with vcnt.8.
4337     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4338     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4339     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4340
4341     // Gather the #bits with vpaddl (pairwise add.)
4342     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4343     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4344         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4345         Cnt8);
4346     if (ElemTy == MVT::i16)
4347       return Cnt16;
4348
4349     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4350     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4351         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4352         Cnt16);
4353     if (ElemTy == MVT::i32)
4354       return Cnt32;
4355
4356     assert(ElemTy == MVT::i64);
4357     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4358         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4359         Cnt32);
4360     return Cnt64;
4361   }
4362
4363   if (!ST->hasV6T2Ops())
4364     return SDValue();
4365
4366   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4367   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4368 }
4369
4370 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4371 /// for each 16-bit element from operand, repeated.  The basic idea is to
4372 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4373 ///
4374 /// Trace for v4i16:
4375 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4376 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4377 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4378 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4379 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4380 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4381 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4382 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4383 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4384   EVT VT = N->getValueType(0);
4385   SDLoc DL(N);
4386
4387   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4388   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4389   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4390   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4391   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4392   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4393 }
4394
4395 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4396 /// bit-count for each 16-bit element from the operand.  We need slightly
4397 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4398 /// 64/128-bit registers.
4399 ///
4400 /// Trace for v4i16:
4401 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4402 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4403 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4404 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4405 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4406   EVT VT = N->getValueType(0);
4407   SDLoc DL(N);
4408
4409   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4410   if (VT.is64BitVector()) {
4411     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4412     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4413                        DAG.getIntPtrConstant(0, DL));
4414   } else {
4415     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4416                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4417     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4418   }
4419 }
4420
4421 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4422 /// bit-count for each 32-bit element from the operand.  The idea here is
4423 /// to split the vector into 16-bit elements, leverage the 16-bit count
4424 /// routine, and then combine the results.
4425 ///
4426 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4427 /// input    = [v0    v1    ] (vi: 32-bit elements)
4428 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4429 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4430 /// vrev: N0 = [k1 k0 k3 k2 ]
4431 ///            [k0 k1 k2 k3 ]
4432 ///       N1 =+[k1 k0 k3 k2 ]
4433 ///            [k0 k2 k1 k3 ]
4434 ///       N2 =+[k1 k3 k0 k2 ]
4435 ///            [k0    k2    k1    k3    ]
4436 /// Extended =+[k1    k3    k0    k2    ]
4437 ///            [k0    k2    ]
4438 /// Extracted=+[k1    k3    ]
4439 ///
4440 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4441   EVT VT = N->getValueType(0);
4442   SDLoc DL(N);
4443
4444   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4445
4446   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4447   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4448   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4449   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4450   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4451
4452   if (VT.is64BitVector()) {
4453     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4454     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4455                        DAG.getIntPtrConstant(0, DL));
4456   } else {
4457     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4458                                     DAG.getIntPtrConstant(0, DL));
4459     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4460   }
4461 }
4462
4463 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4464                           const ARMSubtarget *ST) {
4465   EVT VT = N->getValueType(0);
4466
4467   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4468   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4469           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4470          "Unexpected type for custom ctpop lowering");
4471
4472   if (VT.getVectorElementType() == MVT::i32)
4473     return lowerCTPOP32BitElements(N, DAG);
4474   else
4475     return lowerCTPOP16BitElements(N, DAG);
4476 }
4477
4478 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4479                           const ARMSubtarget *ST) {
4480   EVT VT = N->getValueType(0);
4481   SDLoc dl(N);
4482
4483   if (!VT.isVector())
4484     return SDValue();
4485
4486   // Lower vector shifts on NEON to use VSHL.
4487   assert(ST->hasNEON() && "unexpected vector shift");
4488
4489   // Left shifts translate directly to the vshiftu intrinsic.
4490   if (N->getOpcode() == ISD::SHL)
4491     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4492                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4493                                        MVT::i32),
4494                        N->getOperand(0), N->getOperand(1));
4495
4496   assert((N->getOpcode() == ISD::SRA ||
4497           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4498
4499   // NEON uses the same intrinsics for both left and right shifts.  For
4500   // right shifts, the shift amounts are negative, so negate the vector of
4501   // shift amounts.
4502   EVT ShiftVT = N->getOperand(1).getValueType();
4503   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4504                                      getZeroVector(ShiftVT, DAG, dl),
4505                                      N->getOperand(1));
4506   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4507                              Intrinsic::arm_neon_vshifts :
4508                              Intrinsic::arm_neon_vshiftu);
4509   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4510                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4511                      N->getOperand(0), NegatedCount);
4512 }
4513
4514 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4515                                 const ARMSubtarget *ST) {
4516   EVT VT = N->getValueType(0);
4517   SDLoc dl(N);
4518
4519   // We can get here for a node like i32 = ISD::SHL i32, i64
4520   if (VT != MVT::i64)
4521     return SDValue();
4522
4523   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4524          "Unknown shift to lower!");
4525
4526   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4527   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4528       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4529     return SDValue();
4530
4531   // If we are in thumb mode, we don't have RRX.
4532   if (ST->isThumb1Only()) return SDValue();
4533
4534   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4535   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4536                            DAG.getConstant(0, dl, MVT::i32));
4537   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4538                            DAG.getConstant(1, dl, MVT::i32));
4539
4540   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4541   // captures the result into a carry flag.
4542   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4543   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4544
4545   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4546   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4547
4548   // Merge the pieces into a single i64 value.
4549  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4550 }
4551
4552 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4553   SDValue TmpOp0, TmpOp1;
4554   bool Invert = false;
4555   bool Swap = false;
4556   unsigned Opc = 0;
4557
4558   SDValue Op0 = Op.getOperand(0);
4559   SDValue Op1 = Op.getOperand(1);
4560   SDValue CC = Op.getOperand(2);
4561   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4562   EVT VT = Op.getValueType();
4563   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4564   SDLoc dl(Op);
4565
4566   if (CmpVT.getVectorElementType() == MVT::i64)
4567     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4568     // but it's possible that our operands are 64-bit but our result is 32-bit.
4569     // Bail in this case.
4570     return SDValue();
4571
4572   if (Op1.getValueType().isFloatingPoint()) {
4573     switch (SetCCOpcode) {
4574     default: llvm_unreachable("Illegal FP comparison");
4575     case ISD::SETUNE:
4576     case ISD::SETNE:  Invert = true; // Fallthrough
4577     case ISD::SETOEQ:
4578     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4579     case ISD::SETOLT:
4580     case ISD::SETLT: Swap = true; // Fallthrough
4581     case ISD::SETOGT:
4582     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4583     case ISD::SETOLE:
4584     case ISD::SETLE:  Swap = true; // Fallthrough
4585     case ISD::SETOGE:
4586     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4587     case ISD::SETUGE: Swap = true; // Fallthrough
4588     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4589     case ISD::SETUGT: Swap = true; // Fallthrough
4590     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4591     case ISD::SETUEQ: Invert = true; // Fallthrough
4592     case ISD::SETONE:
4593       // Expand this to (OLT | OGT).
4594       TmpOp0 = Op0;
4595       TmpOp1 = Op1;
4596       Opc = ISD::OR;
4597       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4598       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4599       break;
4600     case ISD::SETUO: Invert = true; // Fallthrough
4601     case ISD::SETO:
4602       // Expand this to (OLT | OGE).
4603       TmpOp0 = Op0;
4604       TmpOp1 = Op1;
4605       Opc = ISD::OR;
4606       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4607       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4608       break;
4609     }
4610   } else {
4611     // Integer comparisons.
4612     switch (SetCCOpcode) {
4613     default: llvm_unreachable("Illegal integer comparison");
4614     case ISD::SETNE:  Invert = true;
4615     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4616     case ISD::SETLT:  Swap = true;
4617     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4618     case ISD::SETLE:  Swap = true;
4619     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4620     case ISD::SETULT: Swap = true;
4621     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4622     case ISD::SETULE: Swap = true;
4623     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4624     }
4625
4626     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4627     if (Opc == ARMISD::VCEQ) {
4628
4629       SDValue AndOp;
4630       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4631         AndOp = Op0;
4632       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4633         AndOp = Op1;
4634
4635       // Ignore bitconvert.
4636       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4637         AndOp = AndOp.getOperand(0);
4638
4639       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4640         Opc = ARMISD::VTST;
4641         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4642         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4643         Invert = !Invert;
4644       }
4645     }
4646   }
4647
4648   if (Swap)
4649     std::swap(Op0, Op1);
4650
4651   // If one of the operands is a constant vector zero, attempt to fold the
4652   // comparison to a specialized compare-against-zero form.
4653   SDValue SingleOp;
4654   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4655     SingleOp = Op0;
4656   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4657     if (Opc == ARMISD::VCGE)
4658       Opc = ARMISD::VCLEZ;
4659     else if (Opc == ARMISD::VCGT)
4660       Opc = ARMISD::VCLTZ;
4661     SingleOp = Op1;
4662   }
4663
4664   SDValue Result;
4665   if (SingleOp.getNode()) {
4666     switch (Opc) {
4667     case ARMISD::VCEQ:
4668       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4669     case ARMISD::VCGE:
4670       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4671     case ARMISD::VCLEZ:
4672       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4673     case ARMISD::VCGT:
4674       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4675     case ARMISD::VCLTZ:
4676       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4677     default:
4678       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4679     }
4680   } else {
4681      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4682   }
4683
4684   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4685
4686   if (Invert)
4687     Result = DAG.getNOT(dl, Result, VT);
4688
4689   return Result;
4690 }
4691
4692 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4693 /// valid vector constant for a NEON instruction with a "modified immediate"
4694 /// operand (e.g., VMOV).  If so, return the encoded value.
4695 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4696                                  unsigned SplatBitSize, SelectionDAG &DAG,
4697                                  SDLoc dl, EVT &VT, bool is128Bits,
4698                                  NEONModImmType type) {
4699   unsigned OpCmode, Imm;
4700
4701   // SplatBitSize is set to the smallest size that splats the vector, so a
4702   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4703   // immediate instructions others than VMOV do not support the 8-bit encoding
4704   // of a zero vector, and the default encoding of zero is supposed to be the
4705   // 32-bit version.
4706   if (SplatBits == 0)
4707     SplatBitSize = 32;
4708
4709   switch (SplatBitSize) {
4710   case 8:
4711     if (type != VMOVModImm)
4712       return SDValue();
4713     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4714     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4715     OpCmode = 0xe;
4716     Imm = SplatBits;
4717     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4718     break;
4719
4720   case 16:
4721     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4722     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4723     if ((SplatBits & ~0xff) == 0) {
4724       // Value = 0x00nn: Op=x, Cmode=100x.
4725       OpCmode = 0x8;
4726       Imm = SplatBits;
4727       break;
4728     }
4729     if ((SplatBits & ~0xff00) == 0) {
4730       // Value = 0xnn00: Op=x, Cmode=101x.
4731       OpCmode = 0xa;
4732       Imm = SplatBits >> 8;
4733       break;
4734     }
4735     return SDValue();
4736
4737   case 32:
4738     // NEON's 32-bit VMOV supports splat values where:
4739     // * only one byte is nonzero, or
4740     // * the least significant byte is 0xff and the second byte is nonzero, or
4741     // * the least significant 2 bytes are 0xff and the third is nonzero.
4742     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4743     if ((SplatBits & ~0xff) == 0) {
4744       // Value = 0x000000nn: Op=x, Cmode=000x.
4745       OpCmode = 0;
4746       Imm = SplatBits;
4747       break;
4748     }
4749     if ((SplatBits & ~0xff00) == 0) {
4750       // Value = 0x0000nn00: Op=x, Cmode=001x.
4751       OpCmode = 0x2;
4752       Imm = SplatBits >> 8;
4753       break;
4754     }
4755     if ((SplatBits & ~0xff0000) == 0) {
4756       // Value = 0x00nn0000: Op=x, Cmode=010x.
4757       OpCmode = 0x4;
4758       Imm = SplatBits >> 16;
4759       break;
4760     }
4761     if ((SplatBits & ~0xff000000) == 0) {
4762       // Value = 0xnn000000: Op=x, Cmode=011x.
4763       OpCmode = 0x6;
4764       Imm = SplatBits >> 24;
4765       break;
4766     }
4767
4768     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4769     if (type == OtherModImm) return SDValue();
4770
4771     if ((SplatBits & ~0xffff) == 0 &&
4772         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4773       // Value = 0x0000nnff: Op=x, Cmode=1100.
4774       OpCmode = 0xc;
4775       Imm = SplatBits >> 8;
4776       break;
4777     }
4778
4779     if ((SplatBits & ~0xffffff) == 0 &&
4780         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4781       // Value = 0x00nnffff: Op=x, Cmode=1101.
4782       OpCmode = 0xd;
4783       Imm = SplatBits >> 16;
4784       break;
4785     }
4786
4787     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4788     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4789     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4790     // and fall through here to test for a valid 64-bit splat.  But, then the
4791     // caller would also need to check and handle the change in size.
4792     return SDValue();
4793
4794   case 64: {
4795     if (type != VMOVModImm)
4796       return SDValue();
4797     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4798     uint64_t BitMask = 0xff;
4799     uint64_t Val = 0;
4800     unsigned ImmMask = 1;
4801     Imm = 0;
4802     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4803       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4804         Val |= BitMask;
4805         Imm |= ImmMask;
4806       } else if ((SplatBits & BitMask) != 0) {
4807         return SDValue();
4808       }
4809       BitMask <<= 8;
4810       ImmMask <<= 1;
4811     }
4812
4813     if (DAG.getDataLayout().isBigEndian())
4814       // swap higher and lower 32 bit word
4815       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4816
4817     // Op=1, Cmode=1110.
4818     OpCmode = 0x1e;
4819     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4820     break;
4821   }
4822
4823   default:
4824     llvm_unreachable("unexpected size for isNEONModifiedImm");
4825   }
4826
4827   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4828   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4829 }
4830
4831 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4832                                            const ARMSubtarget *ST) const {
4833   if (!ST->hasVFP3())
4834     return SDValue();
4835
4836   bool IsDouble = Op.getValueType() == MVT::f64;
4837   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4838
4839   // Use the default (constant pool) lowering for double constants when we have
4840   // an SP-only FPU
4841   if (IsDouble && Subtarget->isFPOnlySP())
4842     return SDValue();
4843
4844   // Try splatting with a VMOV.f32...
4845   APFloat FPVal = CFP->getValueAPF();
4846   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4847
4848   if (ImmVal != -1) {
4849     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4850       // We have code in place to select a valid ConstantFP already, no need to
4851       // do any mangling.
4852       return Op;
4853     }
4854
4855     // It's a float and we are trying to use NEON operations where
4856     // possible. Lower it to a splat followed by an extract.
4857     SDLoc DL(Op);
4858     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4859     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4860                                       NewVal);
4861     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4862                        DAG.getConstant(0, DL, MVT::i32));
4863   }
4864
4865   // The rest of our options are NEON only, make sure that's allowed before
4866   // proceeding..
4867   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4868     return SDValue();
4869
4870   EVT VMovVT;
4871   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4872
4873   // It wouldn't really be worth bothering for doubles except for one very
4874   // important value, which does happen to match: 0.0. So make sure we don't do
4875   // anything stupid.
4876   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4877     return SDValue();
4878
4879   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4880   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4881                                      VMovVT, false, VMOVModImm);
4882   if (NewVal != SDValue()) {
4883     SDLoc DL(Op);
4884     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4885                                       NewVal);
4886     if (IsDouble)
4887       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4888
4889     // It's a float: cast and extract a vector element.
4890     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4891                                        VecConstant);
4892     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4893                        DAG.getConstant(0, DL, MVT::i32));
4894   }
4895
4896   // Finally, try a VMVN.i32
4897   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4898                              false, VMVNModImm);
4899   if (NewVal != SDValue()) {
4900     SDLoc DL(Op);
4901     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4902
4903     if (IsDouble)
4904       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4905
4906     // It's a float: cast and extract a vector element.
4907     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4908                                        VecConstant);
4909     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4910                        DAG.getConstant(0, DL, MVT::i32));
4911   }
4912
4913   return SDValue();
4914 }
4915
4916 // check if an VEXT instruction can handle the shuffle mask when the
4917 // vector sources of the shuffle are the same.
4918 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4919   unsigned NumElts = VT.getVectorNumElements();
4920
4921   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4922   if (M[0] < 0)
4923     return false;
4924
4925   Imm = M[0];
4926
4927   // If this is a VEXT shuffle, the immediate value is the index of the first
4928   // element.  The other shuffle indices must be the successive elements after
4929   // the first one.
4930   unsigned ExpectedElt = Imm;
4931   for (unsigned i = 1; i < NumElts; ++i) {
4932     // Increment the expected index.  If it wraps around, just follow it
4933     // back to index zero and keep going.
4934     ++ExpectedElt;
4935     if (ExpectedElt == NumElts)
4936       ExpectedElt = 0;
4937
4938     if (M[i] < 0) continue; // ignore UNDEF indices
4939     if (ExpectedElt != static_cast<unsigned>(M[i]))
4940       return false;
4941   }
4942
4943   return true;
4944 }
4945
4946
4947 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4948                        bool &ReverseVEXT, unsigned &Imm) {
4949   unsigned NumElts = VT.getVectorNumElements();
4950   ReverseVEXT = false;
4951
4952   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4953   if (M[0] < 0)
4954     return false;
4955
4956   Imm = M[0];
4957
4958   // If this is a VEXT shuffle, the immediate value is the index of the first
4959   // element.  The other shuffle indices must be the successive elements after
4960   // the first one.
4961   unsigned ExpectedElt = Imm;
4962   for (unsigned i = 1; i < NumElts; ++i) {
4963     // Increment the expected index.  If it wraps around, it may still be
4964     // a VEXT but the source vectors must be swapped.
4965     ExpectedElt += 1;
4966     if (ExpectedElt == NumElts * 2) {
4967       ExpectedElt = 0;
4968       ReverseVEXT = true;
4969     }
4970
4971     if (M[i] < 0) continue; // ignore UNDEF indices
4972     if (ExpectedElt != static_cast<unsigned>(M[i]))
4973       return false;
4974   }
4975
4976   // Adjust the index value if the source operands will be swapped.
4977   if (ReverseVEXT)
4978     Imm -= NumElts;
4979
4980   return true;
4981 }
4982
4983 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4984 /// instruction with the specified blocksize.  (The order of the elements
4985 /// within each block of the vector is reversed.)
4986 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4987   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4988          "Only possible block sizes for VREV are: 16, 32, 64");
4989
4990   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4991   if (EltSz == 64)
4992     return false;
4993
4994   unsigned NumElts = VT.getVectorNumElements();
4995   unsigned BlockElts = M[0] + 1;
4996   // If the first shuffle index is UNDEF, be optimistic.
4997   if (M[0] < 0)
4998     BlockElts = BlockSize / EltSz;
4999
5000   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5001     return false;
5002
5003   for (unsigned i = 0; i < NumElts; ++i) {
5004     if (M[i] < 0) continue; // ignore UNDEF indices
5005     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5006       return false;
5007   }
5008
5009   return true;
5010 }
5011
5012 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5013   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5014   // range, then 0 is placed into the resulting vector. So pretty much any mask
5015   // of 8 elements can work here.
5016   return VT == MVT::v8i8 && M.size() == 8;
5017 }
5018
5019 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5020 // checking that pairs of elements in the shuffle mask represent the same index
5021 // in each vector, incrementing the expected index by 2 at each step.
5022 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5023 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5024 //  v2={e,f,g,h}
5025 // WhichResult gives the offset for each element in the mask based on which
5026 // of the two results it belongs to.
5027 //
5028 // The transpose can be represented either as:
5029 // result1 = shufflevector v1, v2, result1_shuffle_mask
5030 // result2 = shufflevector v1, v2, result2_shuffle_mask
5031 // where v1/v2 and the shuffle masks have the same number of elements
5032 // (here WhichResult (see below) indicates which result is being checked)
5033 //
5034 // or as:
5035 // results = shufflevector v1, v2, shuffle_mask
5036 // where both results are returned in one vector and the shuffle mask has twice
5037 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5038 // want to check the low half and high half of the shuffle mask as if it were
5039 // the other case
5040 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5041   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5042   if (EltSz == 64)
5043     return false;
5044
5045   unsigned NumElts = VT.getVectorNumElements();
5046   if (M.size() != NumElts && M.size() != NumElts*2)
5047     return false;
5048
5049   // If the mask is twice as long as the input vector then we need to check the
5050   // upper and lower parts of the mask with a matching value for WhichResult
5051   // FIXME: A mask with only even values will be rejected in case the first
5052   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5053   // M[0] is used to determine WhichResult
5054   for (unsigned i = 0; i < M.size(); i += NumElts) {
5055     if (M.size() == NumElts * 2)
5056       WhichResult = i / NumElts;
5057     else
5058       WhichResult = M[i] == 0 ? 0 : 1;
5059     for (unsigned j = 0; j < NumElts; j += 2) {
5060       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5061           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5062         return false;
5063     }
5064   }
5065
5066   if (M.size() == NumElts*2)
5067     WhichResult = 0;
5068
5069   return true;
5070 }
5071
5072 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5073 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5074 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5075 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5076   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5077   if (EltSz == 64)
5078     return false;
5079
5080   unsigned NumElts = VT.getVectorNumElements();
5081   if (M.size() != NumElts && M.size() != NumElts*2)
5082     return false;
5083
5084   for (unsigned i = 0; i < M.size(); i += NumElts) {
5085     if (M.size() == NumElts * 2)
5086       WhichResult = i / NumElts;
5087     else
5088       WhichResult = M[i] == 0 ? 0 : 1;
5089     for (unsigned j = 0; j < NumElts; j += 2) {
5090       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5091           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5092         return false;
5093     }
5094   }
5095
5096   if (M.size() == NumElts*2)
5097     WhichResult = 0;
5098
5099   return true;
5100 }
5101
5102 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5103 // that the mask elements are either all even and in steps of size 2 or all odd
5104 // and in steps of size 2.
5105 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5106 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5107 //  v2={e,f,g,h}
5108 // Requires similar checks to that of isVTRNMask with
5109 // respect the how results are returned.
5110 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5111   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5112   if (EltSz == 64)
5113     return false;
5114
5115   unsigned NumElts = VT.getVectorNumElements();
5116   if (M.size() != NumElts && M.size() != NumElts*2)
5117     return false;
5118
5119   for (unsigned i = 0; i < M.size(); i += NumElts) {
5120     WhichResult = M[i] == 0 ? 0 : 1;
5121     for (unsigned j = 0; j < NumElts; ++j) {
5122       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5123         return false;
5124     }
5125   }
5126
5127   if (M.size() == NumElts*2)
5128     WhichResult = 0;
5129
5130   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5131   if (VT.is64BitVector() && EltSz == 32)
5132     return false;
5133
5134   return true;
5135 }
5136
5137 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5138 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5139 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5140 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5141   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5142   if (EltSz == 64)
5143     return false;
5144
5145   unsigned NumElts = VT.getVectorNumElements();
5146   if (M.size() != NumElts && M.size() != NumElts*2)
5147     return false;
5148
5149   unsigned Half = NumElts / 2;
5150   for (unsigned i = 0; i < M.size(); i += NumElts) {
5151     WhichResult = M[i] == 0 ? 0 : 1;
5152     for (unsigned j = 0; j < NumElts; j += Half) {
5153       unsigned Idx = WhichResult;
5154       for (unsigned k = 0; k < Half; ++k) {
5155         int MIdx = M[i + j + k];
5156         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5157           return false;
5158         Idx += 2;
5159       }
5160     }
5161   }
5162
5163   if (M.size() == NumElts*2)
5164     WhichResult = 0;
5165
5166   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5167   if (VT.is64BitVector() && EltSz == 32)
5168     return false;
5169
5170   return true;
5171 }
5172
5173 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5174 // that pairs of elements of the shufflemask represent the same index in each
5175 // vector incrementing sequentially through the vectors.
5176 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5177 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5178 //  v2={e,f,g,h}
5179 // Requires similar checks to that of isVTRNMask with respect the how results
5180 // are returned.
5181 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5182   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5183   if (EltSz == 64)
5184     return false;
5185
5186   unsigned NumElts = VT.getVectorNumElements();
5187   if (M.size() != NumElts && M.size() != NumElts*2)
5188     return false;
5189
5190   for (unsigned i = 0; i < M.size(); i += NumElts) {
5191     WhichResult = M[i] == 0 ? 0 : 1;
5192     unsigned Idx = WhichResult * NumElts / 2;
5193     for (unsigned j = 0; j < NumElts; j += 2) {
5194       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5195           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5196         return false;
5197       Idx += 1;
5198     }
5199   }
5200
5201   if (M.size() == NumElts*2)
5202     WhichResult = 0;
5203
5204   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5205   if (VT.is64BitVector() && EltSz == 32)
5206     return false;
5207
5208   return true;
5209 }
5210
5211 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5212 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5213 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5214 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5215   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5216   if (EltSz == 64)
5217     return false;
5218
5219   unsigned NumElts = VT.getVectorNumElements();
5220   if (M.size() != NumElts && M.size() != NumElts*2)
5221     return false;
5222
5223   for (unsigned i = 0; i < M.size(); i += NumElts) {
5224     WhichResult = M[i] == 0 ? 0 : 1;
5225     unsigned Idx = WhichResult * NumElts / 2;
5226     for (unsigned j = 0; j < NumElts; j += 2) {
5227       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5228           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5229         return false;
5230       Idx += 1;
5231     }
5232   }
5233
5234   if (M.size() == NumElts*2)
5235     WhichResult = 0;
5236
5237   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5238   if (VT.is64BitVector() && EltSz == 32)
5239     return false;
5240
5241   return true;
5242 }
5243
5244 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5245 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5246 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5247                                            unsigned &WhichResult,
5248                                            bool &isV_UNDEF) {
5249   isV_UNDEF = false;
5250   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5251     return ARMISD::VTRN;
5252   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5253     return ARMISD::VUZP;
5254   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5255     return ARMISD::VZIP;
5256
5257   isV_UNDEF = true;
5258   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5259     return ARMISD::VTRN;
5260   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5261     return ARMISD::VUZP;
5262   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5263     return ARMISD::VZIP;
5264
5265   return 0;
5266 }
5267
5268 /// \return true if this is a reverse operation on an vector.
5269 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5270   unsigned NumElts = VT.getVectorNumElements();
5271   // Make sure the mask has the right size.
5272   if (NumElts != M.size())
5273       return false;
5274
5275   // Look for <15, ..., 3, -1, 1, 0>.
5276   for (unsigned i = 0; i != NumElts; ++i)
5277     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5278       return false;
5279
5280   return true;
5281 }
5282
5283 // If N is an integer constant that can be moved into a register in one
5284 // instruction, return an SDValue of such a constant (will become a MOV
5285 // instruction).  Otherwise return null.
5286 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5287                                      const ARMSubtarget *ST, SDLoc dl) {
5288   uint64_t Val;
5289   if (!isa<ConstantSDNode>(N))
5290     return SDValue();
5291   Val = cast<ConstantSDNode>(N)->getZExtValue();
5292
5293   if (ST->isThumb1Only()) {
5294     if (Val <= 255 || ~Val <= 255)
5295       return DAG.getConstant(Val, dl, MVT::i32);
5296   } else {
5297     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5298       return DAG.getConstant(Val, dl, MVT::i32);
5299   }
5300   return SDValue();
5301 }
5302
5303 // If this is a case we can't handle, return null and let the default
5304 // expansion code take care of it.
5305 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5306                                              const ARMSubtarget *ST) const {
5307   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5308   SDLoc dl(Op);
5309   EVT VT = Op.getValueType();
5310
5311   APInt SplatBits, SplatUndef;
5312   unsigned SplatBitSize;
5313   bool HasAnyUndefs;
5314   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5315     if (SplatBitSize <= 64) {
5316       // Check if an immediate VMOV works.
5317       EVT VmovVT;
5318       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5319                                       SplatUndef.getZExtValue(), SplatBitSize,
5320                                       DAG, dl, VmovVT, VT.is128BitVector(),
5321                                       VMOVModImm);
5322       if (Val.getNode()) {
5323         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5324         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5325       }
5326
5327       // Try an immediate VMVN.
5328       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5329       Val = isNEONModifiedImm(NegatedImm,
5330                                       SplatUndef.getZExtValue(), SplatBitSize,
5331                                       DAG, dl, VmovVT, VT.is128BitVector(),
5332                                       VMVNModImm);
5333       if (Val.getNode()) {
5334         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5335         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5336       }
5337
5338       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5339       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5340         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5341         if (ImmVal != -1) {
5342           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5343           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5344         }
5345       }
5346     }
5347   }
5348
5349   // Scan through the operands to see if only one value is used.
5350   //
5351   // As an optimisation, even if more than one value is used it may be more
5352   // profitable to splat with one value then change some lanes.
5353   //
5354   // Heuristically we decide to do this if the vector has a "dominant" value,
5355   // defined as splatted to more than half of the lanes.
5356   unsigned NumElts = VT.getVectorNumElements();
5357   bool isOnlyLowElement = true;
5358   bool usesOnlyOneValue = true;
5359   bool hasDominantValue = false;
5360   bool isConstant = true;
5361
5362   // Map of the number of times a particular SDValue appears in the
5363   // element list.
5364   DenseMap<SDValue, unsigned> ValueCounts;
5365   SDValue Value;
5366   for (unsigned i = 0; i < NumElts; ++i) {
5367     SDValue V = Op.getOperand(i);
5368     if (V.getOpcode() == ISD::UNDEF)
5369       continue;
5370     if (i > 0)
5371       isOnlyLowElement = false;
5372     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5373       isConstant = false;
5374
5375     ValueCounts.insert(std::make_pair(V, 0));
5376     unsigned &Count = ValueCounts[V];
5377
5378     // Is this value dominant? (takes up more than half of the lanes)
5379     if (++Count > (NumElts / 2)) {
5380       hasDominantValue = true;
5381       Value = V;
5382     }
5383   }
5384   if (ValueCounts.size() != 1)
5385     usesOnlyOneValue = false;
5386   if (!Value.getNode() && ValueCounts.size() > 0)
5387     Value = ValueCounts.begin()->first;
5388
5389   if (ValueCounts.size() == 0)
5390     return DAG.getUNDEF(VT);
5391
5392   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5393   // Keep going if we are hitting this case.
5394   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5395     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5396
5397   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5398
5399   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5400   // i32 and try again.
5401   if (hasDominantValue && EltSize <= 32) {
5402     if (!isConstant) {
5403       SDValue N;
5404
5405       // If we are VDUPing a value that comes directly from a vector, that will
5406       // cause an unnecessary move to and from a GPR, where instead we could
5407       // just use VDUPLANE. We can only do this if the lane being extracted
5408       // is at a constant index, as the VDUP from lane instructions only have
5409       // constant-index forms.
5410       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5411           isa<ConstantSDNode>(Value->getOperand(1))) {
5412         // We need to create a new undef vector to use for the VDUPLANE if the
5413         // size of the vector from which we get the value is different than the
5414         // size of the vector that we need to create. We will insert the element
5415         // such that the register coalescer will remove unnecessary copies.
5416         if (VT != Value->getOperand(0).getValueType()) {
5417           ConstantSDNode *constIndex;
5418           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5419           assert(constIndex && "The index is not a constant!");
5420           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5421                              VT.getVectorNumElements();
5422           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5423                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5424                         Value, DAG.getConstant(index, dl, MVT::i32)),
5425                            DAG.getConstant(index, dl, MVT::i32));
5426         } else
5427           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5428                         Value->getOperand(0), Value->getOperand(1));
5429       } else
5430         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5431
5432       if (!usesOnlyOneValue) {
5433         // The dominant value was splatted as 'N', but we now have to insert
5434         // all differing elements.
5435         for (unsigned I = 0; I < NumElts; ++I) {
5436           if (Op.getOperand(I) == Value)
5437             continue;
5438           SmallVector<SDValue, 3> Ops;
5439           Ops.push_back(N);
5440           Ops.push_back(Op.getOperand(I));
5441           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5442           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5443         }
5444       }
5445       return N;
5446     }
5447     if (VT.getVectorElementType().isFloatingPoint()) {
5448       SmallVector<SDValue, 8> Ops;
5449       for (unsigned i = 0; i < NumElts; ++i)
5450         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5451                                   Op.getOperand(i)));
5452       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5453       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5454       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5455       if (Val.getNode())
5456         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5457     }
5458     if (usesOnlyOneValue) {
5459       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5460       if (isConstant && Val.getNode())
5461         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5462     }
5463   }
5464
5465   // If all elements are constants and the case above didn't get hit, fall back
5466   // to the default expansion, which will generate a load from the constant
5467   // pool.
5468   if (isConstant)
5469     return SDValue();
5470
5471   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5472   if (NumElts >= 4) {
5473     SDValue shuffle = ReconstructShuffle(Op, DAG);
5474     if (shuffle != SDValue())
5475       return shuffle;
5476   }
5477
5478   // Vectors with 32- or 64-bit elements can be built by directly assigning
5479   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5480   // will be legalized.
5481   if (EltSize >= 32) {
5482     // Do the expansion with floating-point types, since that is what the VFP
5483     // registers are defined to use, and since i64 is not legal.
5484     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5485     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5486     SmallVector<SDValue, 8> Ops;
5487     for (unsigned i = 0; i < NumElts; ++i)
5488       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5489     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5490     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5491   }
5492
5493   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5494   // know the default expansion would otherwise fall back on something even
5495   // worse. For a vector with one or two non-undef values, that's
5496   // scalar_to_vector for the elements followed by a shuffle (provided the
5497   // shuffle is valid for the target) and materialization element by element
5498   // on the stack followed by a load for everything else.
5499   if (!isConstant && !usesOnlyOneValue) {
5500     SDValue Vec = DAG.getUNDEF(VT);
5501     for (unsigned i = 0 ; i < NumElts; ++i) {
5502       SDValue V = Op.getOperand(i);
5503       if (V.getOpcode() == ISD::UNDEF)
5504         continue;
5505       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5506       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5507     }
5508     return Vec;
5509   }
5510
5511   return SDValue();
5512 }
5513
5514 // Gather data to see if the operation can be modelled as a
5515 // shuffle in combination with VEXTs.
5516 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5517                                               SelectionDAG &DAG) const {
5518   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5519   SDLoc dl(Op);
5520   EVT VT = Op.getValueType();
5521   unsigned NumElts = VT.getVectorNumElements();
5522
5523   struct ShuffleSourceInfo {
5524     SDValue Vec;
5525     unsigned MinElt;
5526     unsigned MaxElt;
5527
5528     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5529     // be compatible with the shuffle we intend to construct. As a result
5530     // ShuffleVec will be some sliding window into the original Vec.
5531     SDValue ShuffleVec;
5532
5533     // Code should guarantee that element i in Vec starts at element "WindowBase
5534     // + i * WindowScale in ShuffleVec".
5535     int WindowBase;
5536     int WindowScale;
5537
5538     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5539     ShuffleSourceInfo(SDValue Vec)
5540         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5541           WindowScale(1) {}
5542   };
5543
5544   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5545   // node.
5546   SmallVector<ShuffleSourceInfo, 2> Sources;
5547   for (unsigned i = 0; i < NumElts; ++i) {
5548     SDValue V = Op.getOperand(i);
5549     if (V.getOpcode() == ISD::UNDEF)
5550       continue;
5551     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5552       // A shuffle can only come from building a vector from various
5553       // elements of other vectors.
5554       return SDValue();
5555     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5556       // Furthermore, shuffles require a constant mask, whereas extractelts
5557       // accept variable indices.
5558       return SDValue();
5559     }
5560
5561     // Add this element source to the list if it's not already there.
5562     SDValue SourceVec = V.getOperand(0);
5563     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5564     if (Source == Sources.end())
5565       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5566
5567     // Update the minimum and maximum lane number seen.
5568     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5569     Source->MinElt = std::min(Source->MinElt, EltNo);
5570     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5571   }
5572
5573   // Currently only do something sane when at most two source vectors
5574   // are involved.
5575   if (Sources.size() > 2)
5576     return SDValue();
5577
5578   // Find out the smallest element size among result and two sources, and use
5579   // it as element size to build the shuffle_vector.
5580   EVT SmallestEltTy = VT.getVectorElementType();
5581   for (auto &Source : Sources) {
5582     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5583     if (SrcEltTy.bitsLT(SmallestEltTy))
5584       SmallestEltTy = SrcEltTy;
5585   }
5586   unsigned ResMultiplier =
5587       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5588   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5589   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5590
5591   // If the source vector is too wide or too narrow, we may nevertheless be able
5592   // to construct a compatible shuffle either by concatenating it with UNDEF or
5593   // extracting a suitable range of elements.
5594   for (auto &Src : Sources) {
5595     EVT SrcVT = Src.ShuffleVec.getValueType();
5596
5597     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5598       continue;
5599
5600     // This stage of the search produces a source with the same element type as
5601     // the original, but with a total width matching the BUILD_VECTOR output.
5602     EVT EltVT = SrcVT.getVectorElementType();
5603     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5604     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5605
5606     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5607       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5608         return SDValue();
5609       // We can pad out the smaller vector for free, so if it's part of a
5610       // shuffle...
5611       Src.ShuffleVec =
5612           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5613                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5614       continue;
5615     }
5616
5617     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5618       return SDValue();
5619
5620     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5621       // Span too large for a VEXT to cope
5622       return SDValue();
5623     }
5624
5625     if (Src.MinElt >= NumSrcElts) {
5626       // The extraction can just take the second half
5627       Src.ShuffleVec =
5628           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5629                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5630       Src.WindowBase = -NumSrcElts;
5631     } else if (Src.MaxElt < NumSrcElts) {
5632       // The extraction can just take the first half
5633       Src.ShuffleVec =
5634           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5635                       DAG.getConstant(0, dl, MVT::i32));
5636     } else {
5637       // An actual VEXT is needed
5638       SDValue VEXTSrc1 =
5639           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5640                       DAG.getConstant(0, dl, MVT::i32));
5641       SDValue VEXTSrc2 =
5642           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5643                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5644
5645       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5646                                    VEXTSrc2,
5647                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5648       Src.WindowBase = -Src.MinElt;
5649     }
5650   }
5651
5652   // Another possible incompatibility occurs from the vector element types. We
5653   // can fix this by bitcasting the source vectors to the same type we intend
5654   // for the shuffle.
5655   for (auto &Src : Sources) {
5656     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5657     if (SrcEltTy == SmallestEltTy)
5658       continue;
5659     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5660     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5661     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5662     Src.WindowBase *= Src.WindowScale;
5663   }
5664
5665   // Final sanity check before we try to actually produce a shuffle.
5666   DEBUG(
5667     for (auto Src : Sources)
5668       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5669   );
5670
5671   // The stars all align, our next step is to produce the mask for the shuffle.
5672   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5673   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5674   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5675     SDValue Entry = Op.getOperand(i);
5676     if (Entry.getOpcode() == ISD::UNDEF)
5677       continue;
5678
5679     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5680     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5681
5682     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5683     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5684     // segment.
5685     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5686     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5687                                VT.getVectorElementType().getSizeInBits());
5688     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5689
5690     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5691     // starting at the appropriate offset.
5692     int *LaneMask = &Mask[i * ResMultiplier];
5693
5694     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5695     ExtractBase += NumElts * (Src - Sources.begin());
5696     for (int j = 0; j < LanesDefined; ++j)
5697       LaneMask[j] = ExtractBase + j;
5698   }
5699
5700   // Final check before we try to produce nonsense...
5701   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5702     return SDValue();
5703
5704   // We can't handle more than two sources. This should have already
5705   // been checked before this point.
5706   assert(Sources.size() <= 2 && "Too many sources!");
5707
5708   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5709   for (unsigned i = 0; i < Sources.size(); ++i)
5710     ShuffleOps[i] = Sources[i].ShuffleVec;
5711
5712   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5713                                          ShuffleOps[1], &Mask[0]);
5714   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5715 }
5716
5717 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5718 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5719 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5720 /// are assumed to be legal.
5721 bool
5722 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5723                                       EVT VT) const {
5724   if (VT.getVectorNumElements() == 4 &&
5725       (VT.is128BitVector() || VT.is64BitVector())) {
5726     unsigned PFIndexes[4];
5727     for (unsigned i = 0; i != 4; ++i) {
5728       if (M[i] < 0)
5729         PFIndexes[i] = 8;
5730       else
5731         PFIndexes[i] = M[i];
5732     }
5733
5734     // Compute the index in the perfect shuffle table.
5735     unsigned PFTableIndex =
5736       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5737     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5738     unsigned Cost = (PFEntry >> 30);
5739
5740     if (Cost <= 4)
5741       return true;
5742   }
5743
5744   bool ReverseVEXT, isV_UNDEF;
5745   unsigned Imm, WhichResult;
5746
5747   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5748   return (EltSize >= 32 ||
5749           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5750           isVREVMask(M, VT, 64) ||
5751           isVREVMask(M, VT, 32) ||
5752           isVREVMask(M, VT, 16) ||
5753           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5754           isVTBLMask(M, VT) ||
5755           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5756           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5757 }
5758
5759 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5760 /// the specified operations to build the shuffle.
5761 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5762                                       SDValue RHS, SelectionDAG &DAG,
5763                                       SDLoc dl) {
5764   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5765   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5766   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5767
5768   enum {
5769     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5770     OP_VREV,
5771     OP_VDUP0,
5772     OP_VDUP1,
5773     OP_VDUP2,
5774     OP_VDUP3,
5775     OP_VEXT1,
5776     OP_VEXT2,
5777     OP_VEXT3,
5778     OP_VUZPL, // VUZP, left result
5779     OP_VUZPR, // VUZP, right result
5780     OP_VZIPL, // VZIP, left result
5781     OP_VZIPR, // VZIP, right result
5782     OP_VTRNL, // VTRN, left result
5783     OP_VTRNR  // VTRN, right result
5784   };
5785
5786   if (OpNum == OP_COPY) {
5787     if (LHSID == (1*9+2)*9+3) return LHS;
5788     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5789     return RHS;
5790   }
5791
5792   SDValue OpLHS, OpRHS;
5793   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5794   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5795   EVT VT = OpLHS.getValueType();
5796
5797   switch (OpNum) {
5798   default: llvm_unreachable("Unknown shuffle opcode!");
5799   case OP_VREV:
5800     // VREV divides the vector in half and swaps within the half.
5801     if (VT.getVectorElementType() == MVT::i32 ||
5802         VT.getVectorElementType() == MVT::f32)
5803       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5804     // vrev <4 x i16> -> VREV32
5805     if (VT.getVectorElementType() == MVT::i16)
5806       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5807     // vrev <4 x i8> -> VREV16
5808     assert(VT.getVectorElementType() == MVT::i8);
5809     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5810   case OP_VDUP0:
5811   case OP_VDUP1:
5812   case OP_VDUP2:
5813   case OP_VDUP3:
5814     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5815                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5816   case OP_VEXT1:
5817   case OP_VEXT2:
5818   case OP_VEXT3:
5819     return DAG.getNode(ARMISD::VEXT, dl, VT,
5820                        OpLHS, OpRHS,
5821                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5822   case OP_VUZPL:
5823   case OP_VUZPR:
5824     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5825                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5826   case OP_VZIPL:
5827   case OP_VZIPR:
5828     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5829                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5830   case OP_VTRNL:
5831   case OP_VTRNR:
5832     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5833                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5834   }
5835 }
5836
5837 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5838                                        ArrayRef<int> ShuffleMask,
5839                                        SelectionDAG &DAG) {
5840   // Check to see if we can use the VTBL instruction.
5841   SDValue V1 = Op.getOperand(0);
5842   SDValue V2 = Op.getOperand(1);
5843   SDLoc DL(Op);
5844
5845   SmallVector<SDValue, 8> VTBLMask;
5846   for (ArrayRef<int>::iterator
5847          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5848     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5849
5850   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5851     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5852                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5853
5854   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5855                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5856 }
5857
5858 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5859                                                       SelectionDAG &DAG) {
5860   SDLoc DL(Op);
5861   SDValue OpLHS = Op.getOperand(0);
5862   EVT VT = OpLHS.getValueType();
5863
5864   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5865          "Expect an v8i16/v16i8 type");
5866   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5867   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5868   // extract the first 8 bytes into the top double word and the last 8 bytes
5869   // into the bottom double word. The v8i16 case is similar.
5870   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5871   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5872                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5873 }
5874
5875 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5876   SDValue V1 = Op.getOperand(0);
5877   SDValue V2 = Op.getOperand(1);
5878   SDLoc dl(Op);
5879   EVT VT = Op.getValueType();
5880   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5881
5882   // Convert shuffles that are directly supported on NEON to target-specific
5883   // DAG nodes, instead of keeping them as shuffles and matching them again
5884   // during code selection.  This is more efficient and avoids the possibility
5885   // of inconsistencies between legalization and selection.
5886   // FIXME: floating-point vectors should be canonicalized to integer vectors
5887   // of the same time so that they get CSEd properly.
5888   ArrayRef<int> ShuffleMask = SVN->getMask();
5889
5890   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5891   if (EltSize <= 32) {
5892     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5893       int Lane = SVN->getSplatIndex();
5894       // If this is undef splat, generate it via "just" vdup, if possible.
5895       if (Lane == -1) Lane = 0;
5896
5897       // Test if V1 is a SCALAR_TO_VECTOR.
5898       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5899         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5900       }
5901       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5902       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5903       // reaches it).
5904       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5905           !isa<ConstantSDNode>(V1.getOperand(0))) {
5906         bool IsScalarToVector = true;
5907         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5908           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5909             IsScalarToVector = false;
5910             break;
5911           }
5912         if (IsScalarToVector)
5913           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5914       }
5915       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5916                          DAG.getConstant(Lane, dl, MVT::i32));
5917     }
5918
5919     bool ReverseVEXT;
5920     unsigned Imm;
5921     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5922       if (ReverseVEXT)
5923         std::swap(V1, V2);
5924       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5925                          DAG.getConstant(Imm, dl, MVT::i32));
5926     }
5927
5928     if (isVREVMask(ShuffleMask, VT, 64))
5929       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5930     if (isVREVMask(ShuffleMask, VT, 32))
5931       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5932     if (isVREVMask(ShuffleMask, VT, 16))
5933       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5934
5935     if (V2->getOpcode() == ISD::UNDEF &&
5936         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5937       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5938                          DAG.getConstant(Imm, dl, MVT::i32));
5939     }
5940
5941     // Check for Neon shuffles that modify both input vectors in place.
5942     // If both results are used, i.e., if there are two shuffles with the same
5943     // source operands and with masks corresponding to both results of one of
5944     // these operations, DAG memoization will ensure that a single node is
5945     // used for both shuffles.
5946     unsigned WhichResult;
5947     bool isV_UNDEF;
5948     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5949             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5950       if (isV_UNDEF)
5951         V2 = V1;
5952       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5953           .getValue(WhichResult);
5954     }
5955
5956     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5957     // shuffles that produce a result larger than their operands with:
5958     //   shuffle(concat(v1, undef), concat(v2, undef))
5959     // ->
5960     //   shuffle(concat(v1, v2), undef)
5961     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5962     //
5963     // This is useful in the general case, but there are special cases where
5964     // native shuffles produce larger results: the two-result ops.
5965     //
5966     // Look through the concat when lowering them:
5967     //   shuffle(concat(v1, v2), undef)
5968     // ->
5969     //   concat(VZIP(v1, v2):0, :1)
5970     //
5971     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5972         V2->getOpcode() == ISD::UNDEF) {
5973       SDValue SubV1 = V1->getOperand(0);
5974       SDValue SubV2 = V1->getOperand(1);
5975       EVT SubVT = SubV1.getValueType();
5976
5977       // We expect these to have been canonicalized to -1.
5978       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5979         return i < (int)VT.getVectorNumElements();
5980       }) && "Unexpected shuffle index into UNDEF operand!");
5981
5982       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5983               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5984         if (isV_UNDEF)
5985           SubV2 = SubV1;
5986         assert((WhichResult == 0) &&
5987                "In-place shuffle of concat can only have one result!");
5988         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5989                                   SubV1, SubV2);
5990         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5991                            Res.getValue(1));
5992       }
5993     }
5994   }
5995
5996   // If the shuffle is not directly supported and it has 4 elements, use
5997   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5998   unsigned NumElts = VT.getVectorNumElements();
5999   if (NumElts == 4) {
6000     unsigned PFIndexes[4];
6001     for (unsigned i = 0; i != 4; ++i) {
6002       if (ShuffleMask[i] < 0)
6003         PFIndexes[i] = 8;
6004       else
6005         PFIndexes[i] = ShuffleMask[i];
6006     }
6007
6008     // Compute the index in the perfect shuffle table.
6009     unsigned PFTableIndex =
6010       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6011     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6012     unsigned Cost = (PFEntry >> 30);
6013
6014     if (Cost <= 4)
6015       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6016   }
6017
6018   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6019   if (EltSize >= 32) {
6020     // Do the expansion with floating-point types, since that is what the VFP
6021     // registers are defined to use, and since i64 is not legal.
6022     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6023     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6024     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6025     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6026     SmallVector<SDValue, 8> Ops;
6027     for (unsigned i = 0; i < NumElts; ++i) {
6028       if (ShuffleMask[i] < 0)
6029         Ops.push_back(DAG.getUNDEF(EltVT));
6030       else
6031         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6032                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6033                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6034                                                   dl, MVT::i32)));
6035     }
6036     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6037     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6038   }
6039
6040   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6041     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6042
6043   if (VT == MVT::v8i8) {
6044     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6045     if (NewOp.getNode())
6046       return NewOp;
6047   }
6048
6049   return SDValue();
6050 }
6051
6052 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6053   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6054   SDValue Lane = Op.getOperand(2);
6055   if (!isa<ConstantSDNode>(Lane))
6056     return SDValue();
6057
6058   return Op;
6059 }
6060
6061 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6062   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6063   SDValue Lane = Op.getOperand(1);
6064   if (!isa<ConstantSDNode>(Lane))
6065     return SDValue();
6066
6067   SDValue Vec = Op.getOperand(0);
6068   if (Op.getValueType() == MVT::i32 &&
6069       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6070     SDLoc dl(Op);
6071     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6072   }
6073
6074   return Op;
6075 }
6076
6077 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6078   // The only time a CONCAT_VECTORS operation can have legal types is when
6079   // two 64-bit vectors are concatenated to a 128-bit vector.
6080   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6081          "unexpected CONCAT_VECTORS");
6082   SDLoc dl(Op);
6083   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6084   SDValue Op0 = Op.getOperand(0);
6085   SDValue Op1 = Op.getOperand(1);
6086   if (Op0.getOpcode() != ISD::UNDEF)
6087     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6088                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6089                       DAG.getIntPtrConstant(0, dl));
6090   if (Op1.getOpcode() != ISD::UNDEF)
6091     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6092                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6093                       DAG.getIntPtrConstant(1, dl));
6094   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6095 }
6096
6097 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6098 /// element has been zero/sign-extended, depending on the isSigned parameter,
6099 /// from an integer type half its size.
6100 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6101                                    bool isSigned) {
6102   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6103   EVT VT = N->getValueType(0);
6104   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6105     SDNode *BVN = N->getOperand(0).getNode();
6106     if (BVN->getValueType(0) != MVT::v4i32 ||
6107         BVN->getOpcode() != ISD::BUILD_VECTOR)
6108       return false;
6109     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6110     unsigned HiElt = 1 - LoElt;
6111     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6112     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6113     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6114     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6115     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6116       return false;
6117     if (isSigned) {
6118       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6119           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6120         return true;
6121     } else {
6122       if (Hi0->isNullValue() && Hi1->isNullValue())
6123         return true;
6124     }
6125     return false;
6126   }
6127
6128   if (N->getOpcode() != ISD::BUILD_VECTOR)
6129     return false;
6130
6131   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6132     SDNode *Elt = N->getOperand(i).getNode();
6133     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6134       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6135       unsigned HalfSize = EltSize / 2;
6136       if (isSigned) {
6137         if (!isIntN(HalfSize, C->getSExtValue()))
6138           return false;
6139       } else {
6140         if (!isUIntN(HalfSize, C->getZExtValue()))
6141           return false;
6142       }
6143       continue;
6144     }
6145     return false;
6146   }
6147
6148   return true;
6149 }
6150
6151 /// isSignExtended - Check if a node is a vector value that is sign-extended
6152 /// or a constant BUILD_VECTOR with sign-extended elements.
6153 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6154   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6155     return true;
6156   if (isExtendedBUILD_VECTOR(N, DAG, true))
6157     return true;
6158   return false;
6159 }
6160
6161 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6162 /// or a constant BUILD_VECTOR with zero-extended elements.
6163 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6164   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6165     return true;
6166   if (isExtendedBUILD_VECTOR(N, DAG, false))
6167     return true;
6168   return false;
6169 }
6170
6171 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6172   if (OrigVT.getSizeInBits() >= 64)
6173     return OrigVT;
6174
6175   assert(OrigVT.isSimple() && "Expecting a simple value type");
6176
6177   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6178   switch (OrigSimpleTy) {
6179   default: llvm_unreachable("Unexpected Vector Type");
6180   case MVT::v2i8:
6181   case MVT::v2i16:
6182      return MVT::v2i32;
6183   case MVT::v4i8:
6184     return  MVT::v4i16;
6185   }
6186 }
6187
6188 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6189 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6190 /// We insert the required extension here to get the vector to fill a D register.
6191 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6192                                             const EVT &OrigTy,
6193                                             const EVT &ExtTy,
6194                                             unsigned ExtOpcode) {
6195   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6196   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6197   // 64-bits we need to insert a new extension so that it will be 64-bits.
6198   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6199   if (OrigTy.getSizeInBits() >= 64)
6200     return N;
6201
6202   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6203   EVT NewVT = getExtensionTo64Bits(OrigTy);
6204
6205   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6206 }
6207
6208 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6209 /// does not do any sign/zero extension. If the original vector is less
6210 /// than 64 bits, an appropriate extension will be added after the load to
6211 /// reach a total size of 64 bits. We have to add the extension separately
6212 /// because ARM does not have a sign/zero extending load for vectors.
6213 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6214   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6215
6216   // The load already has the right type.
6217   if (ExtendedTy == LD->getMemoryVT())
6218     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6219                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6220                 LD->isNonTemporal(), LD->isInvariant(),
6221                 LD->getAlignment());
6222
6223   // We need to create a zextload/sextload. We cannot just create a load
6224   // followed by a zext/zext node because LowerMUL is also run during normal
6225   // operation legalization where we can't create illegal types.
6226   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6227                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6228                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6229                         LD->isNonTemporal(), LD->getAlignment());
6230 }
6231
6232 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6233 /// extending load, or BUILD_VECTOR with extended elements, return the
6234 /// unextended value. The unextended vector should be 64 bits so that it can
6235 /// be used as an operand to a VMULL instruction. If the original vector size
6236 /// before extension is less than 64 bits we add a an extension to resize
6237 /// the vector to 64 bits.
6238 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6239   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6240     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6241                                         N->getOperand(0)->getValueType(0),
6242                                         N->getValueType(0),
6243                                         N->getOpcode());
6244
6245   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6246     return SkipLoadExtensionForVMULL(LD, DAG);
6247
6248   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6249   // have been legalized as a BITCAST from v4i32.
6250   if (N->getOpcode() == ISD::BITCAST) {
6251     SDNode *BVN = N->getOperand(0).getNode();
6252     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6253            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6254     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6255     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6256                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6257   }
6258   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6259   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6260   EVT VT = N->getValueType(0);
6261   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6262   unsigned NumElts = VT.getVectorNumElements();
6263   MVT TruncVT = MVT::getIntegerVT(EltSize);
6264   SmallVector<SDValue, 8> Ops;
6265   SDLoc dl(N);
6266   for (unsigned i = 0; i != NumElts; ++i) {
6267     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6268     const APInt &CInt = C->getAPIntValue();
6269     // Element types smaller than 32 bits are not legal, so use i32 elements.
6270     // The values are implicitly truncated so sext vs. zext doesn't matter.
6271     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6272   }
6273   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6274                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6275 }
6276
6277 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6278   unsigned Opcode = N->getOpcode();
6279   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6280     SDNode *N0 = N->getOperand(0).getNode();
6281     SDNode *N1 = N->getOperand(1).getNode();
6282     return N0->hasOneUse() && N1->hasOneUse() &&
6283       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6284   }
6285   return false;
6286 }
6287
6288 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6289   unsigned Opcode = N->getOpcode();
6290   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6291     SDNode *N0 = N->getOperand(0).getNode();
6292     SDNode *N1 = N->getOperand(1).getNode();
6293     return N0->hasOneUse() && N1->hasOneUse() &&
6294       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6295   }
6296   return false;
6297 }
6298
6299 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6300   // Multiplications are only custom-lowered for 128-bit vectors so that
6301   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6302   EVT VT = Op.getValueType();
6303   assert(VT.is128BitVector() && VT.isInteger() &&
6304          "unexpected type for custom-lowering ISD::MUL");
6305   SDNode *N0 = Op.getOperand(0).getNode();
6306   SDNode *N1 = Op.getOperand(1).getNode();
6307   unsigned NewOpc = 0;
6308   bool isMLA = false;
6309   bool isN0SExt = isSignExtended(N0, DAG);
6310   bool isN1SExt = isSignExtended(N1, DAG);
6311   if (isN0SExt && isN1SExt)
6312     NewOpc = ARMISD::VMULLs;
6313   else {
6314     bool isN0ZExt = isZeroExtended(N0, DAG);
6315     bool isN1ZExt = isZeroExtended(N1, DAG);
6316     if (isN0ZExt && isN1ZExt)
6317       NewOpc = ARMISD::VMULLu;
6318     else if (isN1SExt || isN1ZExt) {
6319       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6320       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6321       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6322         NewOpc = ARMISD::VMULLs;
6323         isMLA = true;
6324       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6325         NewOpc = ARMISD::VMULLu;
6326         isMLA = true;
6327       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6328         std::swap(N0, N1);
6329         NewOpc = ARMISD::VMULLu;
6330         isMLA = true;
6331       }
6332     }
6333
6334     if (!NewOpc) {
6335       if (VT == MVT::v2i64)
6336         // Fall through to expand this.  It is not legal.
6337         return SDValue();
6338       else
6339         // Other vector multiplications are legal.
6340         return Op;
6341     }
6342   }
6343
6344   // Legalize to a VMULL instruction.
6345   SDLoc DL(Op);
6346   SDValue Op0;
6347   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6348   if (!isMLA) {
6349     Op0 = SkipExtensionForVMULL(N0, DAG);
6350     assert(Op0.getValueType().is64BitVector() &&
6351            Op1.getValueType().is64BitVector() &&
6352            "unexpected types for extended operands to VMULL");
6353     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6354   }
6355
6356   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6357   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6358   //   vmull q0, d4, d6
6359   //   vmlal q0, d5, d6
6360   // is faster than
6361   //   vaddl q0, d4, d5
6362   //   vmovl q1, d6
6363   //   vmul  q0, q0, q1
6364   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6365   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6366   EVT Op1VT = Op1.getValueType();
6367   return DAG.getNode(N0->getOpcode(), DL, VT,
6368                      DAG.getNode(NewOpc, DL, VT,
6369                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6370                      DAG.getNode(NewOpc, DL, VT,
6371                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6372 }
6373
6374 static SDValue
6375 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6376   // TODO: Should this propagate fast-math-flags?
6377
6378   // Convert to float
6379   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6380   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6381   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6382   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6383   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6384   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6385   // Get reciprocal estimate.
6386   // float4 recip = vrecpeq_f32(yf);
6387   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6388                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6389                    Y);
6390   // Because char has a smaller range than uchar, we can actually get away
6391   // without any newton steps.  This requires that we use a weird bias
6392   // of 0xb000, however (again, this has been exhaustively tested).
6393   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6394   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6395   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6396   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6397   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6398   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6399   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6400   // Convert back to short.
6401   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6402   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6403   return X;
6404 }
6405
6406 static SDValue
6407 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6408   // TODO: Should this propagate fast-math-flags?
6409
6410   SDValue N2;
6411   // Convert to float.
6412   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6413   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6414   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6415   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6416   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6417   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6418
6419   // Use reciprocal estimate and one refinement step.
6420   // float4 recip = vrecpeq_f32(yf);
6421   // recip *= vrecpsq_f32(yf, recip);
6422   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6423                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6424                    N1);
6425   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6426                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6427                    N1, N2);
6428   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6429   // Because short has a smaller range than ushort, we can actually get away
6430   // with only a single newton step.  This requires that we use a weird bias
6431   // of 89, however (again, this has been exhaustively tested).
6432   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6433   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6434   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6435   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6436   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6437   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6438   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6439   // Convert back to integer and return.
6440   // return vmovn_s32(vcvt_s32_f32(result));
6441   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6442   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6443   return N0;
6444 }
6445
6446 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6447   EVT VT = Op.getValueType();
6448   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6449          "unexpected type for custom-lowering ISD::SDIV");
6450
6451   SDLoc dl(Op);
6452   SDValue N0 = Op.getOperand(0);
6453   SDValue N1 = Op.getOperand(1);
6454   SDValue N2, N3;
6455
6456   if (VT == MVT::v8i8) {
6457     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6458     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6459
6460     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6461                      DAG.getIntPtrConstant(4, dl));
6462     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6463                      DAG.getIntPtrConstant(4, dl));
6464     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6465                      DAG.getIntPtrConstant(0, dl));
6466     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6467                      DAG.getIntPtrConstant(0, dl));
6468
6469     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6470     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6471
6472     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6473     N0 = LowerCONCAT_VECTORS(N0, DAG);
6474
6475     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6476     return N0;
6477   }
6478   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6479 }
6480
6481 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6482   // TODO: Should this propagate fast-math-flags?
6483   EVT VT = Op.getValueType();
6484   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6485          "unexpected type for custom-lowering ISD::UDIV");
6486
6487   SDLoc dl(Op);
6488   SDValue N0 = Op.getOperand(0);
6489   SDValue N1 = Op.getOperand(1);
6490   SDValue N2, N3;
6491
6492   if (VT == MVT::v8i8) {
6493     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6494     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6495
6496     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6497                      DAG.getIntPtrConstant(4, dl));
6498     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6499                      DAG.getIntPtrConstant(4, dl));
6500     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6501                      DAG.getIntPtrConstant(0, dl));
6502     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6503                      DAG.getIntPtrConstant(0, dl));
6504
6505     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6506     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6507
6508     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6509     N0 = LowerCONCAT_VECTORS(N0, DAG);
6510
6511     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6512                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6513                                      MVT::i32),
6514                      N0);
6515     return N0;
6516   }
6517
6518   // v4i16 sdiv ... Convert to float.
6519   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6520   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6521   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6522   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6523   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6524   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6525
6526   // Use reciprocal estimate and two refinement steps.
6527   // float4 recip = vrecpeq_f32(yf);
6528   // recip *= vrecpsq_f32(yf, recip);
6529   // recip *= vrecpsq_f32(yf, recip);
6530   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6531                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6532                    BN1);
6533   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6534                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6535                    BN1, N2);
6536   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6537   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6538                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6539                    BN1, N2);
6540   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6541   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6542   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6543   // and that it will never cause us to return an answer too large).
6544   // float4 result = as_float4(as_int4(xf*recip) + 2);
6545   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6546   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6547   N1 = DAG.getConstant(2, dl, MVT::i32);
6548   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6549   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6550   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6551   // Convert back to integer and return.
6552   // return vmovn_u32(vcvt_s32_f32(result));
6553   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6554   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6555   return N0;
6556 }
6557
6558 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6559   EVT VT = Op.getNode()->getValueType(0);
6560   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6561
6562   unsigned Opc;
6563   bool ExtraOp = false;
6564   switch (Op.getOpcode()) {
6565   default: llvm_unreachable("Invalid code");
6566   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6567   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6568   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6569   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6570   }
6571
6572   if (!ExtraOp)
6573     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6574                        Op.getOperand(1));
6575   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6576                      Op.getOperand(1), Op.getOperand(2));
6577 }
6578
6579 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6580   assert(Subtarget->isTargetDarwin());
6581
6582   // For iOS, we want to call an alternative entry point: __sincos_stret,
6583   // return values are passed via sret.
6584   SDLoc dl(Op);
6585   SDValue Arg = Op.getOperand(0);
6586   EVT ArgVT = Arg.getValueType();
6587   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6588   auto PtrVT = getPointerTy(DAG.getDataLayout());
6589
6590   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6591   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6592
6593   // Pair of floats / doubles used to pass the result.
6594   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6595   auto &DL = DAG.getDataLayout();
6596
6597   ArgListTy Args;
6598   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6599   SDValue SRet;
6600   if (ShouldUseSRet) {
6601     // Create stack object for sret.
6602     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6603     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6604     int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6605     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6606
6607     ArgListEntry Entry;
6608     Entry.Node = SRet;
6609     Entry.Ty = RetTy->getPointerTo();
6610     Entry.isSExt = false;
6611     Entry.isZExt = false;
6612     Entry.isSRet = true;
6613     Args.push_back(Entry);
6614     RetTy = Type::getVoidTy(*DAG.getContext());
6615   }
6616
6617   ArgListEntry Entry;
6618   Entry.Node = Arg;
6619   Entry.Ty = ArgTy;
6620   Entry.isSExt = false;
6621   Entry.isZExt = false;
6622   Args.push_back(Entry);
6623
6624   const char *LibcallName =
6625       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6626   RTLIB::Libcall LC =
6627       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6628   CallingConv::ID CC = getLibcallCallingConv(LC);
6629   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6630
6631   TargetLowering::CallLoweringInfo CLI(DAG);
6632   CLI.setDebugLoc(dl)
6633       .setChain(DAG.getEntryNode())
6634       .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6635       .setDiscardResult(ShouldUseSRet);
6636   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6637
6638   if (!ShouldUseSRet)
6639     return CallResult.first;
6640
6641   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6642                                 MachinePointerInfo(), false, false, false, 0);
6643
6644   // Address of cos field.
6645   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6646                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6647   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6648                                 MachinePointerInfo(), false, false, false, 0);
6649
6650   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6651   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6652                      LoadSin.getValue(0), LoadCos.getValue(0));
6653 }
6654
6655 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6656                                                   bool Signed,
6657                                                   SDValue &Chain) const {
6658   EVT VT = Op.getValueType();
6659   assert((VT == MVT::i32 || VT == MVT::i64) &&
6660          "unexpected type for custom lowering DIV");
6661   SDLoc dl(Op);
6662
6663   const auto &DL = DAG.getDataLayout();
6664   const auto &TLI = DAG.getTargetLoweringInfo();
6665
6666   const char *Name = nullptr;
6667   if (Signed)
6668     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6669   else
6670     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6671
6672   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6673
6674   ARMTargetLowering::ArgListTy Args;
6675
6676   for (auto AI : {1, 0}) {
6677     ArgListEntry Arg;
6678     Arg.Node = Op.getOperand(AI);
6679     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6680     Args.push_back(Arg);
6681   }
6682
6683   CallLoweringInfo CLI(DAG);
6684   CLI.setDebugLoc(dl)
6685     .setChain(Chain)
6686     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6687                ES, std::move(Args), 0);
6688
6689   return LowerCallTo(CLI).first;
6690 }
6691
6692 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6693                                             bool Signed) const {
6694   assert(Op.getValueType() == MVT::i32 &&
6695          "unexpected type for custom lowering DIV");
6696   SDLoc dl(Op);
6697
6698   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6699                                DAG.getEntryNode(), Op.getOperand(1));
6700
6701   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6702 }
6703
6704 void ARMTargetLowering::ExpandDIV_Windows(
6705     SDValue Op, SelectionDAG &DAG, bool Signed,
6706     SmallVectorImpl<SDValue> &Results) const {
6707   const auto &DL = DAG.getDataLayout();
6708   const auto &TLI = DAG.getTargetLoweringInfo();
6709
6710   assert(Op.getValueType() == MVT::i64 &&
6711          "unexpected type for custom lowering DIV");
6712   SDLoc dl(Op);
6713
6714   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6715                            DAG.getConstant(0, dl, MVT::i32));
6716   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6717                            DAG.getConstant(1, dl, MVT::i32));
6718   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6719
6720   SDValue DBZCHK =
6721       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6722
6723   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6724
6725   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6726   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6727                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6728   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6729
6730   Results.push_back(Lower);
6731   Results.push_back(Upper);
6732 }
6733
6734 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6735   // Monotonic load/store is legal for all targets
6736   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6737     return Op;
6738
6739   // Acquire/Release load/store is not legal for targets without a
6740   // dmb or equivalent available.
6741   return SDValue();
6742 }
6743
6744 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6745                                     SmallVectorImpl<SDValue> &Results,
6746                                     SelectionDAG &DAG,
6747                                     const ARMSubtarget *Subtarget) {
6748   SDLoc DL(N);
6749   // Under Power Management extensions, the cycle-count is:
6750   //    mrc p15, #0, <Rt>, c9, c13, #0
6751   SDValue Ops[] = { N->getOperand(0), // Chain
6752                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6753                     DAG.getConstant(15, DL, MVT::i32),
6754                     DAG.getConstant(0, DL, MVT::i32),
6755                     DAG.getConstant(9, DL, MVT::i32),
6756                     DAG.getConstant(13, DL, MVT::i32),
6757                     DAG.getConstant(0, DL, MVT::i32)
6758   };
6759
6760   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6761                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6762   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6763                                 DAG.getConstant(0, DL, MVT::i32)));
6764   Results.push_back(Cycles32.getValue(1));
6765 }
6766
6767 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6768   switch (Op.getOpcode()) {
6769   default: llvm_unreachable("Don't know how to custom lower this!");
6770   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6771   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6772   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6773   case ISD::GlobalAddress:
6774     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6775     default: llvm_unreachable("unknown object format");
6776     case Triple::COFF:
6777       return LowerGlobalAddressWindows(Op, DAG);
6778     case Triple::ELF:
6779       return LowerGlobalAddressELF(Op, DAG);
6780     case Triple::MachO:
6781       return LowerGlobalAddressDarwin(Op, DAG);
6782     }
6783   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6784   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6785   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6786   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6787   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6788   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6789   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6790   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6791   case ISD::SINT_TO_FP:
6792   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6793   case ISD::FP_TO_SINT:
6794   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6795   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6796   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6797   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6798   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6799   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6800   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6801   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6802                                                                Subtarget);
6803   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6804   case ISD::SHL:
6805   case ISD::SRL:
6806   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6807   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6808   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6809   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6810   case ISD::SRL_PARTS:
6811   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6812   case ISD::CTTZ:
6813   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6814   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6815   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6816   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6817   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6818   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6819   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6820   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6821   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6822   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6823   case ISD::MUL:           return LowerMUL(Op, DAG);
6824   case ISD::SDIV:
6825     if (Subtarget->isTargetWindows())
6826       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6827     return LowerSDIV(Op, DAG);
6828   case ISD::UDIV:
6829     if (Subtarget->isTargetWindows())
6830       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6831     return LowerUDIV(Op, DAG);
6832   case ISD::ADDC:
6833   case ISD::ADDE:
6834   case ISD::SUBC:
6835   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6836   case ISD::SADDO:
6837   case ISD::UADDO:
6838   case ISD::SSUBO:
6839   case ISD::USUBO:
6840     return LowerXALUO(Op, DAG);
6841   case ISD::ATOMIC_LOAD:
6842   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6843   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6844   case ISD::SDIVREM:
6845   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6846   case ISD::DYNAMIC_STACKALLOC:
6847     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6848       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6849     llvm_unreachable("Don't know how to custom lower this!");
6850   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6851   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6852   case ARMISD::WIN__DBZCHK: return SDValue();
6853   }
6854 }
6855
6856 /// ReplaceNodeResults - Replace the results of node with an illegal result
6857 /// type with new values built out of custom code.
6858 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6859                                            SmallVectorImpl<SDValue> &Results,
6860                                            SelectionDAG &DAG) const {
6861   SDValue Res;
6862   switch (N->getOpcode()) {
6863   default:
6864     llvm_unreachable("Don't know how to custom expand this!");
6865   case ISD::READ_REGISTER:
6866     ExpandREAD_REGISTER(N, Results, DAG);
6867     break;
6868   case ISD::BITCAST:
6869     Res = ExpandBITCAST(N, DAG);
6870     break;
6871   case ISD::SRL:
6872   case ISD::SRA:
6873     Res = Expand64BitShift(N, DAG, Subtarget);
6874     break;
6875   case ISD::SREM:
6876   case ISD::UREM:
6877     Res = LowerREM(N, DAG);
6878     break;
6879   case ISD::READCYCLECOUNTER:
6880     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6881     return;
6882   case ISD::UDIV:
6883   case ISD::SDIV:
6884     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6885     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6886                              Results);
6887   }
6888   if (Res.getNode())
6889     Results.push_back(Res);
6890 }
6891
6892 //===----------------------------------------------------------------------===//
6893 //                           ARM Scheduler Hooks
6894 //===----------------------------------------------------------------------===//
6895
6896 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6897 /// registers the function context.
6898 void ARMTargetLowering::
6899 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6900                        MachineBasicBlock *DispatchBB, int FI) const {
6901   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6902   DebugLoc dl = MI->getDebugLoc();
6903   MachineFunction *MF = MBB->getParent();
6904   MachineRegisterInfo *MRI = &MF->getRegInfo();
6905   MachineConstantPool *MCP = MF->getConstantPool();
6906   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6907   const Function *F = MF->getFunction();
6908
6909   bool isThumb = Subtarget->isThumb();
6910   bool isThumb2 = Subtarget->isThumb2();
6911
6912   unsigned PCLabelId = AFI->createPICLabelUId();
6913   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6914   ARMConstantPoolValue *CPV =
6915     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6916   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6917
6918   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6919                                            : &ARM::GPRRegClass;
6920
6921   // Grab constant pool and fixed stack memory operands.
6922   MachineMemOperand *CPMMO =
6923       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6924                                MachineMemOperand::MOLoad, 4, 4);
6925
6926   MachineMemOperand *FIMMOSt =
6927       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6928                                MachineMemOperand::MOStore, 4, 4);
6929
6930   // Load the address of the dispatch MBB into the jump buffer.
6931   if (isThumb2) {
6932     // Incoming value: jbuf
6933     //   ldr.n  r5, LCPI1_1
6934     //   orr    r5, r5, #1
6935     //   add    r5, pc
6936     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6937     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6938     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6939                    .addConstantPoolIndex(CPI)
6940                    .addMemOperand(CPMMO));
6941     // Set the low bit because of thumb mode.
6942     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6943     AddDefaultCC(
6944       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6945                      .addReg(NewVReg1, RegState::Kill)
6946                      .addImm(0x01)));
6947     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6948     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6949       .addReg(NewVReg2, RegState::Kill)
6950       .addImm(PCLabelId);
6951     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6952                    .addReg(NewVReg3, RegState::Kill)
6953                    .addFrameIndex(FI)
6954                    .addImm(36)  // &jbuf[1] :: pc
6955                    .addMemOperand(FIMMOSt));
6956   } else if (isThumb) {
6957     // Incoming value: jbuf
6958     //   ldr.n  r1, LCPI1_4
6959     //   add    r1, pc
6960     //   mov    r2, #1
6961     //   orrs   r1, r2
6962     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6963     //   str    r1, [r2]
6964     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6965     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6966                    .addConstantPoolIndex(CPI)
6967                    .addMemOperand(CPMMO));
6968     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6969     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6970       .addReg(NewVReg1, RegState::Kill)
6971       .addImm(PCLabelId);
6972     // Set the low bit because of thumb mode.
6973     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6974     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6975                    .addReg(ARM::CPSR, RegState::Define)
6976                    .addImm(1));
6977     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6978     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6979                    .addReg(ARM::CPSR, RegState::Define)
6980                    .addReg(NewVReg2, RegState::Kill)
6981                    .addReg(NewVReg3, RegState::Kill));
6982     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6983     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6984             .addFrameIndex(FI)
6985             .addImm(36); // &jbuf[1] :: pc
6986     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6987                    .addReg(NewVReg4, RegState::Kill)
6988                    .addReg(NewVReg5, RegState::Kill)
6989                    .addImm(0)
6990                    .addMemOperand(FIMMOSt));
6991   } else {
6992     // Incoming value: jbuf
6993     //   ldr  r1, LCPI1_1
6994     //   add  r1, pc, r1
6995     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6996     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6997     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6998                    .addConstantPoolIndex(CPI)
6999                    .addImm(0)
7000                    .addMemOperand(CPMMO));
7001     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7002     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7003                    .addReg(NewVReg1, RegState::Kill)
7004                    .addImm(PCLabelId));
7005     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7006                    .addReg(NewVReg2, RegState::Kill)
7007                    .addFrameIndex(FI)
7008                    .addImm(36)  // &jbuf[1] :: pc
7009                    .addMemOperand(FIMMOSt));
7010   }
7011 }
7012
7013 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7014                                               MachineBasicBlock *MBB) const {
7015   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7016   DebugLoc dl = MI->getDebugLoc();
7017   MachineFunction *MF = MBB->getParent();
7018   MachineRegisterInfo *MRI = &MF->getRegInfo();
7019   MachineFrameInfo *MFI = MF->getFrameInfo();
7020   int FI = MFI->getFunctionContextIndex();
7021
7022   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7023                                                         : &ARM::GPRnopcRegClass;
7024
7025   // Get a mapping of the call site numbers to all of the landing pads they're
7026   // associated with.
7027   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7028   unsigned MaxCSNum = 0;
7029   MachineModuleInfo &MMI = MF->getMMI();
7030   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7031        ++BB) {
7032     if (!BB->isEHPad()) continue;
7033
7034     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7035     // pad.
7036     for (MachineBasicBlock::iterator
7037            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7038       if (!II->isEHLabel()) continue;
7039
7040       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7041       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7042
7043       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7044       for (SmallVectorImpl<unsigned>::iterator
7045              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7046            CSI != CSE; ++CSI) {
7047         CallSiteNumToLPad[*CSI].push_back(&*BB);
7048         MaxCSNum = std::max(MaxCSNum, *CSI);
7049       }
7050       break;
7051     }
7052   }
7053
7054   // Get an ordered list of the machine basic blocks for the jump table.
7055   std::vector<MachineBasicBlock*> LPadList;
7056   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7057   LPadList.reserve(CallSiteNumToLPad.size());
7058   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7059     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7060     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7061            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7062       LPadList.push_back(*II);
7063       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7064     }
7065   }
7066
7067   assert(!LPadList.empty() &&
7068          "No landing pad destinations for the dispatch jump table!");
7069
7070   // Create the jump table and associated information.
7071   MachineJumpTableInfo *JTI =
7072     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7073   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7074   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7075
7076   // Create the MBBs for the dispatch code.
7077
7078   // Shove the dispatch's address into the return slot in the function context.
7079   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7080   DispatchBB->setIsEHPad();
7081
7082   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7083   unsigned trap_opcode;
7084   if (Subtarget->isThumb())
7085     trap_opcode = ARM::tTRAP;
7086   else
7087     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7088
7089   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7090   DispatchBB->addSuccessor(TrapBB);
7091
7092   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7093   DispatchBB->addSuccessor(DispContBB);
7094
7095   // Insert and MBBs.
7096   MF->insert(MF->end(), DispatchBB);
7097   MF->insert(MF->end(), DispContBB);
7098   MF->insert(MF->end(), TrapBB);
7099
7100   // Insert code into the entry block that creates and registers the function
7101   // context.
7102   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7103
7104   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7105       MachinePointerInfo::getFixedStack(*MF, FI),
7106       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7107
7108   MachineInstrBuilder MIB;
7109   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7110
7111   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7112   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7113
7114   // Add a register mask with no preserved registers.  This results in all
7115   // registers being marked as clobbered.
7116   MIB.addRegMask(RI.getNoPreservedMask());
7117
7118   unsigned NumLPads = LPadList.size();
7119   if (Subtarget->isThumb2()) {
7120     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7121     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7122                    .addFrameIndex(FI)
7123                    .addImm(4)
7124                    .addMemOperand(FIMMOLd));
7125
7126     if (NumLPads < 256) {
7127       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7128                      .addReg(NewVReg1)
7129                      .addImm(LPadList.size()));
7130     } else {
7131       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7132       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7133                      .addImm(NumLPads & 0xFFFF));
7134
7135       unsigned VReg2 = VReg1;
7136       if ((NumLPads & 0xFFFF0000) != 0) {
7137         VReg2 = MRI->createVirtualRegister(TRC);
7138         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7139                        .addReg(VReg1)
7140                        .addImm(NumLPads >> 16));
7141       }
7142
7143       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7144                      .addReg(NewVReg1)
7145                      .addReg(VReg2));
7146     }
7147
7148     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7149       .addMBB(TrapBB)
7150       .addImm(ARMCC::HI)
7151       .addReg(ARM::CPSR);
7152
7153     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7154     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7155                    .addJumpTableIndex(MJTI));
7156
7157     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7158     AddDefaultCC(
7159       AddDefaultPred(
7160         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7161         .addReg(NewVReg3, RegState::Kill)
7162         .addReg(NewVReg1)
7163         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7164
7165     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7166       .addReg(NewVReg4, RegState::Kill)
7167       .addReg(NewVReg1)
7168       .addJumpTableIndex(MJTI);
7169   } else if (Subtarget->isThumb()) {
7170     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7171     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7172                    .addFrameIndex(FI)
7173                    .addImm(1)
7174                    .addMemOperand(FIMMOLd));
7175
7176     if (NumLPads < 256) {
7177       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7178                      .addReg(NewVReg1)
7179                      .addImm(NumLPads));
7180     } else {
7181       MachineConstantPool *ConstantPool = MF->getConstantPool();
7182       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7183       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7184
7185       // MachineConstantPool wants an explicit alignment.
7186       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7187       if (Align == 0)
7188         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7189       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7190
7191       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7192       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7193                      .addReg(VReg1, RegState::Define)
7194                      .addConstantPoolIndex(Idx));
7195       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7196                      .addReg(NewVReg1)
7197                      .addReg(VReg1));
7198     }
7199
7200     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7201       .addMBB(TrapBB)
7202       .addImm(ARMCC::HI)
7203       .addReg(ARM::CPSR);
7204
7205     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7206     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7207                    .addReg(ARM::CPSR, RegState::Define)
7208                    .addReg(NewVReg1)
7209                    .addImm(2));
7210
7211     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7212     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7213                    .addJumpTableIndex(MJTI));
7214
7215     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7216     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7217                    .addReg(ARM::CPSR, RegState::Define)
7218                    .addReg(NewVReg2, RegState::Kill)
7219                    .addReg(NewVReg3));
7220
7221     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7222         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7223
7224     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7225     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7226                    .addReg(NewVReg4, RegState::Kill)
7227                    .addImm(0)
7228                    .addMemOperand(JTMMOLd));
7229
7230     unsigned NewVReg6 = NewVReg5;
7231     if (RelocM == Reloc::PIC_) {
7232       NewVReg6 = MRI->createVirtualRegister(TRC);
7233       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7234                      .addReg(ARM::CPSR, RegState::Define)
7235                      .addReg(NewVReg5, RegState::Kill)
7236                      .addReg(NewVReg3));
7237     }
7238
7239     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7240       .addReg(NewVReg6, RegState::Kill)
7241       .addJumpTableIndex(MJTI);
7242   } else {
7243     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7244     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7245                    .addFrameIndex(FI)
7246                    .addImm(4)
7247                    .addMemOperand(FIMMOLd));
7248
7249     if (NumLPads < 256) {
7250       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7251                      .addReg(NewVReg1)
7252                      .addImm(NumLPads));
7253     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7254       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7255       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7256                      .addImm(NumLPads & 0xFFFF));
7257
7258       unsigned VReg2 = VReg1;
7259       if ((NumLPads & 0xFFFF0000) != 0) {
7260         VReg2 = MRI->createVirtualRegister(TRC);
7261         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7262                        .addReg(VReg1)
7263                        .addImm(NumLPads >> 16));
7264       }
7265
7266       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7267                      .addReg(NewVReg1)
7268                      .addReg(VReg2));
7269     } else {
7270       MachineConstantPool *ConstantPool = MF->getConstantPool();
7271       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7272       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7273
7274       // MachineConstantPool wants an explicit alignment.
7275       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7276       if (Align == 0)
7277         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7278       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7279
7280       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7281       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7282                      .addReg(VReg1, RegState::Define)
7283                      .addConstantPoolIndex(Idx)
7284                      .addImm(0));
7285       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7286                      .addReg(NewVReg1)
7287                      .addReg(VReg1, RegState::Kill));
7288     }
7289
7290     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7291       .addMBB(TrapBB)
7292       .addImm(ARMCC::HI)
7293       .addReg(ARM::CPSR);
7294
7295     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7296     AddDefaultCC(
7297       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7298                      .addReg(NewVReg1)
7299                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7300     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7301     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7302                    .addJumpTableIndex(MJTI));
7303
7304     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7305         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7306     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7307     AddDefaultPred(
7308       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7309       .addReg(NewVReg3, RegState::Kill)
7310       .addReg(NewVReg4)
7311       .addImm(0)
7312       .addMemOperand(JTMMOLd));
7313
7314     if (RelocM == Reloc::PIC_) {
7315       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7316         .addReg(NewVReg5, RegState::Kill)
7317         .addReg(NewVReg4)
7318         .addJumpTableIndex(MJTI);
7319     } else {
7320       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7321         .addReg(NewVReg5, RegState::Kill)
7322         .addJumpTableIndex(MJTI);
7323     }
7324   }
7325
7326   // Add the jump table entries as successors to the MBB.
7327   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7328   for (std::vector<MachineBasicBlock*>::iterator
7329          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7330     MachineBasicBlock *CurMBB = *I;
7331     if (SeenMBBs.insert(CurMBB).second)
7332       DispContBB->addSuccessor(CurMBB);
7333   }
7334
7335   // N.B. the order the invoke BBs are processed in doesn't matter here.
7336   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7337   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7338   for (MachineBasicBlock *BB : InvokeBBs) {
7339
7340     // Remove the landing pad successor from the invoke block and replace it
7341     // with the new dispatch block.
7342     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7343                                                   BB->succ_end());
7344     while (!Successors.empty()) {
7345       MachineBasicBlock *SMBB = Successors.pop_back_val();
7346       if (SMBB->isEHPad()) {
7347         BB->removeSuccessor(SMBB);
7348         MBBLPads.push_back(SMBB);
7349       }
7350     }
7351
7352     BB->addSuccessor(DispatchBB);
7353
7354     // Find the invoke call and mark all of the callee-saved registers as
7355     // 'implicit defined' so that they're spilled. This prevents code from
7356     // moving instructions to before the EH block, where they will never be
7357     // executed.
7358     for (MachineBasicBlock::reverse_iterator
7359            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7360       if (!II->isCall()) continue;
7361
7362       DenseMap<unsigned, bool> DefRegs;
7363       for (MachineInstr::mop_iterator
7364              OI = II->operands_begin(), OE = II->operands_end();
7365            OI != OE; ++OI) {
7366         if (!OI->isReg()) continue;
7367         DefRegs[OI->getReg()] = true;
7368       }
7369
7370       MachineInstrBuilder MIB(*MF, &*II);
7371
7372       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7373         unsigned Reg = SavedRegs[i];
7374         if (Subtarget->isThumb2() &&
7375             !ARM::tGPRRegClass.contains(Reg) &&
7376             !ARM::hGPRRegClass.contains(Reg))
7377           continue;
7378         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7379           continue;
7380         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7381           continue;
7382         if (!DefRegs[Reg])
7383           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7384       }
7385
7386       break;
7387     }
7388   }
7389
7390   // Mark all former landing pads as non-landing pads. The dispatch is the only
7391   // landing pad now.
7392   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7393          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7394     (*I)->setIsEHPad(false);
7395
7396   // The instruction is gone now.
7397   MI->eraseFromParent();
7398 }
7399
7400 static
7401 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7402   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7403        E = MBB->succ_end(); I != E; ++I)
7404     if (*I != Succ)
7405       return *I;
7406   llvm_unreachable("Expecting a BB with two successors!");
7407 }
7408
7409 /// Return the load opcode for a given load size. If load size >= 8,
7410 /// neon opcode will be returned.
7411 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7412   if (LdSize >= 8)
7413     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7414                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7415   if (IsThumb1)
7416     return LdSize == 4 ? ARM::tLDRi
7417                        : LdSize == 2 ? ARM::tLDRHi
7418                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7419   if (IsThumb2)
7420     return LdSize == 4 ? ARM::t2LDR_POST
7421                        : LdSize == 2 ? ARM::t2LDRH_POST
7422                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7423   return LdSize == 4 ? ARM::LDR_POST_IMM
7424                      : LdSize == 2 ? ARM::LDRH_POST
7425                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7426 }
7427
7428 /// Return the store opcode for a given store size. If store size >= 8,
7429 /// neon opcode will be returned.
7430 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7431   if (StSize >= 8)
7432     return StSize == 16 ? ARM::VST1q32wb_fixed
7433                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7434   if (IsThumb1)
7435     return StSize == 4 ? ARM::tSTRi
7436                        : StSize == 2 ? ARM::tSTRHi
7437                                      : StSize == 1 ? ARM::tSTRBi : 0;
7438   if (IsThumb2)
7439     return StSize == 4 ? ARM::t2STR_POST
7440                        : StSize == 2 ? ARM::t2STRH_POST
7441                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7442   return StSize == 4 ? ARM::STR_POST_IMM
7443                      : StSize == 2 ? ARM::STRH_POST
7444                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7445 }
7446
7447 /// Emit a post-increment load operation with given size. The instructions
7448 /// will be added to BB at Pos.
7449 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7450                        const TargetInstrInfo *TII, DebugLoc dl,
7451                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7452                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7453   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7454   assert(LdOpc != 0 && "Should have a load opcode");
7455   if (LdSize >= 8) {
7456     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7457                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7458                        .addImm(0));
7459   } else if (IsThumb1) {
7460     // load + update AddrIn
7461     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7462                        .addReg(AddrIn).addImm(0));
7463     MachineInstrBuilder MIB =
7464         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7465     MIB = AddDefaultT1CC(MIB);
7466     MIB.addReg(AddrIn).addImm(LdSize);
7467     AddDefaultPred(MIB);
7468   } else if (IsThumb2) {
7469     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7470                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7471                        .addImm(LdSize));
7472   } else { // arm
7473     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7474                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7475                        .addReg(0).addImm(LdSize));
7476   }
7477 }
7478
7479 /// Emit a post-increment store operation with given size. The instructions
7480 /// will be added to BB at Pos.
7481 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7482                        const TargetInstrInfo *TII, DebugLoc dl,
7483                        unsigned StSize, unsigned Data, unsigned AddrIn,
7484                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7485   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7486   assert(StOpc != 0 && "Should have a store opcode");
7487   if (StSize >= 8) {
7488     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7489                        .addReg(AddrIn).addImm(0).addReg(Data));
7490   } else if (IsThumb1) {
7491     // store + update AddrIn
7492     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7493                        .addReg(AddrIn).addImm(0));
7494     MachineInstrBuilder MIB =
7495         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7496     MIB = AddDefaultT1CC(MIB);
7497     MIB.addReg(AddrIn).addImm(StSize);
7498     AddDefaultPred(MIB);
7499   } else if (IsThumb2) {
7500     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7501                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7502   } else { // arm
7503     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7504                        .addReg(Data).addReg(AddrIn).addReg(0)
7505                        .addImm(StSize));
7506   }
7507 }
7508
7509 MachineBasicBlock *
7510 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7511                                    MachineBasicBlock *BB) const {
7512   // This pseudo instruction has 3 operands: dst, src, size
7513   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7514   // Otherwise, we will generate unrolled scalar copies.
7515   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7516   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7517   MachineFunction::iterator It = ++BB->getIterator();
7518
7519   unsigned dest = MI->getOperand(0).getReg();
7520   unsigned src = MI->getOperand(1).getReg();
7521   unsigned SizeVal = MI->getOperand(2).getImm();
7522   unsigned Align = MI->getOperand(3).getImm();
7523   DebugLoc dl = MI->getDebugLoc();
7524
7525   MachineFunction *MF = BB->getParent();
7526   MachineRegisterInfo &MRI = MF->getRegInfo();
7527   unsigned UnitSize = 0;
7528   const TargetRegisterClass *TRC = nullptr;
7529   const TargetRegisterClass *VecTRC = nullptr;
7530
7531   bool IsThumb1 = Subtarget->isThumb1Only();
7532   bool IsThumb2 = Subtarget->isThumb2();
7533
7534   if (Align & 1) {
7535     UnitSize = 1;
7536   } else if (Align & 2) {
7537     UnitSize = 2;
7538   } else {
7539     // Check whether we can use NEON instructions.
7540     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7541         Subtarget->hasNEON()) {
7542       if ((Align % 16 == 0) && SizeVal >= 16)
7543         UnitSize = 16;
7544       else if ((Align % 8 == 0) && SizeVal >= 8)
7545         UnitSize = 8;
7546     }
7547     // Can't use NEON instructions.
7548     if (UnitSize == 0)
7549       UnitSize = 4;
7550   }
7551
7552   // Select the correct opcode and register class for unit size load/store
7553   bool IsNeon = UnitSize >= 8;
7554   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7555   if (IsNeon)
7556     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7557                             : UnitSize == 8 ? &ARM::DPRRegClass
7558                                             : nullptr;
7559
7560   unsigned BytesLeft = SizeVal % UnitSize;
7561   unsigned LoopSize = SizeVal - BytesLeft;
7562
7563   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7564     // Use LDR and STR to copy.
7565     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7566     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7567     unsigned srcIn = src;
7568     unsigned destIn = dest;
7569     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7570       unsigned srcOut = MRI.createVirtualRegister(TRC);
7571       unsigned destOut = MRI.createVirtualRegister(TRC);
7572       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7573       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7574                  IsThumb1, IsThumb2);
7575       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7576                  IsThumb1, IsThumb2);
7577       srcIn = srcOut;
7578       destIn = destOut;
7579     }
7580
7581     // Handle the leftover bytes with LDRB and STRB.
7582     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7583     // [destOut] = STRB_POST(scratch, destIn, 1)
7584     for (unsigned i = 0; i < BytesLeft; i++) {
7585       unsigned srcOut = MRI.createVirtualRegister(TRC);
7586       unsigned destOut = MRI.createVirtualRegister(TRC);
7587       unsigned scratch = MRI.createVirtualRegister(TRC);
7588       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7589                  IsThumb1, IsThumb2);
7590       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7591                  IsThumb1, IsThumb2);
7592       srcIn = srcOut;
7593       destIn = destOut;
7594     }
7595     MI->eraseFromParent();   // The instruction is gone now.
7596     return BB;
7597   }
7598
7599   // Expand the pseudo op to a loop.
7600   // thisMBB:
7601   //   ...
7602   //   movw varEnd, # --> with thumb2
7603   //   movt varEnd, #
7604   //   ldrcp varEnd, idx --> without thumb2
7605   //   fallthrough --> loopMBB
7606   // loopMBB:
7607   //   PHI varPhi, varEnd, varLoop
7608   //   PHI srcPhi, src, srcLoop
7609   //   PHI destPhi, dst, destLoop
7610   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7611   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7612   //   subs varLoop, varPhi, #UnitSize
7613   //   bne loopMBB
7614   //   fallthrough --> exitMBB
7615   // exitMBB:
7616   //   epilogue to handle left-over bytes
7617   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7618   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7619   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7620   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7621   MF->insert(It, loopMBB);
7622   MF->insert(It, exitMBB);
7623
7624   // Transfer the remainder of BB and its successor edges to exitMBB.
7625   exitMBB->splice(exitMBB->begin(), BB,
7626                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7627   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7628
7629   // Load an immediate to varEnd.
7630   unsigned varEnd = MRI.createVirtualRegister(TRC);
7631   if (Subtarget->useMovt(*MF)) {
7632     unsigned Vtmp = varEnd;
7633     if ((LoopSize & 0xFFFF0000) != 0)
7634       Vtmp = MRI.createVirtualRegister(TRC);
7635     AddDefaultPred(BuildMI(BB, dl,
7636                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7637                            Vtmp).addImm(LoopSize & 0xFFFF));
7638
7639     if ((LoopSize & 0xFFFF0000) != 0)
7640       AddDefaultPred(BuildMI(BB, dl,
7641                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7642                              varEnd)
7643                          .addReg(Vtmp)
7644                          .addImm(LoopSize >> 16));
7645   } else {
7646     MachineConstantPool *ConstantPool = MF->getConstantPool();
7647     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7648     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7649
7650     // MachineConstantPool wants an explicit alignment.
7651     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7652     if (Align == 0)
7653       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7654     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7655
7656     if (IsThumb1)
7657       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7658           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7659     else
7660       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7661           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7662   }
7663   BB->addSuccessor(loopMBB);
7664
7665   // Generate the loop body:
7666   //   varPhi = PHI(varLoop, varEnd)
7667   //   srcPhi = PHI(srcLoop, src)
7668   //   destPhi = PHI(destLoop, dst)
7669   MachineBasicBlock *entryBB = BB;
7670   BB = loopMBB;
7671   unsigned varLoop = MRI.createVirtualRegister(TRC);
7672   unsigned varPhi = MRI.createVirtualRegister(TRC);
7673   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7674   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7675   unsigned destLoop = MRI.createVirtualRegister(TRC);
7676   unsigned destPhi = MRI.createVirtualRegister(TRC);
7677
7678   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7679     .addReg(varLoop).addMBB(loopMBB)
7680     .addReg(varEnd).addMBB(entryBB);
7681   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7682     .addReg(srcLoop).addMBB(loopMBB)
7683     .addReg(src).addMBB(entryBB);
7684   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7685     .addReg(destLoop).addMBB(loopMBB)
7686     .addReg(dest).addMBB(entryBB);
7687
7688   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7689   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7690   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7691   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7692              IsThumb1, IsThumb2);
7693   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7694              IsThumb1, IsThumb2);
7695
7696   // Decrement loop variable by UnitSize.
7697   if (IsThumb1) {
7698     MachineInstrBuilder MIB =
7699         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7700     MIB = AddDefaultT1CC(MIB);
7701     MIB.addReg(varPhi).addImm(UnitSize);
7702     AddDefaultPred(MIB);
7703   } else {
7704     MachineInstrBuilder MIB =
7705         BuildMI(*BB, BB->end(), dl,
7706                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7707     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7708     MIB->getOperand(5).setReg(ARM::CPSR);
7709     MIB->getOperand(5).setIsDef(true);
7710   }
7711   BuildMI(*BB, BB->end(), dl,
7712           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7713       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7714
7715   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7716   BB->addSuccessor(loopMBB);
7717   BB->addSuccessor(exitMBB);
7718
7719   // Add epilogue to handle BytesLeft.
7720   BB = exitMBB;
7721   MachineInstr *StartOfExit = exitMBB->begin();
7722
7723   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7724   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7725   unsigned srcIn = srcLoop;
7726   unsigned destIn = destLoop;
7727   for (unsigned i = 0; i < BytesLeft; i++) {
7728     unsigned srcOut = MRI.createVirtualRegister(TRC);
7729     unsigned destOut = MRI.createVirtualRegister(TRC);
7730     unsigned scratch = MRI.createVirtualRegister(TRC);
7731     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7732                IsThumb1, IsThumb2);
7733     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7734                IsThumb1, IsThumb2);
7735     srcIn = srcOut;
7736     destIn = destOut;
7737   }
7738
7739   MI->eraseFromParent();   // The instruction is gone now.
7740   return BB;
7741 }
7742
7743 MachineBasicBlock *
7744 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7745                                        MachineBasicBlock *MBB) const {
7746   const TargetMachine &TM = getTargetMachine();
7747   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7748   DebugLoc DL = MI->getDebugLoc();
7749
7750   assert(Subtarget->isTargetWindows() &&
7751          "__chkstk is only supported on Windows");
7752   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7753
7754   // __chkstk takes the number of words to allocate on the stack in R4, and
7755   // returns the stack adjustment in number of bytes in R4.  This will not
7756   // clober any other registers (other than the obvious lr).
7757   //
7758   // Although, technically, IP should be considered a register which may be
7759   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7760   // thumb-2 environment, so there is no interworking required.  As a result, we
7761   // do not expect a veneer to be emitted by the linker, clobbering IP.
7762   //
7763   // Each module receives its own copy of __chkstk, so no import thunk is
7764   // required, again, ensuring that IP is not clobbered.
7765   //
7766   // Finally, although some linkers may theoretically provide a trampoline for
7767   // out of range calls (which is quite common due to a 32M range limitation of
7768   // branches for Thumb), we can generate the long-call version via
7769   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7770   // IP.
7771
7772   switch (TM.getCodeModel()) {
7773   case CodeModel::Small:
7774   case CodeModel::Medium:
7775   case CodeModel::Default:
7776   case CodeModel::Kernel:
7777     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7778       .addImm((unsigned)ARMCC::AL).addReg(0)
7779       .addExternalSymbol("__chkstk")
7780       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7781       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7782       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7783     break;
7784   case CodeModel::Large:
7785   case CodeModel::JITDefault: {
7786     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7787     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7788
7789     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7790       .addExternalSymbol("__chkstk");
7791     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7792       .addImm((unsigned)ARMCC::AL).addReg(0)
7793       .addReg(Reg, RegState::Kill)
7794       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7795       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7796       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7797     break;
7798   }
7799   }
7800
7801   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7802                                       ARM::SP)
7803                               .addReg(ARM::SP).addReg(ARM::R4)));
7804
7805   MI->eraseFromParent();
7806   return MBB;
7807 }
7808
7809 MachineBasicBlock *
7810 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7811                                        MachineBasicBlock *MBB) const {
7812   DebugLoc DL = MI->getDebugLoc();
7813   MachineFunction *MF = MBB->getParent();
7814   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7815
7816   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7817   MF->push_back(ContBB);
7818   ContBB->splice(ContBB->begin(), MBB,
7819                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7820   MBB->addSuccessor(ContBB);
7821
7822   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7823   MF->push_back(TrapBB);
7824   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7825   MBB->addSuccessor(TrapBB);
7826
7827   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7828       .addReg(MI->getOperand(0).getReg())
7829       .addMBB(TrapBB);
7830
7831   MI->eraseFromParent();
7832   return ContBB;
7833 }
7834
7835 MachineBasicBlock *
7836 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7837                                                MachineBasicBlock *BB) const {
7838   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7839   DebugLoc dl = MI->getDebugLoc();
7840   bool isThumb2 = Subtarget->isThumb2();
7841   switch (MI->getOpcode()) {
7842   default: {
7843     MI->dump();
7844     llvm_unreachable("Unexpected instr type to insert");
7845   }
7846   // The Thumb2 pre-indexed stores have the same MI operands, they just
7847   // define them differently in the .td files from the isel patterns, so
7848   // they need pseudos.
7849   case ARM::t2STR_preidx:
7850     MI->setDesc(TII->get(ARM::t2STR_PRE));
7851     return BB;
7852   case ARM::t2STRB_preidx:
7853     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7854     return BB;
7855   case ARM::t2STRH_preidx:
7856     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7857     return BB;
7858
7859   case ARM::STRi_preidx:
7860   case ARM::STRBi_preidx: {
7861     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7862       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7863     // Decode the offset.
7864     unsigned Offset = MI->getOperand(4).getImm();
7865     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7866     Offset = ARM_AM::getAM2Offset(Offset);
7867     if (isSub)
7868       Offset = -Offset;
7869
7870     MachineMemOperand *MMO = *MI->memoperands_begin();
7871     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7872       .addOperand(MI->getOperand(0))  // Rn_wb
7873       .addOperand(MI->getOperand(1))  // Rt
7874       .addOperand(MI->getOperand(2))  // Rn
7875       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7876       .addOperand(MI->getOperand(5))  // pred
7877       .addOperand(MI->getOperand(6))
7878       .addMemOperand(MMO);
7879     MI->eraseFromParent();
7880     return BB;
7881   }
7882   case ARM::STRr_preidx:
7883   case ARM::STRBr_preidx:
7884   case ARM::STRH_preidx: {
7885     unsigned NewOpc;
7886     switch (MI->getOpcode()) {
7887     default: llvm_unreachable("unexpected opcode!");
7888     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7889     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7890     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7891     }
7892     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7893     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7894       MIB.addOperand(MI->getOperand(i));
7895     MI->eraseFromParent();
7896     return BB;
7897   }
7898
7899   case ARM::tMOVCCr_pseudo: {
7900     // To "insert" a SELECT_CC instruction, we actually have to insert the
7901     // diamond control-flow pattern.  The incoming instruction knows the
7902     // destination vreg to set, the condition code register to branch on, the
7903     // true/false values to select between, and a branch opcode to use.
7904     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7905     MachineFunction::iterator It = ++BB->getIterator();
7906
7907     //  thisMBB:
7908     //  ...
7909     //   TrueVal = ...
7910     //   cmpTY ccX, r1, r2
7911     //   bCC copy1MBB
7912     //   fallthrough --> copy0MBB
7913     MachineBasicBlock *thisMBB  = BB;
7914     MachineFunction *F = BB->getParent();
7915     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7916     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7917     F->insert(It, copy0MBB);
7918     F->insert(It, sinkMBB);
7919
7920     // Transfer the remainder of BB and its successor edges to sinkMBB.
7921     sinkMBB->splice(sinkMBB->begin(), BB,
7922                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7923     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7924
7925     BB->addSuccessor(copy0MBB);
7926     BB->addSuccessor(sinkMBB);
7927
7928     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7929       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7930
7931     //  copy0MBB:
7932     //   %FalseValue = ...
7933     //   # fallthrough to sinkMBB
7934     BB = copy0MBB;
7935
7936     // Update machine-CFG edges
7937     BB->addSuccessor(sinkMBB);
7938
7939     //  sinkMBB:
7940     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7941     //  ...
7942     BB = sinkMBB;
7943     BuildMI(*BB, BB->begin(), dl,
7944             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7945       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7946       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7947
7948     MI->eraseFromParent();   // The pseudo instruction is gone now.
7949     return BB;
7950   }
7951
7952   case ARM::BCCi64:
7953   case ARM::BCCZi64: {
7954     // If there is an unconditional branch to the other successor, remove it.
7955     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7956
7957     // Compare both parts that make up the double comparison separately for
7958     // equality.
7959     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7960
7961     unsigned LHS1 = MI->getOperand(1).getReg();
7962     unsigned LHS2 = MI->getOperand(2).getReg();
7963     if (RHSisZero) {
7964       AddDefaultPred(BuildMI(BB, dl,
7965                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7966                      .addReg(LHS1).addImm(0));
7967       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7968         .addReg(LHS2).addImm(0)
7969         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7970     } else {
7971       unsigned RHS1 = MI->getOperand(3).getReg();
7972       unsigned RHS2 = MI->getOperand(4).getReg();
7973       AddDefaultPred(BuildMI(BB, dl,
7974                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7975                      .addReg(LHS1).addReg(RHS1));
7976       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7977         .addReg(LHS2).addReg(RHS2)
7978         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7979     }
7980
7981     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7982     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7983     if (MI->getOperand(0).getImm() == ARMCC::NE)
7984       std::swap(destMBB, exitMBB);
7985
7986     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7987       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7988     if (isThumb2)
7989       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7990     else
7991       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7992
7993     MI->eraseFromParent();   // The pseudo instruction is gone now.
7994     return BB;
7995   }
7996
7997   case ARM::Int_eh_sjlj_setjmp:
7998   case ARM::Int_eh_sjlj_setjmp_nofp:
7999   case ARM::tInt_eh_sjlj_setjmp:
8000   case ARM::t2Int_eh_sjlj_setjmp:
8001   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8002     return BB;
8003
8004   case ARM::Int_eh_sjlj_setup_dispatch:
8005     EmitSjLjDispatchBlock(MI, BB);
8006     return BB;
8007
8008   case ARM::ABS:
8009   case ARM::t2ABS: {
8010     // To insert an ABS instruction, we have to insert the
8011     // diamond control-flow pattern.  The incoming instruction knows the
8012     // source vreg to test against 0, the destination vreg to set,
8013     // the condition code register to branch on, the
8014     // true/false values to select between, and a branch opcode to use.
8015     // It transforms
8016     //     V1 = ABS V0
8017     // into
8018     //     V2 = MOVS V0
8019     //     BCC                      (branch to SinkBB if V0 >= 0)
8020     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8021     //     SinkBB: V1 = PHI(V2, V3)
8022     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8023     MachineFunction::iterator BBI = ++BB->getIterator();
8024     MachineFunction *Fn = BB->getParent();
8025     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8026     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8027     Fn->insert(BBI, RSBBB);
8028     Fn->insert(BBI, SinkBB);
8029
8030     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8031     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8032     bool ABSSrcKIll = MI->getOperand(1).isKill();
8033     bool isThumb2 = Subtarget->isThumb2();
8034     MachineRegisterInfo &MRI = Fn->getRegInfo();
8035     // In Thumb mode S must not be specified if source register is the SP or
8036     // PC and if destination register is the SP, so restrict register class
8037     unsigned NewRsbDstReg =
8038       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8039
8040     // Transfer the remainder of BB and its successor edges to sinkMBB.
8041     SinkBB->splice(SinkBB->begin(), BB,
8042                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8043     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8044
8045     BB->addSuccessor(RSBBB);
8046     BB->addSuccessor(SinkBB);
8047
8048     // fall through to SinkMBB
8049     RSBBB->addSuccessor(SinkBB);
8050
8051     // insert a cmp at the end of BB
8052     AddDefaultPred(BuildMI(BB, dl,
8053                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8054                    .addReg(ABSSrcReg).addImm(0));
8055
8056     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8057     BuildMI(BB, dl,
8058       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8059       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8060
8061     // insert rsbri in RSBBB
8062     // Note: BCC and rsbri will be converted into predicated rsbmi
8063     // by if-conversion pass
8064     BuildMI(*RSBBB, RSBBB->begin(), dl,
8065       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8066       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8067       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8068
8069     // insert PHI in SinkBB,
8070     // reuse ABSDstReg to not change uses of ABS instruction
8071     BuildMI(*SinkBB, SinkBB->begin(), dl,
8072       TII->get(ARM::PHI), ABSDstReg)
8073       .addReg(NewRsbDstReg).addMBB(RSBBB)
8074       .addReg(ABSSrcReg).addMBB(BB);
8075
8076     // remove ABS instruction
8077     MI->eraseFromParent();
8078
8079     // return last added BB
8080     return SinkBB;
8081   }
8082   case ARM::COPY_STRUCT_BYVAL_I32:
8083     ++NumLoopByVals;
8084     return EmitStructByval(MI, BB);
8085   case ARM::WIN__CHKSTK:
8086     return EmitLowered__chkstk(MI, BB);
8087   case ARM::WIN__DBZCHK:
8088     return EmitLowered__dbzchk(MI, BB);
8089   }
8090 }
8091
8092 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8093 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8094 /// instead of as a custom inserter because we need the use list from the SDNode.
8095 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8096                                    MachineInstr *MI, const SDNode *Node) {
8097   bool isThumb1 = Subtarget->isThumb1Only();
8098
8099   DebugLoc DL = MI->getDebugLoc();
8100   MachineFunction *MF = MI->getParent()->getParent();
8101   MachineRegisterInfo &MRI = MF->getRegInfo();
8102   MachineInstrBuilder MIB(*MF, MI);
8103
8104   // If the new dst/src is unused mark it as dead.
8105   if (!Node->hasAnyUseOfValue(0)) {
8106     MI->getOperand(0).setIsDead(true);
8107   }
8108   if (!Node->hasAnyUseOfValue(1)) {
8109     MI->getOperand(1).setIsDead(true);
8110   }
8111
8112   // The MEMCPY both defines and kills the scratch registers.
8113   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8114     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8115                                                          : &ARM::GPRRegClass);
8116     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8117   }
8118 }
8119
8120 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8121                                                       SDNode *Node) const {
8122   if (MI->getOpcode() == ARM::MEMCPY) {
8123     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8124     return;
8125   }
8126
8127   const MCInstrDesc *MCID = &MI->getDesc();
8128   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8129   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8130   // operand is still set to noreg. If needed, set the optional operand's
8131   // register to CPSR, and remove the redundant implicit def.
8132   //
8133   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8134
8135   // Rename pseudo opcodes.
8136   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8137   if (NewOpc) {
8138     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8139     MCID = &TII->get(NewOpc);
8140
8141     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8142            "converted opcode should be the same except for cc_out");
8143
8144     MI->setDesc(*MCID);
8145
8146     // Add the optional cc_out operand
8147     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8148   }
8149   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8150
8151   // Any ARM instruction that sets the 's' bit should specify an optional
8152   // "cc_out" operand in the last operand position.
8153   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8154     assert(!NewOpc && "Optional cc_out operand required");
8155     return;
8156   }
8157   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8158   // since we already have an optional CPSR def.
8159   bool definesCPSR = false;
8160   bool deadCPSR = false;
8161   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8162        i != e; ++i) {
8163     const MachineOperand &MO = MI->getOperand(i);
8164     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8165       definesCPSR = true;
8166       if (MO.isDead())
8167         deadCPSR = true;
8168       MI->RemoveOperand(i);
8169       break;
8170     }
8171   }
8172   if (!definesCPSR) {
8173     assert(!NewOpc && "Optional cc_out operand required");
8174     return;
8175   }
8176   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8177   if (deadCPSR) {
8178     assert(!MI->getOperand(ccOutIdx).getReg() &&
8179            "expect uninitialized optional cc_out operand");
8180     return;
8181   }
8182
8183   // If this instruction was defined with an optional CPSR def and its dag node
8184   // had a live implicit CPSR def, then activate the optional CPSR def.
8185   MachineOperand &MO = MI->getOperand(ccOutIdx);
8186   MO.setReg(ARM::CPSR);
8187   MO.setIsDef(true);
8188 }
8189
8190 //===----------------------------------------------------------------------===//
8191 //                           ARM Optimization Hooks
8192 //===----------------------------------------------------------------------===//
8193
8194 // Helper function that checks if N is a null or all ones constant.
8195 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8196   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8197   if (!C)
8198     return false;
8199   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8200 }
8201
8202 // Return true if N is conditionally 0 or all ones.
8203 // Detects these expressions where cc is an i1 value:
8204 //
8205 //   (select cc 0, y)   [AllOnes=0]
8206 //   (select cc y, 0)   [AllOnes=0]
8207 //   (zext cc)          [AllOnes=0]
8208 //   (sext cc)          [AllOnes=0/1]
8209 //   (select cc -1, y)  [AllOnes=1]
8210 //   (select cc y, -1)  [AllOnes=1]
8211 //
8212 // Invert is set when N is the null/all ones constant when CC is false.
8213 // OtherOp is set to the alternative value of N.
8214 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8215                                        SDValue &CC, bool &Invert,
8216                                        SDValue &OtherOp,
8217                                        SelectionDAG &DAG) {
8218   switch (N->getOpcode()) {
8219   default: return false;
8220   case ISD::SELECT: {
8221     CC = N->getOperand(0);
8222     SDValue N1 = N->getOperand(1);
8223     SDValue N2 = N->getOperand(2);
8224     if (isZeroOrAllOnes(N1, AllOnes)) {
8225       Invert = false;
8226       OtherOp = N2;
8227       return true;
8228     }
8229     if (isZeroOrAllOnes(N2, AllOnes)) {
8230       Invert = true;
8231       OtherOp = N1;
8232       return true;
8233     }
8234     return false;
8235   }
8236   case ISD::ZERO_EXTEND:
8237     // (zext cc) can never be the all ones value.
8238     if (AllOnes)
8239       return false;
8240     // Fall through.
8241   case ISD::SIGN_EXTEND: {
8242     SDLoc dl(N);
8243     EVT VT = N->getValueType(0);
8244     CC = N->getOperand(0);
8245     if (CC.getValueType() != MVT::i1)
8246       return false;
8247     Invert = !AllOnes;
8248     if (AllOnes)
8249       // When looking for an AllOnes constant, N is an sext, and the 'other'
8250       // value is 0.
8251       OtherOp = DAG.getConstant(0, dl, VT);
8252     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8253       // When looking for a 0 constant, N can be zext or sext.
8254       OtherOp = DAG.getConstant(1, dl, VT);
8255     else
8256       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8257                                 VT);
8258     return true;
8259   }
8260   }
8261 }
8262
8263 // Combine a constant select operand into its use:
8264 //
8265 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8266 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8267 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8268 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8269 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8270 //
8271 // The transform is rejected if the select doesn't have a constant operand that
8272 // is null, or all ones when AllOnes is set.
8273 //
8274 // Also recognize sext/zext from i1:
8275 //
8276 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8277 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8278 //
8279 // These transformations eventually create predicated instructions.
8280 //
8281 // @param N       The node to transform.
8282 // @param Slct    The N operand that is a select.
8283 // @param OtherOp The other N operand (x above).
8284 // @param DCI     Context.
8285 // @param AllOnes Require the select constant to be all ones instead of null.
8286 // @returns The new node, or SDValue() on failure.
8287 static
8288 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8289                             TargetLowering::DAGCombinerInfo &DCI,
8290                             bool AllOnes = false) {
8291   SelectionDAG &DAG = DCI.DAG;
8292   EVT VT = N->getValueType(0);
8293   SDValue NonConstantVal;
8294   SDValue CCOp;
8295   bool SwapSelectOps;
8296   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8297                                   NonConstantVal, DAG))
8298     return SDValue();
8299
8300   // Slct is now know to be the desired identity constant when CC is true.
8301   SDValue TrueVal = OtherOp;
8302   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8303                                  OtherOp, NonConstantVal);
8304   // Unless SwapSelectOps says CC should be false.
8305   if (SwapSelectOps)
8306     std::swap(TrueVal, FalseVal);
8307
8308   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8309                      CCOp, TrueVal, FalseVal);
8310 }
8311
8312 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8313 static
8314 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8315                                        TargetLowering::DAGCombinerInfo &DCI) {
8316   SDValue N0 = N->getOperand(0);
8317   SDValue N1 = N->getOperand(1);
8318   if (N0.getNode()->hasOneUse()) {
8319     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8320     if (Result.getNode())
8321       return Result;
8322   }
8323   if (N1.getNode()->hasOneUse()) {
8324     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8325     if (Result.getNode())
8326       return Result;
8327   }
8328   return SDValue();
8329 }
8330
8331 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8332 // (only after legalization).
8333 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8334                                  TargetLowering::DAGCombinerInfo &DCI,
8335                                  const ARMSubtarget *Subtarget) {
8336
8337   // Only perform optimization if after legalize, and if NEON is available. We
8338   // also expected both operands to be BUILD_VECTORs.
8339   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8340       || N0.getOpcode() != ISD::BUILD_VECTOR
8341       || N1.getOpcode() != ISD::BUILD_VECTOR)
8342     return SDValue();
8343
8344   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8345   EVT VT = N->getValueType(0);
8346   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8347     return SDValue();
8348
8349   // Check that the vector operands are of the right form.
8350   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8351   // operands, where N is the size of the formed vector.
8352   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8353   // index such that we have a pair wise add pattern.
8354
8355   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8356   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8357     return SDValue();
8358   SDValue Vec = N0->getOperand(0)->getOperand(0);
8359   SDNode *V = Vec.getNode();
8360   unsigned nextIndex = 0;
8361
8362   // For each operands to the ADD which are BUILD_VECTORs,
8363   // check to see if each of their operands are an EXTRACT_VECTOR with
8364   // the same vector and appropriate index.
8365   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8366     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8367         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8368
8369       SDValue ExtVec0 = N0->getOperand(i);
8370       SDValue ExtVec1 = N1->getOperand(i);
8371
8372       // First operand is the vector, verify its the same.
8373       if (V != ExtVec0->getOperand(0).getNode() ||
8374           V != ExtVec1->getOperand(0).getNode())
8375         return SDValue();
8376
8377       // Second is the constant, verify its correct.
8378       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8379       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8380
8381       // For the constant, we want to see all the even or all the odd.
8382       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8383           || C1->getZExtValue() != nextIndex+1)
8384         return SDValue();
8385
8386       // Increment index.
8387       nextIndex+=2;
8388     } else
8389       return SDValue();
8390   }
8391
8392   // Create VPADDL node.
8393   SelectionDAG &DAG = DCI.DAG;
8394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8395
8396   SDLoc dl(N);
8397
8398   // Build operand list.
8399   SmallVector<SDValue, 8> Ops;
8400   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8401                                 TLI.getPointerTy(DAG.getDataLayout())));
8402
8403   // Input is the vector.
8404   Ops.push_back(Vec);
8405
8406   // Get widened type and narrowed type.
8407   MVT widenType;
8408   unsigned numElem = VT.getVectorNumElements();
8409   
8410   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8411   switch (inputLaneType.getSimpleVT().SimpleTy) {
8412     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8413     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8414     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8415     default:
8416       llvm_unreachable("Invalid vector element type for padd optimization.");
8417   }
8418
8419   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8420   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8421   return DAG.getNode(ExtOp, dl, VT, tmp);
8422 }
8423
8424 static SDValue findMUL_LOHI(SDValue V) {
8425   if (V->getOpcode() == ISD::UMUL_LOHI ||
8426       V->getOpcode() == ISD::SMUL_LOHI)
8427     return V;
8428   return SDValue();
8429 }
8430
8431 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8432                                      TargetLowering::DAGCombinerInfo &DCI,
8433                                      const ARMSubtarget *Subtarget) {
8434
8435   if (Subtarget->isThumb1Only()) return SDValue();
8436
8437   // Only perform the checks after legalize when the pattern is available.
8438   if (DCI.isBeforeLegalize()) return SDValue();
8439
8440   // Look for multiply add opportunities.
8441   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8442   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8443   // a glue link from the first add to the second add.
8444   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8445   // a S/UMLAL instruction.
8446   //                  UMUL_LOHI
8447   //                 / :lo    \ :hi
8448   //                /          \          [no multiline comment]
8449   //    loAdd ->  ADDE         |
8450   //                 \ :glue  /
8451   //                  \      /
8452   //                    ADDC   <- hiAdd
8453   //
8454   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8455   SDValue AddcOp0 = AddcNode->getOperand(0);
8456   SDValue AddcOp1 = AddcNode->getOperand(1);
8457
8458   // Check if the two operands are from the same mul_lohi node.
8459   if (AddcOp0.getNode() == AddcOp1.getNode())
8460     return SDValue();
8461
8462   assert(AddcNode->getNumValues() == 2 &&
8463          AddcNode->getValueType(0) == MVT::i32 &&
8464          "Expect ADDC with two result values. First: i32");
8465
8466   // Check that we have a glued ADDC node.
8467   if (AddcNode->getValueType(1) != MVT::Glue)
8468     return SDValue();
8469
8470   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8471   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8472       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8473       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8474       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8475     return SDValue();
8476
8477   // Look for the glued ADDE.
8478   SDNode* AddeNode = AddcNode->getGluedUser();
8479   if (!AddeNode)
8480     return SDValue();
8481
8482   // Make sure it is really an ADDE.
8483   if (AddeNode->getOpcode() != ISD::ADDE)
8484     return SDValue();
8485
8486   assert(AddeNode->getNumOperands() == 3 &&
8487          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8488          "ADDE node has the wrong inputs");
8489
8490   // Check for the triangle shape.
8491   SDValue AddeOp0 = AddeNode->getOperand(0);
8492   SDValue AddeOp1 = AddeNode->getOperand(1);
8493
8494   // Make sure that the ADDE operands are not coming from the same node.
8495   if (AddeOp0.getNode() == AddeOp1.getNode())
8496     return SDValue();
8497
8498   // Find the MUL_LOHI node walking up ADDE's operands.
8499   bool IsLeftOperandMUL = false;
8500   SDValue MULOp = findMUL_LOHI(AddeOp0);
8501   if (MULOp == SDValue())
8502    MULOp = findMUL_LOHI(AddeOp1);
8503   else
8504     IsLeftOperandMUL = true;
8505   if (MULOp == SDValue())
8506     return SDValue();
8507
8508   // Figure out the right opcode.
8509   unsigned Opc = MULOp->getOpcode();
8510   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8511
8512   // Figure out the high and low input values to the MLAL node.
8513   SDValue* HiAdd = nullptr;
8514   SDValue* LoMul = nullptr;
8515   SDValue* LowAdd = nullptr;
8516
8517   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8518   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8519     return SDValue();
8520
8521   if (IsLeftOperandMUL)
8522     HiAdd = &AddeOp1;
8523   else
8524     HiAdd = &AddeOp0;
8525
8526
8527   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8528   // whose low result is fed to the ADDC we are checking.
8529
8530   if (AddcOp0 == MULOp.getValue(0)) {
8531     LoMul = &AddcOp0;
8532     LowAdd = &AddcOp1;
8533   }
8534   if (AddcOp1 == MULOp.getValue(0)) {
8535     LoMul = &AddcOp1;
8536     LowAdd = &AddcOp0;
8537   }
8538
8539   if (!LoMul)
8540     return SDValue();
8541
8542   // Create the merged node.
8543   SelectionDAG &DAG = DCI.DAG;
8544
8545   // Build operand list.
8546   SmallVector<SDValue, 8> Ops;
8547   Ops.push_back(LoMul->getOperand(0));
8548   Ops.push_back(LoMul->getOperand(1));
8549   Ops.push_back(*LowAdd);
8550   Ops.push_back(*HiAdd);
8551
8552   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8553                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8554
8555   // Replace the ADDs' nodes uses by the MLA node's values.
8556   SDValue HiMLALResult(MLALNode.getNode(), 1);
8557   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8558
8559   SDValue LoMLALResult(MLALNode.getNode(), 0);
8560   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8561
8562   // Return original node to notify the driver to stop replacing.
8563   SDValue resNode(AddcNode, 0);
8564   return resNode;
8565 }
8566
8567 /// PerformADDCCombine - Target-specific dag combine transform from
8568 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8569 static SDValue PerformADDCCombine(SDNode *N,
8570                                  TargetLowering::DAGCombinerInfo &DCI,
8571                                  const ARMSubtarget *Subtarget) {
8572
8573   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8574
8575 }
8576
8577 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8578 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8579 /// called with the default operands, and if that fails, with commuted
8580 /// operands.
8581 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8582                                           TargetLowering::DAGCombinerInfo &DCI,
8583                                           const ARMSubtarget *Subtarget){
8584
8585   // Attempt to create vpaddl for this add.
8586   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8587   if (Result.getNode())
8588     return Result;
8589
8590   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8591   if (N0.getNode()->hasOneUse()) {
8592     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8593     if (Result.getNode()) return Result;
8594   }
8595   return SDValue();
8596 }
8597
8598 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8599 ///
8600 static SDValue PerformADDCombine(SDNode *N,
8601                                  TargetLowering::DAGCombinerInfo &DCI,
8602                                  const ARMSubtarget *Subtarget) {
8603   SDValue N0 = N->getOperand(0);
8604   SDValue N1 = N->getOperand(1);
8605
8606   // First try with the default operand order.
8607   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8608   if (Result.getNode())
8609     return Result;
8610
8611   // If that didn't work, try again with the operands commuted.
8612   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8613 }
8614
8615 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8616 ///
8617 static SDValue PerformSUBCombine(SDNode *N,
8618                                  TargetLowering::DAGCombinerInfo &DCI) {
8619   SDValue N0 = N->getOperand(0);
8620   SDValue N1 = N->getOperand(1);
8621
8622   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8623   if (N1.getNode()->hasOneUse()) {
8624     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8625     if (Result.getNode()) return Result;
8626   }
8627
8628   return SDValue();
8629 }
8630
8631 /// PerformVMULCombine
8632 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8633 /// special multiplier accumulator forwarding.
8634 ///   vmul d3, d0, d2
8635 ///   vmla d3, d1, d2
8636 /// is faster than
8637 ///   vadd d3, d0, d1
8638 ///   vmul d3, d3, d2
8639 //  However, for (A + B) * (A + B),
8640 //    vadd d2, d0, d1
8641 //    vmul d3, d0, d2
8642 //    vmla d3, d1, d2
8643 //  is slower than
8644 //    vadd d2, d0, d1
8645 //    vmul d3, d2, d2
8646 static SDValue PerformVMULCombine(SDNode *N,
8647                                   TargetLowering::DAGCombinerInfo &DCI,
8648                                   const ARMSubtarget *Subtarget) {
8649   if (!Subtarget->hasVMLxForwarding())
8650     return SDValue();
8651
8652   SelectionDAG &DAG = DCI.DAG;
8653   SDValue N0 = N->getOperand(0);
8654   SDValue N1 = N->getOperand(1);
8655   unsigned Opcode = N0.getOpcode();
8656   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8657       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8658     Opcode = N1.getOpcode();
8659     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8660         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8661       return SDValue();
8662     std::swap(N0, N1);
8663   }
8664
8665   if (N0 == N1)
8666     return SDValue();
8667
8668   EVT VT = N->getValueType(0);
8669   SDLoc DL(N);
8670   SDValue N00 = N0->getOperand(0);
8671   SDValue N01 = N0->getOperand(1);
8672   return DAG.getNode(Opcode, DL, VT,
8673                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8674                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8675 }
8676
8677 static SDValue PerformMULCombine(SDNode *N,
8678                                  TargetLowering::DAGCombinerInfo &DCI,
8679                                  const ARMSubtarget *Subtarget) {
8680   SelectionDAG &DAG = DCI.DAG;
8681
8682   if (Subtarget->isThumb1Only())
8683     return SDValue();
8684
8685   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8686     return SDValue();
8687
8688   EVT VT = N->getValueType(0);
8689   if (VT.is64BitVector() || VT.is128BitVector())
8690     return PerformVMULCombine(N, DCI, Subtarget);
8691   if (VT != MVT::i32)
8692     return SDValue();
8693
8694   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8695   if (!C)
8696     return SDValue();
8697
8698   int64_t MulAmt = C->getSExtValue();
8699   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8700
8701   ShiftAmt = ShiftAmt & (32 - 1);
8702   SDValue V = N->getOperand(0);
8703   SDLoc DL(N);
8704
8705   SDValue Res;
8706   MulAmt >>= ShiftAmt;
8707
8708   if (MulAmt >= 0) {
8709     if (isPowerOf2_32(MulAmt - 1)) {
8710       // (mul x, 2^N + 1) => (add (shl x, N), x)
8711       Res = DAG.getNode(ISD::ADD, DL, VT,
8712                         V,
8713                         DAG.getNode(ISD::SHL, DL, VT,
8714                                     V,
8715                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8716                                                     MVT::i32)));
8717     } else if (isPowerOf2_32(MulAmt + 1)) {
8718       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8719       Res = DAG.getNode(ISD::SUB, DL, VT,
8720                         DAG.getNode(ISD::SHL, DL, VT,
8721                                     V,
8722                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8723                                                     MVT::i32)),
8724                         V);
8725     } else
8726       return SDValue();
8727   } else {
8728     uint64_t MulAmtAbs = -MulAmt;
8729     if (isPowerOf2_32(MulAmtAbs + 1)) {
8730       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8731       Res = DAG.getNode(ISD::SUB, DL, VT,
8732                         V,
8733                         DAG.getNode(ISD::SHL, DL, VT,
8734                                     V,
8735                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8736                                                     MVT::i32)));
8737     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8738       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8739       Res = DAG.getNode(ISD::ADD, DL, VT,
8740                         V,
8741                         DAG.getNode(ISD::SHL, DL, VT,
8742                                     V,
8743                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8744                                                     MVT::i32)));
8745       Res = DAG.getNode(ISD::SUB, DL, VT,
8746                         DAG.getConstant(0, DL, MVT::i32), Res);
8747
8748     } else
8749       return SDValue();
8750   }
8751
8752   if (ShiftAmt != 0)
8753     Res = DAG.getNode(ISD::SHL, DL, VT,
8754                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8755
8756   // Do not add new nodes to DAG combiner worklist.
8757   DCI.CombineTo(N, Res, false);
8758   return SDValue();
8759 }
8760
8761 static SDValue PerformANDCombine(SDNode *N,
8762                                  TargetLowering::DAGCombinerInfo &DCI,
8763                                  const ARMSubtarget *Subtarget) {
8764
8765   // Attempt to use immediate-form VBIC
8766   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8767   SDLoc dl(N);
8768   EVT VT = N->getValueType(0);
8769   SelectionDAG &DAG = DCI.DAG;
8770
8771   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8772     return SDValue();
8773
8774   APInt SplatBits, SplatUndef;
8775   unsigned SplatBitSize;
8776   bool HasAnyUndefs;
8777   if (BVN &&
8778       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8779     if (SplatBitSize <= 64) {
8780       EVT VbicVT;
8781       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8782                                       SplatUndef.getZExtValue(), SplatBitSize,
8783                                       DAG, dl, VbicVT, VT.is128BitVector(),
8784                                       OtherModImm);
8785       if (Val.getNode()) {
8786         SDValue Input =
8787           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8788         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8789         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8790       }
8791     }
8792   }
8793
8794   if (!Subtarget->isThumb1Only()) {
8795     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8796     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8797     if (Result.getNode())
8798       return Result;
8799   }
8800
8801   return SDValue();
8802 }
8803
8804 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8805 static SDValue PerformORCombine(SDNode *N,
8806                                 TargetLowering::DAGCombinerInfo &DCI,
8807                                 const ARMSubtarget *Subtarget) {
8808   // Attempt to use immediate-form VORR
8809   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8810   SDLoc dl(N);
8811   EVT VT = N->getValueType(0);
8812   SelectionDAG &DAG = DCI.DAG;
8813
8814   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8815     return SDValue();
8816
8817   APInt SplatBits, SplatUndef;
8818   unsigned SplatBitSize;
8819   bool HasAnyUndefs;
8820   if (BVN && Subtarget->hasNEON() &&
8821       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8822     if (SplatBitSize <= 64) {
8823       EVT VorrVT;
8824       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8825                                       SplatUndef.getZExtValue(), SplatBitSize,
8826                                       DAG, dl, VorrVT, VT.is128BitVector(),
8827                                       OtherModImm);
8828       if (Val.getNode()) {
8829         SDValue Input =
8830           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8831         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8832         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8833       }
8834     }
8835   }
8836
8837   if (!Subtarget->isThumb1Only()) {
8838     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8839     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8840     if (Result.getNode())
8841       return Result;
8842   }
8843
8844   // The code below optimizes (or (and X, Y), Z).
8845   // The AND operand needs to have a single user to make these optimizations
8846   // profitable.
8847   SDValue N0 = N->getOperand(0);
8848   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8849     return SDValue();
8850   SDValue N1 = N->getOperand(1);
8851
8852   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8853   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8854       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8855     APInt SplatUndef;
8856     unsigned SplatBitSize;
8857     bool HasAnyUndefs;
8858
8859     APInt SplatBits0, SplatBits1;
8860     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8861     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8862     // Ensure that the second operand of both ands are constants
8863     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8864                                       HasAnyUndefs) && !HasAnyUndefs) {
8865         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8866                                           HasAnyUndefs) && !HasAnyUndefs) {
8867             // Ensure that the bit width of the constants are the same and that
8868             // the splat arguments are logical inverses as per the pattern we
8869             // are trying to simplify.
8870             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8871                 SplatBits0 == ~SplatBits1) {
8872                 // Canonicalize the vector type to make instruction selection
8873                 // simpler.
8874                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8875                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8876                                              N0->getOperand(1),
8877                                              N0->getOperand(0),
8878                                              N1->getOperand(0));
8879                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8880             }
8881         }
8882     }
8883   }
8884
8885   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8886   // reasonable.
8887
8888   // BFI is only available on V6T2+
8889   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8890     return SDValue();
8891
8892   SDLoc DL(N);
8893   // 1) or (and A, mask), val => ARMbfi A, val, mask
8894   //      iff (val & mask) == val
8895   //
8896   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8897   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8898   //          && mask == ~mask2
8899   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8900   //          && ~mask == mask2
8901   //  (i.e., copy a bitfield value into another bitfield of the same width)
8902
8903   if (VT != MVT::i32)
8904     return SDValue();
8905
8906   SDValue N00 = N0.getOperand(0);
8907
8908   // The value and the mask need to be constants so we can verify this is
8909   // actually a bitfield set. If the mask is 0xffff, we can do better
8910   // via a movt instruction, so don't use BFI in that case.
8911   SDValue MaskOp = N0.getOperand(1);
8912   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8913   if (!MaskC)
8914     return SDValue();
8915   unsigned Mask = MaskC->getZExtValue();
8916   if (Mask == 0xffff)
8917     return SDValue();
8918   SDValue Res;
8919   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8920   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8921   if (N1C) {
8922     unsigned Val = N1C->getZExtValue();
8923     if ((Val & ~Mask) != Val)
8924       return SDValue();
8925
8926     if (ARM::isBitFieldInvertedMask(Mask)) {
8927       Val >>= countTrailingZeros(~Mask);
8928
8929       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8930                         DAG.getConstant(Val, DL, MVT::i32),
8931                         DAG.getConstant(Mask, DL, MVT::i32));
8932
8933       // Do not add new nodes to DAG combiner worklist.
8934       DCI.CombineTo(N, Res, false);
8935       return SDValue();
8936     }
8937   } else if (N1.getOpcode() == ISD::AND) {
8938     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8939     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8940     if (!N11C)
8941       return SDValue();
8942     unsigned Mask2 = N11C->getZExtValue();
8943
8944     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8945     // as is to match.
8946     if (ARM::isBitFieldInvertedMask(Mask) &&
8947         (Mask == ~Mask2)) {
8948       // The pack halfword instruction works better for masks that fit it,
8949       // so use that when it's available.
8950       if (Subtarget->hasT2ExtractPack() &&
8951           (Mask == 0xffff || Mask == 0xffff0000))
8952         return SDValue();
8953       // 2a
8954       unsigned amt = countTrailingZeros(Mask2);
8955       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8956                         DAG.getConstant(amt, DL, MVT::i32));
8957       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8958                         DAG.getConstant(Mask, DL, MVT::i32));
8959       // Do not add new nodes to DAG combiner worklist.
8960       DCI.CombineTo(N, Res, false);
8961       return SDValue();
8962     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8963                (~Mask == Mask2)) {
8964       // The pack halfword instruction works better for masks that fit it,
8965       // so use that when it's available.
8966       if (Subtarget->hasT2ExtractPack() &&
8967           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8968         return SDValue();
8969       // 2b
8970       unsigned lsb = countTrailingZeros(Mask);
8971       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8972                         DAG.getConstant(lsb, DL, MVT::i32));
8973       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8974                         DAG.getConstant(Mask2, DL, MVT::i32));
8975       // Do not add new nodes to DAG combiner worklist.
8976       DCI.CombineTo(N, Res, false);
8977       return SDValue();
8978     }
8979   }
8980
8981   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8982       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8983       ARM::isBitFieldInvertedMask(~Mask)) {
8984     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8985     // where lsb(mask) == #shamt and masked bits of B are known zero.
8986     SDValue ShAmt = N00.getOperand(1);
8987     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8988     unsigned LSB = countTrailingZeros(Mask);
8989     if (ShAmtC != LSB)
8990       return SDValue();
8991
8992     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8993                       DAG.getConstant(~Mask, DL, MVT::i32));
8994
8995     // Do not add new nodes to DAG combiner worklist.
8996     DCI.CombineTo(N, Res, false);
8997   }
8998
8999   return SDValue();
9000 }
9001
9002 static SDValue PerformXORCombine(SDNode *N,
9003                                  TargetLowering::DAGCombinerInfo &DCI,
9004                                  const ARMSubtarget *Subtarget) {
9005   EVT VT = N->getValueType(0);
9006   SelectionDAG &DAG = DCI.DAG;
9007
9008   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9009     return SDValue();
9010
9011   if (!Subtarget->isThumb1Only()) {
9012     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9013     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9014     if (Result.getNode())
9015       return Result;
9016   }
9017
9018   return SDValue();
9019 }
9020
9021 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9022 /// the bits being cleared by the AND are not demanded by the BFI.
9023 static SDValue PerformBFICombine(SDNode *N,
9024                                  TargetLowering::DAGCombinerInfo &DCI) {
9025   SDValue N1 = N->getOperand(1);
9026   if (N1.getOpcode() == ISD::AND) {
9027     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9028     if (!N11C)
9029       return SDValue();
9030     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9031     unsigned LSB = countTrailingZeros(~InvMask);
9032     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9033     assert(Width <
9034                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9035            "undefined behavior");
9036     unsigned Mask = (1u << Width) - 1;
9037     unsigned Mask2 = N11C->getZExtValue();
9038     if ((Mask & (~Mask2)) == 0)
9039       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9040                              N->getOperand(0), N1.getOperand(0),
9041                              N->getOperand(2));
9042   }
9043   return SDValue();
9044 }
9045
9046 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9047 /// ARMISD::VMOVRRD.
9048 static SDValue PerformVMOVRRDCombine(SDNode *N,
9049                                      TargetLowering::DAGCombinerInfo &DCI,
9050                                      const ARMSubtarget *Subtarget) {
9051   // vmovrrd(vmovdrr x, y) -> x,y
9052   SDValue InDouble = N->getOperand(0);
9053   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9054     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9055
9056   // vmovrrd(load f64) -> (load i32), (load i32)
9057   SDNode *InNode = InDouble.getNode();
9058   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9059       InNode->getValueType(0) == MVT::f64 &&
9060       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9061       !cast<LoadSDNode>(InNode)->isVolatile()) {
9062     // TODO: Should this be done for non-FrameIndex operands?
9063     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9064
9065     SelectionDAG &DAG = DCI.DAG;
9066     SDLoc DL(LD);
9067     SDValue BasePtr = LD->getBasePtr();
9068     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9069                                  LD->getPointerInfo(), LD->isVolatile(),
9070                                  LD->isNonTemporal(), LD->isInvariant(),
9071                                  LD->getAlignment());
9072
9073     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9074                                     DAG.getConstant(4, DL, MVT::i32));
9075     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9076                                  LD->getPointerInfo(), LD->isVolatile(),
9077                                  LD->isNonTemporal(), LD->isInvariant(),
9078                                  std::min(4U, LD->getAlignment() / 2));
9079
9080     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9081     if (DCI.DAG.getDataLayout().isBigEndian())
9082       std::swap (NewLD1, NewLD2);
9083     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9084     return Result;
9085   }
9086
9087   return SDValue();
9088 }
9089
9090 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9091 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9092 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9093   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9094   SDValue Op0 = N->getOperand(0);
9095   SDValue Op1 = N->getOperand(1);
9096   if (Op0.getOpcode() == ISD::BITCAST)
9097     Op0 = Op0.getOperand(0);
9098   if (Op1.getOpcode() == ISD::BITCAST)
9099     Op1 = Op1.getOperand(0);
9100   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9101       Op0.getNode() == Op1.getNode() &&
9102       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9103     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9104                        N->getValueType(0), Op0.getOperand(0));
9105   return SDValue();
9106 }
9107
9108 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9109 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9110 /// i64 vector to have f64 elements, since the value can then be loaded
9111 /// directly into a VFP register.
9112 static bool hasNormalLoadOperand(SDNode *N) {
9113   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9114   for (unsigned i = 0; i < NumElts; ++i) {
9115     SDNode *Elt = N->getOperand(i).getNode();
9116     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9117       return true;
9118   }
9119   return false;
9120 }
9121
9122 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9123 /// ISD::BUILD_VECTOR.
9124 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9125                                           TargetLowering::DAGCombinerInfo &DCI,
9126                                           const ARMSubtarget *Subtarget) {
9127   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9128   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9129   // into a pair of GPRs, which is fine when the value is used as a scalar,
9130   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9131   SelectionDAG &DAG = DCI.DAG;
9132   if (N->getNumOperands() == 2) {
9133     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9134     if (RV.getNode())
9135       return RV;
9136   }
9137
9138   // Load i64 elements as f64 values so that type legalization does not split
9139   // them up into i32 values.
9140   EVT VT = N->getValueType(0);
9141   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9142     return SDValue();
9143   SDLoc dl(N);
9144   SmallVector<SDValue, 8> Ops;
9145   unsigned NumElts = VT.getVectorNumElements();
9146   for (unsigned i = 0; i < NumElts; ++i) {
9147     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9148     Ops.push_back(V);
9149     // Make the DAGCombiner fold the bitcast.
9150     DCI.AddToWorklist(V.getNode());
9151   }
9152   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9153   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9154   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9155 }
9156
9157 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9158 static SDValue
9159 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9160   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9161   // At that time, we may have inserted bitcasts from integer to float.
9162   // If these bitcasts have survived DAGCombine, change the lowering of this
9163   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9164   // force to use floating point types.
9165
9166   // Make sure we can change the type of the vector.
9167   // This is possible iff:
9168   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9169   //    1.1. Vector is used only once.
9170   //    1.2. Use is a bit convert to an integer type.
9171   // 2. The size of its operands are 32-bits (64-bits are not legal).
9172   EVT VT = N->getValueType(0);
9173   EVT EltVT = VT.getVectorElementType();
9174
9175   // Check 1.1. and 2.
9176   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9177     return SDValue();
9178
9179   // By construction, the input type must be float.
9180   assert(EltVT == MVT::f32 && "Unexpected type!");
9181
9182   // Check 1.2.
9183   SDNode *Use = *N->use_begin();
9184   if (Use->getOpcode() != ISD::BITCAST ||
9185       Use->getValueType(0).isFloatingPoint())
9186     return SDValue();
9187
9188   // Check profitability.
9189   // Model is, if more than half of the relevant operands are bitcast from
9190   // i32, turn the build_vector into a sequence of insert_vector_elt.
9191   // Relevant operands are everything that is not statically
9192   // (i.e., at compile time) bitcasted.
9193   unsigned NumOfBitCastedElts = 0;
9194   unsigned NumElts = VT.getVectorNumElements();
9195   unsigned NumOfRelevantElts = NumElts;
9196   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9197     SDValue Elt = N->getOperand(Idx);
9198     if (Elt->getOpcode() == ISD::BITCAST) {
9199       // Assume only bit cast to i32 will go away.
9200       if (Elt->getOperand(0).getValueType() == MVT::i32)
9201         ++NumOfBitCastedElts;
9202     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9203       // Constants are statically casted, thus do not count them as
9204       // relevant operands.
9205       --NumOfRelevantElts;
9206   }
9207
9208   // Check if more than half of the elements require a non-free bitcast.
9209   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9210     return SDValue();
9211
9212   SelectionDAG &DAG = DCI.DAG;
9213   // Create the new vector type.
9214   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9215   // Check if the type is legal.
9216   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9217   if (!TLI.isTypeLegal(VecVT))
9218     return SDValue();
9219
9220   // Combine:
9221   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9222   // => BITCAST INSERT_VECTOR_ELT
9223   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9224   //                      (BITCAST EN), N.
9225   SDValue Vec = DAG.getUNDEF(VecVT);
9226   SDLoc dl(N);
9227   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9228     SDValue V = N->getOperand(Idx);
9229     if (V.getOpcode() == ISD::UNDEF)
9230       continue;
9231     if (V.getOpcode() == ISD::BITCAST &&
9232         V->getOperand(0).getValueType() == MVT::i32)
9233       // Fold obvious case.
9234       V = V.getOperand(0);
9235     else {
9236       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9237       // Make the DAGCombiner fold the bitcasts.
9238       DCI.AddToWorklist(V.getNode());
9239     }
9240     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9241     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9242   }
9243   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9244   // Make the DAGCombiner fold the bitcasts.
9245   DCI.AddToWorklist(Vec.getNode());
9246   return Vec;
9247 }
9248
9249 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9250 /// ISD::INSERT_VECTOR_ELT.
9251 static SDValue PerformInsertEltCombine(SDNode *N,
9252                                        TargetLowering::DAGCombinerInfo &DCI) {
9253   // Bitcast an i64 load inserted into a vector to f64.
9254   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9255   EVT VT = N->getValueType(0);
9256   SDNode *Elt = N->getOperand(1).getNode();
9257   if (VT.getVectorElementType() != MVT::i64 ||
9258       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9259     return SDValue();
9260
9261   SelectionDAG &DAG = DCI.DAG;
9262   SDLoc dl(N);
9263   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9264                                  VT.getVectorNumElements());
9265   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9266   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9267   // Make the DAGCombiner fold the bitcasts.
9268   DCI.AddToWorklist(Vec.getNode());
9269   DCI.AddToWorklist(V.getNode());
9270   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9271                                Vec, V, N->getOperand(2));
9272   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9273 }
9274
9275 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9276 /// ISD::VECTOR_SHUFFLE.
9277 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9278   // The LLVM shufflevector instruction does not require the shuffle mask
9279   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9280   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9281   // operands do not match the mask length, they are extended by concatenating
9282   // them with undef vectors.  That is probably the right thing for other
9283   // targets, but for NEON it is better to concatenate two double-register
9284   // size vector operands into a single quad-register size vector.  Do that
9285   // transformation here:
9286   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9287   //   shuffle(concat(v1, v2), undef)
9288   SDValue Op0 = N->getOperand(0);
9289   SDValue Op1 = N->getOperand(1);
9290   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9291       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9292       Op0.getNumOperands() != 2 ||
9293       Op1.getNumOperands() != 2)
9294     return SDValue();
9295   SDValue Concat0Op1 = Op0.getOperand(1);
9296   SDValue Concat1Op1 = Op1.getOperand(1);
9297   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9298       Concat1Op1.getOpcode() != ISD::UNDEF)
9299     return SDValue();
9300   // Skip the transformation if any of the types are illegal.
9301   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9302   EVT VT = N->getValueType(0);
9303   if (!TLI.isTypeLegal(VT) ||
9304       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9305       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9306     return SDValue();
9307
9308   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9309                                   Op0.getOperand(0), Op1.getOperand(0));
9310   // Translate the shuffle mask.
9311   SmallVector<int, 16> NewMask;
9312   unsigned NumElts = VT.getVectorNumElements();
9313   unsigned HalfElts = NumElts/2;
9314   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9315   for (unsigned n = 0; n < NumElts; ++n) {
9316     int MaskElt = SVN->getMaskElt(n);
9317     int NewElt = -1;
9318     if (MaskElt < (int)HalfElts)
9319       NewElt = MaskElt;
9320     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9321       NewElt = HalfElts + MaskElt - NumElts;
9322     NewMask.push_back(NewElt);
9323   }
9324   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9325                               DAG.getUNDEF(VT), NewMask.data());
9326 }
9327
9328 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9329 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9330 /// base address updates.
9331 /// For generic load/stores, the memory type is assumed to be a vector.
9332 /// The caller is assumed to have checked legality.
9333 static SDValue CombineBaseUpdate(SDNode *N,
9334                                  TargetLowering::DAGCombinerInfo &DCI) {
9335   SelectionDAG &DAG = DCI.DAG;
9336   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9337                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9338   const bool isStore = N->getOpcode() == ISD::STORE;
9339   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9340   SDValue Addr = N->getOperand(AddrOpIdx);
9341   MemSDNode *MemN = cast<MemSDNode>(N);
9342   SDLoc dl(N);
9343
9344   // Search for a use of the address operand that is an increment.
9345   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9346          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9347     SDNode *User = *UI;
9348     if (User->getOpcode() != ISD::ADD ||
9349         UI.getUse().getResNo() != Addr.getResNo())
9350       continue;
9351
9352     // Check that the add is independent of the load/store.  Otherwise, folding
9353     // it would create a cycle.
9354     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9355       continue;
9356
9357     // Find the new opcode for the updating load/store.
9358     bool isLoadOp = true;
9359     bool isLaneOp = false;
9360     unsigned NewOpc = 0;
9361     unsigned NumVecs = 0;
9362     if (isIntrinsic) {
9363       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9364       switch (IntNo) {
9365       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9366       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9367         NumVecs = 1; break;
9368       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9369         NumVecs = 2; break;
9370       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9371         NumVecs = 3; break;
9372       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9373         NumVecs = 4; break;
9374       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9375         NumVecs = 2; isLaneOp = true; break;
9376       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9377         NumVecs = 3; isLaneOp = true; break;
9378       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9379         NumVecs = 4; isLaneOp = true; break;
9380       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9381         NumVecs = 1; isLoadOp = false; break;
9382       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9383         NumVecs = 2; isLoadOp = false; break;
9384       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9385         NumVecs = 3; isLoadOp = false; break;
9386       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9387         NumVecs = 4; isLoadOp = false; break;
9388       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9389         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9390       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9391         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9392       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9393         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9394       }
9395     } else {
9396       isLaneOp = true;
9397       switch (N->getOpcode()) {
9398       default: llvm_unreachable("unexpected opcode for Neon base update");
9399       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9400       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9401       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9402       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9403         NumVecs = 1; isLaneOp = false; break;
9404       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9405         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9406       }
9407     }
9408
9409     // Find the size of memory referenced by the load/store.
9410     EVT VecTy;
9411     if (isLoadOp) {
9412       VecTy = N->getValueType(0);
9413     } else if (isIntrinsic) {
9414       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9415     } else {
9416       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9417       VecTy = N->getOperand(1).getValueType();
9418     }
9419
9420     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9421     if (isLaneOp)
9422       NumBytes /= VecTy.getVectorNumElements();
9423
9424     // If the increment is a constant, it must match the memory ref size.
9425     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9426     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9427       uint64_t IncVal = CInc->getZExtValue();
9428       if (IncVal != NumBytes)
9429         continue;
9430     } else if (NumBytes >= 3 * 16) {
9431       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9432       // separate instructions that make it harder to use a non-constant update.
9433       continue;
9434     }
9435
9436     // OK, we found an ADD we can fold into the base update.
9437     // Now, create a _UPD node, taking care of not breaking alignment.
9438
9439     EVT AlignedVecTy = VecTy;
9440     unsigned Alignment = MemN->getAlignment();
9441
9442     // If this is a less-than-standard-aligned load/store, change the type to
9443     // match the standard alignment.
9444     // The alignment is overlooked when selecting _UPD variants; and it's
9445     // easier to introduce bitcasts here than fix that.
9446     // There are 3 ways to get to this base-update combine:
9447     // - intrinsics: they are assumed to be properly aligned (to the standard
9448     //   alignment of the memory type), so we don't need to do anything.
9449     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9450     //   intrinsics, so, likewise, there's nothing to do.
9451     // - generic load/store instructions: the alignment is specified as an
9452     //   explicit operand, rather than implicitly as the standard alignment
9453     //   of the memory type (like the intrisics).  We need to change the
9454     //   memory type to match the explicit alignment.  That way, we don't
9455     //   generate non-standard-aligned ARMISD::VLDx nodes.
9456     if (isa<LSBaseSDNode>(N)) {
9457       if (Alignment == 0)
9458         Alignment = 1;
9459       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9460         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9461         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9462         assert(!isLaneOp && "Unexpected generic load/store lane.");
9463         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9464         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9465       }
9466       // Don't set an explicit alignment on regular load/stores that we want
9467       // to transform to VLD/VST 1_UPD nodes.
9468       // This matches the behavior of regular load/stores, which only get an
9469       // explicit alignment if the MMO alignment is larger than the standard
9470       // alignment of the memory type.
9471       // Intrinsics, however, always get an explicit alignment, set to the
9472       // alignment of the MMO.
9473       Alignment = 1;
9474     }
9475
9476     // Create the new updating load/store node.
9477     // First, create an SDVTList for the new updating node's results.
9478     EVT Tys[6];
9479     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9480     unsigned n;
9481     for (n = 0; n < NumResultVecs; ++n)
9482       Tys[n] = AlignedVecTy;
9483     Tys[n++] = MVT::i32;
9484     Tys[n] = MVT::Other;
9485     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9486
9487     // Then, gather the new node's operands.
9488     SmallVector<SDValue, 8> Ops;
9489     Ops.push_back(N->getOperand(0)); // incoming chain
9490     Ops.push_back(N->getOperand(AddrOpIdx));
9491     Ops.push_back(Inc);
9492
9493     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9494       // Try to match the intrinsic's signature
9495       Ops.push_back(StN->getValue());
9496     } else {
9497       // Loads (and of course intrinsics) match the intrinsics' signature,
9498       // so just add all but the alignment operand.
9499       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9500         Ops.push_back(N->getOperand(i));
9501     }
9502
9503     // For all node types, the alignment operand is always the last one.
9504     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9505
9506     // If this is a non-standard-aligned STORE, the penultimate operand is the
9507     // stored value.  Bitcast it to the aligned type.
9508     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9509       SDValue &StVal = Ops[Ops.size()-2];
9510       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9511     }
9512
9513     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9514                                            Ops, AlignedVecTy,
9515                                            MemN->getMemOperand());
9516
9517     // Update the uses.
9518     SmallVector<SDValue, 5> NewResults;
9519     for (unsigned i = 0; i < NumResultVecs; ++i)
9520       NewResults.push_back(SDValue(UpdN.getNode(), i));
9521
9522     // If this is an non-standard-aligned LOAD, the first result is the loaded
9523     // value.  Bitcast it to the expected result type.
9524     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9525       SDValue &LdVal = NewResults[0];
9526       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9527     }
9528
9529     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9530     DCI.CombineTo(N, NewResults);
9531     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9532
9533     break;
9534   }
9535   return SDValue();
9536 }
9537
9538 static SDValue PerformVLDCombine(SDNode *N,
9539                                  TargetLowering::DAGCombinerInfo &DCI) {
9540   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9541     return SDValue();
9542
9543   return CombineBaseUpdate(N, DCI);
9544 }
9545
9546 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9547 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9548 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9549 /// return true.
9550 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9551   SelectionDAG &DAG = DCI.DAG;
9552   EVT VT = N->getValueType(0);
9553   // vldN-dup instructions only support 64-bit vectors for N > 1.
9554   if (!VT.is64BitVector())
9555     return false;
9556
9557   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9558   SDNode *VLD = N->getOperand(0).getNode();
9559   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9560     return false;
9561   unsigned NumVecs = 0;
9562   unsigned NewOpc = 0;
9563   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9564   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9565     NumVecs = 2;
9566     NewOpc = ARMISD::VLD2DUP;
9567   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9568     NumVecs = 3;
9569     NewOpc = ARMISD::VLD3DUP;
9570   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9571     NumVecs = 4;
9572     NewOpc = ARMISD::VLD4DUP;
9573   } else {
9574     return false;
9575   }
9576
9577   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9578   // numbers match the load.
9579   unsigned VLDLaneNo =
9580     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9581   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9582        UI != UE; ++UI) {
9583     // Ignore uses of the chain result.
9584     if (UI.getUse().getResNo() == NumVecs)
9585       continue;
9586     SDNode *User = *UI;
9587     if (User->getOpcode() != ARMISD::VDUPLANE ||
9588         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9589       return false;
9590   }
9591
9592   // Create the vldN-dup node.
9593   EVT Tys[5];
9594   unsigned n;
9595   for (n = 0; n < NumVecs; ++n)
9596     Tys[n] = VT;
9597   Tys[n] = MVT::Other;
9598   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9599   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9600   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9601   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9602                                            Ops, VLDMemInt->getMemoryVT(),
9603                                            VLDMemInt->getMemOperand());
9604
9605   // Update the uses.
9606   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9607        UI != UE; ++UI) {
9608     unsigned ResNo = UI.getUse().getResNo();
9609     // Ignore uses of the chain result.
9610     if (ResNo == NumVecs)
9611       continue;
9612     SDNode *User = *UI;
9613     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9614   }
9615
9616   // Now the vldN-lane intrinsic is dead except for its chain result.
9617   // Update uses of the chain.
9618   std::vector<SDValue> VLDDupResults;
9619   for (unsigned n = 0; n < NumVecs; ++n)
9620     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9621   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9622   DCI.CombineTo(VLD, VLDDupResults);
9623
9624   return true;
9625 }
9626
9627 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9628 /// ARMISD::VDUPLANE.
9629 static SDValue PerformVDUPLANECombine(SDNode *N,
9630                                       TargetLowering::DAGCombinerInfo &DCI) {
9631   SDValue Op = N->getOperand(0);
9632
9633   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9634   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9635   if (CombineVLDDUP(N, DCI))
9636     return SDValue(N, 0);
9637
9638   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9639   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9640   while (Op.getOpcode() == ISD::BITCAST)
9641     Op = Op.getOperand(0);
9642   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9643     return SDValue();
9644
9645   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9646   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9647   // The canonical VMOV for a zero vector uses a 32-bit element size.
9648   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9649   unsigned EltBits;
9650   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9651     EltSize = 8;
9652   EVT VT = N->getValueType(0);
9653   if (EltSize > VT.getVectorElementType().getSizeInBits())
9654     return SDValue();
9655
9656   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9657 }
9658
9659 static SDValue PerformLOADCombine(SDNode *N,
9660                                   TargetLowering::DAGCombinerInfo &DCI) {
9661   EVT VT = N->getValueType(0);
9662
9663   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9664   if (ISD::isNormalLoad(N) && VT.isVector() &&
9665       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9666     return CombineBaseUpdate(N, DCI);
9667
9668   return SDValue();
9669 }
9670
9671 /// PerformSTORECombine - Target-specific dag combine xforms for
9672 /// ISD::STORE.
9673 static SDValue PerformSTORECombine(SDNode *N,
9674                                    TargetLowering::DAGCombinerInfo &DCI) {
9675   StoreSDNode *St = cast<StoreSDNode>(N);
9676   if (St->isVolatile())
9677     return SDValue();
9678
9679   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9680   // pack all of the elements in one place.  Next, store to memory in fewer
9681   // chunks.
9682   SDValue StVal = St->getValue();
9683   EVT VT = StVal.getValueType();
9684   if (St->isTruncatingStore() && VT.isVector()) {
9685     SelectionDAG &DAG = DCI.DAG;
9686     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9687     EVT StVT = St->getMemoryVT();
9688     unsigned NumElems = VT.getVectorNumElements();
9689     assert(StVT != VT && "Cannot truncate to the same type");
9690     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9691     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9692
9693     // From, To sizes and ElemCount must be pow of two
9694     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9695
9696     // We are going to use the original vector elt for storing.
9697     // Accumulated smaller vector elements must be a multiple of the store size.
9698     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9699
9700     unsigned SizeRatio  = FromEltSz / ToEltSz;
9701     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9702
9703     // Create a type on which we perform the shuffle.
9704     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9705                                      NumElems*SizeRatio);
9706     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9707
9708     SDLoc DL(St);
9709     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9710     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9711     for (unsigned i = 0; i < NumElems; ++i)
9712       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9713                           ? (i + 1) * SizeRatio - 1
9714                           : i * SizeRatio;
9715
9716     // Can't shuffle using an illegal type.
9717     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9718
9719     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9720                                 DAG.getUNDEF(WideVec.getValueType()),
9721                                 ShuffleVec.data());
9722     // At this point all of the data is stored at the bottom of the
9723     // register. We now need to save it to mem.
9724
9725     // Find the largest store unit
9726     MVT StoreType = MVT::i8;
9727     for (MVT Tp : MVT::integer_valuetypes()) {
9728       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9729         StoreType = Tp;
9730     }
9731     // Didn't find a legal store type.
9732     if (!TLI.isTypeLegal(StoreType))
9733       return SDValue();
9734
9735     // Bitcast the original vector into a vector of store-size units
9736     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9737             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9738     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9739     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9740     SmallVector<SDValue, 8> Chains;
9741     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9742                                         TLI.getPointerTy(DAG.getDataLayout()));
9743     SDValue BasePtr = St->getBasePtr();
9744
9745     // Perform one or more big stores into memory.
9746     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9747     for (unsigned I = 0; I < E; I++) {
9748       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9749                                    StoreType, ShuffWide,
9750                                    DAG.getIntPtrConstant(I, DL));
9751       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9752                                 St->getPointerInfo(), St->isVolatile(),
9753                                 St->isNonTemporal(), St->getAlignment());
9754       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9755                             Increment);
9756       Chains.push_back(Ch);
9757     }
9758     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9759   }
9760
9761   if (!ISD::isNormalStore(St))
9762     return SDValue();
9763
9764   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9765   // ARM stores of arguments in the same cache line.
9766   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9767       StVal.getNode()->hasOneUse()) {
9768     SelectionDAG  &DAG = DCI.DAG;
9769     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9770     SDLoc DL(St);
9771     SDValue BasePtr = St->getBasePtr();
9772     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9773                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9774                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9775                                   St->isNonTemporal(), St->getAlignment());
9776
9777     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9778                                     DAG.getConstant(4, DL, MVT::i32));
9779     return DAG.getStore(NewST1.getValue(0), DL,
9780                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9781                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9782                         St->isNonTemporal(),
9783                         std::min(4U, St->getAlignment() / 2));
9784   }
9785
9786   if (StVal.getValueType() == MVT::i64 &&
9787       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9788
9789     // Bitcast an i64 store extracted from a vector to f64.
9790     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9791     SelectionDAG &DAG = DCI.DAG;
9792     SDLoc dl(StVal);
9793     SDValue IntVec = StVal.getOperand(0);
9794     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9795                                    IntVec.getValueType().getVectorNumElements());
9796     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9797     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9798                                  Vec, StVal.getOperand(1));
9799     dl = SDLoc(N);
9800     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9801     // Make the DAGCombiner fold the bitcasts.
9802     DCI.AddToWorklist(Vec.getNode());
9803     DCI.AddToWorklist(ExtElt.getNode());
9804     DCI.AddToWorklist(V.getNode());
9805     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9806                         St->getPointerInfo(), St->isVolatile(),
9807                         St->isNonTemporal(), St->getAlignment(),
9808                         St->getAAInfo());
9809   }
9810
9811   // If this is a legal vector store, try to combine it into a VST1_UPD.
9812   if (ISD::isNormalStore(N) && VT.isVector() &&
9813       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9814     return CombineBaseUpdate(N, DCI);
9815
9816   return SDValue();
9817 }
9818
9819 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9820 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9821 /// when the VMUL has a constant operand that is a power of 2.
9822 ///
9823 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9824 ///  vmul.f32        d16, d17, d16
9825 ///  vcvt.s32.f32    d16, d16
9826 /// becomes:
9827 ///  vcvt.s32.f32    d16, d16, #3
9828 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9829                                   const ARMSubtarget *Subtarget) {
9830   if (!Subtarget->hasNEON())
9831     return SDValue();
9832
9833   SDValue Op = N->getOperand(0);
9834   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9835     return SDValue();
9836
9837   SDValue ConstVec = Op->getOperand(1);
9838   if (!isa<BuildVectorSDNode>(ConstVec))
9839     return SDValue();
9840
9841   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9842   uint32_t FloatBits = FloatTy.getSizeInBits();
9843   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9844   uint32_t IntBits = IntTy.getSizeInBits();
9845   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9846   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9847     // These instructions only exist converting from f32 to i32. We can handle
9848     // smaller integers by generating an extra truncate, but larger ones would
9849     // be lossy. We also can't handle more then 4 lanes, since these intructions
9850     // only support v2i32/v4i32 types.
9851     return SDValue();
9852   }
9853
9854   BitVector UndefElements;
9855   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9856   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9857   if (C == -1 || C == 0 || C > 32)
9858     return SDValue();
9859
9860   SDLoc dl(N);
9861   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9862   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9863     Intrinsic::arm_neon_vcvtfp2fxu;
9864   SDValue FixConv = DAG.getNode(
9865       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9866       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9867       DAG.getConstant(C, dl, MVT::i32));
9868
9869   if (IntBits < FloatBits)
9870     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9871
9872   return FixConv;
9873 }
9874
9875 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9876 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9877 /// when the VDIV has a constant operand that is a power of 2.
9878 ///
9879 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9880 ///  vcvt.f32.s32    d16, d16
9881 ///  vdiv.f32        d16, d17, d16
9882 /// becomes:
9883 ///  vcvt.f32.s32    d16, d16, #3
9884 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9885                                   const ARMSubtarget *Subtarget) {
9886   if (!Subtarget->hasNEON())
9887     return SDValue();
9888
9889   SDValue Op = N->getOperand(0);
9890   unsigned OpOpcode = Op.getNode()->getOpcode();
9891   if (!N->getValueType(0).isVector() ||
9892       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9893     return SDValue();
9894
9895   SDValue ConstVec = N->getOperand(1);
9896   if (!isa<BuildVectorSDNode>(ConstVec))
9897     return SDValue();
9898
9899   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9900   uint32_t FloatBits = FloatTy.getSizeInBits();
9901   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9902   uint32_t IntBits = IntTy.getSizeInBits();
9903   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9904   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9905     // These instructions only exist converting from i32 to f32. We can handle
9906     // smaller integers by generating an extra extend, but larger ones would
9907     // be lossy. We also can't handle more then 4 lanes, since these intructions
9908     // only support v2i32/v4i32 types.
9909     return SDValue();
9910   }
9911
9912   BitVector UndefElements;
9913   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9914   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9915   if (C == -1 || C == 0 || C > 32)
9916     return SDValue();
9917
9918   SDLoc dl(N);
9919   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9920   SDValue ConvInput = Op.getOperand(0);
9921   if (IntBits < FloatBits)
9922     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9923                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9924                             ConvInput);
9925
9926   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9927     Intrinsic::arm_neon_vcvtfxu2fp;
9928   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9929                      Op.getValueType(),
9930                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9931                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
9932 }
9933
9934 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9935 /// operand of a vector shift operation, where all the elements of the
9936 /// build_vector must have the same constant integer value.
9937 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9938   // Ignore bit_converts.
9939   while (Op.getOpcode() == ISD::BITCAST)
9940     Op = Op.getOperand(0);
9941   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9942   APInt SplatBits, SplatUndef;
9943   unsigned SplatBitSize;
9944   bool HasAnyUndefs;
9945   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9946                                       HasAnyUndefs, ElementBits) ||
9947       SplatBitSize > ElementBits)
9948     return false;
9949   Cnt = SplatBits.getSExtValue();
9950   return true;
9951 }
9952
9953 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9954 /// operand of a vector shift left operation.  That value must be in the range:
9955 ///   0 <= Value < ElementBits for a left shift; or
9956 ///   0 <= Value <= ElementBits for a long left shift.
9957 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9958   assert(VT.isVector() && "vector shift count is not a vector type");
9959   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9960   if (! getVShiftImm(Op, ElementBits, Cnt))
9961     return false;
9962   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9963 }
9964
9965 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9966 /// operand of a vector shift right operation.  For a shift opcode, the value
9967 /// is positive, but for an intrinsic the value count must be negative. The
9968 /// absolute value must be in the range:
9969 ///   1 <= |Value| <= ElementBits for a right shift; or
9970 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9971 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9972                          int64_t &Cnt) {
9973   assert(VT.isVector() && "vector shift count is not a vector type");
9974   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9975   if (! getVShiftImm(Op, ElementBits, Cnt))
9976     return false;
9977   if (!isIntrinsic)
9978     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9979   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9980     Cnt = -Cnt;
9981     return true;
9982   }
9983   return false;
9984 }
9985
9986 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9987 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9988   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9989   switch (IntNo) {
9990   default:
9991     // Don't do anything for most intrinsics.
9992     break;
9993
9994   case Intrinsic::arm_neon_vabds:
9995     if (!N->getValueType(0).isInteger())
9996       return SDValue();
9997     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9998                        N->getOperand(1), N->getOperand(2));
9999   case Intrinsic::arm_neon_vabdu:
10000     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
10001                        N->getOperand(1), N->getOperand(2));
10002
10003   // Vector shifts: check for immediate versions and lower them.
10004   // Note: This is done during DAG combining instead of DAG legalizing because
10005   // the build_vectors for 64-bit vector element shift counts are generally
10006   // not legal, and it is hard to see their values after they get legalized to
10007   // loads from a constant pool.
10008   case Intrinsic::arm_neon_vshifts:
10009   case Intrinsic::arm_neon_vshiftu:
10010   case Intrinsic::arm_neon_vrshifts:
10011   case Intrinsic::arm_neon_vrshiftu:
10012   case Intrinsic::arm_neon_vrshiftn:
10013   case Intrinsic::arm_neon_vqshifts:
10014   case Intrinsic::arm_neon_vqshiftu:
10015   case Intrinsic::arm_neon_vqshiftsu:
10016   case Intrinsic::arm_neon_vqshiftns:
10017   case Intrinsic::arm_neon_vqshiftnu:
10018   case Intrinsic::arm_neon_vqshiftnsu:
10019   case Intrinsic::arm_neon_vqrshiftns:
10020   case Intrinsic::arm_neon_vqrshiftnu:
10021   case Intrinsic::arm_neon_vqrshiftnsu: {
10022     EVT VT = N->getOperand(1).getValueType();
10023     int64_t Cnt;
10024     unsigned VShiftOpc = 0;
10025
10026     switch (IntNo) {
10027     case Intrinsic::arm_neon_vshifts:
10028     case Intrinsic::arm_neon_vshiftu:
10029       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10030         VShiftOpc = ARMISD::VSHL;
10031         break;
10032       }
10033       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10034         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10035                      ARMISD::VSHRs : ARMISD::VSHRu);
10036         break;
10037       }
10038       return SDValue();
10039
10040     case Intrinsic::arm_neon_vrshifts:
10041     case Intrinsic::arm_neon_vrshiftu:
10042       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10043         break;
10044       return SDValue();
10045
10046     case Intrinsic::arm_neon_vqshifts:
10047     case Intrinsic::arm_neon_vqshiftu:
10048       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10049         break;
10050       return SDValue();
10051
10052     case Intrinsic::arm_neon_vqshiftsu:
10053       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10054         break;
10055       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10056
10057     case Intrinsic::arm_neon_vrshiftn:
10058     case Intrinsic::arm_neon_vqshiftns:
10059     case Intrinsic::arm_neon_vqshiftnu:
10060     case Intrinsic::arm_neon_vqshiftnsu:
10061     case Intrinsic::arm_neon_vqrshiftns:
10062     case Intrinsic::arm_neon_vqrshiftnu:
10063     case Intrinsic::arm_neon_vqrshiftnsu:
10064       // Narrowing shifts require an immediate right shift.
10065       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10066         break;
10067       llvm_unreachable("invalid shift count for narrowing vector shift "
10068                        "intrinsic");
10069
10070     default:
10071       llvm_unreachable("unhandled vector shift");
10072     }
10073
10074     switch (IntNo) {
10075     case Intrinsic::arm_neon_vshifts:
10076     case Intrinsic::arm_neon_vshiftu:
10077       // Opcode already set above.
10078       break;
10079     case Intrinsic::arm_neon_vrshifts:
10080       VShiftOpc = ARMISD::VRSHRs; break;
10081     case Intrinsic::arm_neon_vrshiftu:
10082       VShiftOpc = ARMISD::VRSHRu; break;
10083     case Intrinsic::arm_neon_vrshiftn:
10084       VShiftOpc = ARMISD::VRSHRN; break;
10085     case Intrinsic::arm_neon_vqshifts:
10086       VShiftOpc = ARMISD::VQSHLs; break;
10087     case Intrinsic::arm_neon_vqshiftu:
10088       VShiftOpc = ARMISD::VQSHLu; break;
10089     case Intrinsic::arm_neon_vqshiftsu:
10090       VShiftOpc = ARMISD::VQSHLsu; break;
10091     case Intrinsic::arm_neon_vqshiftns:
10092       VShiftOpc = ARMISD::VQSHRNs; break;
10093     case Intrinsic::arm_neon_vqshiftnu:
10094       VShiftOpc = ARMISD::VQSHRNu; break;
10095     case Intrinsic::arm_neon_vqshiftnsu:
10096       VShiftOpc = ARMISD::VQSHRNsu; break;
10097     case Intrinsic::arm_neon_vqrshiftns:
10098       VShiftOpc = ARMISD::VQRSHRNs; break;
10099     case Intrinsic::arm_neon_vqrshiftnu:
10100       VShiftOpc = ARMISD::VQRSHRNu; break;
10101     case Intrinsic::arm_neon_vqrshiftnsu:
10102       VShiftOpc = ARMISD::VQRSHRNsu; break;
10103     }
10104
10105     SDLoc dl(N);
10106     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10107                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10108   }
10109
10110   case Intrinsic::arm_neon_vshiftins: {
10111     EVT VT = N->getOperand(1).getValueType();
10112     int64_t Cnt;
10113     unsigned VShiftOpc = 0;
10114
10115     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10116       VShiftOpc = ARMISD::VSLI;
10117     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10118       VShiftOpc = ARMISD::VSRI;
10119     else {
10120       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10121     }
10122
10123     SDLoc dl(N);
10124     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10125                        N->getOperand(1), N->getOperand(2),
10126                        DAG.getConstant(Cnt, dl, MVT::i32));
10127   }
10128
10129   case Intrinsic::arm_neon_vqrshifts:
10130   case Intrinsic::arm_neon_vqrshiftu:
10131     // No immediate versions of these to check for.
10132     break;
10133   }
10134
10135   return SDValue();
10136 }
10137
10138 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10139 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10140 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10141 /// vector element shift counts are generally not legal, and it is hard to see
10142 /// their values after they get legalized to loads from a constant pool.
10143 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10144                                    const ARMSubtarget *ST) {
10145   EVT VT = N->getValueType(0);
10146   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10147     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10148     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10149     SDValue N1 = N->getOperand(1);
10150     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10151       SDValue N0 = N->getOperand(0);
10152       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10153           DAG.MaskedValueIsZero(N0.getOperand(0),
10154                                 APInt::getHighBitsSet(32, 16)))
10155         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10156     }
10157   }
10158
10159   // Nothing to be done for scalar shifts.
10160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10161   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10162     return SDValue();
10163
10164   assert(ST->hasNEON() && "unexpected vector shift");
10165   int64_t Cnt;
10166
10167   switch (N->getOpcode()) {
10168   default: llvm_unreachable("unexpected shift opcode");
10169
10170   case ISD::SHL:
10171     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10172       SDLoc dl(N);
10173       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10174                          DAG.getConstant(Cnt, dl, MVT::i32));
10175     }
10176     break;
10177
10178   case ISD::SRA:
10179   case ISD::SRL:
10180     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10181       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10182                             ARMISD::VSHRs : ARMISD::VSHRu);
10183       SDLoc dl(N);
10184       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10185                          DAG.getConstant(Cnt, dl, MVT::i32));
10186     }
10187   }
10188   return SDValue();
10189 }
10190
10191 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10192 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10193 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10194                                     const ARMSubtarget *ST) {
10195   SDValue N0 = N->getOperand(0);
10196
10197   // Check for sign- and zero-extensions of vector extract operations of 8-
10198   // and 16-bit vector elements.  NEON supports these directly.  They are
10199   // handled during DAG combining because type legalization will promote them
10200   // to 32-bit types and it is messy to recognize the operations after that.
10201   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10202     SDValue Vec = N0.getOperand(0);
10203     SDValue Lane = N0.getOperand(1);
10204     EVT VT = N->getValueType(0);
10205     EVT EltVT = N0.getValueType();
10206     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10207
10208     if (VT == MVT::i32 &&
10209         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10210         TLI.isTypeLegal(Vec.getValueType()) &&
10211         isa<ConstantSDNode>(Lane)) {
10212
10213       unsigned Opc = 0;
10214       switch (N->getOpcode()) {
10215       default: llvm_unreachable("unexpected opcode");
10216       case ISD::SIGN_EXTEND:
10217         Opc = ARMISD::VGETLANEs;
10218         break;
10219       case ISD::ZERO_EXTEND:
10220       case ISD::ANY_EXTEND:
10221         Opc = ARMISD::VGETLANEu;
10222         break;
10223       }
10224       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10225     }
10226   }
10227
10228   return SDValue();
10229 }
10230
10231 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10232                              APInt &KnownOne) {
10233   if (Op.getOpcode() == ARMISD::BFI) {
10234     // Conservatively, we can recurse down the first operand
10235     // and just mask out all affected bits.
10236     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10237
10238     // The operand to BFI is already a mask suitable for removing the bits it
10239     // sets.
10240     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10241     APInt Mask = CI->getAPIntValue();
10242     KnownZero &= Mask;
10243     KnownOne &= Mask;
10244     return;
10245   }
10246   if (Op.getOpcode() == ARMISD::CMOV) {
10247     APInt KZ2(KnownZero.getBitWidth(), 0);
10248     APInt KO2(KnownOne.getBitWidth(), 0);
10249     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10250     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10251
10252     KnownZero &= KZ2;
10253     KnownOne &= KO2;
10254     return;
10255   }
10256   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10257 }
10258
10259 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10260   // If we have a CMOV, OR and AND combination such as:
10261   //   if (x & CN)
10262   //     y |= CM;
10263   //
10264   // And:
10265   //   * CN is a single bit;
10266   //   * All bits covered by CM are known zero in y
10267   //
10268   // Then we can convert this into a sequence of BFI instructions. This will
10269   // always be a win if CM is a single bit, will always be no worse than the
10270   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10271   // three bits (due to the extra IT instruction).
10272
10273   SDValue Op0 = CMOV->getOperand(0);
10274   SDValue Op1 = CMOV->getOperand(1);
10275   SDValue CmpZ = CMOV->getOperand(4);
10276
10277   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10278   SDValue And = CmpZ->getOperand(0);
10279   if (And->getOpcode() != ISD::AND)
10280     return SDValue();
10281   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10282   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10283     return SDValue();
10284   SDValue X = And->getOperand(0);
10285
10286   // Canonicalize so that the OR is on the left.
10287   if (Op1->getOpcode() == ISD::OR)
10288     std::swap(Op0, Op1);
10289   if (Op0->getOpcode() != ISD::OR)
10290     return SDValue();
10291
10292   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op0->getOperand(1));
10293   if (!OrC)
10294     return SDValue();
10295   SDValue Y = Op0->getOperand(0);
10296
10297   if (Op1 != Y)
10298     return SDValue();
10299
10300   // Now, is it profitable to continue?
10301   APInt OrCI = OrC->getAPIntValue();
10302   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10303   if (OrCI.countPopulation() > Heuristic)
10304     return SDValue();
10305
10306   // Lastly, can we determine that the bits defined by OrCI
10307   // are zero in Y?
10308   APInt KnownZero, KnownOne;
10309   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10310   if ((OrCI & KnownZero) != OrCI)
10311     return SDValue();
10312
10313   // OK, we can do the combine.
10314   SDValue V = Y;
10315   SDLoc dl(X);
10316   EVT VT = X.getValueType();
10317   unsigned BitInX = AndC->getAPIntValue().logBase2();
10318   
10319   if (BitInX != 0) {
10320     // We must shift X first.
10321     X = DAG.getNode(ISD::SRL, dl, VT, X,
10322                     DAG.getConstant(BitInX, dl, VT));
10323   }
10324
10325   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10326        BitInY < NumActiveBits; ++BitInY) {
10327     if (OrCI[BitInY] == 0)
10328       continue;
10329     APInt Mask(VT.getSizeInBits(), 0);
10330     Mask.setBit(BitInY);
10331     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10332                     // Confusingly, the operand is an *inverted* mask.
10333                     DAG.getConstant(~Mask, dl, VT));
10334   }
10335
10336   return V;
10337 }
10338
10339 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10340 SDValue
10341 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10342   SDValue Cmp = N->getOperand(4);
10343   if (Cmp.getOpcode() != ARMISD::CMPZ)
10344     // Only looking at EQ and NE cases.
10345     return SDValue();
10346
10347   EVT VT = N->getValueType(0);
10348   SDLoc dl(N);
10349   SDValue LHS = Cmp.getOperand(0);
10350   SDValue RHS = Cmp.getOperand(1);
10351   SDValue FalseVal = N->getOperand(0);
10352   SDValue TrueVal = N->getOperand(1);
10353   SDValue ARMcc = N->getOperand(2);
10354   ARMCC::CondCodes CC =
10355     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10356
10357   // BFI is only available on V6T2+.
10358   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10359     SDValue R = PerformCMOVToBFICombine(N, DAG);
10360     if (R)
10361       return R;
10362   }
10363
10364   // Simplify
10365   //   mov     r1, r0
10366   //   cmp     r1, x
10367   //   mov     r0, y
10368   //   moveq   r0, x
10369   // to
10370   //   cmp     r0, x
10371   //   movne   r0, y
10372   //
10373   //   mov     r1, r0
10374   //   cmp     r1, x
10375   //   mov     r0, x
10376   //   movne   r0, y
10377   // to
10378   //   cmp     r0, x
10379   //   movne   r0, y
10380   /// FIXME: Turn this into a target neutral optimization?
10381   SDValue Res;
10382   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10383     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10384                       N->getOperand(3), Cmp);
10385   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10386     SDValue ARMcc;
10387     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10388     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10389                       N->getOperand(3), NewCmp);
10390   }
10391
10392   if (Res.getNode()) {
10393     APInt KnownZero, KnownOne;
10394     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10395     // Capture demanded bits information that would be otherwise lost.
10396     if (KnownZero == 0xfffffffe)
10397       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10398                         DAG.getValueType(MVT::i1));
10399     else if (KnownZero == 0xffffff00)
10400       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10401                         DAG.getValueType(MVT::i8));
10402     else if (KnownZero == 0xffff0000)
10403       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10404                         DAG.getValueType(MVT::i16));
10405   }
10406
10407   return Res;
10408 }
10409
10410 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10411                                              DAGCombinerInfo &DCI) const {
10412   switch (N->getOpcode()) {
10413   default: break;
10414   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10415   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10416   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10417   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10418   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10419   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10420   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10421   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10422   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10423   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10424   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10425   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10426   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10427   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10428   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10429   case ISD::FP_TO_SINT:
10430   case ISD::FP_TO_UINT:
10431     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10432   case ISD::FDIV:
10433     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10434   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10435   case ISD::SHL:
10436   case ISD::SRA:
10437   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10438   case ISD::SIGN_EXTEND:
10439   case ISD::ZERO_EXTEND:
10440   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10441   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10442   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10443   case ARMISD::VLD2DUP:
10444   case ARMISD::VLD3DUP:
10445   case ARMISD::VLD4DUP:
10446     return PerformVLDCombine(N, DCI);
10447   case ARMISD::BUILD_VECTOR:
10448     return PerformARMBUILD_VECTORCombine(N, DCI);
10449   case ISD::INTRINSIC_VOID:
10450   case ISD::INTRINSIC_W_CHAIN:
10451     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10452     case Intrinsic::arm_neon_vld1:
10453     case Intrinsic::arm_neon_vld2:
10454     case Intrinsic::arm_neon_vld3:
10455     case Intrinsic::arm_neon_vld4:
10456     case Intrinsic::arm_neon_vld2lane:
10457     case Intrinsic::arm_neon_vld3lane:
10458     case Intrinsic::arm_neon_vld4lane:
10459     case Intrinsic::arm_neon_vst1:
10460     case Intrinsic::arm_neon_vst2:
10461     case Intrinsic::arm_neon_vst3:
10462     case Intrinsic::arm_neon_vst4:
10463     case Intrinsic::arm_neon_vst2lane:
10464     case Intrinsic::arm_neon_vst3lane:
10465     case Intrinsic::arm_neon_vst4lane:
10466       return PerformVLDCombine(N, DCI);
10467     default: break;
10468     }
10469     break;
10470   }
10471   return SDValue();
10472 }
10473
10474 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10475                                                           EVT VT) const {
10476   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10477 }
10478
10479 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10480                                                        unsigned,
10481                                                        unsigned,
10482                                                        bool *Fast) const {
10483   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10484   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10485
10486   switch (VT.getSimpleVT().SimpleTy) {
10487   default:
10488     return false;
10489   case MVT::i8:
10490   case MVT::i16:
10491   case MVT::i32: {
10492     // Unaligned access can use (for example) LRDB, LRDH, LDR
10493     if (AllowsUnaligned) {
10494       if (Fast)
10495         *Fast = Subtarget->hasV7Ops();
10496       return true;
10497     }
10498     return false;
10499   }
10500   case MVT::f64:
10501   case MVT::v2f64: {
10502     // For any little-endian targets with neon, we can support unaligned ld/st
10503     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10504     // A big-endian target may also explicitly support unaligned accesses
10505     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10506       if (Fast)
10507         *Fast = true;
10508       return true;
10509     }
10510     return false;
10511   }
10512   }
10513 }
10514
10515 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10516                        unsigned AlignCheck) {
10517   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10518           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10519 }
10520
10521 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10522                                            unsigned DstAlign, unsigned SrcAlign,
10523                                            bool IsMemset, bool ZeroMemset,
10524                                            bool MemcpyStrSrc,
10525                                            MachineFunction &MF) const {
10526   const Function *F = MF.getFunction();
10527
10528   // See if we can use NEON instructions for this...
10529   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10530       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10531     bool Fast;
10532     if (Size >= 16 &&
10533         (memOpAlign(SrcAlign, DstAlign, 16) ||
10534          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10535       return MVT::v2f64;
10536     } else if (Size >= 8 &&
10537                (memOpAlign(SrcAlign, DstAlign, 8) ||
10538                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10539                  Fast))) {
10540       return MVT::f64;
10541     }
10542   }
10543
10544   // Lowering to i32/i16 if the size permits.
10545   if (Size >= 4)
10546     return MVT::i32;
10547   else if (Size >= 2)
10548     return MVT::i16;
10549
10550   // Let the target-independent logic figure it out.
10551   return MVT::Other;
10552 }
10553
10554 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10555   if (Val.getOpcode() != ISD::LOAD)
10556     return false;
10557
10558   EVT VT1 = Val.getValueType();
10559   if (!VT1.isSimple() || !VT1.isInteger() ||
10560       !VT2.isSimple() || !VT2.isInteger())
10561     return false;
10562
10563   switch (VT1.getSimpleVT().SimpleTy) {
10564   default: break;
10565   case MVT::i1:
10566   case MVT::i8:
10567   case MVT::i16:
10568     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10569     return true;
10570   }
10571
10572   return false;
10573 }
10574
10575 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10576   EVT VT = ExtVal.getValueType();
10577
10578   if (!isTypeLegal(VT))
10579     return false;
10580
10581   // Don't create a loadext if we can fold the extension into a wide/long
10582   // instruction.
10583   // If there's more than one user instruction, the loadext is desirable no
10584   // matter what.  There can be two uses by the same instruction.
10585   if (ExtVal->use_empty() ||
10586       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10587     return true;
10588
10589   SDNode *U = *ExtVal->use_begin();
10590   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10591        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10592     return false;
10593
10594   return true;
10595 }
10596
10597 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10598   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10599     return false;
10600
10601   if (!isTypeLegal(EVT::getEVT(Ty1)))
10602     return false;
10603
10604   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10605
10606   // Assuming the caller doesn't have a zeroext or signext return parameter,
10607   // truncation all the way down to i1 is valid.
10608   return true;
10609 }
10610
10611
10612 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10613   if (V < 0)
10614     return false;
10615
10616   unsigned Scale = 1;
10617   switch (VT.getSimpleVT().SimpleTy) {
10618   default: return false;
10619   case MVT::i1:
10620   case MVT::i8:
10621     // Scale == 1;
10622     break;
10623   case MVT::i16:
10624     // Scale == 2;
10625     Scale = 2;
10626     break;
10627   case MVT::i32:
10628     // Scale == 4;
10629     Scale = 4;
10630     break;
10631   }
10632
10633   if ((V & (Scale - 1)) != 0)
10634     return false;
10635   V /= Scale;
10636   return V == (V & ((1LL << 5) - 1));
10637 }
10638
10639 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10640                                       const ARMSubtarget *Subtarget) {
10641   bool isNeg = false;
10642   if (V < 0) {
10643     isNeg = true;
10644     V = - V;
10645   }
10646
10647   switch (VT.getSimpleVT().SimpleTy) {
10648   default: return false;
10649   case MVT::i1:
10650   case MVT::i8:
10651   case MVT::i16:
10652   case MVT::i32:
10653     // + imm12 or - imm8
10654     if (isNeg)
10655       return V == (V & ((1LL << 8) - 1));
10656     return V == (V & ((1LL << 12) - 1));
10657   case MVT::f32:
10658   case MVT::f64:
10659     // Same as ARM mode. FIXME: NEON?
10660     if (!Subtarget->hasVFP2())
10661       return false;
10662     if ((V & 3) != 0)
10663       return false;
10664     V >>= 2;
10665     return V == (V & ((1LL << 8) - 1));
10666   }
10667 }
10668
10669 /// isLegalAddressImmediate - Return true if the integer value can be used
10670 /// as the offset of the target addressing mode for load / store of the
10671 /// given type.
10672 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10673                                     const ARMSubtarget *Subtarget) {
10674   if (V == 0)
10675     return true;
10676
10677   if (!VT.isSimple())
10678     return false;
10679
10680   if (Subtarget->isThumb1Only())
10681     return isLegalT1AddressImmediate(V, VT);
10682   else if (Subtarget->isThumb2())
10683     return isLegalT2AddressImmediate(V, VT, Subtarget);
10684
10685   // ARM mode.
10686   if (V < 0)
10687     V = - V;
10688   switch (VT.getSimpleVT().SimpleTy) {
10689   default: return false;
10690   case MVT::i1:
10691   case MVT::i8:
10692   case MVT::i32:
10693     // +- imm12
10694     return V == (V & ((1LL << 12) - 1));
10695   case MVT::i16:
10696     // +- imm8
10697     return V == (V & ((1LL << 8) - 1));
10698   case MVT::f32:
10699   case MVT::f64:
10700     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10701       return false;
10702     if ((V & 3) != 0)
10703       return false;
10704     V >>= 2;
10705     return V == (V & ((1LL << 8) - 1));
10706   }
10707 }
10708
10709 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10710                                                       EVT VT) const {
10711   int Scale = AM.Scale;
10712   if (Scale < 0)
10713     return false;
10714
10715   switch (VT.getSimpleVT().SimpleTy) {
10716   default: return false;
10717   case MVT::i1:
10718   case MVT::i8:
10719   case MVT::i16:
10720   case MVT::i32:
10721     if (Scale == 1)
10722       return true;
10723     // r + r << imm
10724     Scale = Scale & ~1;
10725     return Scale == 2 || Scale == 4 || Scale == 8;
10726   case MVT::i64:
10727     // r + r
10728     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10729       return true;
10730     return false;
10731   case MVT::isVoid:
10732     // Note, we allow "void" uses (basically, uses that aren't loads or
10733     // stores), because arm allows folding a scale into many arithmetic
10734     // operations.  This should be made more precise and revisited later.
10735
10736     // Allow r << imm, but the imm has to be a multiple of two.
10737     if (Scale & 1) return false;
10738     return isPowerOf2_32(Scale);
10739   }
10740 }
10741
10742 /// isLegalAddressingMode - Return true if the addressing mode represented
10743 /// by AM is legal for this target, for a load/store of the specified type.
10744 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10745                                               const AddrMode &AM, Type *Ty,
10746                                               unsigned AS) const {
10747   EVT VT = getValueType(DL, Ty, true);
10748   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10749     return false;
10750
10751   // Can never fold addr of global into load/store.
10752   if (AM.BaseGV)
10753     return false;
10754
10755   switch (AM.Scale) {
10756   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10757     break;
10758   case 1:
10759     if (Subtarget->isThumb1Only())
10760       return false;
10761     // FALL THROUGH.
10762   default:
10763     // ARM doesn't support any R+R*scale+imm addr modes.
10764     if (AM.BaseOffs)
10765       return false;
10766
10767     if (!VT.isSimple())
10768       return false;
10769
10770     if (Subtarget->isThumb2())
10771       return isLegalT2ScaledAddressingMode(AM, VT);
10772
10773     int Scale = AM.Scale;
10774     switch (VT.getSimpleVT().SimpleTy) {
10775     default: return false;
10776     case MVT::i1:
10777     case MVT::i8:
10778     case MVT::i32:
10779       if (Scale < 0) Scale = -Scale;
10780       if (Scale == 1)
10781         return true;
10782       // r + r << imm
10783       return isPowerOf2_32(Scale & ~1);
10784     case MVT::i16:
10785     case MVT::i64:
10786       // r + r
10787       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10788         return true;
10789       return false;
10790
10791     case MVT::isVoid:
10792       // Note, we allow "void" uses (basically, uses that aren't loads or
10793       // stores), because arm allows folding a scale into many arithmetic
10794       // operations.  This should be made more precise and revisited later.
10795
10796       // Allow r << imm, but the imm has to be a multiple of two.
10797       if (Scale & 1) return false;
10798       return isPowerOf2_32(Scale);
10799     }
10800   }
10801   return true;
10802 }
10803
10804 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10805 /// icmp immediate, that is the target has icmp instructions which can compare
10806 /// a register against the immediate without having to materialize the
10807 /// immediate into a register.
10808 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10809   // Thumb2 and ARM modes can use cmn for negative immediates.
10810   if (!Subtarget->isThumb())
10811     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10812   if (Subtarget->isThumb2())
10813     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10814   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10815   return Imm >= 0 && Imm <= 255;
10816 }
10817
10818 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10819 /// *or sub* immediate, that is the target has add or sub instructions which can
10820 /// add a register with the immediate without having to materialize the
10821 /// immediate into a register.
10822 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10823   // Same encoding for add/sub, just flip the sign.
10824   int64_t AbsImm = std::abs(Imm);
10825   if (!Subtarget->isThumb())
10826     return ARM_AM::getSOImmVal(AbsImm) != -1;
10827   if (Subtarget->isThumb2())
10828     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10829   // Thumb1 only has 8-bit unsigned immediate.
10830   return AbsImm >= 0 && AbsImm <= 255;
10831 }
10832
10833 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10834                                       bool isSEXTLoad, SDValue &Base,
10835                                       SDValue &Offset, bool &isInc,
10836                                       SelectionDAG &DAG) {
10837   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10838     return false;
10839
10840   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10841     // AddressingMode 3
10842     Base = Ptr->getOperand(0);
10843     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10844       int RHSC = (int)RHS->getZExtValue();
10845       if (RHSC < 0 && RHSC > -256) {
10846         assert(Ptr->getOpcode() == ISD::ADD);
10847         isInc = false;
10848         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10849         return true;
10850       }
10851     }
10852     isInc = (Ptr->getOpcode() == ISD::ADD);
10853     Offset = Ptr->getOperand(1);
10854     return true;
10855   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10856     // AddressingMode 2
10857     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10858       int RHSC = (int)RHS->getZExtValue();
10859       if (RHSC < 0 && RHSC > -0x1000) {
10860         assert(Ptr->getOpcode() == ISD::ADD);
10861         isInc = false;
10862         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10863         Base = Ptr->getOperand(0);
10864         return true;
10865       }
10866     }
10867
10868     if (Ptr->getOpcode() == ISD::ADD) {
10869       isInc = true;
10870       ARM_AM::ShiftOpc ShOpcVal=
10871         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10872       if (ShOpcVal != ARM_AM::no_shift) {
10873         Base = Ptr->getOperand(1);
10874         Offset = Ptr->getOperand(0);
10875       } else {
10876         Base = Ptr->getOperand(0);
10877         Offset = Ptr->getOperand(1);
10878       }
10879       return true;
10880     }
10881
10882     isInc = (Ptr->getOpcode() == ISD::ADD);
10883     Base = Ptr->getOperand(0);
10884     Offset = Ptr->getOperand(1);
10885     return true;
10886   }
10887
10888   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10889   return false;
10890 }
10891
10892 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10893                                      bool isSEXTLoad, SDValue &Base,
10894                                      SDValue &Offset, bool &isInc,
10895                                      SelectionDAG &DAG) {
10896   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10897     return false;
10898
10899   Base = Ptr->getOperand(0);
10900   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10901     int RHSC = (int)RHS->getZExtValue();
10902     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10903       assert(Ptr->getOpcode() == ISD::ADD);
10904       isInc = false;
10905       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10906       return true;
10907     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10908       isInc = Ptr->getOpcode() == ISD::ADD;
10909       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10910       return true;
10911     }
10912   }
10913
10914   return false;
10915 }
10916
10917 /// getPreIndexedAddressParts - returns true by value, base pointer and
10918 /// offset pointer and addressing mode by reference if the node's address
10919 /// can be legally represented as pre-indexed load / store address.
10920 bool
10921 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10922                                              SDValue &Offset,
10923                                              ISD::MemIndexedMode &AM,
10924                                              SelectionDAG &DAG) const {
10925   if (Subtarget->isThumb1Only())
10926     return false;
10927
10928   EVT VT;
10929   SDValue Ptr;
10930   bool isSEXTLoad = false;
10931   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10932     Ptr = LD->getBasePtr();
10933     VT  = LD->getMemoryVT();
10934     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10935   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10936     Ptr = ST->getBasePtr();
10937     VT  = ST->getMemoryVT();
10938   } else
10939     return false;
10940
10941   bool isInc;
10942   bool isLegal = false;
10943   if (Subtarget->isThumb2())
10944     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10945                                        Offset, isInc, DAG);
10946   else
10947     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10948                                         Offset, isInc, DAG);
10949   if (!isLegal)
10950     return false;
10951
10952   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10953   return true;
10954 }
10955
10956 /// getPostIndexedAddressParts - returns true by value, base pointer and
10957 /// offset pointer and addressing mode by reference if this node can be
10958 /// combined with a load / store to form a post-indexed load / store.
10959 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10960                                                    SDValue &Base,
10961                                                    SDValue &Offset,
10962                                                    ISD::MemIndexedMode &AM,
10963                                                    SelectionDAG &DAG) const {
10964   if (Subtarget->isThumb1Only())
10965     return false;
10966
10967   EVT VT;
10968   SDValue Ptr;
10969   bool isSEXTLoad = false;
10970   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10971     VT  = LD->getMemoryVT();
10972     Ptr = LD->getBasePtr();
10973     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10974   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10975     VT  = ST->getMemoryVT();
10976     Ptr = ST->getBasePtr();
10977   } else
10978     return false;
10979
10980   bool isInc;
10981   bool isLegal = false;
10982   if (Subtarget->isThumb2())
10983     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10984                                        isInc, DAG);
10985   else
10986     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10987                                         isInc, DAG);
10988   if (!isLegal)
10989     return false;
10990
10991   if (Ptr != Base) {
10992     // Swap base ptr and offset to catch more post-index load / store when
10993     // it's legal. In Thumb2 mode, offset must be an immediate.
10994     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10995         !Subtarget->isThumb2())
10996       std::swap(Base, Offset);
10997
10998     // Post-indexed load / store update the base pointer.
10999     if (Ptr != Base)
11000       return false;
11001   }
11002
11003   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11004   return true;
11005 }
11006
11007 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11008                                                       APInt &KnownZero,
11009                                                       APInt &KnownOne,
11010                                                       const SelectionDAG &DAG,
11011                                                       unsigned Depth) const {
11012   unsigned BitWidth = KnownOne.getBitWidth();
11013   KnownZero = KnownOne = APInt(BitWidth, 0);
11014   switch (Op.getOpcode()) {
11015   default: break;
11016   case ARMISD::ADDC:
11017   case ARMISD::ADDE:
11018   case ARMISD::SUBC:
11019   case ARMISD::SUBE:
11020     // These nodes' second result is a boolean
11021     if (Op.getResNo() == 0)
11022       break;
11023     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11024     break;
11025   case ARMISD::CMOV: {
11026     // Bits are known zero/one if known on the LHS and RHS.
11027     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11028     if (KnownZero == 0 && KnownOne == 0) return;
11029
11030     APInt KnownZeroRHS, KnownOneRHS;
11031     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11032     KnownZero &= KnownZeroRHS;
11033     KnownOne  &= KnownOneRHS;
11034     return;
11035   }
11036   case ISD::INTRINSIC_W_CHAIN: {
11037     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11038     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11039     switch (IntID) {
11040     default: return;
11041     case Intrinsic::arm_ldaex:
11042     case Intrinsic::arm_ldrex: {
11043       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11044       unsigned MemBits = VT.getScalarType().getSizeInBits();
11045       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11046       return;
11047     }
11048     }
11049   }
11050   }
11051 }
11052
11053 //===----------------------------------------------------------------------===//
11054 //                           ARM Inline Assembly Support
11055 //===----------------------------------------------------------------------===//
11056
11057 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11058   // Looking for "rev" which is V6+.
11059   if (!Subtarget->hasV6Ops())
11060     return false;
11061
11062   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11063   std::string AsmStr = IA->getAsmString();
11064   SmallVector<StringRef, 4> AsmPieces;
11065   SplitString(AsmStr, AsmPieces, ";\n");
11066
11067   switch (AsmPieces.size()) {
11068   default: return false;
11069   case 1:
11070     AsmStr = AsmPieces[0];
11071     AsmPieces.clear();
11072     SplitString(AsmStr, AsmPieces, " \t,");
11073
11074     // rev $0, $1
11075     if (AsmPieces.size() == 3 &&
11076         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11077         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11078       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11079       if (Ty && Ty->getBitWidth() == 32)
11080         return IntrinsicLowering::LowerToByteSwap(CI);
11081     }
11082     break;
11083   }
11084
11085   return false;
11086 }
11087
11088 /// getConstraintType - Given a constraint letter, return the type of
11089 /// constraint it is for this target.
11090 ARMTargetLowering::ConstraintType
11091 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11092   if (Constraint.size() == 1) {
11093     switch (Constraint[0]) {
11094     default:  break;
11095     case 'l': return C_RegisterClass;
11096     case 'w': return C_RegisterClass;
11097     case 'h': return C_RegisterClass;
11098     case 'x': return C_RegisterClass;
11099     case 't': return C_RegisterClass;
11100     case 'j': return C_Other; // Constant for movw.
11101       // An address with a single base register. Due to the way we
11102       // currently handle addresses it is the same as an 'r' memory constraint.
11103     case 'Q': return C_Memory;
11104     }
11105   } else if (Constraint.size() == 2) {
11106     switch (Constraint[0]) {
11107     default: break;
11108     // All 'U+' constraints are addresses.
11109     case 'U': return C_Memory;
11110     }
11111   }
11112   return TargetLowering::getConstraintType(Constraint);
11113 }
11114
11115 /// Examine constraint type and operand type and determine a weight value.
11116 /// This object must already have been set up with the operand type
11117 /// and the current alternative constraint selected.
11118 TargetLowering::ConstraintWeight
11119 ARMTargetLowering::getSingleConstraintMatchWeight(
11120     AsmOperandInfo &info, const char *constraint) const {
11121   ConstraintWeight weight = CW_Invalid;
11122   Value *CallOperandVal = info.CallOperandVal;
11123     // If we don't have a value, we can't do a match,
11124     // but allow it at the lowest weight.
11125   if (!CallOperandVal)
11126     return CW_Default;
11127   Type *type = CallOperandVal->getType();
11128   // Look at the constraint type.
11129   switch (*constraint) {
11130   default:
11131     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11132     break;
11133   case 'l':
11134     if (type->isIntegerTy()) {
11135       if (Subtarget->isThumb())
11136         weight = CW_SpecificReg;
11137       else
11138         weight = CW_Register;
11139     }
11140     break;
11141   case 'w':
11142     if (type->isFloatingPointTy())
11143       weight = CW_Register;
11144     break;
11145   }
11146   return weight;
11147 }
11148
11149 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11150 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11151     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11152   if (Constraint.size() == 1) {
11153     // GCC ARM Constraint Letters
11154     switch (Constraint[0]) {
11155     case 'l': // Low regs or general regs.
11156       if (Subtarget->isThumb())
11157         return RCPair(0U, &ARM::tGPRRegClass);
11158       return RCPair(0U, &ARM::GPRRegClass);
11159     case 'h': // High regs or no regs.
11160       if (Subtarget->isThumb())
11161         return RCPair(0U, &ARM::hGPRRegClass);
11162       break;
11163     case 'r':
11164       if (Subtarget->isThumb1Only())
11165         return RCPair(0U, &ARM::tGPRRegClass);
11166       return RCPair(0U, &ARM::GPRRegClass);
11167     case 'w':
11168       if (VT == MVT::Other)
11169         break;
11170       if (VT == MVT::f32)
11171         return RCPair(0U, &ARM::SPRRegClass);
11172       if (VT.getSizeInBits() == 64)
11173         return RCPair(0U, &ARM::DPRRegClass);
11174       if (VT.getSizeInBits() == 128)
11175         return RCPair(0U, &ARM::QPRRegClass);
11176       break;
11177     case 'x':
11178       if (VT == MVT::Other)
11179         break;
11180       if (VT == MVT::f32)
11181         return RCPair(0U, &ARM::SPR_8RegClass);
11182       if (VT.getSizeInBits() == 64)
11183         return RCPair(0U, &ARM::DPR_8RegClass);
11184       if (VT.getSizeInBits() == 128)
11185         return RCPair(0U, &ARM::QPR_8RegClass);
11186       break;
11187     case 't':
11188       if (VT == MVT::f32)
11189         return RCPair(0U, &ARM::SPRRegClass);
11190       break;
11191     }
11192   }
11193   if (StringRef("{cc}").equals_lower(Constraint))
11194     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11195
11196   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11197 }
11198
11199 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11200 /// vector.  If it is invalid, don't add anything to Ops.
11201 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11202                                                      std::string &Constraint,
11203                                                      std::vector<SDValue>&Ops,
11204                                                      SelectionDAG &DAG) const {
11205   SDValue Result;
11206
11207   // Currently only support length 1 constraints.
11208   if (Constraint.length() != 1) return;
11209
11210   char ConstraintLetter = Constraint[0];
11211   switch (ConstraintLetter) {
11212   default: break;
11213   case 'j':
11214   case 'I': case 'J': case 'K': case 'L':
11215   case 'M': case 'N': case 'O':
11216     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11217     if (!C)
11218       return;
11219
11220     int64_t CVal64 = C->getSExtValue();
11221     int CVal = (int) CVal64;
11222     // None of these constraints allow values larger than 32 bits.  Check
11223     // that the value fits in an int.
11224     if (CVal != CVal64)
11225       return;
11226
11227     switch (ConstraintLetter) {
11228       case 'j':
11229         // Constant suitable for movw, must be between 0 and
11230         // 65535.
11231         if (Subtarget->hasV6T2Ops())
11232           if (CVal >= 0 && CVal <= 65535)
11233             break;
11234         return;
11235       case 'I':
11236         if (Subtarget->isThumb1Only()) {
11237           // This must be a constant between 0 and 255, for ADD
11238           // immediates.
11239           if (CVal >= 0 && CVal <= 255)
11240             break;
11241         } else if (Subtarget->isThumb2()) {
11242           // A constant that can be used as an immediate value in a
11243           // data-processing instruction.
11244           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11245             break;
11246         } else {
11247           // A constant that can be used as an immediate value in a
11248           // data-processing instruction.
11249           if (ARM_AM::getSOImmVal(CVal) != -1)
11250             break;
11251         }
11252         return;
11253
11254       case 'J':
11255         if (Subtarget->isThumb()) {  // FIXME thumb2
11256           // This must be a constant between -255 and -1, for negated ADD
11257           // immediates. This can be used in GCC with an "n" modifier that
11258           // prints the negated value, for use with SUB instructions. It is
11259           // not useful otherwise but is implemented for compatibility.
11260           if (CVal >= -255 && CVal <= -1)
11261             break;
11262         } else {
11263           // This must be a constant between -4095 and 4095. It is not clear
11264           // what this constraint is intended for. Implemented for
11265           // compatibility with GCC.
11266           if (CVal >= -4095 && CVal <= 4095)
11267             break;
11268         }
11269         return;
11270
11271       case 'K':
11272         if (Subtarget->isThumb1Only()) {
11273           // A 32-bit value where only one byte has a nonzero value. Exclude
11274           // zero to match GCC. This constraint is used by GCC internally for
11275           // constants that can be loaded with a move/shift combination.
11276           // It is not useful otherwise but is implemented for compatibility.
11277           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11278             break;
11279         } else if (Subtarget->isThumb2()) {
11280           // A constant whose bitwise inverse can be used as an immediate
11281           // value in a data-processing instruction. This can be used in GCC
11282           // with a "B" modifier that prints the inverted value, for use with
11283           // BIC and MVN instructions. It is not useful otherwise but is
11284           // implemented for compatibility.
11285           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11286             break;
11287         } else {
11288           // A constant whose bitwise inverse can be used as an immediate
11289           // value in a data-processing instruction. This can be used in GCC
11290           // with a "B" modifier that prints the inverted value, for use with
11291           // BIC and MVN instructions. It is not useful otherwise but is
11292           // implemented for compatibility.
11293           if (ARM_AM::getSOImmVal(~CVal) != -1)
11294             break;
11295         }
11296         return;
11297
11298       case 'L':
11299         if (Subtarget->isThumb1Only()) {
11300           // This must be a constant between -7 and 7,
11301           // for 3-operand ADD/SUB immediate instructions.
11302           if (CVal >= -7 && CVal < 7)
11303             break;
11304         } else if (Subtarget->isThumb2()) {
11305           // A constant whose negation can be used as an immediate value in a
11306           // data-processing instruction. This can be used in GCC with an "n"
11307           // modifier that prints the negated value, for use with SUB
11308           // instructions. It is not useful otherwise but is implemented for
11309           // compatibility.
11310           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11311             break;
11312         } else {
11313           // A constant whose negation can be used as an immediate value in a
11314           // data-processing instruction. This can be used in GCC with an "n"
11315           // modifier that prints the negated value, for use with SUB
11316           // instructions. It is not useful otherwise but is implemented for
11317           // compatibility.
11318           if (ARM_AM::getSOImmVal(-CVal) != -1)
11319             break;
11320         }
11321         return;
11322
11323       case 'M':
11324         if (Subtarget->isThumb()) { // FIXME thumb2
11325           // This must be a multiple of 4 between 0 and 1020, for
11326           // ADD sp + immediate.
11327           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11328             break;
11329         } else {
11330           // A power of two or a constant between 0 and 32.  This is used in
11331           // GCC for the shift amount on shifted register operands, but it is
11332           // useful in general for any shift amounts.
11333           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11334             break;
11335         }
11336         return;
11337
11338       case 'N':
11339         if (Subtarget->isThumb()) {  // FIXME thumb2
11340           // This must be a constant between 0 and 31, for shift amounts.
11341           if (CVal >= 0 && CVal <= 31)
11342             break;
11343         }
11344         return;
11345
11346       case 'O':
11347         if (Subtarget->isThumb()) {  // FIXME thumb2
11348           // This must be a multiple of 4 between -508 and 508, for
11349           // ADD/SUB sp = sp + immediate.
11350           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11351             break;
11352         }
11353         return;
11354     }
11355     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11356     break;
11357   }
11358
11359   if (Result.getNode()) {
11360     Ops.push_back(Result);
11361     return;
11362   }
11363   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11364 }
11365
11366 static RTLIB::Libcall getDivRemLibcall(
11367     const SDNode *N, MVT::SimpleValueType SVT) {
11368   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11369           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11370          "Unhandled Opcode in getDivRemLibcall");
11371   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11372                   N->getOpcode() == ISD::SREM;
11373   RTLIB::Libcall LC;
11374   switch (SVT) {
11375   default: llvm_unreachable("Unexpected request for libcall!");
11376   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11377   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11378   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11379   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11380   }
11381   return LC;
11382 }
11383
11384 static TargetLowering::ArgListTy getDivRemArgList(
11385     const SDNode *N, LLVMContext *Context) {
11386   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11387           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11388          "Unhandled Opcode in getDivRemArgList");
11389   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11390                   N->getOpcode() == ISD::SREM;
11391   TargetLowering::ArgListTy Args;
11392   TargetLowering::ArgListEntry Entry;
11393   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11394     EVT ArgVT = N->getOperand(i).getValueType();
11395     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11396     Entry.Node = N->getOperand(i);
11397     Entry.Ty = ArgTy;
11398     Entry.isSExt = isSigned;
11399     Entry.isZExt = !isSigned;
11400     Args.push_back(Entry);
11401   }
11402   return Args;
11403 }
11404
11405 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11406   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11407          "Register-based DivRem lowering only");
11408   unsigned Opcode = Op->getOpcode();
11409   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11410          "Invalid opcode for Div/Rem lowering");
11411   bool isSigned = (Opcode == ISD::SDIVREM);
11412   EVT VT = Op->getValueType(0);
11413   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11414
11415   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11416                                        VT.getSimpleVT().SimpleTy);
11417   SDValue InChain = DAG.getEntryNode();
11418
11419   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11420                                                     DAG.getContext());
11421
11422   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11423                                          getPointerTy(DAG.getDataLayout()));
11424
11425   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11426
11427   SDLoc dl(Op);
11428   TargetLowering::CallLoweringInfo CLI(DAG);
11429   CLI.setDebugLoc(dl).setChain(InChain)
11430     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11431     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11432
11433   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11434   return CallInfo.first;
11435 }
11436
11437 // Lowers REM using divmod helpers
11438 // see RTABI section 4.2/4.3
11439 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11440   // Build return types (div and rem)
11441   std::vector<Type*> RetTyParams;
11442   Type *RetTyElement;
11443
11444   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11445   default: llvm_unreachable("Unexpected request for libcall!");
11446   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11447   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11448   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11449   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11450   }
11451
11452   RetTyParams.push_back(RetTyElement);
11453   RetTyParams.push_back(RetTyElement);
11454   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11455   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11456
11457   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11458                                                              SimpleTy);
11459   SDValue InChain = DAG.getEntryNode();
11460   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11461   bool isSigned = N->getOpcode() == ISD::SREM;
11462   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11463                                          getPointerTy(DAG.getDataLayout()));
11464
11465   // Lower call
11466   CallLoweringInfo CLI(DAG);
11467   CLI.setChain(InChain)
11468      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11469      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11470   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11471
11472   // Return second (rem) result operand (first contains div)
11473   SDNode *ResNode = CallResult.first.getNode();
11474   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11475   return ResNode->getOperand(1);
11476 }
11477
11478 SDValue
11479 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11480   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11481   SDLoc DL(Op);
11482
11483   // Get the inputs.
11484   SDValue Chain = Op.getOperand(0);
11485   SDValue Size  = Op.getOperand(1);
11486
11487   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11488                               DAG.getConstant(2, DL, MVT::i32));
11489
11490   SDValue Flag;
11491   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11492   Flag = Chain.getValue(1);
11493
11494   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11495   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11496
11497   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11498   Chain = NewSP.getValue(1);
11499
11500   SDValue Ops[2] = { NewSP, Chain };
11501   return DAG.getMergeValues(Ops, DL);
11502 }
11503
11504 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11505   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11506          "Unexpected type for custom-lowering FP_EXTEND");
11507
11508   RTLIB::Libcall LC;
11509   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11510
11511   SDValue SrcVal = Op.getOperand(0);
11512   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11513                      SDLoc(Op)).first;
11514 }
11515
11516 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11517   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11518          Subtarget->isFPOnlySP() &&
11519          "Unexpected type for custom-lowering FP_ROUND");
11520
11521   RTLIB::Libcall LC;
11522   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11523
11524   SDValue SrcVal = Op.getOperand(0);
11525   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11526                      SDLoc(Op)).first;
11527 }
11528
11529 bool
11530 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11531   // The ARM target isn't yet aware of offsets.
11532   return false;
11533 }
11534
11535 bool ARM::isBitFieldInvertedMask(unsigned v) {
11536   if (v == 0xffffffff)
11537     return false;
11538
11539   // there can be 1's on either or both "outsides", all the "inside"
11540   // bits must be 0's
11541   return isShiftedMask_32(~v);
11542 }
11543
11544 /// isFPImmLegal - Returns true if the target can instruction select the
11545 /// specified FP immediate natively. If false, the legalizer will
11546 /// materialize the FP immediate as a load from a constant pool.
11547 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11548   if (!Subtarget->hasVFP3())
11549     return false;
11550   if (VT == MVT::f32)
11551     return ARM_AM::getFP32Imm(Imm) != -1;
11552   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11553     return ARM_AM::getFP64Imm(Imm) != -1;
11554   return false;
11555 }
11556
11557 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11558 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11559 /// specified in the intrinsic calls.
11560 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11561                                            const CallInst &I,
11562                                            unsigned Intrinsic) const {
11563   switch (Intrinsic) {
11564   case Intrinsic::arm_neon_vld1:
11565   case Intrinsic::arm_neon_vld2:
11566   case Intrinsic::arm_neon_vld3:
11567   case Intrinsic::arm_neon_vld4:
11568   case Intrinsic::arm_neon_vld2lane:
11569   case Intrinsic::arm_neon_vld3lane:
11570   case Intrinsic::arm_neon_vld4lane: {
11571     Info.opc = ISD::INTRINSIC_W_CHAIN;
11572     // Conservatively set memVT to the entire set of vectors loaded.
11573     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11574     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11575     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11576     Info.ptrVal = I.getArgOperand(0);
11577     Info.offset = 0;
11578     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11579     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11580     Info.vol = false; // volatile loads with NEON intrinsics not supported
11581     Info.readMem = true;
11582     Info.writeMem = false;
11583     return true;
11584   }
11585   case Intrinsic::arm_neon_vst1:
11586   case Intrinsic::arm_neon_vst2:
11587   case Intrinsic::arm_neon_vst3:
11588   case Intrinsic::arm_neon_vst4:
11589   case Intrinsic::arm_neon_vst2lane:
11590   case Intrinsic::arm_neon_vst3lane:
11591   case Intrinsic::arm_neon_vst4lane: {
11592     Info.opc = ISD::INTRINSIC_VOID;
11593     // Conservatively set memVT to the entire set of vectors stored.
11594     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11595     unsigned NumElts = 0;
11596     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11597       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11598       if (!ArgTy->isVectorTy())
11599         break;
11600       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11601     }
11602     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11603     Info.ptrVal = I.getArgOperand(0);
11604     Info.offset = 0;
11605     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11606     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11607     Info.vol = false; // volatile stores with NEON intrinsics not supported
11608     Info.readMem = false;
11609     Info.writeMem = true;
11610     return true;
11611   }
11612   case Intrinsic::arm_ldaex:
11613   case Intrinsic::arm_ldrex: {
11614     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11615     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11616     Info.opc = ISD::INTRINSIC_W_CHAIN;
11617     Info.memVT = MVT::getVT(PtrTy->getElementType());
11618     Info.ptrVal = I.getArgOperand(0);
11619     Info.offset = 0;
11620     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11621     Info.vol = true;
11622     Info.readMem = true;
11623     Info.writeMem = false;
11624     return true;
11625   }
11626   case Intrinsic::arm_stlex:
11627   case Intrinsic::arm_strex: {
11628     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11629     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11630     Info.opc = ISD::INTRINSIC_W_CHAIN;
11631     Info.memVT = MVT::getVT(PtrTy->getElementType());
11632     Info.ptrVal = I.getArgOperand(1);
11633     Info.offset = 0;
11634     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11635     Info.vol = true;
11636     Info.readMem = false;
11637     Info.writeMem = true;
11638     return true;
11639   }
11640   case Intrinsic::arm_stlexd:
11641   case Intrinsic::arm_strexd: {
11642     Info.opc = ISD::INTRINSIC_W_CHAIN;
11643     Info.memVT = MVT::i64;
11644     Info.ptrVal = I.getArgOperand(2);
11645     Info.offset = 0;
11646     Info.align = 8;
11647     Info.vol = true;
11648     Info.readMem = false;
11649     Info.writeMem = true;
11650     return true;
11651   }
11652   case Intrinsic::arm_ldaexd:
11653   case Intrinsic::arm_ldrexd: {
11654     Info.opc = ISD::INTRINSIC_W_CHAIN;
11655     Info.memVT = MVT::i64;
11656     Info.ptrVal = I.getArgOperand(0);
11657     Info.offset = 0;
11658     Info.align = 8;
11659     Info.vol = true;
11660     Info.readMem = true;
11661     Info.writeMem = false;
11662     return true;
11663   }
11664   default:
11665     break;
11666   }
11667
11668   return false;
11669 }
11670
11671 /// \brief Returns true if it is beneficial to convert a load of a constant
11672 /// to just the constant itself.
11673 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11674                                                           Type *Ty) const {
11675   assert(Ty->isIntegerTy());
11676
11677   unsigned Bits = Ty->getPrimitiveSizeInBits();
11678   if (Bits == 0 || Bits > 32)
11679     return false;
11680   return true;
11681 }
11682
11683 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11684                                         ARM_MB::MemBOpt Domain) const {
11685   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11686
11687   // First, if the target has no DMB, see what fallback we can use.
11688   if (!Subtarget->hasDataBarrier()) {
11689     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11690     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11691     // here.
11692     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11693       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11694       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11695                         Builder.getInt32(0), Builder.getInt32(7),
11696                         Builder.getInt32(10), Builder.getInt32(5)};
11697       return Builder.CreateCall(MCR, args);
11698     } else {
11699       // Instead of using barriers, atomic accesses on these subtargets use
11700       // libcalls.
11701       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11702     }
11703   } else {
11704     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11705     // Only a full system barrier exists in the M-class architectures.
11706     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11707     Constant *CDomain = Builder.getInt32(Domain);
11708     return Builder.CreateCall(DMB, CDomain);
11709   }
11710 }
11711
11712 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11713 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11714                                          AtomicOrdering Ord, bool IsStore,
11715                                          bool IsLoad) const {
11716   if (!getInsertFencesForAtomic())
11717     return nullptr;
11718
11719   switch (Ord) {
11720   case NotAtomic:
11721   case Unordered:
11722     llvm_unreachable("Invalid fence: unordered/non-atomic");
11723   case Monotonic:
11724   case Acquire:
11725     return nullptr; // Nothing to do
11726   case SequentiallyConsistent:
11727     if (!IsStore)
11728       return nullptr; // Nothing to do
11729     /*FALLTHROUGH*/
11730   case Release:
11731   case AcquireRelease:
11732     if (Subtarget->isSwift())
11733       return makeDMB(Builder, ARM_MB::ISHST);
11734     // FIXME: add a comment with a link to documentation justifying this.
11735     else
11736       return makeDMB(Builder, ARM_MB::ISH);
11737   }
11738   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11739 }
11740
11741 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11742                                           AtomicOrdering Ord, bool IsStore,
11743                                           bool IsLoad) const {
11744   if (!getInsertFencesForAtomic())
11745     return nullptr;
11746
11747   switch (Ord) {
11748   case NotAtomic:
11749   case Unordered:
11750     llvm_unreachable("Invalid fence: unordered/not-atomic");
11751   case Monotonic:
11752   case Release:
11753     return nullptr; // Nothing to do
11754   case Acquire:
11755   case AcquireRelease:
11756   case SequentiallyConsistent:
11757     return makeDMB(Builder, ARM_MB::ISH);
11758   }
11759   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11760 }
11761
11762 // Loads and stores less than 64-bits are already atomic; ones above that
11763 // are doomed anyway, so defer to the default libcall and blame the OS when
11764 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11765 // anything for those.
11766 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11767   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11768   return (Size == 64) && !Subtarget->isMClass();
11769 }
11770
11771 // Loads and stores less than 64-bits are already atomic; ones above that
11772 // are doomed anyway, so defer to the default libcall and blame the OS when
11773 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11774 // anything for those.
11775 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11776 // guarantee, see DDI0406C ARM architecture reference manual,
11777 // sections A8.8.72-74 LDRD)
11778 TargetLowering::AtomicExpansionKind
11779 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11780   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11781   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11782                                                   : AtomicExpansionKind::None;
11783 }
11784
11785 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11786 // and up to 64 bits on the non-M profiles
11787 TargetLowering::AtomicExpansionKind
11788 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11789   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11790   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11791              ? AtomicExpansionKind::LLSC
11792              : AtomicExpansionKind::None;
11793 }
11794
11795 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11796     AtomicCmpXchgInst *AI) const {
11797   return true;
11798 }
11799
11800 // This has so far only been implemented for MachO.
11801 bool ARMTargetLowering::useLoadStackGuardNode() const {
11802   return Subtarget->isTargetMachO();
11803 }
11804
11805 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11806                                                   unsigned &Cost) const {
11807   // If we do not have NEON, vector types are not natively supported.
11808   if (!Subtarget->hasNEON())
11809     return false;
11810
11811   // Floating point values and vector values map to the same register file.
11812   // Therefore, although we could do a store extract of a vector type, this is
11813   // better to leave at float as we have more freedom in the addressing mode for
11814   // those.
11815   if (VectorTy->isFPOrFPVectorTy())
11816     return false;
11817
11818   // If the index is unknown at compile time, this is very expensive to lower
11819   // and it is not possible to combine the store with the extract.
11820   if (!isa<ConstantInt>(Idx))
11821     return false;
11822
11823   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11824   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11825   // We can do a store + vector extract on any vector that fits perfectly in a D
11826   // or Q register.
11827   if (BitWidth == 64 || BitWidth == 128) {
11828     Cost = 0;
11829     return true;
11830   }
11831   return false;
11832 }
11833
11834 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11835                                          AtomicOrdering Ord) const {
11836   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11837   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11838   bool IsAcquire = isAtLeastAcquire(Ord);
11839
11840   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11841   // intrinsic must return {i32, i32} and we have to recombine them into a
11842   // single i64 here.
11843   if (ValTy->getPrimitiveSizeInBits() == 64) {
11844     Intrinsic::ID Int =
11845         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11846     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11847
11848     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11849     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11850
11851     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11852     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11853     if (!Subtarget->isLittle())
11854       std::swap (Lo, Hi);
11855     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11856     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11857     return Builder.CreateOr(
11858         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11859   }
11860
11861   Type *Tys[] = { Addr->getType() };
11862   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11863   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11864
11865   return Builder.CreateTruncOrBitCast(
11866       Builder.CreateCall(Ldrex, Addr),
11867       cast<PointerType>(Addr->getType())->getElementType());
11868 }
11869
11870 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11871     IRBuilder<> &Builder) const {
11872   if (!Subtarget->hasV7Ops())
11873     return;
11874   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11875   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11876 }
11877
11878 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11879                                                Value *Addr,
11880                                                AtomicOrdering Ord) const {
11881   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11882   bool IsRelease = isAtLeastRelease(Ord);
11883
11884   // Since the intrinsics must have legal type, the i64 intrinsics take two
11885   // parameters: "i32, i32". We must marshal Val into the appropriate form
11886   // before the call.
11887   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11888     Intrinsic::ID Int =
11889         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11890     Function *Strex = Intrinsic::getDeclaration(M, Int);
11891     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11892
11893     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11894     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11895     if (!Subtarget->isLittle())
11896       std::swap (Lo, Hi);
11897     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11898     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11899   }
11900
11901   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11902   Type *Tys[] = { Addr->getType() };
11903   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11904
11905   return Builder.CreateCall(
11906       Strex, {Builder.CreateZExtOrBitCast(
11907                   Val, Strex->getFunctionType()->getParamType(0)),
11908               Addr});
11909 }
11910
11911 /// \brief Lower an interleaved load into a vldN intrinsic.
11912 ///
11913 /// E.g. Lower an interleaved load (Factor = 2):
11914 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11915 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11916 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11917 ///
11918 ///      Into:
11919 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11920 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11921 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11922 bool ARMTargetLowering::lowerInterleavedLoad(
11923     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11924     ArrayRef<unsigned> Indices, unsigned Factor) const {
11925   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11926          "Invalid interleave factor");
11927   assert(!Shuffles.empty() && "Empty shufflevector input");
11928   assert(Shuffles.size() == Indices.size() &&
11929          "Unmatched number of shufflevectors and indices");
11930
11931   VectorType *VecTy = Shuffles[0]->getType();
11932   Type *EltTy = VecTy->getVectorElementType();
11933
11934   const DataLayout &DL = LI->getModule()->getDataLayout();
11935   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11936   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11937
11938   // Skip if we do not have NEON and skip illegal vector types and vector types
11939   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
11940   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
11941     return false;
11942
11943   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11944   // load integer vectors first and then convert to pointer vectors.
11945   if (EltTy->isPointerTy())
11946     VecTy =
11947         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11948
11949   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11950                                             Intrinsic::arm_neon_vld3,
11951                                             Intrinsic::arm_neon_vld4};
11952
11953   IRBuilder<> Builder(LI);
11954   SmallVector<Value *, 2> Ops;
11955
11956   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11957   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11958   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11959
11960   Type *Tys[] = { VecTy, Int8Ptr };
11961   Function *VldnFunc =
11962       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11963   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11964
11965   // Replace uses of each shufflevector with the corresponding vector loaded
11966   // by ldN.
11967   for (unsigned i = 0; i < Shuffles.size(); i++) {
11968     ShuffleVectorInst *SV = Shuffles[i];
11969     unsigned Index = Indices[i];
11970
11971     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11972
11973     // Convert the integer vector to pointer vector if the element is pointer.
11974     if (EltTy->isPointerTy())
11975       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11976
11977     SV->replaceAllUsesWith(SubVec);
11978   }
11979
11980   return true;
11981 }
11982
11983 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11984 ///
11985 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11986 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11987                                    unsigned NumElts) {
11988   SmallVector<Constant *, 16> Mask;
11989   for (unsigned i = 0; i < NumElts; i++)
11990     Mask.push_back(Builder.getInt32(Start + i));
11991
11992   return ConstantVector::get(Mask);
11993 }
11994
11995 /// \brief Lower an interleaved store into a vstN intrinsic.
11996 ///
11997 /// E.g. Lower an interleaved store (Factor = 3):
11998 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11999 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12000 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12001 ///
12002 ///      Into:
12003 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12004 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12005 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12006 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12007 ///
12008 /// Note that the new shufflevectors will be removed and we'll only generate one
12009 /// vst3 instruction in CodeGen.
12010 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12011                                               ShuffleVectorInst *SVI,
12012                                               unsigned Factor) const {
12013   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12014          "Invalid interleave factor");
12015
12016   VectorType *VecTy = SVI->getType();
12017   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12018          "Invalid interleaved store");
12019
12020   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12021   Type *EltTy = VecTy->getVectorElementType();
12022   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12023
12024   const DataLayout &DL = SI->getModule()->getDataLayout();
12025   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
12026   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12027
12028   // Skip if we do not have NEON and skip illegal vector types and vector types
12029   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12030   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12031       EltIs64Bits)
12032     return false;
12033
12034   Value *Op0 = SVI->getOperand(0);
12035   Value *Op1 = SVI->getOperand(1);
12036   IRBuilder<> Builder(SI);
12037
12038   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12039   // vectors to integer vectors.
12040   if (EltTy->isPointerTy()) {
12041     Type *IntTy = DL.getIntPtrType(EltTy);
12042
12043     // Convert to the corresponding integer vector.
12044     Type *IntVecTy =
12045         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12046     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12047     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12048
12049     SubVecTy = VectorType::get(IntTy, NumSubElts);
12050   }
12051
12052   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12053                                              Intrinsic::arm_neon_vst3,
12054                                              Intrinsic::arm_neon_vst4};
12055   SmallVector<Value *, 6> Ops;
12056
12057   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12058   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12059
12060   Type *Tys[] = { Int8Ptr, SubVecTy };
12061   Function *VstNFunc = Intrinsic::getDeclaration(
12062       SI->getModule(), StoreInts[Factor - 2], Tys);
12063
12064   // Split the shufflevector operands into sub vectors for the new vstN call.
12065   for (unsigned i = 0; i < Factor; i++)
12066     Ops.push_back(Builder.CreateShuffleVector(
12067         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12068
12069   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12070   Builder.CreateCall(VstNFunc, Ops);
12071   return true;
12072 }
12073
12074 enum HABaseType {
12075   HA_UNKNOWN = 0,
12076   HA_FLOAT,
12077   HA_DOUBLE,
12078   HA_VECT64,
12079   HA_VECT128
12080 };
12081
12082 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12083                                    uint64_t &Members) {
12084   if (auto *ST = dyn_cast<StructType>(Ty)) {
12085     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12086       uint64_t SubMembers = 0;
12087       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12088         return false;
12089       Members += SubMembers;
12090     }
12091   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12092     uint64_t SubMembers = 0;
12093     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12094       return false;
12095     Members += SubMembers * AT->getNumElements();
12096   } else if (Ty->isFloatTy()) {
12097     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12098       return false;
12099     Members = 1;
12100     Base = HA_FLOAT;
12101   } else if (Ty->isDoubleTy()) {
12102     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12103       return false;
12104     Members = 1;
12105     Base = HA_DOUBLE;
12106   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12107     Members = 1;
12108     switch (Base) {
12109     case HA_FLOAT:
12110     case HA_DOUBLE:
12111       return false;
12112     case HA_VECT64:
12113       return VT->getBitWidth() == 64;
12114     case HA_VECT128:
12115       return VT->getBitWidth() == 128;
12116     case HA_UNKNOWN:
12117       switch (VT->getBitWidth()) {
12118       case 64:
12119         Base = HA_VECT64;
12120         return true;
12121       case 128:
12122         Base = HA_VECT128;
12123         return true;
12124       default:
12125         return false;
12126       }
12127     }
12128   }
12129
12130   return (Members > 0 && Members <= 4);
12131 }
12132
12133 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12134 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12135 /// passing according to AAPCS rules.
12136 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12137     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12138   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12139       CallingConv::ARM_AAPCS_VFP)
12140     return false;
12141
12142   HABaseType Base = HA_UNKNOWN;
12143   uint64_t Members = 0;
12144   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12145   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12146
12147   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12148   return IsHA || IsIntArray;
12149 }