d49f46004d1e1a22e100603d27bf41fc3c57f046
[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.isFloatingPoint() &&
147       VT != MVT::v2i64 && VT != MVT::v1i64)
148     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
149       setOperationAction(Opcode, VT, Legal);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       static const struct {
175         const RTLIB::Libcall Op;
176         const char * const Name;
177         const ISD::CondCode Cond;
178       } LibraryCalls[] = {
179         // Single-precision floating-point arithmetic.
180         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
184
185         // Double-precision floating-point arithmetic.
186         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
190
191         // Single-precision comparisons.
192         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
193         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
194         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
195         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
196         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
197         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
198         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
199         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
200
201         // Double-precision comparisons.
202         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
203         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
204         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
205         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
206         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
207         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
208         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
209         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
210
211         // Floating-point to integer conversions.
212         // i64 conversions are done via library routines even when generating VFP
213         // instructions, so use the same ones.
214         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
215         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
217         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
218
219         // Conversions between floating types.
220         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
221         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
222
223         // Integer to floating-point conversions.
224         // i64 conversions are done via library routines even when generating VFP
225         // instructions, so use the same ones.
226         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227         // e.g., __floatunsidf vs. __floatunssidfvfp.
228         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
229         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
231         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
232       };
233
234       for (const auto &LC : LibraryCalls) {
235         setLibcallName(LC.Op, LC.Name);
236         if (LC.Cond != ISD::SETCC_INVALID)
237           setCmpLibcallCC(LC.Op, LC.Cond);
238       }
239     }
240
241     // Set the correct calling convention for ARMv7k WatchOS. It's just
242     // AAPCS_VFP for functions as simple as libcalls.
243     if (Subtarget->isTargetWatchOS()) {
244       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
245         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
246     }
247   }
248
249   // These libcalls are not available in 32-bit.
250   setLibcallName(RTLIB::SHL_I128, nullptr);
251   setLibcallName(RTLIB::SRL_I128, nullptr);
252   setLibcallName(RTLIB::SRA_I128, nullptr);
253
254   // RTLIB
255   if (Subtarget->isAAPCS_ABI() &&
256       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
257        Subtarget->isTargetAndroid())) {
258     static const struct {
259       const RTLIB::Libcall Op;
260       const char * const Name;
261       const CallingConv::ID CC;
262       const ISD::CondCode Cond;
263     } LibraryCalls[] = {
264       // Double-precision floating-point arithmetic helper functions
265       // RTABI chapter 4.1.2, Table 2
266       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270
271       // Double-precision floating-point comparison helper functions
272       // RTABI chapter 4.1.2, Table 3
273       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
275       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
281
282       // Single-precision floating-point arithmetic helper functions
283       // RTABI chapter 4.1.2, Table 4
284       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288
289       // Single-precision floating-point comparison helper functions
290       // RTABI chapter 4.1.2, Table 5
291       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
293       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
299
300       // Floating-point to integer conversions.
301       // RTABI chapter 4.1.2, Table 6
302       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310
311       // Conversions between floating types.
312       // RTABI chapter 4.1.2, Table 7
313       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316
317       // Integer to floating-point conversions.
318       // RTABI chapter 4.1.2, Table 8
319       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327
328       // Long long helper functions
329       // RTABI chapter 4.2, Table 9
330       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334
335       // Integer division functions
336       // RTABI chapter 4.3.1
337       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345     };
346
347     for (const auto &LC : LibraryCalls) {
348       setLibcallName(LC.Op, LC.Name);
349       setLibcallCallingConv(LC.Op, LC.CC);
350       if (LC.Cond != ISD::SETCC_INVALID)
351         setCmpLibcallCC(LC.Op, LC.Cond);
352     }
353
354     // EABI dependent RTLIB
355     if (TM.Options.EABIVersion == EABI::EABI4 ||
356         TM.Options.EABIVersion == EABI::EABI5) {
357       static const struct {
358         const RTLIB::Libcall Op;
359         const char *const Name;
360         const CallingConv::ID CC;
361         const ISD::CondCode Cond;
362       } MemOpsLibraryCalls[] = {
363         // Memory operations
364         // RTABI chapter 4.3.4
365         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368       };
369
370       for (const auto &LC : MemOpsLibraryCalls) {
371         setLibcallName(LC.Op, LC.Name);
372         setLibcallCallingConv(LC.Op, LC.CC);
373         if (LC.Cond != ISD::SETCC_INVALID)
374           setCmpLibcallCC(LC.Op, LC.Cond);
375       }
376     }
377   }
378
379   if (Subtarget->isTargetWindows()) {
380     static const struct {
381       const RTLIB::Libcall Op;
382       const char * const Name;
383       const CallingConv::ID CC;
384     } LibraryCalls[] = {
385       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
386       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
387       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
388       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
389       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
390       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
391       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
392       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
393       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
394       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
395       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
396       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
397     };
398
399     for (const auto &LC : LibraryCalls) {
400       setLibcallName(LC.Op, LC.Name);
401       setLibcallCallingConv(LC.Op, LC.CC);
402     }
403   }
404
405   // Use divmod compiler-rt calls for iOS 5.0 and later.
406   if (Subtarget->isTargetWatchOS() ||
407       (Subtarget->isTargetIOS() &&
408        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
409     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
410     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
411   }
412
413   // The half <-> float conversion functions are always soft-float, but are
414   // needed for some targets which use a hard-float calling convention by
415   // default.
416   if (Subtarget->isAAPCS_ABI()) {
417     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
420   } else {
421     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
422     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
423     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
424   }
425
426   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
427   // a __gnu_ prefix (which is the default).
428   if (Subtarget->isTargetAEABI()) {
429     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
430     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
431     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
432   }
433
434   if (Subtarget->isThumb1Only())
435     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
436   else
437     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
438   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
439       !Subtarget->isThumb1Only()) {
440     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
441     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
442   }
443
444   for (MVT VT : MVT::vector_valuetypes()) {
445     for (MVT InnerVT : MVT::vector_valuetypes()) {
446       setTruncStoreAction(VT, InnerVT, Expand);
447       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
448       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
449       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
450     }
451
452     setOperationAction(ISD::MULHS, VT, Expand);
453     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
454     setOperationAction(ISD::MULHU, VT, Expand);
455     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
456
457     setOperationAction(ISD::BSWAP, VT, Expand);
458   }
459
460   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
461   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
462
463   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
464   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
465
466   if (Subtarget->hasNEON()) {
467     addDRTypeForNEON(MVT::v2f32);
468     addDRTypeForNEON(MVT::v8i8);
469     addDRTypeForNEON(MVT::v4i16);
470     addDRTypeForNEON(MVT::v2i32);
471     addDRTypeForNEON(MVT::v1i64);
472
473     addQRTypeForNEON(MVT::v4f32);
474     addQRTypeForNEON(MVT::v2f64);
475     addQRTypeForNEON(MVT::v16i8);
476     addQRTypeForNEON(MVT::v8i16);
477     addQRTypeForNEON(MVT::v4i32);
478     addQRTypeForNEON(MVT::v2i64);
479
480     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
481     // neither Neon nor VFP support any arithmetic operations on it.
482     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
483     // supported for v4f32.
484     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
485     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
486     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
487     // FIXME: Code duplication: FDIV and FREM are expanded always, see
488     // ARMTargetLowering::addTypeForNEON method for details.
489     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
490     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
491     // FIXME: Create unittest.
492     // In another words, find a way when "copysign" appears in DAG with vector
493     // operands.
494     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
495     // FIXME: Code duplication: SETCC has custom operation action, see
496     // ARMTargetLowering::addTypeForNEON method for details.
497     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
498     // FIXME: Create unittest for FNEG and for FABS.
499     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
501     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
502     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
503     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
504     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
505     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
506     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
507     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
508     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
509     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
510     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
511     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
512     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
513     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
514     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
515     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
516     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
517     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
518
519     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
520     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
521     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
522     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
523     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
524     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
525     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
526     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
527     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
528     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
529     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
530     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
531     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
532     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
533     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
534
535     // Mark v2f32 intrinsics.
536     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
537     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
538     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
539     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
540     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
541     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
542     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
543     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
544     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
545     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
546     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
547     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
548     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
549     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
550     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
551
552     // Neon does not support some operations on v1i64 and v2i64 types.
553     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
554     // Custom handling for some quad-vector types to detect VMULL.
555     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
556     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
557     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
558     // Custom handling for some vector types to avoid expensive expansions
559     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
560     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
561     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
562     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
563     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
564     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
565     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
566     // a destination type that is wider than the source, and nor does
567     // it have a FP_TO_[SU]INT instruction with a narrower destination than
568     // source.
569     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
570     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
571     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
572     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
573
574     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
575     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
576
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585     // NEON does not have single instruction CTTZ for vectors.
586     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
587     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
588     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
589     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
590
591     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
592     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
593     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
594     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
595
596     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
597     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
598     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
599     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
600
601     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
602     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
603     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
604     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
605
606     // NEON only has FMA instructions as of VFP4.
607     if (!Subtarget->hasVFP4()) {
608       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
609       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
610     }
611
612     setTargetDAGCombine(ISD::INTRINSIC_VOID);
613     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
614     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
615     setTargetDAGCombine(ISD::SHL);
616     setTargetDAGCombine(ISD::SRL);
617     setTargetDAGCombine(ISD::SRA);
618     setTargetDAGCombine(ISD::SIGN_EXTEND);
619     setTargetDAGCombine(ISD::ZERO_EXTEND);
620     setTargetDAGCombine(ISD::ANY_EXTEND);
621     setTargetDAGCombine(ISD::BUILD_VECTOR);
622     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
623     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
624     setTargetDAGCombine(ISD::STORE);
625     setTargetDAGCombine(ISD::FP_TO_SINT);
626     setTargetDAGCombine(ISD::FP_TO_UINT);
627     setTargetDAGCombine(ISD::FDIV);
628     setTargetDAGCombine(ISD::LOAD);
629
630     // It is legal to extload from v4i8 to v4i16 or v4i32.
631     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
632                    MVT::v2i32}) {
633       for (MVT VT : MVT::integer_vector_valuetypes()) {
634         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
635         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
636         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
637       }
638     }
639   }
640
641   // ARM and Thumb2 support UMLAL/SMLAL.
642   if (!Subtarget->isThumb1Only())
643     setTargetDAGCombine(ISD::ADDC);
644
645   if (Subtarget->isFPOnlySP()) {
646     // When targeting a floating-point unit with only single-precision
647     // operations, f64 is legal for the few double-precision instructions which
648     // are present However, no double-precision operations other than moves,
649     // loads and stores are provided by the hardware.
650     setOperationAction(ISD::FADD,       MVT::f64, Expand);
651     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
652     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
653     setOperationAction(ISD::FMA,        MVT::f64, Expand);
654     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
655     setOperationAction(ISD::FREM,       MVT::f64, Expand);
656     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
657     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
658     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
659     setOperationAction(ISD::FABS,       MVT::f64, Expand);
660     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
661     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
662     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
663     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
664     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
665     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
666     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
667     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
668     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
669     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
670     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
671     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
672     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
673     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
674     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
675     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
676     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
677     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
678     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
679     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
680     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
681     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
682     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
683   }
684
685   computeRegisterProperties(Subtarget->getRegisterInfo());
686
687   // ARM does not have floating-point extending loads.
688   for (MVT VT : MVT::fp_valuetypes()) {
689     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
690     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
691   }
692
693   // ... or truncating stores
694   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
695   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
696   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
697
698   // ARM does not have i1 sign extending load.
699   for (MVT VT : MVT::integer_valuetypes())
700     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
701
702   // ARM supports all 4 flavors of integer indexed load / store.
703   if (!Subtarget->isThumb1Only()) {
704     for (unsigned im = (unsigned)ISD::PRE_INC;
705          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
706       setIndexedLoadAction(im,  MVT::i1,  Legal);
707       setIndexedLoadAction(im,  MVT::i8,  Legal);
708       setIndexedLoadAction(im,  MVT::i16, Legal);
709       setIndexedLoadAction(im,  MVT::i32, Legal);
710       setIndexedStoreAction(im, MVT::i1,  Legal);
711       setIndexedStoreAction(im, MVT::i8,  Legal);
712       setIndexedStoreAction(im, MVT::i16, Legal);
713       setIndexedStoreAction(im, MVT::i32, Legal);
714     }
715   }
716
717   setOperationAction(ISD::SADDO, MVT::i32, Custom);
718   setOperationAction(ISD::UADDO, MVT::i32, Custom);
719   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
720   setOperationAction(ISD::USUBO, MVT::i32, Custom);
721
722   // i64 operation support.
723   setOperationAction(ISD::MUL,     MVT::i64, Expand);
724   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
725   if (Subtarget->isThumb1Only()) {
726     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
727     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
728   }
729   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
730       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
731     setOperationAction(ISD::MULHS, MVT::i32, Expand);
732
733   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
734   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
735   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
736   setOperationAction(ISD::SRL,       MVT::i64, Custom);
737   setOperationAction(ISD::SRA,       MVT::i64, Custom);
738
739   if (!Subtarget->isThumb1Only()) {
740     // FIXME: We should do this for Thumb1 as well.
741     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
742     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
743     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
744     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
745   }
746
747   if (!Subtarget->isThumb1Only())
748     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
749
750   // ARM does not have ROTL.
751   setOperationAction(ISD::ROTL, MVT::i32, Expand);
752   for (MVT VT : MVT::vector_valuetypes()) {
753     setOperationAction(ISD::ROTL, VT, Expand);
754     setOperationAction(ISD::ROTR, VT, Expand);
755   }
756   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
757   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
758   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
759     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
760
761   // These just redirect to CTTZ and CTLZ on ARM.
762   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
763   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
764
765   // @llvm.readcyclecounter requires the Performance Monitors extension.
766   // Default to the 0 expansion on unsupported platforms.
767   // FIXME: Technically there are older ARM CPUs that have
768   // implementation-specific ways of obtaining this information.
769   if (Subtarget->hasPerfMon())
770     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
771
772   // Only ARMv6 has BSWAP.
773   if (!Subtarget->hasV6Ops())
774     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
775
776   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
777       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
778     // These are expanded into libcalls if the cpu doesn't have HW divider.
779     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
780     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
781   }
782
783   setOperationAction(ISD::SREM,  MVT::i32, Expand);
784   setOperationAction(ISD::UREM,  MVT::i32, Expand);
785   // Register based DivRem for AEABI (RTABI 4.2)
786   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
787     setOperationAction(ISD::SREM, MVT::i64, Custom);
788     setOperationAction(ISD::UREM, MVT::i64, Custom);
789
790     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
791     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
792     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
793     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
794     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
795     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
796     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
797     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
798
799     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
800     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
801     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
802     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
803     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
804     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
805     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
806     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
807
808     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
809     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
810   } else {
811     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
812     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
813   }
814
815   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
816   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
817   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
818   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
819
820   setOperationAction(ISD::TRAP, MVT::Other, Legal);
821
822   // Use the default implementation.
823   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
824   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
825   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
826   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
827   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
828   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
829
830   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
831     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
832   else
833     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
834
835   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
836   // the default expansion. If we are targeting a single threaded system,
837   // then set them all for expand so we can lower them later into their
838   // non-atomic form.
839   if (TM.Options.ThreadModel == ThreadModel::Single)
840     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
841   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
842     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
843     // to ldrex/strex loops already.
844     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
845
846     // On v8, we have particularly efficient implementations of atomic fences
847     // if they can be combined with nearby atomic loads and stores.
848     if (!Subtarget->hasV8Ops()) {
849       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
850       setInsertFencesForAtomic(true);
851     }
852   } else {
853     // If there's anything we can use as a barrier, go through custom lowering
854     // for ATOMIC_FENCE.
855     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
856                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
857
858     // Set them all for expansion, which will force libcalls.
859     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
860     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
861     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
862     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
863     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
864     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
865     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
866     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
867     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
868     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
869     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
870     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
871     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
872     // Unordered/Monotonic case.
873     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
874     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
875   }
876
877   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
878
879   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
880   if (!Subtarget->hasV6Ops()) {
881     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
882     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
883   }
884   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
885
886   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
887       !Subtarget->isThumb1Only()) {
888     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
889     // iff target supports vfp2.
890     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
891     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
892   }
893
894   // We want to custom lower some of our intrinsics.
895   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
896   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
897   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
898   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
899   if (Subtarget->useSjLjEH())
900     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
901
902   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
903   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
904   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
905   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
906   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
907   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
908   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
909   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
910   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
911
912   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
913   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
914   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
915   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
916   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
917
918   // We don't support sin/cos/fmod/copysign/pow
919   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
920   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
921   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
922   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
923   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
924   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
925   setOperationAction(ISD::FREM,      MVT::f64, Expand);
926   setOperationAction(ISD::FREM,      MVT::f32, Expand);
927   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
928       !Subtarget->isThumb1Only()) {
929     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
930     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
931   }
932   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
933   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
934
935   if (!Subtarget->hasVFP4()) {
936     setOperationAction(ISD::FMA, MVT::f64, Expand);
937     setOperationAction(ISD::FMA, MVT::f32, Expand);
938   }
939
940   // Various VFP goodness
941   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
942     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
943     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
944       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
945       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
946     }
947
948     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
949     if (!Subtarget->hasFP16()) {
950       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
951       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
952     }
953   }
954
955   // Combine sin / cos into one node or libcall if possible.
956   if (Subtarget->hasSinCos()) {
957     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
958     setLibcallName(RTLIB::SINCOS_F64, "sincos");
959     if (Subtarget->isTargetWatchOS()) {
960       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
961       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
962     }
963     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
964       // For iOS, we don't want to the normal expansion of a libcall to
965       // sincos. We want to issue a libcall to __sincos_stret.
966       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
967       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
968     }
969   }
970
971   // FP-ARMv8 implements a lot of rounding-like FP operations.
972   if (Subtarget->hasFPARMv8()) {
973     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
974     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
975     setOperationAction(ISD::FROUND, MVT::f32, Legal);
976     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
977     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
978     setOperationAction(ISD::FRINT, MVT::f32, Legal);
979     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
980     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
981     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
982     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
983     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
984     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
985
986     if (!Subtarget->isFPOnlySP()) {
987       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
988       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
989       setOperationAction(ISD::FROUND, MVT::f64, Legal);
990       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
991       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
992       setOperationAction(ISD::FRINT, MVT::f64, Legal);
993       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
994       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
995     }
996   }
997
998   if (Subtarget->hasNEON()) {
999     // vmin and vmax aren't available in a scalar form, so we use
1000     // a NEON instruction with an undef lane instead.
1001     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1002     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1003     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1004     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1005     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1006     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1007   }
1008
1009   // We have target-specific dag combine patterns for the following nodes:
1010   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1011   setTargetDAGCombine(ISD::ADD);
1012   setTargetDAGCombine(ISD::SUB);
1013   setTargetDAGCombine(ISD::MUL);
1014   setTargetDAGCombine(ISD::AND);
1015   setTargetDAGCombine(ISD::OR);
1016   setTargetDAGCombine(ISD::XOR);
1017
1018   if (Subtarget->hasV6Ops())
1019     setTargetDAGCombine(ISD::SRL);
1020
1021   setStackPointerRegisterToSaveRestore(ARM::SP);
1022
1023   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1024       !Subtarget->hasVFP2())
1025     setSchedulingPreference(Sched::RegPressure);
1026   else
1027     setSchedulingPreference(Sched::Hybrid);
1028
1029   //// temporary - rewrite interface to use type
1030   MaxStoresPerMemset = 8;
1031   MaxStoresPerMemsetOptSize = 4;
1032   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1033   MaxStoresPerMemcpyOptSize = 2;
1034   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1035   MaxStoresPerMemmoveOptSize = 2;
1036
1037   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1038   // are at least 4 bytes aligned.
1039   setMinStackArgumentAlignment(4);
1040
1041   // Prefer likely predicted branches to selects on out-of-order cores.
1042   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1043
1044   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1045 }
1046
1047 bool ARMTargetLowering::useSoftFloat() const {
1048   return Subtarget->useSoftFloat();
1049 }
1050
1051 // FIXME: It might make sense to define the representative register class as the
1052 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1053 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1054 // SPR's representative would be DPR_VFP2. This should work well if register
1055 // pressure tracking were modified such that a register use would increment the
1056 // pressure of the register class's representative and all of it's super
1057 // classes' representatives transitively. We have not implemented this because
1058 // of the difficulty prior to coalescing of modeling operand register classes
1059 // due to the common occurrence of cross class copies and subregister insertions
1060 // and extractions.
1061 std::pair<const TargetRegisterClass *, uint8_t>
1062 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1063                                            MVT VT) const {
1064   const TargetRegisterClass *RRC = nullptr;
1065   uint8_t Cost = 1;
1066   switch (VT.SimpleTy) {
1067   default:
1068     return TargetLowering::findRepresentativeClass(TRI, VT);
1069   // Use DPR as representative register class for all floating point
1070   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1071   // the cost is 1 for both f32 and f64.
1072   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1073   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1074     RRC = &ARM::DPRRegClass;
1075     // When NEON is used for SP, only half of the register file is available
1076     // because operations that define both SP and DP results will be constrained
1077     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1078     // coalescing by double-counting the SP regs. See the FIXME above.
1079     if (Subtarget->useNEONForSinglePrecisionFP())
1080       Cost = 2;
1081     break;
1082   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1083   case MVT::v4f32: case MVT::v2f64:
1084     RRC = &ARM::DPRRegClass;
1085     Cost = 2;
1086     break;
1087   case MVT::v4i64:
1088     RRC = &ARM::DPRRegClass;
1089     Cost = 4;
1090     break;
1091   case MVT::v8i64:
1092     RRC = &ARM::DPRRegClass;
1093     Cost = 8;
1094     break;
1095   }
1096   return std::make_pair(RRC, Cost);
1097 }
1098
1099 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1100   switch ((ARMISD::NodeType)Opcode) {
1101   case ARMISD::FIRST_NUMBER:  break;
1102   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1103   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1104   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1105   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1106   case ARMISD::CALL:          return "ARMISD::CALL";
1107   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1108   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1109   case ARMISD::tCALL:         return "ARMISD::tCALL";
1110   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1111   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1112   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1113   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1114   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1115   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1116   case ARMISD::CMP:           return "ARMISD::CMP";
1117   case ARMISD::CMN:           return "ARMISD::CMN";
1118   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1119   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1120   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1121   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1122   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1123
1124   case ARMISD::CMOV:          return "ARMISD::CMOV";
1125
1126   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1127   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1128   case ARMISD::RRX:           return "ARMISD::RRX";
1129
1130   case ARMISD::ADDC:          return "ARMISD::ADDC";
1131   case ARMISD::ADDE:          return "ARMISD::ADDE";
1132   case ARMISD::SUBC:          return "ARMISD::SUBC";
1133   case ARMISD::SUBE:          return "ARMISD::SUBE";
1134
1135   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1136   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1137
1138   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1139   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1140   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1141
1142   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1143
1144   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1145
1146   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1147
1148   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1149
1150   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1151
1152   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1153   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1154
1155   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1156   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1157   case ARMISD::VCGE:          return "ARMISD::VCGE";
1158   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1159   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1160   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1161   case ARMISD::VCGT:          return "ARMISD::VCGT";
1162   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1163   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1164   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1165   case ARMISD::VTST:          return "ARMISD::VTST";
1166
1167   case ARMISD::VSHL:          return "ARMISD::VSHL";
1168   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1169   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1170   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1171   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1172   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1173   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1174   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1175   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1176   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1177   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1178   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1179   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1180   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1181   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1182   case ARMISD::VSLI:          return "ARMISD::VSLI";
1183   case ARMISD::VSRI:          return "ARMISD::VSRI";
1184   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1185   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1186   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1187   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1188   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1189   case ARMISD::VDUP:          return "ARMISD::VDUP";
1190   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1191   case ARMISD::VEXT:          return "ARMISD::VEXT";
1192   case ARMISD::VREV64:        return "ARMISD::VREV64";
1193   case ARMISD::VREV32:        return "ARMISD::VREV32";
1194   case ARMISD::VREV16:        return "ARMISD::VREV16";
1195   case ARMISD::VZIP:          return "ARMISD::VZIP";
1196   case ARMISD::VUZP:          return "ARMISD::VUZP";
1197   case ARMISD::VTRN:          return "ARMISD::VTRN";
1198   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1199   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1200   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1201   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1202   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1203   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1204   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1205   case ARMISD::BFI:           return "ARMISD::BFI";
1206   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1207   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1208   case ARMISD::VBSL:          return "ARMISD::VBSL";
1209   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1210   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1211   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1212   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1213   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1214   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1215   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1216   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1217   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1218   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1219   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1220   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1221   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1222   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1223   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1224   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1225   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1226   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1227   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1228   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1229   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1230   }
1231   return nullptr;
1232 }
1233
1234 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1235                                           EVT VT) const {
1236   if (!VT.isVector())
1237     return getPointerTy(DL);
1238   return VT.changeVectorElementTypeToInteger();
1239 }
1240
1241 /// getRegClassFor - Return the register class that should be used for the
1242 /// specified value type.
1243 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1244   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1245   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1246   // load / store 4 to 8 consecutive D registers.
1247   if (Subtarget->hasNEON()) {
1248     if (VT == MVT::v4i64)
1249       return &ARM::QQPRRegClass;
1250     if (VT == MVT::v8i64)
1251       return &ARM::QQQQPRRegClass;
1252   }
1253   return TargetLowering::getRegClassFor(VT);
1254 }
1255
1256 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1257 // source/dest is aligned and the copy size is large enough. We therefore want
1258 // to align such objects passed to memory intrinsics.
1259 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1260                                                unsigned &PrefAlign) const {
1261   if (!isa<MemIntrinsic>(CI))
1262     return false;
1263   MinSize = 8;
1264   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1265   // cycle faster than 4-byte aligned LDM.
1266   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1267   return true;
1268 }
1269
1270 // Create a fast isel object.
1271 FastISel *
1272 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1273                                   const TargetLibraryInfo *libInfo) const {
1274   return ARM::createFastISel(funcInfo, libInfo);
1275 }
1276
1277 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1278   unsigned NumVals = N->getNumValues();
1279   if (!NumVals)
1280     return Sched::RegPressure;
1281
1282   for (unsigned i = 0; i != NumVals; ++i) {
1283     EVT VT = N->getValueType(i);
1284     if (VT == MVT::Glue || VT == MVT::Other)
1285       continue;
1286     if (VT.isFloatingPoint() || VT.isVector())
1287       return Sched::ILP;
1288   }
1289
1290   if (!N->isMachineOpcode())
1291     return Sched::RegPressure;
1292
1293   // Load are scheduled for latency even if there instruction itinerary
1294   // is not available.
1295   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1296   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1297
1298   if (MCID.getNumDefs() == 0)
1299     return Sched::RegPressure;
1300   if (!Itins->isEmpty() &&
1301       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1302     return Sched::ILP;
1303
1304   return Sched::RegPressure;
1305 }
1306
1307 //===----------------------------------------------------------------------===//
1308 // Lowering Code
1309 //===----------------------------------------------------------------------===//
1310
1311 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1312 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1313   switch (CC) {
1314   default: llvm_unreachable("Unknown condition code!");
1315   case ISD::SETNE:  return ARMCC::NE;
1316   case ISD::SETEQ:  return ARMCC::EQ;
1317   case ISD::SETGT:  return ARMCC::GT;
1318   case ISD::SETGE:  return ARMCC::GE;
1319   case ISD::SETLT:  return ARMCC::LT;
1320   case ISD::SETLE:  return ARMCC::LE;
1321   case ISD::SETUGT: return ARMCC::HI;
1322   case ISD::SETUGE: return ARMCC::HS;
1323   case ISD::SETULT: return ARMCC::LO;
1324   case ISD::SETULE: return ARMCC::LS;
1325   }
1326 }
1327
1328 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1329 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1330                         ARMCC::CondCodes &CondCode2) {
1331   CondCode2 = ARMCC::AL;
1332   switch (CC) {
1333   default: llvm_unreachable("Unknown FP condition!");
1334   case ISD::SETEQ:
1335   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1336   case ISD::SETGT:
1337   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1338   case ISD::SETGE:
1339   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1340   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1341   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1342   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1343   case ISD::SETO:   CondCode = ARMCC::VC; break;
1344   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1345   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1346   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1347   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1348   case ISD::SETLT:
1349   case ISD::SETULT: CondCode = ARMCC::LT; break;
1350   case ISD::SETLE:
1351   case ISD::SETULE: CondCode = ARMCC::LE; break;
1352   case ISD::SETNE:
1353   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1354   }
1355 }
1356
1357 //===----------------------------------------------------------------------===//
1358 //                      Calling Convention Implementation
1359 //===----------------------------------------------------------------------===//
1360
1361 #include "ARMGenCallingConv.inc"
1362
1363 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1364 /// account presence of floating point hardware and calling convention
1365 /// limitations, such as support for variadic functions.
1366 CallingConv::ID
1367 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1368                                            bool isVarArg) const {
1369   switch (CC) {
1370   default:
1371     llvm_unreachable("Unsupported calling convention");
1372   case CallingConv::ARM_AAPCS:
1373   case CallingConv::ARM_APCS:
1374   case CallingConv::GHC:
1375     return CC;
1376   case CallingConv::ARM_AAPCS_VFP:
1377     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1378   case CallingConv::C:
1379     if (!Subtarget->isAAPCS_ABI())
1380       return CallingConv::ARM_APCS;
1381     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1382              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1383              !isVarArg)
1384       return CallingConv::ARM_AAPCS_VFP;
1385     else
1386       return CallingConv::ARM_AAPCS;
1387   case CallingConv::Fast:
1388     if (!Subtarget->isAAPCS_ABI()) {
1389       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1390         return CallingConv::Fast;
1391       return CallingConv::ARM_APCS;
1392     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1393       return CallingConv::ARM_AAPCS_VFP;
1394     else
1395       return CallingConv::ARM_AAPCS;
1396   }
1397 }
1398
1399 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1400 /// CallingConvention.
1401 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1402                                                  bool Return,
1403                                                  bool isVarArg) const {
1404   switch (getEffectiveCallingConv(CC, isVarArg)) {
1405   default:
1406     llvm_unreachable("Unsupported calling convention");
1407   case CallingConv::ARM_APCS:
1408     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1409   case CallingConv::ARM_AAPCS:
1410     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1411   case CallingConv::ARM_AAPCS_VFP:
1412     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1413   case CallingConv::Fast:
1414     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1415   case CallingConv::GHC:
1416     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1417   }
1418 }
1419
1420 /// LowerCallResult - Lower the result values of a call into the
1421 /// appropriate copies out of appropriate physical registers.
1422 SDValue
1423 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1424                                    CallingConv::ID CallConv, bool isVarArg,
1425                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1426                                    SDLoc dl, SelectionDAG &DAG,
1427                                    SmallVectorImpl<SDValue> &InVals,
1428                                    bool isThisReturn, SDValue ThisVal) const {
1429
1430   // Assign locations to each value returned by this call.
1431   SmallVector<CCValAssign, 16> RVLocs;
1432   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1433                     *DAG.getContext(), Call);
1434   CCInfo.AnalyzeCallResult(Ins,
1435                            CCAssignFnForNode(CallConv, /* Return*/ true,
1436                                              isVarArg));
1437
1438   // Copy all of the result registers out of their specified physreg.
1439   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1440     CCValAssign VA = RVLocs[i];
1441
1442     // Pass 'this' value directly from the argument to return value, to avoid
1443     // reg unit interference
1444     if (i == 0 && isThisReturn) {
1445       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1446              "unexpected return calling convention register assignment");
1447       InVals.push_back(ThisVal);
1448       continue;
1449     }
1450
1451     SDValue Val;
1452     if (VA.needsCustom()) {
1453       // Handle f64 or half of a v2f64.
1454       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1455                                       InFlag);
1456       Chain = Lo.getValue(1);
1457       InFlag = Lo.getValue(2);
1458       VA = RVLocs[++i]; // skip ahead to next loc
1459       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1460                                       InFlag);
1461       Chain = Hi.getValue(1);
1462       InFlag = Hi.getValue(2);
1463       if (!Subtarget->isLittle())
1464         std::swap (Lo, Hi);
1465       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1466
1467       if (VA.getLocVT() == MVT::v2f64) {
1468         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1469         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1470                           DAG.getConstant(0, dl, MVT::i32));
1471
1472         VA = RVLocs[++i]; // skip ahead to next loc
1473         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1474         Chain = Lo.getValue(1);
1475         InFlag = Lo.getValue(2);
1476         VA = RVLocs[++i]; // skip ahead to next loc
1477         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1478         Chain = Hi.getValue(1);
1479         InFlag = Hi.getValue(2);
1480         if (!Subtarget->isLittle())
1481           std::swap (Lo, Hi);
1482         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1483         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1484                           DAG.getConstant(1, dl, MVT::i32));
1485       }
1486     } else {
1487       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1488                                InFlag);
1489       Chain = Val.getValue(1);
1490       InFlag = Val.getValue(2);
1491     }
1492
1493     switch (VA.getLocInfo()) {
1494     default: llvm_unreachable("Unknown loc info!");
1495     case CCValAssign::Full: break;
1496     case CCValAssign::BCvt:
1497       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1498       break;
1499     }
1500
1501     InVals.push_back(Val);
1502   }
1503
1504   return Chain;
1505 }
1506
1507 /// LowerMemOpCallTo - Store the argument to the stack.
1508 SDValue
1509 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1510                                     SDValue StackPtr, SDValue Arg,
1511                                     SDLoc dl, SelectionDAG &DAG,
1512                                     const CCValAssign &VA,
1513                                     ISD::ArgFlagsTy Flags) const {
1514   unsigned LocMemOffset = VA.getLocMemOffset();
1515   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1516   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1517                        StackPtr, PtrOff);
1518   return DAG.getStore(
1519       Chain, dl, Arg, PtrOff,
1520       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1521       false, false, 0);
1522 }
1523
1524 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1525                                          SDValue Chain, SDValue &Arg,
1526                                          RegsToPassVector &RegsToPass,
1527                                          CCValAssign &VA, CCValAssign &NextVA,
1528                                          SDValue &StackPtr,
1529                                          SmallVectorImpl<SDValue> &MemOpChains,
1530                                          ISD::ArgFlagsTy Flags) const {
1531
1532   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1533                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1534   unsigned id = Subtarget->isLittle() ? 0 : 1;
1535   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1536
1537   if (NextVA.isRegLoc())
1538     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1539   else {
1540     assert(NextVA.isMemLoc());
1541     if (!StackPtr.getNode())
1542       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1543                                     getPointerTy(DAG.getDataLayout()));
1544
1545     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1546                                            dl, DAG, NextVA,
1547                                            Flags));
1548   }
1549 }
1550
1551 /// LowerCall - Lowering a call into a callseq_start <-
1552 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1553 /// nodes.
1554 SDValue
1555 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1556                              SmallVectorImpl<SDValue> &InVals) const {
1557   SelectionDAG &DAG                     = CLI.DAG;
1558   SDLoc &dl                             = CLI.DL;
1559   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1560   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1561   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1562   SDValue Chain                         = CLI.Chain;
1563   SDValue Callee                        = CLI.Callee;
1564   bool &isTailCall                      = CLI.IsTailCall;
1565   CallingConv::ID CallConv              = CLI.CallConv;
1566   bool doesNotRet                       = CLI.DoesNotReturn;
1567   bool isVarArg                         = CLI.IsVarArg;
1568
1569   MachineFunction &MF = DAG.getMachineFunction();
1570   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1571   bool isThisReturn   = false;
1572   bool isSibCall      = false;
1573   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1574
1575   // Disable tail calls if they're not supported.
1576   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1577     isTailCall = false;
1578
1579   if (isTailCall) {
1580     // Check if it's really possible to do a tail call.
1581     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1582                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1583                                                    Outs, OutVals, Ins, DAG);
1584     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1585       report_fatal_error("failed to perform tail call elimination on a call "
1586                          "site marked musttail");
1587     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1588     // detected sibcalls.
1589     if (isTailCall) {
1590       ++NumTailCalls;
1591       isSibCall = true;
1592     }
1593   }
1594
1595   // Analyze operands of the call, assigning locations to each operand.
1596   SmallVector<CCValAssign, 16> ArgLocs;
1597   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1598                     *DAG.getContext(), Call);
1599   CCInfo.AnalyzeCallOperands(Outs,
1600                              CCAssignFnForNode(CallConv, /* Return*/ false,
1601                                                isVarArg));
1602
1603   // Get a count of how many bytes are to be pushed on the stack.
1604   unsigned NumBytes = CCInfo.getNextStackOffset();
1605
1606   // For tail calls, memory operands are available in our caller's stack.
1607   if (isSibCall)
1608     NumBytes = 0;
1609
1610   // Adjust the stack pointer for the new arguments...
1611   // These operations are automatically eliminated by the prolog/epilog pass
1612   if (!isSibCall)
1613     Chain = DAG.getCALLSEQ_START(Chain,
1614                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1615
1616   SDValue StackPtr =
1617       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1618
1619   RegsToPassVector RegsToPass;
1620   SmallVector<SDValue, 8> MemOpChains;
1621
1622   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1623   // of tail call optimization, arguments are handled later.
1624   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1625        i != e;
1626        ++i, ++realArgIdx) {
1627     CCValAssign &VA = ArgLocs[i];
1628     SDValue Arg = OutVals[realArgIdx];
1629     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1630     bool isByVal = Flags.isByVal();
1631
1632     // Promote the value if needed.
1633     switch (VA.getLocInfo()) {
1634     default: llvm_unreachable("Unknown loc info!");
1635     case CCValAssign::Full: break;
1636     case CCValAssign::SExt:
1637       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1638       break;
1639     case CCValAssign::ZExt:
1640       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1641       break;
1642     case CCValAssign::AExt:
1643       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1644       break;
1645     case CCValAssign::BCvt:
1646       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1647       break;
1648     }
1649
1650     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1651     if (VA.needsCustom()) {
1652       if (VA.getLocVT() == MVT::v2f64) {
1653         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1654                                   DAG.getConstant(0, dl, MVT::i32));
1655         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1656                                   DAG.getConstant(1, dl, MVT::i32));
1657
1658         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1659                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1660
1661         VA = ArgLocs[++i]; // skip ahead to next loc
1662         if (VA.isRegLoc()) {
1663           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1664                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1665         } else {
1666           assert(VA.isMemLoc());
1667
1668           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1669                                                  dl, DAG, VA, Flags));
1670         }
1671       } else {
1672         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1673                          StackPtr, MemOpChains, Flags);
1674       }
1675     } else if (VA.isRegLoc()) {
1676       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1677         assert(VA.getLocVT() == MVT::i32 &&
1678                "unexpected calling convention register assignment");
1679         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1680                "unexpected use of 'returned'");
1681         isThisReturn = true;
1682       }
1683       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1684     } else if (isByVal) {
1685       assert(VA.isMemLoc());
1686       unsigned offset = 0;
1687
1688       // True if this byval aggregate will be split between registers
1689       // and memory.
1690       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1691       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1692
1693       if (CurByValIdx < ByValArgsCount) {
1694
1695         unsigned RegBegin, RegEnd;
1696         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1697
1698         EVT PtrVT =
1699             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1700         unsigned int i, j;
1701         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1702           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1703           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1704           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1705                                      MachinePointerInfo(),
1706                                      false, false, false,
1707                                      DAG.InferPtrAlignment(AddArg));
1708           MemOpChains.push_back(Load.getValue(1));
1709           RegsToPass.push_back(std::make_pair(j, Load));
1710         }
1711
1712         // If parameter size outsides register area, "offset" value
1713         // helps us to calculate stack slot for remained part properly.
1714         offset = RegEnd - RegBegin;
1715
1716         CCInfo.nextInRegsParam();
1717       }
1718
1719       if (Flags.getByValSize() > 4*offset) {
1720         auto PtrVT = getPointerTy(DAG.getDataLayout());
1721         unsigned LocMemOffset = VA.getLocMemOffset();
1722         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1723         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1724         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1725         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1726         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1727                                            MVT::i32);
1728         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1729                                             MVT::i32);
1730
1731         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1732         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1733         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1734                                           Ops));
1735       }
1736     } else if (!isSibCall) {
1737       assert(VA.isMemLoc());
1738
1739       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1740                                              dl, DAG, VA, Flags));
1741     }
1742   }
1743
1744   if (!MemOpChains.empty())
1745     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1746
1747   // Build a sequence of copy-to-reg nodes chained together with token chain
1748   // and flag operands which copy the outgoing args into the appropriate regs.
1749   SDValue InFlag;
1750   // Tail call byval lowering might overwrite argument registers so in case of
1751   // tail call optimization the copies to registers are lowered later.
1752   if (!isTailCall)
1753     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1754       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1755                                RegsToPass[i].second, InFlag);
1756       InFlag = Chain.getValue(1);
1757     }
1758
1759   // For tail calls lower the arguments to the 'real' stack slot.
1760   if (isTailCall) {
1761     // Force all the incoming stack arguments to be loaded from the stack
1762     // before any new outgoing arguments are stored to the stack, because the
1763     // outgoing stack slots may alias the incoming argument stack slots, and
1764     // the alias isn't otherwise explicit. This is slightly more conservative
1765     // than necessary, because it means that each store effectively depends
1766     // on every argument instead of just those arguments it would clobber.
1767
1768     // Do not flag preceding copytoreg stuff together with the following stuff.
1769     InFlag = SDValue();
1770     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1771       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1772                                RegsToPass[i].second, InFlag);
1773       InFlag = Chain.getValue(1);
1774     }
1775     InFlag = SDValue();
1776   }
1777
1778   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1779   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1780   // node so that legalize doesn't hack it.
1781   bool isDirect = false;
1782   bool isARMFunc = false;
1783   bool isLocalARMFunc = false;
1784   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1785   auto PtrVt = getPointerTy(DAG.getDataLayout());
1786
1787   if (Subtarget->genLongCalls()) {
1788     assert((Subtarget->isTargetWindows() ||
1789             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1790            "long-calls with non-static relocation model!");
1791     // Handle a global address or an external symbol. If it's not one of
1792     // those, the target's already in a register, so we don't need to do
1793     // anything extra.
1794     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1795       const GlobalValue *GV = G->getGlobal();
1796       // Create a constant pool entry for the callee address
1797       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1798       ARMConstantPoolValue *CPV =
1799         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1800
1801       // Get the address of the callee into a register
1802       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1803       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1804       Callee = DAG.getLoad(
1805           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1806           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1807           false, false, 0);
1808     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1809       const char *Sym = S->getSymbol();
1810
1811       // Create a constant pool entry for the callee address
1812       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1813       ARMConstantPoolValue *CPV =
1814         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1815                                       ARMPCLabelIndex, 0);
1816       // Get the address of the callee into a register
1817       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1818       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1819       Callee = DAG.getLoad(
1820           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1821           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1822           false, false, 0);
1823     }
1824   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1825     const GlobalValue *GV = G->getGlobal();
1826     isDirect = true;
1827     bool isDef = GV->isStrongDefinitionForLinker();
1828     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1829                    getTargetMachine().getRelocationModel() != Reloc::Static;
1830     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1831     // ARM call to a local ARM function is predicable.
1832     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1833     // tBX takes a register source operand.
1834     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1835       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1836       Callee = DAG.getNode(
1837           ARMISD::WrapperPIC, dl, PtrVt,
1838           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1839       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1840                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1841                            false, false, true, 0);
1842     } else if (Subtarget->isTargetCOFF()) {
1843       assert(Subtarget->isTargetWindows() &&
1844              "Windows is the only supported COFF target");
1845       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1846                                  ? ARMII::MO_DLLIMPORT
1847                                  : ARMII::MO_NO_FLAG;
1848       Callee =
1849           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1850       if (GV->hasDLLImportStorageClass())
1851         Callee =
1852             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1853                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1854                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1855                         false, false, false, 0);
1856     } else {
1857       // On ELF targets for PIC code, direct calls should go through the PLT
1858       unsigned OpFlags = 0;
1859       if (Subtarget->isTargetELF() &&
1860           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1861         OpFlags = ARMII::MO_PLT;
1862       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1863     }
1864   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1865     isDirect = true;
1866     bool isStub = Subtarget->isTargetMachO() &&
1867                   getTargetMachine().getRelocationModel() != Reloc::Static;
1868     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1869     // tBX takes a register source operand.
1870     const char *Sym = S->getSymbol();
1871     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1872       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1873       ARMConstantPoolValue *CPV =
1874         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1875                                       ARMPCLabelIndex, 4);
1876       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1877       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1878       Callee = DAG.getLoad(
1879           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1880           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1881           false, false, 0);
1882       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1883       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1884     } else {
1885       unsigned OpFlags = 0;
1886       // On ELF targets for PIC code, direct calls should go through the PLT
1887       if (Subtarget->isTargetELF() &&
1888                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1889         OpFlags = ARMII::MO_PLT;
1890       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1891     }
1892   }
1893
1894   // FIXME: handle tail calls differently.
1895   unsigned CallOpc;
1896   if (Subtarget->isThumb()) {
1897     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1898       CallOpc = ARMISD::CALL_NOLINK;
1899     else
1900       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1901   } else {
1902     if (!isDirect && !Subtarget->hasV5TOps())
1903       CallOpc = ARMISD::CALL_NOLINK;
1904     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1905              // Emit regular call when code size is the priority
1906              !MF.getFunction()->optForMinSize())
1907       // "mov lr, pc; b _foo" to avoid confusing the RSP
1908       CallOpc = ARMISD::CALL_NOLINK;
1909     else
1910       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1911   }
1912
1913   std::vector<SDValue> Ops;
1914   Ops.push_back(Chain);
1915   Ops.push_back(Callee);
1916
1917   // Add argument registers to the end of the list so that they are known live
1918   // into the call.
1919   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1920     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1921                                   RegsToPass[i].second.getValueType()));
1922
1923   // Add a register mask operand representing the call-preserved registers.
1924   if (!isTailCall) {
1925     const uint32_t *Mask;
1926     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1927     if (isThisReturn) {
1928       // For 'this' returns, use the R0-preserving mask if applicable
1929       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1930       if (!Mask) {
1931         // Set isThisReturn to false if the calling convention is not one that
1932         // allows 'returned' to be modeled in this way, so LowerCallResult does
1933         // not try to pass 'this' straight through
1934         isThisReturn = false;
1935         Mask = ARI->getCallPreservedMask(MF, CallConv);
1936       }
1937     } else
1938       Mask = ARI->getCallPreservedMask(MF, CallConv);
1939
1940     assert(Mask && "Missing call preserved mask for calling convention");
1941     Ops.push_back(DAG.getRegisterMask(Mask));
1942   }
1943
1944   if (InFlag.getNode())
1945     Ops.push_back(InFlag);
1946
1947   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1948   if (isTailCall) {
1949     MF.getFrameInfo()->setHasTailCall();
1950     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1951   }
1952
1953   // Returns a chain and a flag for retval copy to use.
1954   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1955   InFlag = Chain.getValue(1);
1956
1957   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1958                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1959   if (!Ins.empty())
1960     InFlag = Chain.getValue(1);
1961
1962   // Handle result values, copying them out of physregs into vregs that we
1963   // return.
1964   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1965                          InVals, isThisReturn,
1966                          isThisReturn ? OutVals[0] : SDValue());
1967 }
1968
1969 /// HandleByVal - Every parameter *after* a byval parameter is passed
1970 /// on the stack.  Remember the next parameter register to allocate,
1971 /// and then confiscate the rest of the parameter registers to insure
1972 /// this.
1973 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1974                                     unsigned Align) const {
1975   assert((State->getCallOrPrologue() == Prologue ||
1976           State->getCallOrPrologue() == Call) &&
1977          "unhandled ParmContext");
1978
1979   // Byval (as with any stack) slots are always at least 4 byte aligned.
1980   Align = std::max(Align, 4U);
1981
1982   unsigned Reg = State->AllocateReg(GPRArgRegs);
1983   if (!Reg)
1984     return;
1985
1986   unsigned AlignInRegs = Align / 4;
1987   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1988   for (unsigned i = 0; i < Waste; ++i)
1989     Reg = State->AllocateReg(GPRArgRegs);
1990
1991   if (!Reg)
1992     return;
1993
1994   unsigned Excess = 4 * (ARM::R4 - Reg);
1995
1996   // Special case when NSAA != SP and parameter size greater than size of
1997   // all remained GPR regs. In that case we can't split parameter, we must
1998   // send it to stack. We also must set NCRN to R4, so waste all
1999   // remained registers.
2000   const unsigned NSAAOffset = State->getNextStackOffset();
2001   if (NSAAOffset != 0 && Size > Excess) {
2002     while (State->AllocateReg(GPRArgRegs))
2003       ;
2004     return;
2005   }
2006
2007   // First register for byval parameter is the first register that wasn't
2008   // allocated before this method call, so it would be "reg".
2009   // If parameter is small enough to be saved in range [reg, r4), then
2010   // the end (first after last) register would be reg + param-size-in-regs,
2011   // else parameter would be splitted between registers and stack,
2012   // end register would be r4 in this case.
2013   unsigned ByValRegBegin = Reg;
2014   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2015   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2016   // Note, first register is allocated in the beginning of function already,
2017   // allocate remained amount of registers we need.
2018   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2019     State->AllocateReg(GPRArgRegs);
2020   // A byval parameter that is split between registers and memory needs its
2021   // size truncated here.
2022   // In the case where the entire structure fits in registers, we set the
2023   // size in memory to zero.
2024   Size = std::max<int>(Size - Excess, 0);
2025 }
2026
2027 /// MatchingStackOffset - Return true if the given stack call argument is
2028 /// already available in the same position (relatively) of the caller's
2029 /// incoming argument stack.
2030 static
2031 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2032                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2033                          const TargetInstrInfo *TII) {
2034   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2035   int FI = INT_MAX;
2036   if (Arg.getOpcode() == ISD::CopyFromReg) {
2037     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2038     if (!TargetRegisterInfo::isVirtualRegister(VR))
2039       return false;
2040     MachineInstr *Def = MRI->getVRegDef(VR);
2041     if (!Def)
2042       return false;
2043     if (!Flags.isByVal()) {
2044       if (!TII->isLoadFromStackSlot(Def, FI))
2045         return false;
2046     } else {
2047       return false;
2048     }
2049   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2050     if (Flags.isByVal())
2051       // ByVal argument is passed in as a pointer but it's now being
2052       // dereferenced. e.g.
2053       // define @foo(%struct.X* %A) {
2054       //   tail call @bar(%struct.X* byval %A)
2055       // }
2056       return false;
2057     SDValue Ptr = Ld->getBasePtr();
2058     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2059     if (!FINode)
2060       return false;
2061     FI = FINode->getIndex();
2062   } else
2063     return false;
2064
2065   assert(FI != INT_MAX);
2066   if (!MFI->isFixedObjectIndex(FI))
2067     return false;
2068   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2069 }
2070
2071 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2072 /// for tail call optimization. Targets which want to do tail call
2073 /// optimization should implement this function.
2074 bool
2075 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2076                                                      CallingConv::ID CalleeCC,
2077                                                      bool isVarArg,
2078                                                      bool isCalleeStructRet,
2079                                                      bool isCallerStructRet,
2080                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2081                                     const SmallVectorImpl<SDValue> &OutVals,
2082                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2083                                                      SelectionDAG& DAG) const {
2084   const Function *CallerF = DAG.getMachineFunction().getFunction();
2085   CallingConv::ID CallerCC = CallerF->getCallingConv();
2086   bool CCMatch = CallerCC == CalleeCC;
2087
2088   assert(Subtarget->supportsTailCall());
2089
2090   // Look for obvious safe cases to perform tail call optimization that do not
2091   // require ABI changes. This is what gcc calls sibcall.
2092
2093   // Do not sibcall optimize vararg calls unless the call site is not passing
2094   // any arguments.
2095   if (isVarArg && !Outs.empty())
2096     return false;
2097
2098   // Exception-handling functions need a special set of instructions to indicate
2099   // a return to the hardware. Tail-calling another function would probably
2100   // break this.
2101   if (CallerF->hasFnAttribute("interrupt"))
2102     return false;
2103
2104   // Also avoid sibcall optimization if either caller or callee uses struct
2105   // return semantics.
2106   if (isCalleeStructRet || isCallerStructRet)
2107     return false;
2108
2109   // Externally-defined functions with weak linkage should not be
2110   // tail-called on ARM when the OS does not support dynamic
2111   // pre-emption of symbols, as the AAELF spec requires normal calls
2112   // to undefined weak functions to be replaced with a NOP or jump to the
2113   // next instruction. The behaviour of branch instructions in this
2114   // situation (as used for tail calls) is implementation-defined, so we
2115   // cannot rely on the linker replacing the tail call with a return.
2116   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2117     const GlobalValue *GV = G->getGlobal();
2118     const Triple &TT = getTargetMachine().getTargetTriple();
2119     if (GV->hasExternalWeakLinkage() &&
2120         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2121       return false;
2122   }
2123
2124   // If the calling conventions do not match, then we'd better make sure the
2125   // results are returned in the same way as what the caller expects.
2126   if (!CCMatch) {
2127     SmallVector<CCValAssign, 16> RVLocs1;
2128     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2129                        *DAG.getContext(), Call);
2130     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2131
2132     SmallVector<CCValAssign, 16> RVLocs2;
2133     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2134                        *DAG.getContext(), Call);
2135     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2136
2137     if (RVLocs1.size() != RVLocs2.size())
2138       return false;
2139     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2140       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2141         return false;
2142       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2143         return false;
2144       if (RVLocs1[i].isRegLoc()) {
2145         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2146           return false;
2147       } else {
2148         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2149           return false;
2150       }
2151     }
2152   }
2153
2154   // If Caller's vararg or byval argument has been split between registers and
2155   // stack, do not perform tail call, since part of the argument is in caller's
2156   // local frame.
2157   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2158                                       getInfo<ARMFunctionInfo>();
2159   if (AFI_Caller->getArgRegsSaveSize())
2160     return false;
2161
2162   // If the callee takes no arguments then go on to check the results of the
2163   // call.
2164   if (!Outs.empty()) {
2165     // Check if stack adjustment is needed. For now, do not do this if any
2166     // argument is passed on the stack.
2167     SmallVector<CCValAssign, 16> ArgLocs;
2168     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2169                       *DAG.getContext(), Call);
2170     CCInfo.AnalyzeCallOperands(Outs,
2171                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2172     if (CCInfo.getNextStackOffset()) {
2173       MachineFunction &MF = DAG.getMachineFunction();
2174
2175       // Check if the arguments are already laid out in the right way as
2176       // the caller's fixed stack objects.
2177       MachineFrameInfo *MFI = MF.getFrameInfo();
2178       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2179       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2180       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2181            i != e;
2182            ++i, ++realArgIdx) {
2183         CCValAssign &VA = ArgLocs[i];
2184         EVT RegVT = VA.getLocVT();
2185         SDValue Arg = OutVals[realArgIdx];
2186         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2187         if (VA.getLocInfo() == CCValAssign::Indirect)
2188           return false;
2189         if (VA.needsCustom()) {
2190           // f64 and vector types are split into multiple registers or
2191           // register/stack-slot combinations.  The types will not match
2192           // the registers; give up on memory f64 refs until we figure
2193           // out what to do about this.
2194           if (!VA.isRegLoc())
2195             return false;
2196           if (!ArgLocs[++i].isRegLoc())
2197             return false;
2198           if (RegVT == MVT::v2f64) {
2199             if (!ArgLocs[++i].isRegLoc())
2200               return false;
2201             if (!ArgLocs[++i].isRegLoc())
2202               return false;
2203           }
2204         } else if (!VA.isRegLoc()) {
2205           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2206                                    MFI, MRI, TII))
2207             return false;
2208         }
2209       }
2210     }
2211   }
2212
2213   return true;
2214 }
2215
2216 bool
2217 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2218                                   MachineFunction &MF, bool isVarArg,
2219                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2220                                   LLVMContext &Context) const {
2221   SmallVector<CCValAssign, 16> RVLocs;
2222   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2223   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2224                                                     isVarArg));
2225 }
2226
2227 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2228                                     SDLoc DL, SelectionDAG &DAG) {
2229   const MachineFunction &MF = DAG.getMachineFunction();
2230   const Function *F = MF.getFunction();
2231
2232   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2233
2234   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2235   // version of the "preferred return address". These offsets affect the return
2236   // instruction if this is a return from PL1 without hypervisor extensions.
2237   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2238   //    SWI:     0      "subs pc, lr, #0"
2239   //    ABORT:   +4     "subs pc, lr, #4"
2240   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2241   // UNDEF varies depending on where the exception came from ARM or Thumb
2242   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2243
2244   int64_t LROffset;
2245   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2246       IntKind == "ABORT")
2247     LROffset = 4;
2248   else if (IntKind == "SWI" || IntKind == "UNDEF")
2249     LROffset = 0;
2250   else
2251     report_fatal_error("Unsupported interrupt attribute. If present, value "
2252                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2253
2254   RetOps.insert(RetOps.begin() + 1,
2255                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2256
2257   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2258 }
2259
2260 SDValue
2261 ARMTargetLowering::LowerReturn(SDValue Chain,
2262                                CallingConv::ID CallConv, bool isVarArg,
2263                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2264                                const SmallVectorImpl<SDValue> &OutVals,
2265                                SDLoc dl, SelectionDAG &DAG) const {
2266
2267   // CCValAssign - represent the assignment of the return value to a location.
2268   SmallVector<CCValAssign, 16> RVLocs;
2269
2270   // CCState - Info about the registers and stack slots.
2271   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2272                     *DAG.getContext(), Call);
2273
2274   // Analyze outgoing return values.
2275   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2276                                                isVarArg));
2277
2278   SDValue Flag;
2279   SmallVector<SDValue, 4> RetOps;
2280   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2281   bool isLittleEndian = Subtarget->isLittle();
2282
2283   MachineFunction &MF = DAG.getMachineFunction();
2284   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2285   AFI->setReturnRegsCount(RVLocs.size());
2286
2287   // Copy the result values into the output registers.
2288   for (unsigned i = 0, realRVLocIdx = 0;
2289        i != RVLocs.size();
2290        ++i, ++realRVLocIdx) {
2291     CCValAssign &VA = RVLocs[i];
2292     assert(VA.isRegLoc() && "Can only return in registers!");
2293
2294     SDValue Arg = OutVals[realRVLocIdx];
2295
2296     switch (VA.getLocInfo()) {
2297     default: llvm_unreachable("Unknown loc info!");
2298     case CCValAssign::Full: break;
2299     case CCValAssign::BCvt:
2300       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2301       break;
2302     }
2303
2304     if (VA.needsCustom()) {
2305       if (VA.getLocVT() == MVT::v2f64) {
2306         // Extract the first half and return it in two registers.
2307         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2308                                    DAG.getConstant(0, dl, MVT::i32));
2309         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2310                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2311
2312         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2313                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2314                                  Flag);
2315         Flag = Chain.getValue(1);
2316         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2317         VA = RVLocs[++i]; // skip ahead to next loc
2318         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2319                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2320                                  Flag);
2321         Flag = Chain.getValue(1);
2322         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2323         VA = RVLocs[++i]; // skip ahead to next loc
2324
2325         // Extract the 2nd half and fall through to handle it as an f64 value.
2326         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2327                           DAG.getConstant(1, dl, MVT::i32));
2328       }
2329       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2330       // available.
2331       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2332                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2333       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2334                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2335                                Flag);
2336       Flag = Chain.getValue(1);
2337       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2338       VA = RVLocs[++i]; // skip ahead to next loc
2339       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2340                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2341                                Flag);
2342     } else
2343       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2344
2345     // Guarantee that all emitted copies are
2346     // stuck together, avoiding something bad.
2347     Flag = Chain.getValue(1);
2348     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2349   }
2350
2351   // Update chain and glue.
2352   RetOps[0] = Chain;
2353   if (Flag.getNode())
2354     RetOps.push_back(Flag);
2355
2356   // CPUs which aren't M-class use a special sequence to return from
2357   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2358   // though we use "subs pc, lr, #N").
2359   //
2360   // M-class CPUs actually use a normal return sequence with a special
2361   // (hardware-provided) value in LR, so the normal code path works.
2362   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2363       !Subtarget->isMClass()) {
2364     if (Subtarget->isThumb1Only())
2365       report_fatal_error("interrupt attribute is not supported in Thumb1");
2366     return LowerInterruptReturn(RetOps, dl, DAG);
2367   }
2368
2369   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2370 }
2371
2372 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2373   if (N->getNumValues() != 1)
2374     return false;
2375   if (!N->hasNUsesOfValue(1, 0))
2376     return false;
2377
2378   SDValue TCChain = Chain;
2379   SDNode *Copy = *N->use_begin();
2380   if (Copy->getOpcode() == ISD::CopyToReg) {
2381     // If the copy has a glue operand, we conservatively assume it isn't safe to
2382     // perform a tail call.
2383     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2384       return false;
2385     TCChain = Copy->getOperand(0);
2386   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2387     SDNode *VMov = Copy;
2388     // f64 returned in a pair of GPRs.
2389     SmallPtrSet<SDNode*, 2> Copies;
2390     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2391          UI != UE; ++UI) {
2392       if (UI->getOpcode() != ISD::CopyToReg)
2393         return false;
2394       Copies.insert(*UI);
2395     }
2396     if (Copies.size() > 2)
2397       return false;
2398
2399     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2400          UI != UE; ++UI) {
2401       SDValue UseChain = UI->getOperand(0);
2402       if (Copies.count(UseChain.getNode()))
2403         // Second CopyToReg
2404         Copy = *UI;
2405       else {
2406         // We are at the top of this chain.
2407         // If the copy has a glue operand, we conservatively assume it
2408         // isn't safe to perform a tail call.
2409         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2410           return false;
2411         // First CopyToReg
2412         TCChain = UseChain;
2413       }
2414     }
2415   } else if (Copy->getOpcode() == ISD::BITCAST) {
2416     // f32 returned in a single GPR.
2417     if (!Copy->hasOneUse())
2418       return false;
2419     Copy = *Copy->use_begin();
2420     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2421       return false;
2422     // If the copy has a glue operand, we conservatively assume it isn't safe to
2423     // perform a tail call.
2424     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2425       return false;
2426     TCChain = Copy->getOperand(0);
2427   } else {
2428     return false;
2429   }
2430
2431   bool HasRet = false;
2432   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2433        UI != UE; ++UI) {
2434     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2435         UI->getOpcode() != ARMISD::INTRET_FLAG)
2436       return false;
2437     HasRet = true;
2438   }
2439
2440   if (!HasRet)
2441     return false;
2442
2443   Chain = TCChain;
2444   return true;
2445 }
2446
2447 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2448   if (!Subtarget->supportsTailCall())
2449     return false;
2450
2451   auto Attr =
2452       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2453   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2454     return false;
2455
2456   return true;
2457 }
2458
2459 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2460 // and pass the lower and high parts through.
2461 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2462   SDLoc DL(Op);
2463   SDValue WriteValue = Op->getOperand(2);
2464
2465   // This function is only supposed to be called for i64 type argument.
2466   assert(WriteValue.getValueType() == MVT::i64
2467           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2468
2469   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2470                            DAG.getConstant(0, DL, MVT::i32));
2471   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2472                            DAG.getConstant(1, DL, MVT::i32));
2473   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2474   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2475 }
2476
2477 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2478 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2479 // one of the above mentioned nodes. It has to be wrapped because otherwise
2480 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2481 // be used to form addressing mode. These wrapped nodes will be selected
2482 // into MOVi.
2483 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2484   EVT PtrVT = Op.getValueType();
2485   // FIXME there is no actual debug info here
2486   SDLoc dl(Op);
2487   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2488   SDValue Res;
2489   if (CP->isMachineConstantPoolEntry())
2490     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2491                                     CP->getAlignment());
2492   else
2493     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2494                                     CP->getAlignment());
2495   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2496 }
2497
2498 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2499   return MachineJumpTableInfo::EK_Inline;
2500 }
2501
2502 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2503                                              SelectionDAG &DAG) const {
2504   MachineFunction &MF = DAG.getMachineFunction();
2505   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2506   unsigned ARMPCLabelIndex = 0;
2507   SDLoc DL(Op);
2508   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2509   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2510   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2511   SDValue CPAddr;
2512   if (RelocM == Reloc::Static) {
2513     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2514   } else {
2515     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2516     ARMPCLabelIndex = AFI->createPICLabelUId();
2517     ARMConstantPoolValue *CPV =
2518       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2519                                       ARMCP::CPBlockAddress, PCAdj);
2520     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2521   }
2522   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2523   SDValue Result =
2524       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2525                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2526                   false, false, false, 0);
2527   if (RelocM == Reloc::Static)
2528     return Result;
2529   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2530   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2531 }
2532
2533 /// \brief Convert a TLS address reference into the correct sequence of loads
2534 /// and calls to compute the variable's address for Darwin, and return an
2535 /// SDValue containing the final node.
2536
2537 /// Darwin only has one TLS scheme which must be capable of dealing with the
2538 /// fully general situation, in the worst case. This means:
2539 ///     + "extern __thread" declaration.
2540 ///     + Defined in a possibly unknown dynamic library.
2541 ///
2542 /// The general system is that each __thread variable has a [3 x i32] descriptor
2543 /// which contains information used by the runtime to calculate the address. The
2544 /// only part of this the compiler needs to know about is the first word, which
2545 /// contains a function pointer that must be called with the address of the
2546 /// entire descriptor in "r0".
2547 ///
2548 /// Since this descriptor may be in a different unit, in general access must
2549 /// proceed along the usual ARM rules. A common sequence to produce is:
2550 ///
2551 ///     movw rT1, :lower16:_var$non_lazy_ptr
2552 ///     movt rT1, :upper16:_var$non_lazy_ptr
2553 ///     ldr r0, [rT1]
2554 ///     ldr rT2, [r0]
2555 ///     blx rT2
2556 ///     [...address now in r0...]
2557 SDValue
2558 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2559                                                SelectionDAG &DAG) const {
2560   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2561   SDLoc DL(Op);
2562
2563   // First step is to get the address of the actua global symbol. This is where
2564   // the TLS descriptor lives.
2565   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2566
2567   // The first entry in the descriptor is a function pointer that we must call
2568   // to obtain the address of the variable.
2569   SDValue Chain = DAG.getEntryNode();
2570   SDValue FuncTLVGet =
2571       DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2572                   MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2573                   false, true, true, 4);
2574   Chain = FuncTLVGet.getValue(1);
2575
2576   MachineFunction &F = DAG.getMachineFunction();
2577   MachineFrameInfo *MFI = F.getFrameInfo();
2578   MFI->setAdjustsStack(true);
2579
2580   // TLS calls preserve all registers except those that absolutely must be
2581   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2582   // silly).
2583   auto TRI =
2584       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2585   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2586   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2587
2588   // Finally, we can make the call. This is just a degenerate version of a
2589   // normal AArch64 call node: r0 takes the address of the descriptor, and
2590   // returns the address of the variable in this thread.
2591   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2592   Chain =
2593       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2594                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2595                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2596   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2597 }
2598
2599 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2600 SDValue
2601 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2602                                                  SelectionDAG &DAG) const {
2603   SDLoc dl(GA);
2604   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2605   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2606   MachineFunction &MF = DAG.getMachineFunction();
2607   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2608   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2609   ARMConstantPoolValue *CPV =
2610     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2611                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2612   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2613   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2614   Argument =
2615       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2616                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2617                   false, false, false, 0);
2618   SDValue Chain = Argument.getValue(1);
2619
2620   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2621   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2622
2623   // call __tls_get_addr.
2624   ArgListTy Args;
2625   ArgListEntry Entry;
2626   Entry.Node = Argument;
2627   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2628   Args.push_back(Entry);
2629
2630   // FIXME: is there useful debug info available here?
2631   TargetLowering::CallLoweringInfo CLI(DAG);
2632   CLI.setDebugLoc(dl).setChain(Chain)
2633     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2634                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2635                0);
2636
2637   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2638   return CallResult.first;
2639 }
2640
2641 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2642 // "local exec" model.
2643 SDValue
2644 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2645                                         SelectionDAG &DAG,
2646                                         TLSModel::Model model) const {
2647   const GlobalValue *GV = GA->getGlobal();
2648   SDLoc dl(GA);
2649   SDValue Offset;
2650   SDValue Chain = DAG.getEntryNode();
2651   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2652   // Get the Thread Pointer
2653   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2654
2655   if (model == TLSModel::InitialExec) {
2656     MachineFunction &MF = DAG.getMachineFunction();
2657     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2658     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2659     // Initial exec model.
2660     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2661     ARMConstantPoolValue *CPV =
2662       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2663                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2664                                       true);
2665     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2666     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2667     Offset = DAG.getLoad(
2668         PtrVT, dl, Chain, Offset,
2669         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2670         false, false, 0);
2671     Chain = Offset.getValue(1);
2672
2673     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2674     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2675
2676     Offset = DAG.getLoad(
2677         PtrVT, dl, Chain, Offset,
2678         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2679         false, false, 0);
2680   } else {
2681     // local exec model
2682     assert(model == TLSModel::LocalExec);
2683     ARMConstantPoolValue *CPV =
2684       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2685     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2686     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2687     Offset = DAG.getLoad(
2688         PtrVT, dl, Chain, Offset,
2689         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2690         false, false, 0);
2691   }
2692
2693   // The address of the thread local variable is the add of the thread
2694   // pointer with the offset of the variable.
2695   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2696 }
2697
2698 SDValue
2699 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2700   if (Subtarget->isTargetDarwin())
2701     return LowerGlobalTLSAddressDarwin(Op, DAG);
2702
2703   // TODO: implement the "local dynamic" model
2704   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2705   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2706   if (DAG.getTarget().Options.EmulatedTLS)
2707     return LowerToTLSEmulatedModel(GA, DAG);
2708
2709   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2710
2711   switch (model) {
2712     case TLSModel::GeneralDynamic:
2713     case TLSModel::LocalDynamic:
2714       return LowerToTLSGeneralDynamicModel(GA, DAG);
2715     case TLSModel::InitialExec:
2716     case TLSModel::LocalExec:
2717       return LowerToTLSExecModels(GA, DAG, model);
2718   }
2719   llvm_unreachable("bogus TLS model");
2720 }
2721
2722 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2723                                                  SelectionDAG &DAG) const {
2724   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2725   SDLoc dl(Op);
2726   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2727   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2728     bool UseGOT_PREL =
2729         !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2730
2731     MachineFunction &MF = DAG.getMachineFunction();
2732     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2733     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2734     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2735     SDLoc dl(Op);
2736     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2737     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2738         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2739         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2740         /*AddCurrentAddress=*/UseGOT_PREL);
2741     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2742     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2743     SDValue Result = DAG.getLoad(
2744         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2745         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2746         false, false, 0);
2747     SDValue Chain = Result.getValue(1);
2748     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2749     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2750     if (UseGOT_PREL)
2751       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2752                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2753                            false, false, false, 0);
2754     return Result;
2755   }
2756
2757   // If we have T2 ops, we can materialize the address directly via movt/movw
2758   // pair. This is always cheaper.
2759   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2760     ++NumMovwMovt;
2761     // FIXME: Once remat is capable of dealing with instructions with register
2762     // operands, expand this into two nodes.
2763     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2764                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2765   } else {
2766     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2767     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2768     return DAG.getLoad(
2769         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2770         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2771         false, false, 0);
2772   }
2773 }
2774
2775 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2776                                                     SelectionDAG &DAG) const {
2777   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2778   SDLoc dl(Op);
2779   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2780   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2781
2782   if (Subtarget->useMovt(DAG.getMachineFunction()))
2783     ++NumMovwMovt;
2784
2785   // FIXME: Once remat is capable of dealing with instructions with register
2786   // operands, expand this into multiple nodes
2787   unsigned Wrapper =
2788       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2789
2790   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2791   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2792
2793   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2794     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2795                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2796                          false, false, false, 0);
2797   return Result;
2798 }
2799
2800 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2801                                                      SelectionDAG &DAG) const {
2802   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2803   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2804          "Windows on ARM expects to use movw/movt");
2805
2806   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2807   const ARMII::TOF TargetFlags =
2808     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2809   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2810   SDValue Result;
2811   SDLoc DL(Op);
2812
2813   ++NumMovwMovt;
2814
2815   // FIXME: Once remat is capable of dealing with instructions with register
2816   // operands, expand this into two nodes.
2817   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2818                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2819                                                   TargetFlags));
2820   if (GV->hasDLLImportStorageClass())
2821     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2822                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2823                          false, false, false, 0);
2824   return Result;
2825 }
2826
2827 SDValue
2828 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2829   SDLoc dl(Op);
2830   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2831   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2832                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2833                      Op.getOperand(1), Val);
2834 }
2835
2836 SDValue
2837 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2838   SDLoc dl(Op);
2839   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2840                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2841 }
2842
2843 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2844                                                       SelectionDAG &DAG) const {
2845   SDLoc dl(Op);
2846   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2847                      Op.getOperand(0));
2848 }
2849
2850 SDValue
2851 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2852                                           const ARMSubtarget *Subtarget) const {
2853   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2854   SDLoc dl(Op);
2855   switch (IntNo) {
2856   default: return SDValue();    // Don't custom lower most intrinsics.
2857   case Intrinsic::arm_rbit: {
2858     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2859            "RBIT intrinsic must have i32 type!");
2860     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2861   }
2862   case Intrinsic::arm_thread_pointer: {
2863     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2864     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2865   }
2866   case Intrinsic::eh_sjlj_lsda: {
2867     MachineFunction &MF = DAG.getMachineFunction();
2868     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2869     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2870     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2871     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2872     SDValue CPAddr;
2873     unsigned PCAdj = (RelocM != Reloc::PIC_)
2874       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2875     ARMConstantPoolValue *CPV =
2876       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2877                                       ARMCP::CPLSDA, PCAdj);
2878     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2879     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2880     SDValue Result = DAG.getLoad(
2881         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2882         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2883         false, false, 0);
2884
2885     if (RelocM == Reloc::PIC_) {
2886       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2887       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2888     }
2889     return Result;
2890   }
2891   case Intrinsic::arm_neon_vmulls:
2892   case Intrinsic::arm_neon_vmullu: {
2893     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2894       ? ARMISD::VMULLs : ARMISD::VMULLu;
2895     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2896                        Op.getOperand(1), Op.getOperand(2));
2897   }
2898   case Intrinsic::arm_neon_vminnm:
2899   case Intrinsic::arm_neon_vmaxnm: {
2900     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2901       ? ISD::FMINNUM : ISD::FMAXNUM;
2902     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2903                        Op.getOperand(1), Op.getOperand(2));
2904   }
2905   case Intrinsic::arm_neon_vminu:
2906   case Intrinsic::arm_neon_vmaxu: {
2907     if (Op.getValueType().isFloatingPoint())
2908       return SDValue();
2909     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2910       ? ISD::UMIN : ISD::UMAX;
2911     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2912                          Op.getOperand(1), Op.getOperand(2));
2913   }
2914   case Intrinsic::arm_neon_vmins:
2915   case Intrinsic::arm_neon_vmaxs: {
2916     // v{min,max}s is overloaded between signed integers and floats.
2917     if (!Op.getValueType().isFloatingPoint()) {
2918       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2919         ? ISD::SMIN : ISD::SMAX;
2920       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2921                          Op.getOperand(1), Op.getOperand(2));
2922     }
2923     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2924       ? ISD::FMINNAN : ISD::FMAXNAN;
2925     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2926                        Op.getOperand(1), Op.getOperand(2));
2927   }
2928   }
2929 }
2930
2931 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2932                                  const ARMSubtarget *Subtarget) {
2933   // FIXME: handle "fence singlethread" more efficiently.
2934   SDLoc dl(Op);
2935   if (!Subtarget->hasDataBarrier()) {
2936     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2937     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2938     // here.
2939     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2940            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2941     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2942                        DAG.getConstant(0, dl, MVT::i32));
2943   }
2944
2945   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2946   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2947   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2948   if (Subtarget->isMClass()) {
2949     // Only a full system barrier exists in the M-class architectures.
2950     Domain = ARM_MB::SY;
2951   } else if (Subtarget->isSwift() && Ord == Release) {
2952     // Swift happens to implement ISHST barriers in a way that's compatible with
2953     // Release semantics but weaker than ISH so we'd be fools not to use
2954     // it. Beware: other processors probably don't!
2955     Domain = ARM_MB::ISHST;
2956   }
2957
2958   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2959                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2960                      DAG.getConstant(Domain, dl, MVT::i32));
2961 }
2962
2963 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2964                              const ARMSubtarget *Subtarget) {
2965   // ARM pre v5TE and Thumb1 does not have preload instructions.
2966   if (!(Subtarget->isThumb2() ||
2967         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2968     // Just preserve the chain.
2969     return Op.getOperand(0);
2970
2971   SDLoc dl(Op);
2972   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2973   if (!isRead &&
2974       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2975     // ARMv7 with MP extension has PLDW.
2976     return Op.getOperand(0);
2977
2978   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2979   if (Subtarget->isThumb()) {
2980     // Invert the bits.
2981     isRead = ~isRead & 1;
2982     isData = ~isData & 1;
2983   }
2984
2985   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2986                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2987                      DAG.getConstant(isData, dl, MVT::i32));
2988 }
2989
2990 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2991   MachineFunction &MF = DAG.getMachineFunction();
2992   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2993
2994   // vastart just stores the address of the VarArgsFrameIndex slot into the
2995   // memory location argument.
2996   SDLoc dl(Op);
2997   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2998   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2999   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3000   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3001                       MachinePointerInfo(SV), false, false, 0);
3002 }
3003
3004 SDValue
3005 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
3006                                         SDValue &Root, SelectionDAG &DAG,
3007                                         SDLoc dl) const {
3008   MachineFunction &MF = DAG.getMachineFunction();
3009   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3010
3011   const TargetRegisterClass *RC;
3012   if (AFI->isThumb1OnlyFunction())
3013     RC = &ARM::tGPRRegClass;
3014   else
3015     RC = &ARM::GPRRegClass;
3016
3017   // Transform the arguments stored in physical registers into virtual ones.
3018   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3019   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3020
3021   SDValue ArgValue2;
3022   if (NextVA.isMemLoc()) {
3023     MachineFrameInfo *MFI = MF.getFrameInfo();
3024     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3025
3026     // Create load node to retrieve arguments from the stack.
3027     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3028     ArgValue2 = DAG.getLoad(
3029         MVT::i32, dl, Root, FIN,
3030         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3031         false, false, 0);
3032   } else {
3033     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3034     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3035   }
3036   if (!Subtarget->isLittle())
3037     std::swap (ArgValue, ArgValue2);
3038   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3039 }
3040
3041 // The remaining GPRs hold either the beginning of variable-argument
3042 // data, or the beginning of an aggregate passed by value (usually
3043 // byval).  Either way, we allocate stack slots adjacent to the data
3044 // provided by our caller, and store the unallocated registers there.
3045 // If this is a variadic function, the va_list pointer will begin with
3046 // these values; otherwise, this reassembles a (byval) structure that
3047 // was split between registers and memory.
3048 // Return: The frame index registers were stored into.
3049 int
3050 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3051                                   SDLoc dl, SDValue &Chain,
3052                                   const Value *OrigArg,
3053                                   unsigned InRegsParamRecordIdx,
3054                                   int ArgOffset,
3055                                   unsigned ArgSize) const {
3056   // Currently, two use-cases possible:
3057   // Case #1. Non-var-args function, and we meet first byval parameter.
3058   //          Setup first unallocated register as first byval register;
3059   //          eat all remained registers
3060   //          (these two actions are performed by HandleByVal method).
3061   //          Then, here, we initialize stack frame with
3062   //          "store-reg" instructions.
3063   // Case #2. Var-args function, that doesn't contain byval parameters.
3064   //          The same: eat all remained unallocated registers,
3065   //          initialize stack frame.
3066
3067   MachineFunction &MF = DAG.getMachineFunction();
3068   MachineFrameInfo *MFI = MF.getFrameInfo();
3069   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3070   unsigned RBegin, REnd;
3071   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3072     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3073   } else {
3074     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3075     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3076     REnd = ARM::R4;
3077   }
3078
3079   if (REnd != RBegin)
3080     ArgOffset = -4 * (ARM::R4 - RBegin);
3081
3082   auto PtrVT = getPointerTy(DAG.getDataLayout());
3083   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3084   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3085
3086   SmallVector<SDValue, 4> MemOps;
3087   const TargetRegisterClass *RC =
3088       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3089
3090   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3091     unsigned VReg = MF.addLiveIn(Reg, RC);
3092     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3093     SDValue Store =
3094         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3095                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3096     MemOps.push_back(Store);
3097     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3098   }
3099
3100   if (!MemOps.empty())
3101     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3102   return FrameIndex;
3103 }
3104
3105 // Setup stack frame, the va_list pointer will start from.
3106 void
3107 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3108                                         SDLoc dl, SDValue &Chain,
3109                                         unsigned ArgOffset,
3110                                         unsigned TotalArgRegsSaveSize,
3111                                         bool ForceMutable) const {
3112   MachineFunction &MF = DAG.getMachineFunction();
3113   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3114
3115   // Try to store any remaining integer argument regs
3116   // to their spots on the stack so that they may be loaded by deferencing
3117   // the result of va_next.
3118   // If there is no regs to be stored, just point address after last
3119   // argument passed via stack.
3120   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3121                                   CCInfo.getInRegsParamsCount(),
3122                                   CCInfo.getNextStackOffset(), 4);
3123   AFI->setVarArgsFrameIndex(FrameIndex);
3124 }
3125
3126 SDValue
3127 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3128                                         CallingConv::ID CallConv, bool isVarArg,
3129                                         const SmallVectorImpl<ISD::InputArg>
3130                                           &Ins,
3131                                         SDLoc dl, SelectionDAG &DAG,
3132                                         SmallVectorImpl<SDValue> &InVals)
3133                                           const {
3134   MachineFunction &MF = DAG.getMachineFunction();
3135   MachineFrameInfo *MFI = MF.getFrameInfo();
3136
3137   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3138
3139   // Assign locations to all of the incoming arguments.
3140   SmallVector<CCValAssign, 16> ArgLocs;
3141   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3142                     *DAG.getContext(), Prologue);
3143   CCInfo.AnalyzeFormalArguments(Ins,
3144                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3145                                                   isVarArg));
3146
3147   SmallVector<SDValue, 16> ArgValues;
3148   SDValue ArgValue;
3149   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3150   unsigned CurArgIdx = 0;
3151
3152   // Initially ArgRegsSaveSize is zero.
3153   // Then we increase this value each time we meet byval parameter.
3154   // We also increase this value in case of varargs function.
3155   AFI->setArgRegsSaveSize(0);
3156
3157   // Calculate the amount of stack space that we need to allocate to store
3158   // byval and variadic arguments that are passed in registers.
3159   // We need to know this before we allocate the first byval or variadic
3160   // argument, as they will be allocated a stack slot below the CFA (Canonical
3161   // Frame Address, the stack pointer at entry to the function).
3162   unsigned ArgRegBegin = ARM::R4;
3163   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3164     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3165       break;
3166
3167     CCValAssign &VA = ArgLocs[i];
3168     unsigned Index = VA.getValNo();
3169     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3170     if (!Flags.isByVal())
3171       continue;
3172
3173     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3174     unsigned RBegin, REnd;
3175     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3176     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3177
3178     CCInfo.nextInRegsParam();
3179   }
3180   CCInfo.rewindByValRegsInfo();
3181
3182   int lastInsIndex = -1;
3183   if (isVarArg && MFI->hasVAStart()) {
3184     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3185     if (RegIdx != array_lengthof(GPRArgRegs))
3186       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3187   }
3188
3189   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3190   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3191   auto PtrVT = getPointerTy(DAG.getDataLayout());
3192
3193   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3194     CCValAssign &VA = ArgLocs[i];
3195     if (Ins[VA.getValNo()].isOrigArg()) {
3196       std::advance(CurOrigArg,
3197                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3198       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3199     }
3200     // Arguments stored in registers.
3201     if (VA.isRegLoc()) {
3202       EVT RegVT = VA.getLocVT();
3203
3204       if (VA.needsCustom()) {
3205         // f64 and vector types are split up into multiple registers or
3206         // combinations of registers and stack slots.
3207         if (VA.getLocVT() == MVT::v2f64) {
3208           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3209                                                    Chain, DAG, dl);
3210           VA = ArgLocs[++i]; // skip ahead to next loc
3211           SDValue ArgValue2;
3212           if (VA.isMemLoc()) {
3213             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3214             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3215             ArgValue2 = DAG.getLoad(
3216                 MVT::f64, dl, Chain, FIN,
3217                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3218                 false, false, false, 0);
3219           } else {
3220             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3221                                              Chain, DAG, dl);
3222           }
3223           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3224           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3225                                  ArgValue, ArgValue1,
3226                                  DAG.getIntPtrConstant(0, dl));
3227           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3228                                  ArgValue, ArgValue2,
3229                                  DAG.getIntPtrConstant(1, dl));
3230         } else
3231           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3232
3233       } else {
3234         const TargetRegisterClass *RC;
3235
3236         if (RegVT == MVT::f32)
3237           RC = &ARM::SPRRegClass;
3238         else if (RegVT == MVT::f64)
3239           RC = &ARM::DPRRegClass;
3240         else if (RegVT == MVT::v2f64)
3241           RC = &ARM::QPRRegClass;
3242         else if (RegVT == MVT::i32)
3243           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3244                                            : &ARM::GPRRegClass;
3245         else
3246           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3247
3248         // Transform the arguments in physical registers into virtual ones.
3249         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3250         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3251       }
3252
3253       // If this is an 8 or 16-bit value, it is really passed promoted
3254       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3255       // truncate to the right size.
3256       switch (VA.getLocInfo()) {
3257       default: llvm_unreachable("Unknown loc info!");
3258       case CCValAssign::Full: break;
3259       case CCValAssign::BCvt:
3260         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3261         break;
3262       case CCValAssign::SExt:
3263         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3264                                DAG.getValueType(VA.getValVT()));
3265         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3266         break;
3267       case CCValAssign::ZExt:
3268         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3269                                DAG.getValueType(VA.getValVT()));
3270         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3271         break;
3272       }
3273
3274       InVals.push_back(ArgValue);
3275
3276     } else { // VA.isRegLoc()
3277
3278       // sanity check
3279       assert(VA.isMemLoc());
3280       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3281
3282       int index = VA.getValNo();
3283
3284       // Some Ins[] entries become multiple ArgLoc[] entries.
3285       // Process them only once.
3286       if (index != lastInsIndex)
3287         {
3288           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3289           // FIXME: For now, all byval parameter objects are marked mutable.
3290           // This can be changed with more analysis.
3291           // In case of tail call optimization mark all arguments mutable.
3292           // Since they could be overwritten by lowering of arguments in case of
3293           // a tail call.
3294           if (Flags.isByVal()) {
3295             assert(Ins[index].isOrigArg() &&
3296                    "Byval arguments cannot be implicit");
3297             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3298
3299             int FrameIndex = StoreByValRegs(
3300                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3301                 VA.getLocMemOffset(), Flags.getByValSize());
3302             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3303             CCInfo.nextInRegsParam();
3304           } else {
3305             unsigned FIOffset = VA.getLocMemOffset();
3306             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3307                                             FIOffset, true);
3308
3309             // Create load nodes to retrieve arguments from the stack.
3310             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3311             InVals.push_back(DAG.getLoad(
3312                 VA.getValVT(), dl, Chain, FIN,
3313                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3314                 false, false, false, 0));
3315           }
3316           lastInsIndex = index;
3317         }
3318     }
3319   }
3320
3321   // varargs
3322   if (isVarArg && MFI->hasVAStart())
3323     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3324                          CCInfo.getNextStackOffset(),
3325                          TotalArgRegsSaveSize);
3326
3327   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3328
3329   return Chain;
3330 }
3331
3332 /// isFloatingPointZero - Return true if this is +0.0.
3333 static bool isFloatingPointZero(SDValue Op) {
3334   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3335     return CFP->getValueAPF().isPosZero();
3336   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3337     // Maybe this has already been legalized into the constant pool?
3338     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3339       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3340       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3341         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3342           return CFP->getValueAPF().isPosZero();
3343     }
3344   } else if (Op->getOpcode() == ISD::BITCAST &&
3345              Op->getValueType(0) == MVT::f64) {
3346     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3347     // created by LowerConstantFP().
3348     SDValue BitcastOp = Op->getOperand(0);
3349     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3350         isNullConstant(BitcastOp->getOperand(0)))
3351       return true;
3352   }
3353   return false;
3354 }
3355
3356 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3357 /// the given operands.
3358 SDValue
3359 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3360                              SDValue &ARMcc, SelectionDAG &DAG,
3361                              SDLoc dl) const {
3362   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3363     unsigned C = RHSC->getZExtValue();
3364     if (!isLegalICmpImmediate(C)) {
3365       // Constant does not fit, try adjusting it by one?
3366       switch (CC) {
3367       default: break;
3368       case ISD::SETLT:
3369       case ISD::SETGE:
3370         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3371           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3372           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3373         }
3374         break;
3375       case ISD::SETULT:
3376       case ISD::SETUGE:
3377         if (C != 0 && isLegalICmpImmediate(C-1)) {
3378           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3379           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3380         }
3381         break;
3382       case ISD::SETLE:
3383       case ISD::SETGT:
3384         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3385           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3386           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3387         }
3388         break;
3389       case ISD::SETULE:
3390       case ISD::SETUGT:
3391         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3392           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3393           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3394         }
3395         break;
3396       }
3397     }
3398   }
3399
3400   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3401   ARMISD::NodeType CompareType;
3402   switch (CondCode) {
3403   default:
3404     CompareType = ARMISD::CMP;
3405     break;
3406   case ARMCC::EQ:
3407   case ARMCC::NE:
3408     // Uses only Z Flag
3409     CompareType = ARMISD::CMPZ;
3410     break;
3411   }
3412   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3413   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3414 }
3415
3416 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3417 SDValue
3418 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3419                              SDLoc dl) const {
3420   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3421   SDValue Cmp;
3422   if (!isFloatingPointZero(RHS))
3423     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3424   else
3425     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3426   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3427 }
3428
3429 /// duplicateCmp - Glue values can have only one use, so this function
3430 /// duplicates a comparison node.
3431 SDValue
3432 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3433   unsigned Opc = Cmp.getOpcode();
3434   SDLoc DL(Cmp);
3435   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3436     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3437
3438   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3439   Cmp = Cmp.getOperand(0);
3440   Opc = Cmp.getOpcode();
3441   if (Opc == ARMISD::CMPFP)
3442     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3443   else {
3444     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3445     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3446   }
3447   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3448 }
3449
3450 std::pair<SDValue, SDValue>
3451 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3452                                  SDValue &ARMcc) const {
3453   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3454
3455   SDValue Value, OverflowCmp;
3456   SDValue LHS = Op.getOperand(0);
3457   SDValue RHS = Op.getOperand(1);
3458   SDLoc dl(Op);
3459
3460   // FIXME: We are currently always generating CMPs because we don't support
3461   // generating CMN through the backend. This is not as good as the natural
3462   // CMP case because it causes a register dependency and cannot be folded
3463   // later.
3464
3465   switch (Op.getOpcode()) {
3466   default:
3467     llvm_unreachable("Unknown overflow instruction!");
3468   case ISD::SADDO:
3469     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3470     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3471     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3472     break;
3473   case ISD::UADDO:
3474     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3475     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3476     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3477     break;
3478   case ISD::SSUBO:
3479     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3480     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3481     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3482     break;
3483   case ISD::USUBO:
3484     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3485     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3486     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3487     break;
3488   } // switch (...)
3489
3490   return std::make_pair(Value, OverflowCmp);
3491 }
3492
3493
3494 SDValue
3495 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3496   // Let legalize expand this if it isn't a legal type yet.
3497   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3498     return SDValue();
3499
3500   SDValue Value, OverflowCmp;
3501   SDValue ARMcc;
3502   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3503   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3504   SDLoc dl(Op);
3505   // We use 0 and 1 as false and true values.
3506   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3507   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3508   EVT VT = Op.getValueType();
3509
3510   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3511                                  ARMcc, CCR, OverflowCmp);
3512
3513   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3514   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3515 }
3516
3517
3518 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3519   SDValue Cond = Op.getOperand(0);
3520   SDValue SelectTrue = Op.getOperand(1);
3521   SDValue SelectFalse = Op.getOperand(2);
3522   SDLoc dl(Op);
3523   unsigned Opc = Cond.getOpcode();
3524
3525   if (Cond.getResNo() == 1 &&
3526       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3527        Opc == ISD::USUBO)) {
3528     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3529       return SDValue();
3530
3531     SDValue Value, OverflowCmp;
3532     SDValue ARMcc;
3533     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3534     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3535     EVT VT = Op.getValueType();
3536
3537     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3538                    OverflowCmp, DAG);
3539   }
3540
3541   // Convert:
3542   //
3543   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3544   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3545   //
3546   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3547     const ConstantSDNode *CMOVTrue =
3548       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3549     const ConstantSDNode *CMOVFalse =
3550       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3551
3552     if (CMOVTrue && CMOVFalse) {
3553       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3554       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3555
3556       SDValue True;
3557       SDValue False;
3558       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3559         True = SelectTrue;
3560         False = SelectFalse;
3561       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3562         True = SelectFalse;
3563         False = SelectTrue;
3564       }
3565
3566       if (True.getNode() && False.getNode()) {
3567         EVT VT = Op.getValueType();
3568         SDValue ARMcc = Cond.getOperand(2);
3569         SDValue CCR = Cond.getOperand(3);
3570         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3571         assert(True.getValueType() == VT);
3572         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3573       }
3574     }
3575   }
3576
3577   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3578   // undefined bits before doing a full-word comparison with zero.
3579   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3580                      DAG.getConstant(1, dl, Cond.getValueType()));
3581
3582   return DAG.getSelectCC(dl, Cond,
3583                          DAG.getConstant(0, dl, Cond.getValueType()),
3584                          SelectTrue, SelectFalse, ISD::SETNE);
3585 }
3586
3587 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3588                                  bool &swpCmpOps, bool &swpVselOps) {
3589   // Start by selecting the GE condition code for opcodes that return true for
3590   // 'equality'
3591   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3592       CC == ISD::SETULE)
3593     CondCode = ARMCC::GE;
3594
3595   // and GT for opcodes that return false for 'equality'.
3596   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3597            CC == ISD::SETULT)
3598     CondCode = ARMCC::GT;
3599
3600   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3601   // to swap the compare operands.
3602   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3603       CC == ISD::SETULT)
3604     swpCmpOps = true;
3605
3606   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3607   // If we have an unordered opcode, we need to swap the operands to the VSEL
3608   // instruction (effectively negating the condition).
3609   //
3610   // This also has the effect of swapping which one of 'less' or 'greater'
3611   // returns true, so we also swap the compare operands. It also switches
3612   // whether we return true for 'equality', so we compensate by picking the
3613   // opposite condition code to our original choice.
3614   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3615       CC == ISD::SETUGT) {
3616     swpCmpOps = !swpCmpOps;
3617     swpVselOps = !swpVselOps;
3618     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3619   }
3620
3621   // 'ordered' is 'anything but unordered', so use the VS condition code and
3622   // swap the VSEL operands.
3623   if (CC == ISD::SETO) {
3624     CondCode = ARMCC::VS;
3625     swpVselOps = true;
3626   }
3627
3628   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3629   // code and swap the VSEL operands.
3630   if (CC == ISD::SETUNE) {
3631     CondCode = ARMCC::EQ;
3632     swpVselOps = true;
3633   }
3634 }
3635
3636 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3637                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3638                                    SDValue Cmp, SelectionDAG &DAG) const {
3639   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3640     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3641                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3642     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3643                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3644
3645     SDValue TrueLow = TrueVal.getValue(0);
3646     SDValue TrueHigh = TrueVal.getValue(1);
3647     SDValue FalseLow = FalseVal.getValue(0);
3648     SDValue FalseHigh = FalseVal.getValue(1);
3649
3650     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3651                               ARMcc, CCR, Cmp);
3652     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3653                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3654
3655     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3656   } else {
3657     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3658                        Cmp);
3659   }
3660 }
3661
3662 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3663   EVT VT = Op.getValueType();
3664   SDValue LHS = Op.getOperand(0);
3665   SDValue RHS = Op.getOperand(1);
3666   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3667   SDValue TrueVal = Op.getOperand(2);
3668   SDValue FalseVal = Op.getOperand(3);
3669   SDLoc dl(Op);
3670
3671   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3672     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3673                                                     dl);
3674
3675     // If softenSetCCOperands only returned one value, we should compare it to
3676     // zero.
3677     if (!RHS.getNode()) {
3678       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3679       CC = ISD::SETNE;
3680     }
3681   }
3682
3683   if (LHS.getValueType() == MVT::i32) {
3684     // Try to generate VSEL on ARMv8.
3685     // The VSEL instruction can't use all the usual ARM condition
3686     // codes: it only has two bits to select the condition code, so it's
3687     // constrained to use only GE, GT, VS and EQ.
3688     //
3689     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3690     // swap the operands of the previous compare instruction (effectively
3691     // inverting the compare condition, swapping 'less' and 'greater') and
3692     // sometimes need to swap the operands to the VSEL (which inverts the
3693     // condition in the sense of firing whenever the previous condition didn't)
3694     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3695                                     TrueVal.getValueType() == MVT::f64)) {
3696       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3697       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3698           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3699         CC = ISD::getSetCCInverse(CC, true);
3700         std::swap(TrueVal, FalseVal);
3701       }
3702     }
3703
3704     SDValue ARMcc;
3705     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3706     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3707     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3708   }
3709
3710   ARMCC::CondCodes CondCode, CondCode2;
3711   FPCCToARMCC(CC, CondCode, CondCode2);
3712
3713   // Try to generate VMAXNM/VMINNM on ARMv8.
3714   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3715                                   TrueVal.getValueType() == MVT::f64)) {
3716     bool swpCmpOps = false;
3717     bool swpVselOps = false;
3718     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3719
3720     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3721         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3722       if (swpCmpOps)
3723         std::swap(LHS, RHS);
3724       if (swpVselOps)
3725         std::swap(TrueVal, FalseVal);
3726     }
3727   }
3728
3729   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3730   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3731   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3732   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3733   if (CondCode2 != ARMCC::AL) {
3734     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3735     // FIXME: Needs another CMP because flag can have but one use.
3736     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3737     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3738   }
3739   return Result;
3740 }
3741
3742 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3743 /// to morph to an integer compare sequence.
3744 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3745                            const ARMSubtarget *Subtarget) {
3746   SDNode *N = Op.getNode();
3747   if (!N->hasOneUse())
3748     // Otherwise it requires moving the value from fp to integer registers.
3749     return false;
3750   if (!N->getNumValues())
3751     return false;
3752   EVT VT = Op.getValueType();
3753   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3754     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3755     // vmrs are very slow, e.g. cortex-a8.
3756     return false;
3757
3758   if (isFloatingPointZero(Op)) {
3759     SeenZero = true;
3760     return true;
3761   }
3762   return ISD::isNormalLoad(N);
3763 }
3764
3765 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3766   if (isFloatingPointZero(Op))
3767     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3768
3769   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3770     return DAG.getLoad(MVT::i32, SDLoc(Op),
3771                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3772                        Ld->isVolatile(), Ld->isNonTemporal(),
3773                        Ld->isInvariant(), Ld->getAlignment());
3774
3775   llvm_unreachable("Unknown VFP cmp argument!");
3776 }
3777
3778 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3779                            SDValue &RetVal1, SDValue &RetVal2) {
3780   SDLoc dl(Op);
3781
3782   if (isFloatingPointZero(Op)) {
3783     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3784     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3785     return;
3786   }
3787
3788   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3789     SDValue Ptr = Ld->getBasePtr();
3790     RetVal1 = DAG.getLoad(MVT::i32, dl,
3791                           Ld->getChain(), Ptr,
3792                           Ld->getPointerInfo(),
3793                           Ld->isVolatile(), Ld->isNonTemporal(),
3794                           Ld->isInvariant(), Ld->getAlignment());
3795
3796     EVT PtrType = Ptr.getValueType();
3797     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3798     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3799                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3800     RetVal2 = DAG.getLoad(MVT::i32, dl,
3801                           Ld->getChain(), NewPtr,
3802                           Ld->getPointerInfo().getWithOffset(4),
3803                           Ld->isVolatile(), Ld->isNonTemporal(),
3804                           Ld->isInvariant(), NewAlign);
3805     return;
3806   }
3807
3808   llvm_unreachable("Unknown VFP cmp argument!");
3809 }
3810
3811 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3812 /// f32 and even f64 comparisons to integer ones.
3813 SDValue
3814 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3815   SDValue Chain = Op.getOperand(0);
3816   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3817   SDValue LHS = Op.getOperand(2);
3818   SDValue RHS = Op.getOperand(3);
3819   SDValue Dest = Op.getOperand(4);
3820   SDLoc dl(Op);
3821
3822   bool LHSSeenZero = false;
3823   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3824   bool RHSSeenZero = false;
3825   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3826   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3827     // If unsafe fp math optimization is enabled and there are no other uses of
3828     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3829     // to an integer comparison.
3830     if (CC == ISD::SETOEQ)
3831       CC = ISD::SETEQ;
3832     else if (CC == ISD::SETUNE)
3833       CC = ISD::SETNE;
3834
3835     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3836     SDValue ARMcc;
3837     if (LHS.getValueType() == MVT::f32) {
3838       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3839                         bitcastf32Toi32(LHS, DAG), Mask);
3840       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3841                         bitcastf32Toi32(RHS, DAG), Mask);
3842       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3843       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3844       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3845                          Chain, Dest, ARMcc, CCR, Cmp);
3846     }
3847
3848     SDValue LHS1, LHS2;
3849     SDValue RHS1, RHS2;
3850     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3851     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3852     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3853     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3854     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3855     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3856     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3857     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3858     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3859   }
3860
3861   return SDValue();
3862 }
3863
3864 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3865   SDValue Chain = Op.getOperand(0);
3866   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3867   SDValue LHS = Op.getOperand(2);
3868   SDValue RHS = Op.getOperand(3);
3869   SDValue Dest = Op.getOperand(4);
3870   SDLoc dl(Op);
3871
3872   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3873     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3874                                                     dl);
3875
3876     // If softenSetCCOperands only returned one value, we should compare it to
3877     // zero.
3878     if (!RHS.getNode()) {
3879       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3880       CC = ISD::SETNE;
3881     }
3882   }
3883
3884   if (LHS.getValueType() == MVT::i32) {
3885     SDValue ARMcc;
3886     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3887     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3888     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3889                        Chain, Dest, ARMcc, CCR, Cmp);
3890   }
3891
3892   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3893
3894   if (getTargetMachine().Options.UnsafeFPMath &&
3895       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3896        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3897     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3898     if (Result.getNode())
3899       return Result;
3900   }
3901
3902   ARMCC::CondCodes CondCode, CondCode2;
3903   FPCCToARMCC(CC, CondCode, CondCode2);
3904
3905   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3906   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3907   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3908   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3909   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3910   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3911   if (CondCode2 != ARMCC::AL) {
3912     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3913     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3914     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3915   }
3916   return Res;
3917 }
3918
3919 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3920   SDValue Chain = Op.getOperand(0);
3921   SDValue Table = Op.getOperand(1);
3922   SDValue Index = Op.getOperand(2);
3923   SDLoc dl(Op);
3924
3925   EVT PTy = getPointerTy(DAG.getDataLayout());
3926   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3927   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3928   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3929   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3930   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3931   if (Subtarget->isThumb2()) {
3932     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3933     // which does another jump to the destination. This also makes it easier
3934     // to translate it to TBB / TBH later.
3935     // FIXME: This might not work if the function is extremely large.
3936     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3937                        Addr, Op.getOperand(2), JTI);
3938   }
3939   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3940     Addr =
3941         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3942                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3943                     false, false, false, 0);
3944     Chain = Addr.getValue(1);
3945     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3946     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3947   } else {
3948     Addr =
3949         DAG.getLoad(PTy, dl, Chain, Addr,
3950                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3951                     false, false, false, 0);
3952     Chain = Addr.getValue(1);
3953     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3954   }
3955 }
3956
3957 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3958   EVT VT = Op.getValueType();
3959   SDLoc dl(Op);
3960
3961   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3962     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3963       return Op;
3964     return DAG.UnrollVectorOp(Op.getNode());
3965   }
3966
3967   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3968          "Invalid type for custom lowering!");
3969   if (VT != MVT::v4i16)
3970     return DAG.UnrollVectorOp(Op.getNode());
3971
3972   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3973   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3974 }
3975
3976 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3977   EVT VT = Op.getValueType();
3978   if (VT.isVector())
3979     return LowerVectorFP_TO_INT(Op, DAG);
3980   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3981     RTLIB::Libcall LC;
3982     if (Op.getOpcode() == ISD::FP_TO_SINT)
3983       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3984                               Op.getValueType());
3985     else
3986       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3987                               Op.getValueType());
3988     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3989                        /*isSigned*/ false, SDLoc(Op)).first;
3990   }
3991
3992   return Op;
3993 }
3994
3995 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3996   EVT VT = Op.getValueType();
3997   SDLoc dl(Op);
3998
3999   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4000     if (VT.getVectorElementType() == MVT::f32)
4001       return Op;
4002     return DAG.UnrollVectorOp(Op.getNode());
4003   }
4004
4005   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4006          "Invalid type for custom lowering!");
4007   if (VT != MVT::v4f32)
4008     return DAG.UnrollVectorOp(Op.getNode());
4009
4010   unsigned CastOpc;
4011   unsigned Opc;
4012   switch (Op.getOpcode()) {
4013   default: llvm_unreachable("Invalid opcode!");
4014   case ISD::SINT_TO_FP:
4015     CastOpc = ISD::SIGN_EXTEND;
4016     Opc = ISD::SINT_TO_FP;
4017     break;
4018   case ISD::UINT_TO_FP:
4019     CastOpc = ISD::ZERO_EXTEND;
4020     Opc = ISD::UINT_TO_FP;
4021     break;
4022   }
4023
4024   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4025   return DAG.getNode(Opc, dl, VT, Op);
4026 }
4027
4028 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4029   EVT VT = Op.getValueType();
4030   if (VT.isVector())
4031     return LowerVectorINT_TO_FP(Op, DAG);
4032   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4033     RTLIB::Libcall LC;
4034     if (Op.getOpcode() == ISD::SINT_TO_FP)
4035       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4036                               Op.getValueType());
4037     else
4038       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4039                               Op.getValueType());
4040     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4041                        /*isSigned*/ false, SDLoc(Op)).first;
4042   }
4043
4044   return Op;
4045 }
4046
4047 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4048   // Implement fcopysign with a fabs and a conditional fneg.
4049   SDValue Tmp0 = Op.getOperand(0);
4050   SDValue Tmp1 = Op.getOperand(1);
4051   SDLoc dl(Op);
4052   EVT VT = Op.getValueType();
4053   EVT SrcVT = Tmp1.getValueType();
4054   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4055     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4056   bool UseNEON = !InGPR && Subtarget->hasNEON();
4057
4058   if (UseNEON) {
4059     // Use VBSL to copy the sign bit.
4060     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4061     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4062                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4063     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4064     if (VT == MVT::f64)
4065       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4066                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4067                          DAG.getConstant(32, dl, MVT::i32));
4068     else /*if (VT == MVT::f32)*/
4069       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4070     if (SrcVT == MVT::f32) {
4071       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4072       if (VT == MVT::f64)
4073         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4074                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4075                            DAG.getConstant(32, dl, MVT::i32));
4076     } else if (VT == MVT::f32)
4077       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4078                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4079                          DAG.getConstant(32, dl, MVT::i32));
4080     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4081     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4082
4083     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4084                                             dl, MVT::i32);
4085     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4086     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4087                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4088
4089     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4090                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4091                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4092     if (VT == MVT::f32) {
4093       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4094       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4095                         DAG.getConstant(0, dl, MVT::i32));
4096     } else {
4097       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4098     }
4099
4100     return Res;
4101   }
4102
4103   // Bitcast operand 1 to i32.
4104   if (SrcVT == MVT::f64)
4105     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4106                        Tmp1).getValue(1);
4107   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4108
4109   // Or in the signbit with integer operations.
4110   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4111   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4112   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4113   if (VT == MVT::f32) {
4114     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4115                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4116     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4117                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4118   }
4119
4120   // f64: Or the high part with signbit and then combine two parts.
4121   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4122                      Tmp0);
4123   SDValue Lo = Tmp0.getValue(0);
4124   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4125   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4126   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4127 }
4128
4129 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4130   MachineFunction &MF = DAG.getMachineFunction();
4131   MachineFrameInfo *MFI = MF.getFrameInfo();
4132   MFI->setReturnAddressIsTaken(true);
4133
4134   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4135     return SDValue();
4136
4137   EVT VT = Op.getValueType();
4138   SDLoc dl(Op);
4139   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4140   if (Depth) {
4141     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4142     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4143     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4144                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4145                        MachinePointerInfo(), false, false, false, 0);
4146   }
4147
4148   // Return LR, which contains the return address. Mark it an implicit live-in.
4149   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4150   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4151 }
4152
4153 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4154   const ARMBaseRegisterInfo &ARI =
4155     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4156   MachineFunction &MF = DAG.getMachineFunction();
4157   MachineFrameInfo *MFI = MF.getFrameInfo();
4158   MFI->setFrameAddressIsTaken(true);
4159
4160   EVT VT = Op.getValueType();
4161   SDLoc dl(Op);  // FIXME probably not meaningful
4162   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4163   unsigned FrameReg = ARI.getFrameRegister(MF);
4164   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4165   while (Depth--)
4166     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4167                             MachinePointerInfo(),
4168                             false, false, false, 0);
4169   return FrameAddr;
4170 }
4171
4172 // FIXME? Maybe this could be a TableGen attribute on some registers and
4173 // this table could be generated automatically from RegInfo.
4174 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4175                                               SelectionDAG &DAG) const {
4176   unsigned Reg = StringSwitch<unsigned>(RegName)
4177                        .Case("sp", ARM::SP)
4178                        .Default(0);
4179   if (Reg)
4180     return Reg;
4181   report_fatal_error(Twine("Invalid register name \""
4182                               + StringRef(RegName)  + "\"."));
4183 }
4184
4185 // Result is 64 bit value so split into two 32 bit values and return as a
4186 // pair of values.
4187 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4188                                 SelectionDAG &DAG) {
4189   SDLoc DL(N);
4190
4191   // This function is only supposed to be called for i64 type destination.
4192   assert(N->getValueType(0) == MVT::i64
4193           && "ExpandREAD_REGISTER called for non-i64 type result.");
4194
4195   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4196                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4197                              N->getOperand(0),
4198                              N->getOperand(1));
4199
4200   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4201                     Read.getValue(1)));
4202   Results.push_back(Read.getOperand(0));
4203 }
4204
4205 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4206 /// When \p DstVT, the destination type of \p BC, is on the vector
4207 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4208 /// it might be possible to combine them, such that everything stays on the
4209 /// vector register bank.
4210 /// \p return The node that would replace \p BT, if the combine
4211 /// is possible.
4212 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4213                                                 SelectionDAG &DAG) {
4214   SDValue Op = BC->getOperand(0);
4215   EVT DstVT = BC->getValueType(0);
4216
4217   // The only vector instruction that can produce a scalar (remember,
4218   // since the bitcast was about to be turned into VMOVDRR, the source
4219   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4220   // Moreover, we can do this combine only if there is one use.
4221   // Finally, if the destination type is not a vector, there is not
4222   // much point on forcing everything on the vector bank.
4223   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4224       !Op.hasOneUse())
4225     return SDValue();
4226
4227   // If the index is not constant, we will introduce an additional
4228   // multiply that will stick.
4229   // Give up in that case.
4230   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4231   if (!Index)
4232     return SDValue();
4233   unsigned DstNumElt = DstVT.getVectorNumElements();
4234
4235   // Compute the new index.
4236   const APInt &APIntIndex = Index->getAPIntValue();
4237   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4238   NewIndex *= APIntIndex;
4239   // Check if the new constant index fits into i32.
4240   if (NewIndex.getBitWidth() > 32)
4241     return SDValue();
4242
4243   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4244   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4245   SDLoc dl(Op);
4246   SDValue ExtractSrc = Op.getOperand(0);
4247   EVT VecVT = EVT::getVectorVT(
4248       *DAG.getContext(), DstVT.getScalarType(),
4249       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4250   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4251   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4252                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4253 }
4254
4255 /// ExpandBITCAST - If the target supports VFP, this function is called to
4256 /// expand a bit convert where either the source or destination type is i64 to
4257 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4258 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4259 /// vectors), since the legalizer won't know what to do with that.
4260 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4262   SDLoc dl(N);
4263   SDValue Op = N->getOperand(0);
4264
4265   // This function is only supposed to be called for i64 types, either as the
4266   // source or destination of the bit convert.
4267   EVT SrcVT = Op.getValueType();
4268   EVT DstVT = N->getValueType(0);
4269   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4270          "ExpandBITCAST called for non-i64 type");
4271
4272   // Turn i64->f64 into VMOVDRR.
4273   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4274     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4275     // if we can combine the bitcast with its source.
4276     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4277       return Val;
4278
4279     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4280                              DAG.getConstant(0, dl, MVT::i32));
4281     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4282                              DAG.getConstant(1, dl, MVT::i32));
4283     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4284                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4285   }
4286
4287   // Turn f64->i64 into VMOVRRD.
4288   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4289     SDValue Cvt;
4290     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4291         SrcVT.getVectorNumElements() > 1)
4292       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4293                         DAG.getVTList(MVT::i32, MVT::i32),
4294                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4295     else
4296       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4297                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4298     // Merge the pieces into a single i64 value.
4299     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4300   }
4301
4302   return SDValue();
4303 }
4304
4305 /// getZeroVector - Returns a vector of specified type with all zero elements.
4306 /// Zero vectors are used to represent vector negation and in those cases
4307 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4308 /// not support i64 elements, so sometimes the zero vectors will need to be
4309 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4310 /// zero vector.
4311 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4312   assert(VT.isVector() && "Expected a vector type");
4313   // The canonical modified immediate encoding of a zero vector is....0!
4314   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4315   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4316   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4317   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4318 }
4319
4320 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4321 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4322 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4323                                                 SelectionDAG &DAG) const {
4324   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4325   EVT VT = Op.getValueType();
4326   unsigned VTBits = VT.getSizeInBits();
4327   SDLoc dl(Op);
4328   SDValue ShOpLo = Op.getOperand(0);
4329   SDValue ShOpHi = Op.getOperand(1);
4330   SDValue ShAmt  = Op.getOperand(2);
4331   SDValue ARMcc;
4332   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4333
4334   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4335
4336   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4337                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4338   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4339   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4340                                    DAG.getConstant(VTBits, dl, MVT::i32));
4341   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4342   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4343   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4344
4345   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4346   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4347                           ISD::SETGE, ARMcc, DAG, dl);
4348   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4349   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4350                            CCR, Cmp);
4351
4352   SDValue Ops[2] = { Lo, Hi };
4353   return DAG.getMergeValues(Ops, dl);
4354 }
4355
4356 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4357 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4358 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4359                                                SelectionDAG &DAG) const {
4360   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4361   EVT VT = Op.getValueType();
4362   unsigned VTBits = VT.getSizeInBits();
4363   SDLoc dl(Op);
4364   SDValue ShOpLo = Op.getOperand(0);
4365   SDValue ShOpHi = Op.getOperand(1);
4366   SDValue ShAmt  = Op.getOperand(2);
4367   SDValue ARMcc;
4368
4369   assert(Op.getOpcode() == ISD::SHL_PARTS);
4370   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4371                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4372   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4373   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4374                                    DAG.getConstant(VTBits, dl, MVT::i32));
4375   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4376   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4377
4378   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4379   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4380   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4381                           ISD::SETGE, ARMcc, DAG, dl);
4382   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4383   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4384                            CCR, Cmp);
4385
4386   SDValue Ops[2] = { Lo, Hi };
4387   return DAG.getMergeValues(Ops, dl);
4388 }
4389
4390 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4391                                             SelectionDAG &DAG) const {
4392   // The rounding mode is in bits 23:22 of the FPSCR.
4393   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4394   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4395   // so that the shift + and get folded into a bitfield extract.
4396   SDLoc dl(Op);
4397   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4398                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4399                                               MVT::i32));
4400   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4401                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4402   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4403                               DAG.getConstant(22, dl, MVT::i32));
4404   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4405                      DAG.getConstant(3, dl, MVT::i32));
4406 }
4407
4408 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4409                          const ARMSubtarget *ST) {
4410   SDLoc dl(N);
4411   EVT VT = N->getValueType(0);
4412   if (VT.isVector()) {
4413     assert(ST->hasNEON());
4414
4415     // Compute the least significant set bit: LSB = X & -X
4416     SDValue X = N->getOperand(0);
4417     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4418     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4419
4420     EVT ElemTy = VT.getVectorElementType();
4421
4422     if (ElemTy == MVT::i8) {
4423       // Compute with: cttz(x) = ctpop(lsb - 1)
4424       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4425                                 DAG.getTargetConstant(1, dl, ElemTy));
4426       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4427       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4428     }
4429
4430     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4431         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4432       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4433       unsigned NumBits = ElemTy.getSizeInBits();
4434       SDValue WidthMinus1 =
4435           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4436                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4437       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4438       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4439     }
4440
4441     // Compute with: cttz(x) = ctpop(lsb - 1)
4442
4443     // Since we can only compute the number of bits in a byte with vcnt.8, we
4444     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4445     // and i64.
4446
4447     // Compute LSB - 1.
4448     SDValue Bits;
4449     if (ElemTy == MVT::i64) {
4450       // Load constant 0xffff'ffff'ffff'ffff to register.
4451       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4452                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4453       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4454     } else {
4455       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4456                                 DAG.getTargetConstant(1, dl, ElemTy));
4457       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4458     }
4459
4460     // Count #bits with vcnt.8.
4461     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4462     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4463     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4464
4465     // Gather the #bits with vpaddl (pairwise add.)
4466     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4467     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4468         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4469         Cnt8);
4470     if (ElemTy == MVT::i16)
4471       return Cnt16;
4472
4473     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4474     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4475         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4476         Cnt16);
4477     if (ElemTy == MVT::i32)
4478       return Cnt32;
4479
4480     assert(ElemTy == MVT::i64);
4481     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4482         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4483         Cnt32);
4484     return Cnt64;
4485   }
4486
4487   if (!ST->hasV6T2Ops())
4488     return SDValue();
4489
4490   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4491   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4492 }
4493
4494 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4495 /// for each 16-bit element from operand, repeated.  The basic idea is to
4496 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4497 ///
4498 /// Trace for v4i16:
4499 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4500 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4501 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4502 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4503 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4504 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4505 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4506 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4507 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4508   EVT VT = N->getValueType(0);
4509   SDLoc DL(N);
4510
4511   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4512   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4513   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4514   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4515   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4516   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4517 }
4518
4519 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4520 /// bit-count for each 16-bit element from the operand.  We need slightly
4521 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4522 /// 64/128-bit registers.
4523 ///
4524 /// Trace for v4i16:
4525 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4526 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4527 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4528 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4529 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4530   EVT VT = N->getValueType(0);
4531   SDLoc DL(N);
4532
4533   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4534   if (VT.is64BitVector()) {
4535     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4536     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4537                        DAG.getIntPtrConstant(0, DL));
4538   } else {
4539     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4540                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4541     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4542   }
4543 }
4544
4545 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4546 /// bit-count for each 32-bit element from the operand.  The idea here is
4547 /// to split the vector into 16-bit elements, leverage the 16-bit count
4548 /// routine, and then combine the results.
4549 ///
4550 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4551 /// input    = [v0    v1    ] (vi: 32-bit elements)
4552 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4553 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4554 /// vrev: N0 = [k1 k0 k3 k2 ]
4555 ///            [k0 k1 k2 k3 ]
4556 ///       N1 =+[k1 k0 k3 k2 ]
4557 ///            [k0 k2 k1 k3 ]
4558 ///       N2 =+[k1 k3 k0 k2 ]
4559 ///            [k0    k2    k1    k3    ]
4560 /// Extended =+[k1    k3    k0    k2    ]
4561 ///            [k0    k2    ]
4562 /// Extracted=+[k1    k3    ]
4563 ///
4564 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4565   EVT VT = N->getValueType(0);
4566   SDLoc DL(N);
4567
4568   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4569
4570   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4571   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4572   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4573   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4574   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4575
4576   if (VT.is64BitVector()) {
4577     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4578     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4579                        DAG.getIntPtrConstant(0, DL));
4580   } else {
4581     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4582                                     DAG.getIntPtrConstant(0, DL));
4583     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4584   }
4585 }
4586
4587 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4588                           const ARMSubtarget *ST) {
4589   EVT VT = N->getValueType(0);
4590
4591   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4592   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4593           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4594          "Unexpected type for custom ctpop lowering");
4595
4596   if (VT.getVectorElementType() == MVT::i32)
4597     return lowerCTPOP32BitElements(N, DAG);
4598   else
4599     return lowerCTPOP16BitElements(N, DAG);
4600 }
4601
4602 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4603                           const ARMSubtarget *ST) {
4604   EVT VT = N->getValueType(0);
4605   SDLoc dl(N);
4606
4607   if (!VT.isVector())
4608     return SDValue();
4609
4610   // Lower vector shifts on NEON to use VSHL.
4611   assert(ST->hasNEON() && "unexpected vector shift");
4612
4613   // Left shifts translate directly to the vshiftu intrinsic.
4614   if (N->getOpcode() == ISD::SHL)
4615     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4616                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4617                                        MVT::i32),
4618                        N->getOperand(0), N->getOperand(1));
4619
4620   assert((N->getOpcode() == ISD::SRA ||
4621           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4622
4623   // NEON uses the same intrinsics for both left and right shifts.  For
4624   // right shifts, the shift amounts are negative, so negate the vector of
4625   // shift amounts.
4626   EVT ShiftVT = N->getOperand(1).getValueType();
4627   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4628                                      getZeroVector(ShiftVT, DAG, dl),
4629                                      N->getOperand(1));
4630   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4631                              Intrinsic::arm_neon_vshifts :
4632                              Intrinsic::arm_neon_vshiftu);
4633   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4634                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4635                      N->getOperand(0), NegatedCount);
4636 }
4637
4638 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4639                                 const ARMSubtarget *ST) {
4640   EVT VT = N->getValueType(0);
4641   SDLoc dl(N);
4642
4643   // We can get here for a node like i32 = ISD::SHL i32, i64
4644   if (VT != MVT::i64)
4645     return SDValue();
4646
4647   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4648          "Unknown shift to lower!");
4649
4650   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4651   if (!isOneConstant(N->getOperand(1)))
4652     return SDValue();
4653
4654   // If we are in thumb mode, we don't have RRX.
4655   if (ST->isThumb1Only()) return SDValue();
4656
4657   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4658   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4659                            DAG.getConstant(0, dl, MVT::i32));
4660   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4661                            DAG.getConstant(1, dl, MVT::i32));
4662
4663   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4664   // captures the result into a carry flag.
4665   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4666   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4667
4668   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4669   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4670
4671   // Merge the pieces into a single i64 value.
4672  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4673 }
4674
4675 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4676   SDValue TmpOp0, TmpOp1;
4677   bool Invert = false;
4678   bool Swap = false;
4679   unsigned Opc = 0;
4680
4681   SDValue Op0 = Op.getOperand(0);
4682   SDValue Op1 = Op.getOperand(1);
4683   SDValue CC = Op.getOperand(2);
4684   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4685   EVT VT = Op.getValueType();
4686   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4687   SDLoc dl(Op);
4688
4689   if (CmpVT.getVectorElementType() == MVT::i64)
4690     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4691     // but it's possible that our operands are 64-bit but our result is 32-bit.
4692     // Bail in this case.
4693     return SDValue();
4694
4695   if (Op1.getValueType().isFloatingPoint()) {
4696     switch (SetCCOpcode) {
4697     default: llvm_unreachable("Illegal FP comparison");
4698     case ISD::SETUNE:
4699     case ISD::SETNE:  Invert = true; // Fallthrough
4700     case ISD::SETOEQ:
4701     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4702     case ISD::SETOLT:
4703     case ISD::SETLT: Swap = true; // Fallthrough
4704     case ISD::SETOGT:
4705     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4706     case ISD::SETOLE:
4707     case ISD::SETLE:  Swap = true; // Fallthrough
4708     case ISD::SETOGE:
4709     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4710     case ISD::SETUGE: Swap = true; // Fallthrough
4711     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4712     case ISD::SETUGT: Swap = true; // Fallthrough
4713     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4714     case ISD::SETUEQ: Invert = true; // Fallthrough
4715     case ISD::SETONE:
4716       // Expand this to (OLT | OGT).
4717       TmpOp0 = Op0;
4718       TmpOp1 = Op1;
4719       Opc = ISD::OR;
4720       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4721       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4722       break;
4723     case ISD::SETUO: Invert = true; // Fallthrough
4724     case ISD::SETO:
4725       // Expand this to (OLT | OGE).
4726       TmpOp0 = Op0;
4727       TmpOp1 = Op1;
4728       Opc = ISD::OR;
4729       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4730       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4731       break;
4732     }
4733   } else {
4734     // Integer comparisons.
4735     switch (SetCCOpcode) {
4736     default: llvm_unreachable("Illegal integer comparison");
4737     case ISD::SETNE:  Invert = true;
4738     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4739     case ISD::SETLT:  Swap = true;
4740     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4741     case ISD::SETLE:  Swap = true;
4742     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4743     case ISD::SETULT: Swap = true;
4744     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4745     case ISD::SETULE: Swap = true;
4746     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4747     }
4748
4749     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4750     if (Opc == ARMISD::VCEQ) {
4751
4752       SDValue AndOp;
4753       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4754         AndOp = Op0;
4755       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4756         AndOp = Op1;
4757
4758       // Ignore bitconvert.
4759       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4760         AndOp = AndOp.getOperand(0);
4761
4762       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4763         Opc = ARMISD::VTST;
4764         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4765         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4766         Invert = !Invert;
4767       }
4768     }
4769   }
4770
4771   if (Swap)
4772     std::swap(Op0, Op1);
4773
4774   // If one of the operands is a constant vector zero, attempt to fold the
4775   // comparison to a specialized compare-against-zero form.
4776   SDValue SingleOp;
4777   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4778     SingleOp = Op0;
4779   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4780     if (Opc == ARMISD::VCGE)
4781       Opc = ARMISD::VCLEZ;
4782     else if (Opc == ARMISD::VCGT)
4783       Opc = ARMISD::VCLTZ;
4784     SingleOp = Op1;
4785   }
4786
4787   SDValue Result;
4788   if (SingleOp.getNode()) {
4789     switch (Opc) {
4790     case ARMISD::VCEQ:
4791       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4792     case ARMISD::VCGE:
4793       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4794     case ARMISD::VCLEZ:
4795       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4796     case ARMISD::VCGT:
4797       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4798     case ARMISD::VCLTZ:
4799       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4800     default:
4801       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4802     }
4803   } else {
4804      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4805   }
4806
4807   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4808
4809   if (Invert)
4810     Result = DAG.getNOT(dl, Result, VT);
4811
4812   return Result;
4813 }
4814
4815 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4816 /// valid vector constant for a NEON instruction with a "modified immediate"
4817 /// operand (e.g., VMOV).  If so, return the encoded value.
4818 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4819                                  unsigned SplatBitSize, SelectionDAG &DAG,
4820                                  SDLoc dl, EVT &VT, bool is128Bits,
4821                                  NEONModImmType type) {
4822   unsigned OpCmode, Imm;
4823
4824   // SplatBitSize is set to the smallest size that splats the vector, so a
4825   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4826   // immediate instructions others than VMOV do not support the 8-bit encoding
4827   // of a zero vector, and the default encoding of zero is supposed to be the
4828   // 32-bit version.
4829   if (SplatBits == 0)
4830     SplatBitSize = 32;
4831
4832   switch (SplatBitSize) {
4833   case 8:
4834     if (type != VMOVModImm)
4835       return SDValue();
4836     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4837     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4838     OpCmode = 0xe;
4839     Imm = SplatBits;
4840     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4841     break;
4842
4843   case 16:
4844     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4845     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4846     if ((SplatBits & ~0xff) == 0) {
4847       // Value = 0x00nn: Op=x, Cmode=100x.
4848       OpCmode = 0x8;
4849       Imm = SplatBits;
4850       break;
4851     }
4852     if ((SplatBits & ~0xff00) == 0) {
4853       // Value = 0xnn00: Op=x, Cmode=101x.
4854       OpCmode = 0xa;
4855       Imm = SplatBits >> 8;
4856       break;
4857     }
4858     return SDValue();
4859
4860   case 32:
4861     // NEON's 32-bit VMOV supports splat values where:
4862     // * only one byte is nonzero, or
4863     // * the least significant byte is 0xff and the second byte is nonzero, or
4864     // * the least significant 2 bytes are 0xff and the third is nonzero.
4865     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4866     if ((SplatBits & ~0xff) == 0) {
4867       // Value = 0x000000nn: Op=x, Cmode=000x.
4868       OpCmode = 0;
4869       Imm = SplatBits;
4870       break;
4871     }
4872     if ((SplatBits & ~0xff00) == 0) {
4873       // Value = 0x0000nn00: Op=x, Cmode=001x.
4874       OpCmode = 0x2;
4875       Imm = SplatBits >> 8;
4876       break;
4877     }
4878     if ((SplatBits & ~0xff0000) == 0) {
4879       // Value = 0x00nn0000: Op=x, Cmode=010x.
4880       OpCmode = 0x4;
4881       Imm = SplatBits >> 16;
4882       break;
4883     }
4884     if ((SplatBits & ~0xff000000) == 0) {
4885       // Value = 0xnn000000: Op=x, Cmode=011x.
4886       OpCmode = 0x6;
4887       Imm = SplatBits >> 24;
4888       break;
4889     }
4890
4891     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4892     if (type == OtherModImm) return SDValue();
4893
4894     if ((SplatBits & ~0xffff) == 0 &&
4895         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4896       // Value = 0x0000nnff: Op=x, Cmode=1100.
4897       OpCmode = 0xc;
4898       Imm = SplatBits >> 8;
4899       break;
4900     }
4901
4902     if ((SplatBits & ~0xffffff) == 0 &&
4903         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4904       // Value = 0x00nnffff: Op=x, Cmode=1101.
4905       OpCmode = 0xd;
4906       Imm = SplatBits >> 16;
4907       break;
4908     }
4909
4910     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4911     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4912     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4913     // and fall through here to test for a valid 64-bit splat.  But, then the
4914     // caller would also need to check and handle the change in size.
4915     return SDValue();
4916
4917   case 64: {
4918     if (type != VMOVModImm)
4919       return SDValue();
4920     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4921     uint64_t BitMask = 0xff;
4922     uint64_t Val = 0;
4923     unsigned ImmMask = 1;
4924     Imm = 0;
4925     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4926       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4927         Val |= BitMask;
4928         Imm |= ImmMask;
4929       } else if ((SplatBits & BitMask) != 0) {
4930         return SDValue();
4931       }
4932       BitMask <<= 8;
4933       ImmMask <<= 1;
4934     }
4935
4936     if (DAG.getDataLayout().isBigEndian())
4937       // swap higher and lower 32 bit word
4938       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4939
4940     // Op=1, Cmode=1110.
4941     OpCmode = 0x1e;
4942     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4943     break;
4944   }
4945
4946   default:
4947     llvm_unreachable("unexpected size for isNEONModifiedImm");
4948   }
4949
4950   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4951   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4952 }
4953
4954 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4955                                            const ARMSubtarget *ST) const {
4956   if (!ST->hasVFP3())
4957     return SDValue();
4958
4959   bool IsDouble = Op.getValueType() == MVT::f64;
4960   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4961
4962   // Use the default (constant pool) lowering for double constants when we have
4963   // an SP-only FPU
4964   if (IsDouble && Subtarget->isFPOnlySP())
4965     return SDValue();
4966
4967   // Try splatting with a VMOV.f32...
4968   APFloat FPVal = CFP->getValueAPF();
4969   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4970
4971   if (ImmVal != -1) {
4972     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4973       // We have code in place to select a valid ConstantFP already, no need to
4974       // do any mangling.
4975       return Op;
4976     }
4977
4978     // It's a float and we are trying to use NEON operations where
4979     // possible. Lower it to a splat followed by an extract.
4980     SDLoc DL(Op);
4981     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4982     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4983                                       NewVal);
4984     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4985                        DAG.getConstant(0, DL, MVT::i32));
4986   }
4987
4988   // The rest of our options are NEON only, make sure that's allowed before
4989   // proceeding..
4990   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4991     return SDValue();
4992
4993   EVT VMovVT;
4994   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4995
4996   // It wouldn't really be worth bothering for doubles except for one very
4997   // important value, which does happen to match: 0.0. So make sure we don't do
4998   // anything stupid.
4999   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5000     return SDValue();
5001
5002   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5003   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5004                                      VMovVT, false, VMOVModImm);
5005   if (NewVal != SDValue()) {
5006     SDLoc DL(Op);
5007     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5008                                       NewVal);
5009     if (IsDouble)
5010       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5011
5012     // It's a float: cast and extract a vector element.
5013     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5014                                        VecConstant);
5015     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5016                        DAG.getConstant(0, DL, MVT::i32));
5017   }
5018
5019   // Finally, try a VMVN.i32
5020   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5021                              false, VMVNModImm);
5022   if (NewVal != SDValue()) {
5023     SDLoc DL(Op);
5024     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5025
5026     if (IsDouble)
5027       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5028
5029     // It's a float: cast and extract a vector element.
5030     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5031                                        VecConstant);
5032     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5033                        DAG.getConstant(0, DL, MVT::i32));
5034   }
5035
5036   return SDValue();
5037 }
5038
5039 // check if an VEXT instruction can handle the shuffle mask when the
5040 // vector sources of the shuffle are the same.
5041 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5042   unsigned NumElts = VT.getVectorNumElements();
5043
5044   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5045   if (M[0] < 0)
5046     return false;
5047
5048   Imm = M[0];
5049
5050   // If this is a VEXT shuffle, the immediate value is the index of the first
5051   // element.  The other shuffle indices must be the successive elements after
5052   // the first one.
5053   unsigned ExpectedElt = Imm;
5054   for (unsigned i = 1; i < NumElts; ++i) {
5055     // Increment the expected index.  If it wraps around, just follow it
5056     // back to index zero and keep going.
5057     ++ExpectedElt;
5058     if (ExpectedElt == NumElts)
5059       ExpectedElt = 0;
5060
5061     if (M[i] < 0) continue; // ignore UNDEF indices
5062     if (ExpectedElt != static_cast<unsigned>(M[i]))
5063       return false;
5064   }
5065
5066   return true;
5067 }
5068
5069
5070 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5071                        bool &ReverseVEXT, unsigned &Imm) {
5072   unsigned NumElts = VT.getVectorNumElements();
5073   ReverseVEXT = false;
5074
5075   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5076   if (M[0] < 0)
5077     return false;
5078
5079   Imm = M[0];
5080
5081   // If this is a VEXT shuffle, the immediate value is the index of the first
5082   // element.  The other shuffle indices must be the successive elements after
5083   // the first one.
5084   unsigned ExpectedElt = Imm;
5085   for (unsigned i = 1; i < NumElts; ++i) {
5086     // Increment the expected index.  If it wraps around, it may still be
5087     // a VEXT but the source vectors must be swapped.
5088     ExpectedElt += 1;
5089     if (ExpectedElt == NumElts * 2) {
5090       ExpectedElt = 0;
5091       ReverseVEXT = true;
5092     }
5093
5094     if (M[i] < 0) continue; // ignore UNDEF indices
5095     if (ExpectedElt != static_cast<unsigned>(M[i]))
5096       return false;
5097   }
5098
5099   // Adjust the index value if the source operands will be swapped.
5100   if (ReverseVEXT)
5101     Imm -= NumElts;
5102
5103   return true;
5104 }
5105
5106 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5107 /// instruction with the specified blocksize.  (The order of the elements
5108 /// within each block of the vector is reversed.)
5109 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5110   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5111          "Only possible block sizes for VREV are: 16, 32, 64");
5112
5113   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5114   if (EltSz == 64)
5115     return false;
5116
5117   unsigned NumElts = VT.getVectorNumElements();
5118   unsigned BlockElts = M[0] + 1;
5119   // If the first shuffle index is UNDEF, be optimistic.
5120   if (M[0] < 0)
5121     BlockElts = BlockSize / EltSz;
5122
5123   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5124     return false;
5125
5126   for (unsigned i = 0; i < NumElts; ++i) {
5127     if (M[i] < 0) continue; // ignore UNDEF indices
5128     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5129       return false;
5130   }
5131
5132   return true;
5133 }
5134
5135 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5136   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5137   // range, then 0 is placed into the resulting vector. So pretty much any mask
5138   // of 8 elements can work here.
5139   return VT == MVT::v8i8 && M.size() == 8;
5140 }
5141
5142 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5143 // checking that pairs of elements in the shuffle mask represent the same index
5144 // in each vector, incrementing the expected index by 2 at each step.
5145 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5146 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5147 //  v2={e,f,g,h}
5148 // WhichResult gives the offset for each element in the mask based on which
5149 // of the two results it belongs to.
5150 //
5151 // The transpose can be represented either as:
5152 // result1 = shufflevector v1, v2, result1_shuffle_mask
5153 // result2 = shufflevector v1, v2, result2_shuffle_mask
5154 // where v1/v2 and the shuffle masks have the same number of elements
5155 // (here WhichResult (see below) indicates which result is being checked)
5156 //
5157 // or as:
5158 // results = shufflevector v1, v2, shuffle_mask
5159 // where both results are returned in one vector and the shuffle mask has twice
5160 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5161 // want to check the low half and high half of the shuffle mask as if it were
5162 // the other case
5163 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5164   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5165   if (EltSz == 64)
5166     return false;
5167
5168   unsigned NumElts = VT.getVectorNumElements();
5169   if (M.size() != NumElts && M.size() != NumElts*2)
5170     return false;
5171
5172   // If the mask is twice as long as the input vector then we need to check the
5173   // upper and lower parts of the mask with a matching value for WhichResult
5174   // FIXME: A mask with only even values will be rejected in case the first
5175   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5176   // M[0] is used to determine WhichResult
5177   for (unsigned i = 0; i < M.size(); i += NumElts) {
5178     if (M.size() == NumElts * 2)
5179       WhichResult = i / NumElts;
5180     else
5181       WhichResult = M[i] == 0 ? 0 : 1;
5182     for (unsigned j = 0; j < NumElts; j += 2) {
5183       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5184           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5185         return false;
5186     }
5187   }
5188
5189   if (M.size() == NumElts*2)
5190     WhichResult = 0;
5191
5192   return true;
5193 }
5194
5195 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5196 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5197 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5198 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5199   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5200   if (EltSz == 64)
5201     return false;
5202
5203   unsigned NumElts = VT.getVectorNumElements();
5204   if (M.size() != NumElts && M.size() != NumElts*2)
5205     return false;
5206
5207   for (unsigned i = 0; i < M.size(); i += NumElts) {
5208     if (M.size() == NumElts * 2)
5209       WhichResult = i / NumElts;
5210     else
5211       WhichResult = M[i] == 0 ? 0 : 1;
5212     for (unsigned j = 0; j < NumElts; j += 2) {
5213       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5214           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5215         return false;
5216     }
5217   }
5218
5219   if (M.size() == NumElts*2)
5220     WhichResult = 0;
5221
5222   return true;
5223 }
5224
5225 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5226 // that the mask elements are either all even and in steps of size 2 or all odd
5227 // and in steps of size 2.
5228 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5229 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5230 //  v2={e,f,g,h}
5231 // Requires similar checks to that of isVTRNMask with
5232 // respect the how results are returned.
5233 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5234   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5235   if (EltSz == 64)
5236     return false;
5237
5238   unsigned NumElts = VT.getVectorNumElements();
5239   if (M.size() != NumElts && M.size() != NumElts*2)
5240     return false;
5241
5242   for (unsigned i = 0; i < M.size(); i += NumElts) {
5243     WhichResult = M[i] == 0 ? 0 : 1;
5244     for (unsigned j = 0; j < NumElts; ++j) {
5245       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5246         return false;
5247     }
5248   }
5249
5250   if (M.size() == NumElts*2)
5251     WhichResult = 0;
5252
5253   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5254   if (VT.is64BitVector() && EltSz == 32)
5255     return false;
5256
5257   return true;
5258 }
5259
5260 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5261 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5262 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5263 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5264   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5265   if (EltSz == 64)
5266     return false;
5267
5268   unsigned NumElts = VT.getVectorNumElements();
5269   if (M.size() != NumElts && M.size() != NumElts*2)
5270     return false;
5271
5272   unsigned Half = NumElts / 2;
5273   for (unsigned i = 0; i < M.size(); i += NumElts) {
5274     WhichResult = M[i] == 0 ? 0 : 1;
5275     for (unsigned j = 0; j < NumElts; j += Half) {
5276       unsigned Idx = WhichResult;
5277       for (unsigned k = 0; k < Half; ++k) {
5278         int MIdx = M[i + j + k];
5279         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5280           return false;
5281         Idx += 2;
5282       }
5283     }
5284   }
5285
5286   if (M.size() == NumElts*2)
5287     WhichResult = 0;
5288
5289   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5290   if (VT.is64BitVector() && EltSz == 32)
5291     return false;
5292
5293   return true;
5294 }
5295
5296 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5297 // that pairs of elements of the shufflemask represent the same index in each
5298 // vector incrementing sequentially through the vectors.
5299 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5300 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5301 //  v2={e,f,g,h}
5302 // Requires similar checks to that of isVTRNMask with respect the how results
5303 // are returned.
5304 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5305   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5306   if (EltSz == 64)
5307     return false;
5308
5309   unsigned NumElts = VT.getVectorNumElements();
5310   if (M.size() != NumElts && M.size() != NumElts*2)
5311     return false;
5312
5313   for (unsigned i = 0; i < M.size(); i += NumElts) {
5314     WhichResult = M[i] == 0 ? 0 : 1;
5315     unsigned Idx = WhichResult * NumElts / 2;
5316     for (unsigned j = 0; j < NumElts; j += 2) {
5317       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5318           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5319         return false;
5320       Idx += 1;
5321     }
5322   }
5323
5324   if (M.size() == NumElts*2)
5325     WhichResult = 0;
5326
5327   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5328   if (VT.is64BitVector() && EltSz == 32)
5329     return false;
5330
5331   return true;
5332 }
5333
5334 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5335 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5336 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5337 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5338   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5339   if (EltSz == 64)
5340     return false;
5341
5342   unsigned NumElts = VT.getVectorNumElements();
5343   if (M.size() != NumElts && M.size() != NumElts*2)
5344     return false;
5345
5346   for (unsigned i = 0; i < M.size(); i += NumElts) {
5347     WhichResult = M[i] == 0 ? 0 : 1;
5348     unsigned Idx = WhichResult * NumElts / 2;
5349     for (unsigned j = 0; j < NumElts; j += 2) {
5350       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5351           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5352         return false;
5353       Idx += 1;
5354     }
5355   }
5356
5357   if (M.size() == NumElts*2)
5358     WhichResult = 0;
5359
5360   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5361   if (VT.is64BitVector() && EltSz == 32)
5362     return false;
5363
5364   return true;
5365 }
5366
5367 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5368 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5369 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5370                                            unsigned &WhichResult,
5371                                            bool &isV_UNDEF) {
5372   isV_UNDEF = false;
5373   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5374     return ARMISD::VTRN;
5375   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5376     return ARMISD::VUZP;
5377   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5378     return ARMISD::VZIP;
5379
5380   isV_UNDEF = true;
5381   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5382     return ARMISD::VTRN;
5383   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5384     return ARMISD::VUZP;
5385   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5386     return ARMISD::VZIP;
5387
5388   return 0;
5389 }
5390
5391 /// \return true if this is a reverse operation on an vector.
5392 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5393   unsigned NumElts = VT.getVectorNumElements();
5394   // Make sure the mask has the right size.
5395   if (NumElts != M.size())
5396       return false;
5397
5398   // Look for <15, ..., 3, -1, 1, 0>.
5399   for (unsigned i = 0; i != NumElts; ++i)
5400     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5401       return false;
5402
5403   return true;
5404 }
5405
5406 // If N is an integer constant that can be moved into a register in one
5407 // instruction, return an SDValue of such a constant (will become a MOV
5408 // instruction).  Otherwise return null.
5409 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5410                                      const ARMSubtarget *ST, SDLoc dl) {
5411   uint64_t Val;
5412   if (!isa<ConstantSDNode>(N))
5413     return SDValue();
5414   Val = cast<ConstantSDNode>(N)->getZExtValue();
5415
5416   if (ST->isThumb1Only()) {
5417     if (Val <= 255 || ~Val <= 255)
5418       return DAG.getConstant(Val, dl, MVT::i32);
5419   } else {
5420     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5421       return DAG.getConstant(Val, dl, MVT::i32);
5422   }
5423   return SDValue();
5424 }
5425
5426 // If this is a case we can't handle, return null and let the default
5427 // expansion code take care of it.
5428 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5429                                              const ARMSubtarget *ST) const {
5430   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5431   SDLoc dl(Op);
5432   EVT VT = Op.getValueType();
5433
5434   APInt SplatBits, SplatUndef;
5435   unsigned SplatBitSize;
5436   bool HasAnyUndefs;
5437   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5438     if (SplatBitSize <= 64) {
5439       // Check if an immediate VMOV works.
5440       EVT VmovVT;
5441       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5442                                       SplatUndef.getZExtValue(), SplatBitSize,
5443                                       DAG, dl, VmovVT, VT.is128BitVector(),
5444                                       VMOVModImm);
5445       if (Val.getNode()) {
5446         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5447         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5448       }
5449
5450       // Try an immediate VMVN.
5451       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5452       Val = isNEONModifiedImm(NegatedImm,
5453                                       SplatUndef.getZExtValue(), SplatBitSize,
5454                                       DAG, dl, VmovVT, VT.is128BitVector(),
5455                                       VMVNModImm);
5456       if (Val.getNode()) {
5457         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5458         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5459       }
5460
5461       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5462       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5463         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5464         if (ImmVal != -1) {
5465           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5466           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5467         }
5468       }
5469     }
5470   }
5471
5472   // Scan through the operands to see if only one value is used.
5473   //
5474   // As an optimisation, even if more than one value is used it may be more
5475   // profitable to splat with one value then change some lanes.
5476   //
5477   // Heuristically we decide to do this if the vector has a "dominant" value,
5478   // defined as splatted to more than half of the lanes.
5479   unsigned NumElts = VT.getVectorNumElements();
5480   bool isOnlyLowElement = true;
5481   bool usesOnlyOneValue = true;
5482   bool hasDominantValue = false;
5483   bool isConstant = true;
5484
5485   // Map of the number of times a particular SDValue appears in the
5486   // element list.
5487   DenseMap<SDValue, unsigned> ValueCounts;
5488   SDValue Value;
5489   for (unsigned i = 0; i < NumElts; ++i) {
5490     SDValue V = Op.getOperand(i);
5491     if (V.getOpcode() == ISD::UNDEF)
5492       continue;
5493     if (i > 0)
5494       isOnlyLowElement = false;
5495     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5496       isConstant = false;
5497
5498     ValueCounts.insert(std::make_pair(V, 0));
5499     unsigned &Count = ValueCounts[V];
5500
5501     // Is this value dominant? (takes up more than half of the lanes)
5502     if (++Count > (NumElts / 2)) {
5503       hasDominantValue = true;
5504       Value = V;
5505     }
5506   }
5507   if (ValueCounts.size() != 1)
5508     usesOnlyOneValue = false;
5509   if (!Value.getNode() && ValueCounts.size() > 0)
5510     Value = ValueCounts.begin()->first;
5511
5512   if (ValueCounts.size() == 0)
5513     return DAG.getUNDEF(VT);
5514
5515   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5516   // Keep going if we are hitting this case.
5517   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5518     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5519
5520   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5521
5522   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5523   // i32 and try again.
5524   if (hasDominantValue && EltSize <= 32) {
5525     if (!isConstant) {
5526       SDValue N;
5527
5528       // If we are VDUPing a value that comes directly from a vector, that will
5529       // cause an unnecessary move to and from a GPR, where instead we could
5530       // just use VDUPLANE. We can only do this if the lane being extracted
5531       // is at a constant index, as the VDUP from lane instructions only have
5532       // constant-index forms.
5533       ConstantSDNode *constIndex;
5534       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5535           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5536         // We need to create a new undef vector to use for the VDUPLANE if the
5537         // size of the vector from which we get the value is different than the
5538         // size of the vector that we need to create. We will insert the element
5539         // such that the register coalescer will remove unnecessary copies.
5540         if (VT != Value->getOperand(0).getValueType()) {
5541           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5542                              VT.getVectorNumElements();
5543           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5544                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5545                         Value, DAG.getConstant(index, dl, MVT::i32)),
5546                            DAG.getConstant(index, dl, MVT::i32));
5547         } else
5548           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5549                         Value->getOperand(0), Value->getOperand(1));
5550       } else
5551         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5552
5553       if (!usesOnlyOneValue) {
5554         // The dominant value was splatted as 'N', but we now have to insert
5555         // all differing elements.
5556         for (unsigned I = 0; I < NumElts; ++I) {
5557           if (Op.getOperand(I) == Value)
5558             continue;
5559           SmallVector<SDValue, 3> Ops;
5560           Ops.push_back(N);
5561           Ops.push_back(Op.getOperand(I));
5562           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5563           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5564         }
5565       }
5566       return N;
5567     }
5568     if (VT.getVectorElementType().isFloatingPoint()) {
5569       SmallVector<SDValue, 8> Ops;
5570       for (unsigned i = 0; i < NumElts; ++i)
5571         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5572                                   Op.getOperand(i)));
5573       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5574       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5575       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5576       if (Val.getNode())
5577         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5578     }
5579     if (usesOnlyOneValue) {
5580       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5581       if (isConstant && Val.getNode())
5582         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5583     }
5584   }
5585
5586   // If all elements are constants and the case above didn't get hit, fall back
5587   // to the default expansion, which will generate a load from the constant
5588   // pool.
5589   if (isConstant)
5590     return SDValue();
5591
5592   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5593   if (NumElts >= 4) {
5594     SDValue shuffle = ReconstructShuffle(Op, DAG);
5595     if (shuffle != SDValue())
5596       return shuffle;
5597   }
5598
5599   // Vectors with 32- or 64-bit elements can be built by directly assigning
5600   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5601   // will be legalized.
5602   if (EltSize >= 32) {
5603     // Do the expansion with floating-point types, since that is what the VFP
5604     // registers are defined to use, and since i64 is not legal.
5605     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5606     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5607     SmallVector<SDValue, 8> Ops;
5608     for (unsigned i = 0; i < NumElts; ++i)
5609       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5610     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5611     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5612   }
5613
5614   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5615   // know the default expansion would otherwise fall back on something even
5616   // worse. For a vector with one or two non-undef values, that's
5617   // scalar_to_vector for the elements followed by a shuffle (provided the
5618   // shuffle is valid for the target) and materialization element by element
5619   // on the stack followed by a load for everything else.
5620   if (!isConstant && !usesOnlyOneValue) {
5621     SDValue Vec = DAG.getUNDEF(VT);
5622     for (unsigned i = 0 ; i < NumElts; ++i) {
5623       SDValue V = Op.getOperand(i);
5624       if (V.getOpcode() == ISD::UNDEF)
5625         continue;
5626       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5627       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5628     }
5629     return Vec;
5630   }
5631
5632   return SDValue();
5633 }
5634
5635 // Gather data to see if the operation can be modelled as a
5636 // shuffle in combination with VEXTs.
5637 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5638                                               SelectionDAG &DAG) const {
5639   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5640   SDLoc dl(Op);
5641   EVT VT = Op.getValueType();
5642   unsigned NumElts = VT.getVectorNumElements();
5643
5644   struct ShuffleSourceInfo {
5645     SDValue Vec;
5646     unsigned MinElt;
5647     unsigned MaxElt;
5648
5649     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5650     // be compatible with the shuffle we intend to construct. As a result
5651     // ShuffleVec will be some sliding window into the original Vec.
5652     SDValue ShuffleVec;
5653
5654     // Code should guarantee that element i in Vec starts at element "WindowBase
5655     // + i * WindowScale in ShuffleVec".
5656     int WindowBase;
5657     int WindowScale;
5658
5659     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5660     ShuffleSourceInfo(SDValue Vec)
5661         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5662           WindowScale(1) {}
5663   };
5664
5665   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5666   // node.
5667   SmallVector<ShuffleSourceInfo, 2> Sources;
5668   for (unsigned i = 0; i < NumElts; ++i) {
5669     SDValue V = Op.getOperand(i);
5670     if (V.getOpcode() == ISD::UNDEF)
5671       continue;
5672     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5673       // A shuffle can only come from building a vector from various
5674       // elements of other vectors.
5675       return SDValue();
5676     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5677       // Furthermore, shuffles require a constant mask, whereas extractelts
5678       // accept variable indices.
5679       return SDValue();
5680     }
5681
5682     // Add this element source to the list if it's not already there.
5683     SDValue SourceVec = V.getOperand(0);
5684     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5685     if (Source == Sources.end())
5686       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5687
5688     // Update the minimum and maximum lane number seen.
5689     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5690     Source->MinElt = std::min(Source->MinElt, EltNo);
5691     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5692   }
5693
5694   // Currently only do something sane when at most two source vectors
5695   // are involved.
5696   if (Sources.size() > 2)
5697     return SDValue();
5698
5699   // Find out the smallest element size among result and two sources, and use
5700   // it as element size to build the shuffle_vector.
5701   EVT SmallestEltTy = VT.getVectorElementType();
5702   for (auto &Source : Sources) {
5703     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5704     if (SrcEltTy.bitsLT(SmallestEltTy))
5705       SmallestEltTy = SrcEltTy;
5706   }
5707   unsigned ResMultiplier =
5708       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5709   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5710   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5711
5712   // If the source vector is too wide or too narrow, we may nevertheless be able
5713   // to construct a compatible shuffle either by concatenating it with UNDEF or
5714   // extracting a suitable range of elements.
5715   for (auto &Src : Sources) {
5716     EVT SrcVT = Src.ShuffleVec.getValueType();
5717
5718     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5719       continue;
5720
5721     // This stage of the search produces a source with the same element type as
5722     // the original, but with a total width matching the BUILD_VECTOR output.
5723     EVT EltVT = SrcVT.getVectorElementType();
5724     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5725     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5726
5727     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5728       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5729         return SDValue();
5730       // We can pad out the smaller vector for free, so if it's part of a
5731       // shuffle...
5732       Src.ShuffleVec =
5733           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5734                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5735       continue;
5736     }
5737
5738     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5739       return SDValue();
5740
5741     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5742       // Span too large for a VEXT to cope
5743       return SDValue();
5744     }
5745
5746     if (Src.MinElt >= NumSrcElts) {
5747       // The extraction can just take the second half
5748       Src.ShuffleVec =
5749           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5750                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5751       Src.WindowBase = -NumSrcElts;
5752     } else if (Src.MaxElt < NumSrcElts) {
5753       // The extraction can just take the first half
5754       Src.ShuffleVec =
5755           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5756                       DAG.getConstant(0, dl, MVT::i32));
5757     } else {
5758       // An actual VEXT is needed
5759       SDValue VEXTSrc1 =
5760           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5761                       DAG.getConstant(0, dl, MVT::i32));
5762       SDValue VEXTSrc2 =
5763           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5764                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5765
5766       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5767                                    VEXTSrc2,
5768                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5769       Src.WindowBase = -Src.MinElt;
5770     }
5771   }
5772
5773   // Another possible incompatibility occurs from the vector element types. We
5774   // can fix this by bitcasting the source vectors to the same type we intend
5775   // for the shuffle.
5776   for (auto &Src : Sources) {
5777     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5778     if (SrcEltTy == SmallestEltTy)
5779       continue;
5780     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5781     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5782     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5783     Src.WindowBase *= Src.WindowScale;
5784   }
5785
5786   // Final sanity check before we try to actually produce a shuffle.
5787   DEBUG(
5788     for (auto Src : Sources)
5789       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5790   );
5791
5792   // The stars all align, our next step is to produce the mask for the shuffle.
5793   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5794   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5795   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5796     SDValue Entry = Op.getOperand(i);
5797     if (Entry.getOpcode() == ISD::UNDEF)
5798       continue;
5799
5800     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5801     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5802
5803     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5804     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5805     // segment.
5806     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5807     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5808                                VT.getVectorElementType().getSizeInBits());
5809     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5810
5811     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5812     // starting at the appropriate offset.
5813     int *LaneMask = &Mask[i * ResMultiplier];
5814
5815     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5816     ExtractBase += NumElts * (Src - Sources.begin());
5817     for (int j = 0; j < LanesDefined; ++j)
5818       LaneMask[j] = ExtractBase + j;
5819   }
5820
5821   // Final check before we try to produce nonsense...
5822   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5823     return SDValue();
5824
5825   // We can't handle more than two sources. This should have already
5826   // been checked before this point.
5827   assert(Sources.size() <= 2 && "Too many sources!");
5828
5829   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5830   for (unsigned i = 0; i < Sources.size(); ++i)
5831     ShuffleOps[i] = Sources[i].ShuffleVec;
5832
5833   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5834                                          ShuffleOps[1], &Mask[0]);
5835   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5836 }
5837
5838 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5839 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5840 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5841 /// are assumed to be legal.
5842 bool
5843 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5844                                       EVT VT) const {
5845   if (VT.getVectorNumElements() == 4 &&
5846       (VT.is128BitVector() || VT.is64BitVector())) {
5847     unsigned PFIndexes[4];
5848     for (unsigned i = 0; i != 4; ++i) {
5849       if (M[i] < 0)
5850         PFIndexes[i] = 8;
5851       else
5852         PFIndexes[i] = M[i];
5853     }
5854
5855     // Compute the index in the perfect shuffle table.
5856     unsigned PFTableIndex =
5857       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5858     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5859     unsigned Cost = (PFEntry >> 30);
5860
5861     if (Cost <= 4)
5862       return true;
5863   }
5864
5865   bool ReverseVEXT, isV_UNDEF;
5866   unsigned Imm, WhichResult;
5867
5868   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5869   return (EltSize >= 32 ||
5870           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5871           isVREVMask(M, VT, 64) ||
5872           isVREVMask(M, VT, 32) ||
5873           isVREVMask(M, VT, 16) ||
5874           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5875           isVTBLMask(M, VT) ||
5876           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5877           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5878 }
5879
5880 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5881 /// the specified operations to build the shuffle.
5882 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5883                                       SDValue RHS, SelectionDAG &DAG,
5884                                       SDLoc dl) {
5885   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5886   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5887   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5888
5889   enum {
5890     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5891     OP_VREV,
5892     OP_VDUP0,
5893     OP_VDUP1,
5894     OP_VDUP2,
5895     OP_VDUP3,
5896     OP_VEXT1,
5897     OP_VEXT2,
5898     OP_VEXT3,
5899     OP_VUZPL, // VUZP, left result
5900     OP_VUZPR, // VUZP, right result
5901     OP_VZIPL, // VZIP, left result
5902     OP_VZIPR, // VZIP, right result
5903     OP_VTRNL, // VTRN, left result
5904     OP_VTRNR  // VTRN, right result
5905   };
5906
5907   if (OpNum == OP_COPY) {
5908     if (LHSID == (1*9+2)*9+3) return LHS;
5909     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5910     return RHS;
5911   }
5912
5913   SDValue OpLHS, OpRHS;
5914   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5915   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5916   EVT VT = OpLHS.getValueType();
5917
5918   switch (OpNum) {
5919   default: llvm_unreachable("Unknown shuffle opcode!");
5920   case OP_VREV:
5921     // VREV divides the vector in half and swaps within the half.
5922     if (VT.getVectorElementType() == MVT::i32 ||
5923         VT.getVectorElementType() == MVT::f32)
5924       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5925     // vrev <4 x i16> -> VREV32
5926     if (VT.getVectorElementType() == MVT::i16)
5927       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5928     // vrev <4 x i8> -> VREV16
5929     assert(VT.getVectorElementType() == MVT::i8);
5930     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5931   case OP_VDUP0:
5932   case OP_VDUP1:
5933   case OP_VDUP2:
5934   case OP_VDUP3:
5935     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5936                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5937   case OP_VEXT1:
5938   case OP_VEXT2:
5939   case OP_VEXT3:
5940     return DAG.getNode(ARMISD::VEXT, dl, VT,
5941                        OpLHS, OpRHS,
5942                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5943   case OP_VUZPL:
5944   case OP_VUZPR:
5945     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5946                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5947   case OP_VZIPL:
5948   case OP_VZIPR:
5949     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5950                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5951   case OP_VTRNL:
5952   case OP_VTRNR:
5953     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5954                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5955   }
5956 }
5957
5958 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5959                                        ArrayRef<int> ShuffleMask,
5960                                        SelectionDAG &DAG) {
5961   // Check to see if we can use the VTBL instruction.
5962   SDValue V1 = Op.getOperand(0);
5963   SDValue V2 = Op.getOperand(1);
5964   SDLoc DL(Op);
5965
5966   SmallVector<SDValue, 8> VTBLMask;
5967   for (ArrayRef<int>::iterator
5968          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5969     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5970
5971   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5972     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5973                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5974
5975   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5976                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5977 }
5978
5979 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5980                                                       SelectionDAG &DAG) {
5981   SDLoc DL(Op);
5982   SDValue OpLHS = Op.getOperand(0);
5983   EVT VT = OpLHS.getValueType();
5984
5985   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5986          "Expect an v8i16/v16i8 type");
5987   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5988   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5989   // extract the first 8 bytes into the top double word and the last 8 bytes
5990   // into the bottom double word. The v8i16 case is similar.
5991   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5992   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5993                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5994 }
5995
5996 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5997   SDValue V1 = Op.getOperand(0);
5998   SDValue V2 = Op.getOperand(1);
5999   SDLoc dl(Op);
6000   EVT VT = Op.getValueType();
6001   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6002
6003   // Convert shuffles that are directly supported on NEON to target-specific
6004   // DAG nodes, instead of keeping them as shuffles and matching them again
6005   // during code selection.  This is more efficient and avoids the possibility
6006   // of inconsistencies between legalization and selection.
6007   // FIXME: floating-point vectors should be canonicalized to integer vectors
6008   // of the same time so that they get CSEd properly.
6009   ArrayRef<int> ShuffleMask = SVN->getMask();
6010
6011   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6012   if (EltSize <= 32) {
6013     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
6014       int Lane = SVN->getSplatIndex();
6015       // If this is undef splat, generate it via "just" vdup, if possible.
6016       if (Lane == -1) Lane = 0;
6017
6018       // Test if V1 is a SCALAR_TO_VECTOR.
6019       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6020         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6021       }
6022       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6023       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6024       // reaches it).
6025       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6026           !isa<ConstantSDNode>(V1.getOperand(0))) {
6027         bool IsScalarToVector = true;
6028         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6029           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
6030             IsScalarToVector = false;
6031             break;
6032           }
6033         if (IsScalarToVector)
6034           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6035       }
6036       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6037                          DAG.getConstant(Lane, dl, MVT::i32));
6038     }
6039
6040     bool ReverseVEXT;
6041     unsigned Imm;
6042     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6043       if (ReverseVEXT)
6044         std::swap(V1, V2);
6045       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6046                          DAG.getConstant(Imm, dl, MVT::i32));
6047     }
6048
6049     if (isVREVMask(ShuffleMask, VT, 64))
6050       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6051     if (isVREVMask(ShuffleMask, VT, 32))
6052       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6053     if (isVREVMask(ShuffleMask, VT, 16))
6054       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6055
6056     if (V2->getOpcode() == ISD::UNDEF &&
6057         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6058       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6059                          DAG.getConstant(Imm, dl, MVT::i32));
6060     }
6061
6062     // Check for Neon shuffles that modify both input vectors in place.
6063     // If both results are used, i.e., if there are two shuffles with the same
6064     // source operands and with masks corresponding to both results of one of
6065     // these operations, DAG memoization will ensure that a single node is
6066     // used for both shuffles.
6067     unsigned WhichResult;
6068     bool isV_UNDEF;
6069     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6070             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6071       if (isV_UNDEF)
6072         V2 = V1;
6073       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6074           .getValue(WhichResult);
6075     }
6076
6077     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6078     // shuffles that produce a result larger than their operands with:
6079     //   shuffle(concat(v1, undef), concat(v2, undef))
6080     // ->
6081     //   shuffle(concat(v1, v2), undef)
6082     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6083     //
6084     // This is useful in the general case, but there are special cases where
6085     // native shuffles produce larger results: the two-result ops.
6086     //
6087     // Look through the concat when lowering them:
6088     //   shuffle(concat(v1, v2), undef)
6089     // ->
6090     //   concat(VZIP(v1, v2):0, :1)
6091     //
6092     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6093         V2->getOpcode() == ISD::UNDEF) {
6094       SDValue SubV1 = V1->getOperand(0);
6095       SDValue SubV2 = V1->getOperand(1);
6096       EVT SubVT = SubV1.getValueType();
6097
6098       // We expect these to have been canonicalized to -1.
6099       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6100         return i < (int)VT.getVectorNumElements();
6101       }) && "Unexpected shuffle index into UNDEF operand!");
6102
6103       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6104               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6105         if (isV_UNDEF)
6106           SubV2 = SubV1;
6107         assert((WhichResult == 0) &&
6108                "In-place shuffle of concat can only have one result!");
6109         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6110                                   SubV1, SubV2);
6111         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6112                            Res.getValue(1));
6113       }
6114     }
6115   }
6116
6117   // If the shuffle is not directly supported and it has 4 elements, use
6118   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6119   unsigned NumElts = VT.getVectorNumElements();
6120   if (NumElts == 4) {
6121     unsigned PFIndexes[4];
6122     for (unsigned i = 0; i != 4; ++i) {
6123       if (ShuffleMask[i] < 0)
6124         PFIndexes[i] = 8;
6125       else
6126         PFIndexes[i] = ShuffleMask[i];
6127     }
6128
6129     // Compute the index in the perfect shuffle table.
6130     unsigned PFTableIndex =
6131       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6132     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6133     unsigned Cost = (PFEntry >> 30);
6134
6135     if (Cost <= 4)
6136       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6137   }
6138
6139   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6140   if (EltSize >= 32) {
6141     // Do the expansion with floating-point types, since that is what the VFP
6142     // registers are defined to use, and since i64 is not legal.
6143     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6144     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6145     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6146     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6147     SmallVector<SDValue, 8> Ops;
6148     for (unsigned i = 0; i < NumElts; ++i) {
6149       if (ShuffleMask[i] < 0)
6150         Ops.push_back(DAG.getUNDEF(EltVT));
6151       else
6152         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6153                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6154                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6155                                                   dl, MVT::i32)));
6156     }
6157     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6158     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6159   }
6160
6161   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6162     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6163
6164   if (VT == MVT::v8i8) {
6165     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6166     if (NewOp.getNode())
6167       return NewOp;
6168   }
6169
6170   return SDValue();
6171 }
6172
6173 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6174   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6175   SDValue Lane = Op.getOperand(2);
6176   if (!isa<ConstantSDNode>(Lane))
6177     return SDValue();
6178
6179   return Op;
6180 }
6181
6182 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6183   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6184   SDValue Lane = Op.getOperand(1);
6185   if (!isa<ConstantSDNode>(Lane))
6186     return SDValue();
6187
6188   SDValue Vec = Op.getOperand(0);
6189   if (Op.getValueType() == MVT::i32 &&
6190       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6191     SDLoc dl(Op);
6192     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6193   }
6194
6195   return Op;
6196 }
6197
6198 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6199   // The only time a CONCAT_VECTORS operation can have legal types is when
6200   // two 64-bit vectors are concatenated to a 128-bit vector.
6201   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6202          "unexpected CONCAT_VECTORS");
6203   SDLoc dl(Op);
6204   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6205   SDValue Op0 = Op.getOperand(0);
6206   SDValue Op1 = Op.getOperand(1);
6207   if (Op0.getOpcode() != ISD::UNDEF)
6208     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6209                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6210                       DAG.getIntPtrConstant(0, dl));
6211   if (Op1.getOpcode() != ISD::UNDEF)
6212     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6213                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6214                       DAG.getIntPtrConstant(1, dl));
6215   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6216 }
6217
6218 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6219 /// element has been zero/sign-extended, depending on the isSigned parameter,
6220 /// from an integer type half its size.
6221 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6222                                    bool isSigned) {
6223   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6224   EVT VT = N->getValueType(0);
6225   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6226     SDNode *BVN = N->getOperand(0).getNode();
6227     if (BVN->getValueType(0) != MVT::v4i32 ||
6228         BVN->getOpcode() != ISD::BUILD_VECTOR)
6229       return false;
6230     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6231     unsigned HiElt = 1 - LoElt;
6232     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6233     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6234     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6235     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6236     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6237       return false;
6238     if (isSigned) {
6239       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6240           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6241         return true;
6242     } else {
6243       if (Hi0->isNullValue() && Hi1->isNullValue())
6244         return true;
6245     }
6246     return false;
6247   }
6248
6249   if (N->getOpcode() != ISD::BUILD_VECTOR)
6250     return false;
6251
6252   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6253     SDNode *Elt = N->getOperand(i).getNode();
6254     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6255       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6256       unsigned HalfSize = EltSize / 2;
6257       if (isSigned) {
6258         if (!isIntN(HalfSize, C->getSExtValue()))
6259           return false;
6260       } else {
6261         if (!isUIntN(HalfSize, C->getZExtValue()))
6262           return false;
6263       }
6264       continue;
6265     }
6266     return false;
6267   }
6268
6269   return true;
6270 }
6271
6272 /// isSignExtended - Check if a node is a vector value that is sign-extended
6273 /// or a constant BUILD_VECTOR with sign-extended elements.
6274 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6275   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6276     return true;
6277   if (isExtendedBUILD_VECTOR(N, DAG, true))
6278     return true;
6279   return false;
6280 }
6281
6282 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6283 /// or a constant BUILD_VECTOR with zero-extended elements.
6284 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6285   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6286     return true;
6287   if (isExtendedBUILD_VECTOR(N, DAG, false))
6288     return true;
6289   return false;
6290 }
6291
6292 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6293   if (OrigVT.getSizeInBits() >= 64)
6294     return OrigVT;
6295
6296   assert(OrigVT.isSimple() && "Expecting a simple value type");
6297
6298   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6299   switch (OrigSimpleTy) {
6300   default: llvm_unreachable("Unexpected Vector Type");
6301   case MVT::v2i8:
6302   case MVT::v2i16:
6303      return MVT::v2i32;
6304   case MVT::v4i8:
6305     return  MVT::v4i16;
6306   }
6307 }
6308
6309 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6310 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6311 /// We insert the required extension here to get the vector to fill a D register.
6312 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6313                                             const EVT &OrigTy,
6314                                             const EVT &ExtTy,
6315                                             unsigned ExtOpcode) {
6316   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6317   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6318   // 64-bits we need to insert a new extension so that it will be 64-bits.
6319   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6320   if (OrigTy.getSizeInBits() >= 64)
6321     return N;
6322
6323   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6324   EVT NewVT = getExtensionTo64Bits(OrigTy);
6325
6326   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6327 }
6328
6329 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6330 /// does not do any sign/zero extension. If the original vector is less
6331 /// than 64 bits, an appropriate extension will be added after the load to
6332 /// reach a total size of 64 bits. We have to add the extension separately
6333 /// because ARM does not have a sign/zero extending load for vectors.
6334 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6335   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6336
6337   // The load already has the right type.
6338   if (ExtendedTy == LD->getMemoryVT())
6339     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6340                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6341                 LD->isNonTemporal(), LD->isInvariant(),
6342                 LD->getAlignment());
6343
6344   // We need to create a zextload/sextload. We cannot just create a load
6345   // followed by a zext/zext node because LowerMUL is also run during normal
6346   // operation legalization where we can't create illegal types.
6347   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6348                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6349                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6350                         LD->isNonTemporal(), LD->getAlignment());
6351 }
6352
6353 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6354 /// extending load, or BUILD_VECTOR with extended elements, return the
6355 /// unextended value. The unextended vector should be 64 bits so that it can
6356 /// be used as an operand to a VMULL instruction. If the original vector size
6357 /// before extension is less than 64 bits we add a an extension to resize
6358 /// the vector to 64 bits.
6359 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6360   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6361     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6362                                         N->getOperand(0)->getValueType(0),
6363                                         N->getValueType(0),
6364                                         N->getOpcode());
6365
6366   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6367     return SkipLoadExtensionForVMULL(LD, DAG);
6368
6369   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6370   // have been legalized as a BITCAST from v4i32.
6371   if (N->getOpcode() == ISD::BITCAST) {
6372     SDNode *BVN = N->getOperand(0).getNode();
6373     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6374            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6375     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6376     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6377                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6378   }
6379   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6380   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6381   EVT VT = N->getValueType(0);
6382   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6383   unsigned NumElts = VT.getVectorNumElements();
6384   MVT TruncVT = MVT::getIntegerVT(EltSize);
6385   SmallVector<SDValue, 8> Ops;
6386   SDLoc dl(N);
6387   for (unsigned i = 0; i != NumElts; ++i) {
6388     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6389     const APInt &CInt = C->getAPIntValue();
6390     // Element types smaller than 32 bits are not legal, so use i32 elements.
6391     // The values are implicitly truncated so sext vs. zext doesn't matter.
6392     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6393   }
6394   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6395                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6396 }
6397
6398 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6399   unsigned Opcode = N->getOpcode();
6400   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6401     SDNode *N0 = N->getOperand(0).getNode();
6402     SDNode *N1 = N->getOperand(1).getNode();
6403     return N0->hasOneUse() && N1->hasOneUse() &&
6404       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6405   }
6406   return false;
6407 }
6408
6409 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6410   unsigned Opcode = N->getOpcode();
6411   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6412     SDNode *N0 = N->getOperand(0).getNode();
6413     SDNode *N1 = N->getOperand(1).getNode();
6414     return N0->hasOneUse() && N1->hasOneUse() &&
6415       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6416   }
6417   return false;
6418 }
6419
6420 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6421   // Multiplications are only custom-lowered for 128-bit vectors so that
6422   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6423   EVT VT = Op.getValueType();
6424   assert(VT.is128BitVector() && VT.isInteger() &&
6425          "unexpected type for custom-lowering ISD::MUL");
6426   SDNode *N0 = Op.getOperand(0).getNode();
6427   SDNode *N1 = Op.getOperand(1).getNode();
6428   unsigned NewOpc = 0;
6429   bool isMLA = false;
6430   bool isN0SExt = isSignExtended(N0, DAG);
6431   bool isN1SExt = isSignExtended(N1, DAG);
6432   if (isN0SExt && isN1SExt)
6433     NewOpc = ARMISD::VMULLs;
6434   else {
6435     bool isN0ZExt = isZeroExtended(N0, DAG);
6436     bool isN1ZExt = isZeroExtended(N1, DAG);
6437     if (isN0ZExt && isN1ZExt)
6438       NewOpc = ARMISD::VMULLu;
6439     else if (isN1SExt || isN1ZExt) {
6440       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6441       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6442       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6443         NewOpc = ARMISD::VMULLs;
6444         isMLA = true;
6445       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6446         NewOpc = ARMISD::VMULLu;
6447         isMLA = true;
6448       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6449         std::swap(N0, N1);
6450         NewOpc = ARMISD::VMULLu;
6451         isMLA = true;
6452       }
6453     }
6454
6455     if (!NewOpc) {
6456       if (VT == MVT::v2i64)
6457         // Fall through to expand this.  It is not legal.
6458         return SDValue();
6459       else
6460         // Other vector multiplications are legal.
6461         return Op;
6462     }
6463   }
6464
6465   // Legalize to a VMULL instruction.
6466   SDLoc DL(Op);
6467   SDValue Op0;
6468   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6469   if (!isMLA) {
6470     Op0 = SkipExtensionForVMULL(N0, DAG);
6471     assert(Op0.getValueType().is64BitVector() &&
6472            Op1.getValueType().is64BitVector() &&
6473            "unexpected types for extended operands to VMULL");
6474     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6475   }
6476
6477   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6478   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6479   //   vmull q0, d4, d6
6480   //   vmlal q0, d5, d6
6481   // is faster than
6482   //   vaddl q0, d4, d5
6483   //   vmovl q1, d6
6484   //   vmul  q0, q0, q1
6485   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6486   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6487   EVT Op1VT = Op1.getValueType();
6488   return DAG.getNode(N0->getOpcode(), DL, VT,
6489                      DAG.getNode(NewOpc, DL, VT,
6490                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6491                      DAG.getNode(NewOpc, DL, VT,
6492                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6493 }
6494
6495 static SDValue
6496 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6497   // TODO: Should this propagate fast-math-flags?
6498
6499   // Convert to float
6500   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6501   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6502   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6503   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6504   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6505   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6506   // Get reciprocal estimate.
6507   // float4 recip = vrecpeq_f32(yf);
6508   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6509                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6510                    Y);
6511   // Because char has a smaller range than uchar, we can actually get away
6512   // without any newton steps.  This requires that we use a weird bias
6513   // of 0xb000, however (again, this has been exhaustively tested).
6514   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6515   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6516   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6517   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6518   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6519   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6520   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6521   // Convert back to short.
6522   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6523   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6524   return X;
6525 }
6526
6527 static SDValue
6528 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6529   // TODO: Should this propagate fast-math-flags?
6530
6531   SDValue N2;
6532   // Convert to float.
6533   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6534   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6535   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6536   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6537   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6538   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6539
6540   // Use reciprocal estimate and one refinement step.
6541   // float4 recip = vrecpeq_f32(yf);
6542   // recip *= vrecpsq_f32(yf, recip);
6543   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6544                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6545                    N1);
6546   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6547                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6548                    N1, N2);
6549   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6550   // Because short has a smaller range than ushort, we can actually get away
6551   // with only a single newton step.  This requires that we use a weird bias
6552   // of 89, however (again, this has been exhaustively tested).
6553   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6554   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6555   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6556   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6557   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6558   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6559   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6560   // Convert back to integer and return.
6561   // return vmovn_s32(vcvt_s32_f32(result));
6562   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6563   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6564   return N0;
6565 }
6566
6567 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6568   EVT VT = Op.getValueType();
6569   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6570          "unexpected type for custom-lowering ISD::SDIV");
6571
6572   SDLoc dl(Op);
6573   SDValue N0 = Op.getOperand(0);
6574   SDValue N1 = Op.getOperand(1);
6575   SDValue N2, N3;
6576
6577   if (VT == MVT::v8i8) {
6578     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6579     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6580
6581     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6582                      DAG.getIntPtrConstant(4, dl));
6583     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6584                      DAG.getIntPtrConstant(4, dl));
6585     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6586                      DAG.getIntPtrConstant(0, dl));
6587     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6588                      DAG.getIntPtrConstant(0, dl));
6589
6590     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6591     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6592
6593     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6594     N0 = LowerCONCAT_VECTORS(N0, DAG);
6595
6596     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6597     return N0;
6598   }
6599   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6600 }
6601
6602 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6603   // TODO: Should this propagate fast-math-flags?
6604   EVT VT = Op.getValueType();
6605   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6606          "unexpected type for custom-lowering ISD::UDIV");
6607
6608   SDLoc dl(Op);
6609   SDValue N0 = Op.getOperand(0);
6610   SDValue N1 = Op.getOperand(1);
6611   SDValue N2, N3;
6612
6613   if (VT == MVT::v8i8) {
6614     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6615     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6616
6617     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6618                      DAG.getIntPtrConstant(4, dl));
6619     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6620                      DAG.getIntPtrConstant(4, dl));
6621     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6622                      DAG.getIntPtrConstant(0, dl));
6623     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6624                      DAG.getIntPtrConstant(0, dl));
6625
6626     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6627     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6628
6629     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6630     N0 = LowerCONCAT_VECTORS(N0, DAG);
6631
6632     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6633                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6634                                      MVT::i32),
6635                      N0);
6636     return N0;
6637   }
6638
6639   // v4i16 sdiv ... Convert to float.
6640   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6641   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6642   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6643   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6644   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6645   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6646
6647   // Use reciprocal estimate and two refinement steps.
6648   // float4 recip = vrecpeq_f32(yf);
6649   // recip *= vrecpsq_f32(yf, recip);
6650   // recip *= vrecpsq_f32(yf, recip);
6651   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6652                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6653                    BN1);
6654   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6655                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6656                    BN1, N2);
6657   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6658   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6659                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6660                    BN1, N2);
6661   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6662   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6663   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6664   // and that it will never cause us to return an answer too large).
6665   // float4 result = as_float4(as_int4(xf*recip) + 2);
6666   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6667   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6668   N1 = DAG.getConstant(2, dl, MVT::i32);
6669   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6670   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6671   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6672   // Convert back to integer and return.
6673   // return vmovn_u32(vcvt_s32_f32(result));
6674   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6675   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6676   return N0;
6677 }
6678
6679 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6680   EVT VT = Op.getNode()->getValueType(0);
6681   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6682
6683   unsigned Opc;
6684   bool ExtraOp = false;
6685   switch (Op.getOpcode()) {
6686   default: llvm_unreachable("Invalid code");
6687   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6688   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6689   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6690   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6691   }
6692
6693   if (!ExtraOp)
6694     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6695                        Op.getOperand(1));
6696   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6697                      Op.getOperand(1), Op.getOperand(2));
6698 }
6699
6700 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6701   assert(Subtarget->isTargetDarwin());
6702
6703   // For iOS, we want to call an alternative entry point: __sincos_stret,
6704   // return values are passed via sret.
6705   SDLoc dl(Op);
6706   SDValue Arg = Op.getOperand(0);
6707   EVT ArgVT = Arg.getValueType();
6708   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6709   auto PtrVT = getPointerTy(DAG.getDataLayout());
6710
6711   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6713
6714   // Pair of floats / doubles used to pass the result.
6715   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6716   auto &DL = DAG.getDataLayout();
6717
6718   ArgListTy Args;
6719   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6720   SDValue SRet;
6721   if (ShouldUseSRet) {
6722     // Create stack object for sret.
6723     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6724     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6725     int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6726     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6727
6728     ArgListEntry Entry;
6729     Entry.Node = SRet;
6730     Entry.Ty = RetTy->getPointerTo();
6731     Entry.isSExt = false;
6732     Entry.isZExt = false;
6733     Entry.isSRet = true;
6734     Args.push_back(Entry);
6735     RetTy = Type::getVoidTy(*DAG.getContext());
6736   }
6737
6738   ArgListEntry Entry;
6739   Entry.Node = Arg;
6740   Entry.Ty = ArgTy;
6741   Entry.isSExt = false;
6742   Entry.isZExt = false;
6743   Args.push_back(Entry);
6744
6745   const char *LibcallName =
6746       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6747   RTLIB::Libcall LC =
6748       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6749   CallingConv::ID CC = getLibcallCallingConv(LC);
6750   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6751
6752   TargetLowering::CallLoweringInfo CLI(DAG);
6753   CLI.setDebugLoc(dl)
6754       .setChain(DAG.getEntryNode())
6755       .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6756       .setDiscardResult(ShouldUseSRet);
6757   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6758
6759   if (!ShouldUseSRet)
6760     return CallResult.first;
6761
6762   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6763                                 MachinePointerInfo(), false, false, false, 0);
6764
6765   // Address of cos field.
6766   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6767                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6768   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6769                                 MachinePointerInfo(), false, false, false, 0);
6770
6771   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6772   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6773                      LoadSin.getValue(0), LoadCos.getValue(0));
6774 }
6775
6776 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6777                                                   bool Signed,
6778                                                   SDValue &Chain) const {
6779   EVT VT = Op.getValueType();
6780   assert((VT == MVT::i32 || VT == MVT::i64) &&
6781          "unexpected type for custom lowering DIV");
6782   SDLoc dl(Op);
6783
6784   const auto &DL = DAG.getDataLayout();
6785   const auto &TLI = DAG.getTargetLoweringInfo();
6786
6787   const char *Name = nullptr;
6788   if (Signed)
6789     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6790   else
6791     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6792
6793   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6794
6795   ARMTargetLowering::ArgListTy Args;
6796
6797   for (auto AI : {1, 0}) {
6798     ArgListEntry Arg;
6799     Arg.Node = Op.getOperand(AI);
6800     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6801     Args.push_back(Arg);
6802   }
6803
6804   CallLoweringInfo CLI(DAG);
6805   CLI.setDebugLoc(dl)
6806     .setChain(Chain)
6807     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6808                ES, std::move(Args), 0);
6809
6810   return LowerCallTo(CLI).first;
6811 }
6812
6813 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6814                                             bool Signed) const {
6815   assert(Op.getValueType() == MVT::i32 &&
6816          "unexpected type for custom lowering DIV");
6817   SDLoc dl(Op);
6818
6819   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6820                                DAG.getEntryNode(), Op.getOperand(1));
6821
6822   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6823 }
6824
6825 void ARMTargetLowering::ExpandDIV_Windows(
6826     SDValue Op, SelectionDAG &DAG, bool Signed,
6827     SmallVectorImpl<SDValue> &Results) const {
6828   const auto &DL = DAG.getDataLayout();
6829   const auto &TLI = DAG.getTargetLoweringInfo();
6830
6831   assert(Op.getValueType() == MVT::i64 &&
6832          "unexpected type for custom lowering DIV");
6833   SDLoc dl(Op);
6834
6835   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6836                            DAG.getConstant(0, dl, MVT::i32));
6837   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6838                            DAG.getConstant(1, dl, MVT::i32));
6839   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6840
6841   SDValue DBZCHK =
6842       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6843
6844   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6845
6846   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6847   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6848                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6849   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6850
6851   Results.push_back(Lower);
6852   Results.push_back(Upper);
6853 }
6854
6855 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6856   // Monotonic load/store is legal for all targets
6857   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6858     return Op;
6859
6860   // Acquire/Release load/store is not legal for targets without a
6861   // dmb or equivalent available.
6862   return SDValue();
6863 }
6864
6865 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6866                                     SmallVectorImpl<SDValue> &Results,
6867                                     SelectionDAG &DAG,
6868                                     const ARMSubtarget *Subtarget) {
6869   SDLoc DL(N);
6870   // Under Power Management extensions, the cycle-count is:
6871   //    mrc p15, #0, <Rt>, c9, c13, #0
6872   SDValue Ops[] = { N->getOperand(0), // Chain
6873                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6874                     DAG.getConstant(15, DL, MVT::i32),
6875                     DAG.getConstant(0, DL, MVT::i32),
6876                     DAG.getConstant(9, DL, MVT::i32),
6877                     DAG.getConstant(13, DL, MVT::i32),
6878                     DAG.getConstant(0, DL, MVT::i32)
6879   };
6880
6881   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6882                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6883   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6884                                 DAG.getConstant(0, DL, MVT::i32)));
6885   Results.push_back(Cycles32.getValue(1));
6886 }
6887
6888 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6889   switch (Op.getOpcode()) {
6890   default: llvm_unreachable("Don't know how to custom lower this!");
6891   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6892   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6893   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6894   case ISD::GlobalAddress:
6895     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6896     default: llvm_unreachable("unknown object format");
6897     case Triple::COFF:
6898       return LowerGlobalAddressWindows(Op, DAG);
6899     case Triple::ELF:
6900       return LowerGlobalAddressELF(Op, DAG);
6901     case Triple::MachO:
6902       return LowerGlobalAddressDarwin(Op, DAG);
6903     }
6904   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6905   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6906   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6907   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6908   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6909   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6910   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6911   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6912   case ISD::SINT_TO_FP:
6913   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6914   case ISD::FP_TO_SINT:
6915   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6916   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6917   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6918   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6919   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6920   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6921   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6922   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6923                                                                Subtarget);
6924   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6925   case ISD::SHL:
6926   case ISD::SRL:
6927   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6928   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6929   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6930   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6931   case ISD::SRL_PARTS:
6932   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6933   case ISD::CTTZ:
6934   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6935   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6936   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6937   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6938   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6939   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6940   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6941   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6942   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6943   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6944   case ISD::MUL:           return LowerMUL(Op, DAG);
6945   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6946   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6947   case ISD::ADDC:
6948   case ISD::ADDE:
6949   case ISD::SUBC:
6950   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6951   case ISD::SADDO:
6952   case ISD::UADDO:
6953   case ISD::SSUBO:
6954   case ISD::USUBO:
6955     return LowerXALUO(Op, DAG);
6956   case ISD::ATOMIC_LOAD:
6957   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6958   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6959   case ISD::SDIVREM:
6960   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6961   case ISD::DYNAMIC_STACKALLOC:
6962     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6963       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6964     llvm_unreachable("Don't know how to custom lower this!");
6965   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6966   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6967   case ARMISD::WIN__DBZCHK: return SDValue();
6968   }
6969 }
6970
6971 /// ReplaceNodeResults - Replace the results of node with an illegal result
6972 /// type with new values built out of custom code.
6973 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6974                                            SmallVectorImpl<SDValue> &Results,
6975                                            SelectionDAG &DAG) const {
6976   SDValue Res;
6977   switch (N->getOpcode()) {
6978   default:
6979     llvm_unreachable("Don't know how to custom expand this!");
6980   case ISD::READ_REGISTER:
6981     ExpandREAD_REGISTER(N, Results, DAG);
6982     break;
6983   case ISD::BITCAST:
6984     Res = ExpandBITCAST(N, DAG);
6985     break;
6986   case ISD::SRL:
6987   case ISD::SRA:
6988     Res = Expand64BitShift(N, DAG, Subtarget);
6989     break;
6990   case ISD::SREM:
6991   case ISD::UREM:
6992     Res = LowerREM(N, DAG);
6993     break;
6994   case ISD::READCYCLECOUNTER:
6995     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6996     return;
6997   case ISD::UDIV:
6998   case ISD::SDIV:
6999     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7000     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7001                              Results);
7002   }
7003   if (Res.getNode())
7004     Results.push_back(Res);
7005 }
7006
7007 //===----------------------------------------------------------------------===//
7008 //                           ARM Scheduler Hooks
7009 //===----------------------------------------------------------------------===//
7010
7011 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7012 /// registers the function context.
7013 void ARMTargetLowering::
7014 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
7015                        MachineBasicBlock *DispatchBB, int FI) const {
7016   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7017   DebugLoc dl = MI->getDebugLoc();
7018   MachineFunction *MF = MBB->getParent();
7019   MachineRegisterInfo *MRI = &MF->getRegInfo();
7020   MachineConstantPool *MCP = MF->getConstantPool();
7021   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7022   const Function *F = MF->getFunction();
7023
7024   bool isThumb = Subtarget->isThumb();
7025   bool isThumb2 = Subtarget->isThumb2();
7026
7027   unsigned PCLabelId = AFI->createPICLabelUId();
7028   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7029   ARMConstantPoolValue *CPV =
7030     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7031   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7032
7033   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7034                                            : &ARM::GPRRegClass;
7035
7036   // Grab constant pool and fixed stack memory operands.
7037   MachineMemOperand *CPMMO =
7038       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7039                                MachineMemOperand::MOLoad, 4, 4);
7040
7041   MachineMemOperand *FIMMOSt =
7042       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7043                                MachineMemOperand::MOStore, 4, 4);
7044
7045   // Load the address of the dispatch MBB into the jump buffer.
7046   if (isThumb2) {
7047     // Incoming value: jbuf
7048     //   ldr.n  r5, LCPI1_1
7049     //   orr    r5, r5, #1
7050     //   add    r5, pc
7051     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7052     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7053     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7054                    .addConstantPoolIndex(CPI)
7055                    .addMemOperand(CPMMO));
7056     // Set the low bit because of thumb mode.
7057     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7058     AddDefaultCC(
7059       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7060                      .addReg(NewVReg1, RegState::Kill)
7061                      .addImm(0x01)));
7062     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7063     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7064       .addReg(NewVReg2, RegState::Kill)
7065       .addImm(PCLabelId);
7066     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7067                    .addReg(NewVReg3, RegState::Kill)
7068                    .addFrameIndex(FI)
7069                    .addImm(36)  // &jbuf[1] :: pc
7070                    .addMemOperand(FIMMOSt));
7071   } else if (isThumb) {
7072     // Incoming value: jbuf
7073     //   ldr.n  r1, LCPI1_4
7074     //   add    r1, pc
7075     //   mov    r2, #1
7076     //   orrs   r1, r2
7077     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7078     //   str    r1, [r2]
7079     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7080     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7081                    .addConstantPoolIndex(CPI)
7082                    .addMemOperand(CPMMO));
7083     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7084     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7085       .addReg(NewVReg1, RegState::Kill)
7086       .addImm(PCLabelId);
7087     // Set the low bit because of thumb mode.
7088     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7089     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7090                    .addReg(ARM::CPSR, RegState::Define)
7091                    .addImm(1));
7092     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7093     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7094                    .addReg(ARM::CPSR, RegState::Define)
7095                    .addReg(NewVReg2, RegState::Kill)
7096                    .addReg(NewVReg3, RegState::Kill));
7097     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7098     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7099             .addFrameIndex(FI)
7100             .addImm(36); // &jbuf[1] :: pc
7101     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7102                    .addReg(NewVReg4, RegState::Kill)
7103                    .addReg(NewVReg5, RegState::Kill)
7104                    .addImm(0)
7105                    .addMemOperand(FIMMOSt));
7106   } else {
7107     // Incoming value: jbuf
7108     //   ldr  r1, LCPI1_1
7109     //   add  r1, pc, r1
7110     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7111     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7112     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7113                    .addConstantPoolIndex(CPI)
7114                    .addImm(0)
7115                    .addMemOperand(CPMMO));
7116     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7117     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7118                    .addReg(NewVReg1, RegState::Kill)
7119                    .addImm(PCLabelId));
7120     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7121                    .addReg(NewVReg2, RegState::Kill)
7122                    .addFrameIndex(FI)
7123                    .addImm(36)  // &jbuf[1] :: pc
7124                    .addMemOperand(FIMMOSt));
7125   }
7126 }
7127
7128 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7129                                               MachineBasicBlock *MBB) const {
7130   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7131   DebugLoc dl = MI->getDebugLoc();
7132   MachineFunction *MF = MBB->getParent();
7133   MachineRegisterInfo *MRI = &MF->getRegInfo();
7134   MachineFrameInfo *MFI = MF->getFrameInfo();
7135   int FI = MFI->getFunctionContextIndex();
7136
7137   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7138                                                         : &ARM::GPRnopcRegClass;
7139
7140   // Get a mapping of the call site numbers to all of the landing pads they're
7141   // associated with.
7142   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7143   unsigned MaxCSNum = 0;
7144   MachineModuleInfo &MMI = MF->getMMI();
7145   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7146        ++BB) {
7147     if (!BB->isEHPad()) continue;
7148
7149     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7150     // pad.
7151     for (MachineBasicBlock::iterator
7152            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7153       if (!II->isEHLabel()) continue;
7154
7155       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7156       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7157
7158       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7159       for (SmallVectorImpl<unsigned>::iterator
7160              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7161            CSI != CSE; ++CSI) {
7162         CallSiteNumToLPad[*CSI].push_back(&*BB);
7163         MaxCSNum = std::max(MaxCSNum, *CSI);
7164       }
7165       break;
7166     }
7167   }
7168
7169   // Get an ordered list of the machine basic blocks for the jump table.
7170   std::vector<MachineBasicBlock*> LPadList;
7171   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7172   LPadList.reserve(CallSiteNumToLPad.size());
7173   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7174     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7175     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7176            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7177       LPadList.push_back(*II);
7178       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7179     }
7180   }
7181
7182   assert(!LPadList.empty() &&
7183          "No landing pad destinations for the dispatch jump table!");
7184
7185   // Create the jump table and associated information.
7186   MachineJumpTableInfo *JTI =
7187     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7188   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7189   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7190
7191   // Create the MBBs for the dispatch code.
7192
7193   // Shove the dispatch's address into the return slot in the function context.
7194   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7195   DispatchBB->setIsEHPad();
7196
7197   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7198   unsigned trap_opcode;
7199   if (Subtarget->isThumb())
7200     trap_opcode = ARM::tTRAP;
7201   else
7202     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7203
7204   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7205   DispatchBB->addSuccessor(TrapBB);
7206
7207   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7208   DispatchBB->addSuccessor(DispContBB);
7209
7210   // Insert and MBBs.
7211   MF->insert(MF->end(), DispatchBB);
7212   MF->insert(MF->end(), DispContBB);
7213   MF->insert(MF->end(), TrapBB);
7214
7215   // Insert code into the entry block that creates and registers the function
7216   // context.
7217   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7218
7219   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7220       MachinePointerInfo::getFixedStack(*MF, FI),
7221       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7222
7223   MachineInstrBuilder MIB;
7224   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7225
7226   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7227   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7228
7229   // Add a register mask with no preserved registers.  This results in all
7230   // registers being marked as clobbered.
7231   MIB.addRegMask(RI.getNoPreservedMask());
7232
7233   unsigned NumLPads = LPadList.size();
7234   if (Subtarget->isThumb2()) {
7235     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7236     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7237                    .addFrameIndex(FI)
7238                    .addImm(4)
7239                    .addMemOperand(FIMMOLd));
7240
7241     if (NumLPads < 256) {
7242       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7243                      .addReg(NewVReg1)
7244                      .addImm(LPadList.size()));
7245     } else {
7246       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7247       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7248                      .addImm(NumLPads & 0xFFFF));
7249
7250       unsigned VReg2 = VReg1;
7251       if ((NumLPads & 0xFFFF0000) != 0) {
7252         VReg2 = MRI->createVirtualRegister(TRC);
7253         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7254                        .addReg(VReg1)
7255                        .addImm(NumLPads >> 16));
7256       }
7257
7258       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7259                      .addReg(NewVReg1)
7260                      .addReg(VReg2));
7261     }
7262
7263     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7264       .addMBB(TrapBB)
7265       .addImm(ARMCC::HI)
7266       .addReg(ARM::CPSR);
7267
7268     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7269     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7270                    .addJumpTableIndex(MJTI));
7271
7272     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7273     AddDefaultCC(
7274       AddDefaultPred(
7275         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7276         .addReg(NewVReg3, RegState::Kill)
7277         .addReg(NewVReg1)
7278         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7279
7280     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7281       .addReg(NewVReg4, RegState::Kill)
7282       .addReg(NewVReg1)
7283       .addJumpTableIndex(MJTI);
7284   } else if (Subtarget->isThumb()) {
7285     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7286     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7287                    .addFrameIndex(FI)
7288                    .addImm(1)
7289                    .addMemOperand(FIMMOLd));
7290
7291     if (NumLPads < 256) {
7292       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7293                      .addReg(NewVReg1)
7294                      .addImm(NumLPads));
7295     } else {
7296       MachineConstantPool *ConstantPool = MF->getConstantPool();
7297       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7298       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7299
7300       // MachineConstantPool wants an explicit alignment.
7301       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7302       if (Align == 0)
7303         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7304       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7305
7306       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7307       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7308                      .addReg(VReg1, RegState::Define)
7309                      .addConstantPoolIndex(Idx));
7310       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7311                      .addReg(NewVReg1)
7312                      .addReg(VReg1));
7313     }
7314
7315     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7316       .addMBB(TrapBB)
7317       .addImm(ARMCC::HI)
7318       .addReg(ARM::CPSR);
7319
7320     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7321     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7322                    .addReg(ARM::CPSR, RegState::Define)
7323                    .addReg(NewVReg1)
7324                    .addImm(2));
7325
7326     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7327     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7328                    .addJumpTableIndex(MJTI));
7329
7330     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7331     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7332                    .addReg(ARM::CPSR, RegState::Define)
7333                    .addReg(NewVReg2, RegState::Kill)
7334                    .addReg(NewVReg3));
7335
7336     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7337         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7338
7339     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7340     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7341                    .addReg(NewVReg4, RegState::Kill)
7342                    .addImm(0)
7343                    .addMemOperand(JTMMOLd));
7344
7345     unsigned NewVReg6 = NewVReg5;
7346     if (RelocM == Reloc::PIC_) {
7347       NewVReg6 = MRI->createVirtualRegister(TRC);
7348       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7349                      .addReg(ARM::CPSR, RegState::Define)
7350                      .addReg(NewVReg5, RegState::Kill)
7351                      .addReg(NewVReg3));
7352     }
7353
7354     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7355       .addReg(NewVReg6, RegState::Kill)
7356       .addJumpTableIndex(MJTI);
7357   } else {
7358     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7359     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7360                    .addFrameIndex(FI)
7361                    .addImm(4)
7362                    .addMemOperand(FIMMOLd));
7363
7364     if (NumLPads < 256) {
7365       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7366                      .addReg(NewVReg1)
7367                      .addImm(NumLPads));
7368     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7369       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7370       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7371                      .addImm(NumLPads & 0xFFFF));
7372
7373       unsigned VReg2 = VReg1;
7374       if ((NumLPads & 0xFFFF0000) != 0) {
7375         VReg2 = MRI->createVirtualRegister(TRC);
7376         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7377                        .addReg(VReg1)
7378                        .addImm(NumLPads >> 16));
7379       }
7380
7381       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7382                      .addReg(NewVReg1)
7383                      .addReg(VReg2));
7384     } else {
7385       MachineConstantPool *ConstantPool = MF->getConstantPool();
7386       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7387       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7388
7389       // MachineConstantPool wants an explicit alignment.
7390       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7391       if (Align == 0)
7392         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7393       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7394
7395       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7396       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7397                      .addReg(VReg1, RegState::Define)
7398                      .addConstantPoolIndex(Idx)
7399                      .addImm(0));
7400       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7401                      .addReg(NewVReg1)
7402                      .addReg(VReg1, RegState::Kill));
7403     }
7404
7405     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7406       .addMBB(TrapBB)
7407       .addImm(ARMCC::HI)
7408       .addReg(ARM::CPSR);
7409
7410     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7411     AddDefaultCC(
7412       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7413                      .addReg(NewVReg1)
7414                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7415     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7416     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7417                    .addJumpTableIndex(MJTI));
7418
7419     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7420         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7421     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7422     AddDefaultPred(
7423       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7424       .addReg(NewVReg3, RegState::Kill)
7425       .addReg(NewVReg4)
7426       .addImm(0)
7427       .addMemOperand(JTMMOLd));
7428
7429     if (RelocM == Reloc::PIC_) {
7430       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7431         .addReg(NewVReg5, RegState::Kill)
7432         .addReg(NewVReg4)
7433         .addJumpTableIndex(MJTI);
7434     } else {
7435       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7436         .addReg(NewVReg5, RegState::Kill)
7437         .addJumpTableIndex(MJTI);
7438     }
7439   }
7440
7441   // Add the jump table entries as successors to the MBB.
7442   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7443   for (std::vector<MachineBasicBlock*>::iterator
7444          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7445     MachineBasicBlock *CurMBB = *I;
7446     if (SeenMBBs.insert(CurMBB).second)
7447       DispContBB->addSuccessor(CurMBB);
7448   }
7449
7450   // N.B. the order the invoke BBs are processed in doesn't matter here.
7451   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7452   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7453   for (MachineBasicBlock *BB : InvokeBBs) {
7454
7455     // Remove the landing pad successor from the invoke block and replace it
7456     // with the new dispatch block.
7457     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7458                                                   BB->succ_end());
7459     while (!Successors.empty()) {
7460       MachineBasicBlock *SMBB = Successors.pop_back_val();
7461       if (SMBB->isEHPad()) {
7462         BB->removeSuccessor(SMBB);
7463         MBBLPads.push_back(SMBB);
7464       }
7465     }
7466
7467     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7468     BB->normalizeSuccProbs();
7469
7470     // Find the invoke call and mark all of the callee-saved registers as
7471     // 'implicit defined' so that they're spilled. This prevents code from
7472     // moving instructions to before the EH block, where they will never be
7473     // executed.
7474     for (MachineBasicBlock::reverse_iterator
7475            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7476       if (!II->isCall()) continue;
7477
7478       DenseMap<unsigned, bool> DefRegs;
7479       for (MachineInstr::mop_iterator
7480              OI = II->operands_begin(), OE = II->operands_end();
7481            OI != OE; ++OI) {
7482         if (!OI->isReg()) continue;
7483         DefRegs[OI->getReg()] = true;
7484       }
7485
7486       MachineInstrBuilder MIB(*MF, &*II);
7487
7488       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7489         unsigned Reg = SavedRegs[i];
7490         if (Subtarget->isThumb2() &&
7491             !ARM::tGPRRegClass.contains(Reg) &&
7492             !ARM::hGPRRegClass.contains(Reg))
7493           continue;
7494         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7495           continue;
7496         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7497           continue;
7498         if (!DefRegs[Reg])
7499           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7500       }
7501
7502       break;
7503     }
7504   }
7505
7506   // Mark all former landing pads as non-landing pads. The dispatch is the only
7507   // landing pad now.
7508   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7509          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7510     (*I)->setIsEHPad(false);
7511
7512   // The instruction is gone now.
7513   MI->eraseFromParent();
7514 }
7515
7516 static
7517 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7518   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7519        E = MBB->succ_end(); I != E; ++I)
7520     if (*I != Succ)
7521       return *I;
7522   llvm_unreachable("Expecting a BB with two successors!");
7523 }
7524
7525 /// Return the load opcode for a given load size. If load size >= 8,
7526 /// neon opcode will be returned.
7527 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7528   if (LdSize >= 8)
7529     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7530                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7531   if (IsThumb1)
7532     return LdSize == 4 ? ARM::tLDRi
7533                        : LdSize == 2 ? ARM::tLDRHi
7534                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7535   if (IsThumb2)
7536     return LdSize == 4 ? ARM::t2LDR_POST
7537                        : LdSize == 2 ? ARM::t2LDRH_POST
7538                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7539   return LdSize == 4 ? ARM::LDR_POST_IMM
7540                      : LdSize == 2 ? ARM::LDRH_POST
7541                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7542 }
7543
7544 /// Return the store opcode for a given store size. If store size >= 8,
7545 /// neon opcode will be returned.
7546 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7547   if (StSize >= 8)
7548     return StSize == 16 ? ARM::VST1q32wb_fixed
7549                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7550   if (IsThumb1)
7551     return StSize == 4 ? ARM::tSTRi
7552                        : StSize == 2 ? ARM::tSTRHi
7553                                      : StSize == 1 ? ARM::tSTRBi : 0;
7554   if (IsThumb2)
7555     return StSize == 4 ? ARM::t2STR_POST
7556                        : StSize == 2 ? ARM::t2STRH_POST
7557                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7558   return StSize == 4 ? ARM::STR_POST_IMM
7559                      : StSize == 2 ? ARM::STRH_POST
7560                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7561 }
7562
7563 /// Emit a post-increment load operation with given size. The instructions
7564 /// will be added to BB at Pos.
7565 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7566                        const TargetInstrInfo *TII, DebugLoc dl,
7567                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7568                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7569   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7570   assert(LdOpc != 0 && "Should have a load opcode");
7571   if (LdSize >= 8) {
7572     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7573                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7574                        .addImm(0));
7575   } else if (IsThumb1) {
7576     // load + update AddrIn
7577     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7578                        .addReg(AddrIn).addImm(0));
7579     MachineInstrBuilder MIB =
7580         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7581     MIB = AddDefaultT1CC(MIB);
7582     MIB.addReg(AddrIn).addImm(LdSize);
7583     AddDefaultPred(MIB);
7584   } else if (IsThumb2) {
7585     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7586                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7587                        .addImm(LdSize));
7588   } else { // arm
7589     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7590                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7591                        .addReg(0).addImm(LdSize));
7592   }
7593 }
7594
7595 /// Emit a post-increment store operation with given size. The instructions
7596 /// will be added to BB at Pos.
7597 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7598                        const TargetInstrInfo *TII, DebugLoc dl,
7599                        unsigned StSize, unsigned Data, unsigned AddrIn,
7600                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7601   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7602   assert(StOpc != 0 && "Should have a store opcode");
7603   if (StSize >= 8) {
7604     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7605                        .addReg(AddrIn).addImm(0).addReg(Data));
7606   } else if (IsThumb1) {
7607     // store + update AddrIn
7608     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7609                        .addReg(AddrIn).addImm(0));
7610     MachineInstrBuilder MIB =
7611         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7612     MIB = AddDefaultT1CC(MIB);
7613     MIB.addReg(AddrIn).addImm(StSize);
7614     AddDefaultPred(MIB);
7615   } else if (IsThumb2) {
7616     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7617                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7618   } else { // arm
7619     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7620                        .addReg(Data).addReg(AddrIn).addReg(0)
7621                        .addImm(StSize));
7622   }
7623 }
7624
7625 MachineBasicBlock *
7626 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7627                                    MachineBasicBlock *BB) const {
7628   // This pseudo instruction has 3 operands: dst, src, size
7629   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7630   // Otherwise, we will generate unrolled scalar copies.
7631   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7632   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7633   MachineFunction::iterator It = ++BB->getIterator();
7634
7635   unsigned dest = MI->getOperand(0).getReg();
7636   unsigned src = MI->getOperand(1).getReg();
7637   unsigned SizeVal = MI->getOperand(2).getImm();
7638   unsigned Align = MI->getOperand(3).getImm();
7639   DebugLoc dl = MI->getDebugLoc();
7640
7641   MachineFunction *MF = BB->getParent();
7642   MachineRegisterInfo &MRI = MF->getRegInfo();
7643   unsigned UnitSize = 0;
7644   const TargetRegisterClass *TRC = nullptr;
7645   const TargetRegisterClass *VecTRC = nullptr;
7646
7647   bool IsThumb1 = Subtarget->isThumb1Only();
7648   bool IsThumb2 = Subtarget->isThumb2();
7649
7650   if (Align & 1) {
7651     UnitSize = 1;
7652   } else if (Align & 2) {
7653     UnitSize = 2;
7654   } else {
7655     // Check whether we can use NEON instructions.
7656     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7657         Subtarget->hasNEON()) {
7658       if ((Align % 16 == 0) && SizeVal >= 16)
7659         UnitSize = 16;
7660       else if ((Align % 8 == 0) && SizeVal >= 8)
7661         UnitSize = 8;
7662     }
7663     // Can't use NEON instructions.
7664     if (UnitSize == 0)
7665       UnitSize = 4;
7666   }
7667
7668   // Select the correct opcode and register class for unit size load/store
7669   bool IsNeon = UnitSize >= 8;
7670   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7671   if (IsNeon)
7672     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7673                             : UnitSize == 8 ? &ARM::DPRRegClass
7674                                             : nullptr;
7675
7676   unsigned BytesLeft = SizeVal % UnitSize;
7677   unsigned LoopSize = SizeVal - BytesLeft;
7678
7679   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7680     // Use LDR and STR to copy.
7681     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7682     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7683     unsigned srcIn = src;
7684     unsigned destIn = dest;
7685     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7686       unsigned srcOut = MRI.createVirtualRegister(TRC);
7687       unsigned destOut = MRI.createVirtualRegister(TRC);
7688       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7689       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7690                  IsThumb1, IsThumb2);
7691       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7692                  IsThumb1, IsThumb2);
7693       srcIn = srcOut;
7694       destIn = destOut;
7695     }
7696
7697     // Handle the leftover bytes with LDRB and STRB.
7698     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7699     // [destOut] = STRB_POST(scratch, destIn, 1)
7700     for (unsigned i = 0; i < BytesLeft; i++) {
7701       unsigned srcOut = MRI.createVirtualRegister(TRC);
7702       unsigned destOut = MRI.createVirtualRegister(TRC);
7703       unsigned scratch = MRI.createVirtualRegister(TRC);
7704       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7705                  IsThumb1, IsThumb2);
7706       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7707                  IsThumb1, IsThumb2);
7708       srcIn = srcOut;
7709       destIn = destOut;
7710     }
7711     MI->eraseFromParent();   // The instruction is gone now.
7712     return BB;
7713   }
7714
7715   // Expand the pseudo op to a loop.
7716   // thisMBB:
7717   //   ...
7718   //   movw varEnd, # --> with thumb2
7719   //   movt varEnd, #
7720   //   ldrcp varEnd, idx --> without thumb2
7721   //   fallthrough --> loopMBB
7722   // loopMBB:
7723   //   PHI varPhi, varEnd, varLoop
7724   //   PHI srcPhi, src, srcLoop
7725   //   PHI destPhi, dst, destLoop
7726   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7727   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7728   //   subs varLoop, varPhi, #UnitSize
7729   //   bne loopMBB
7730   //   fallthrough --> exitMBB
7731   // exitMBB:
7732   //   epilogue to handle left-over bytes
7733   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7734   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7735   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7736   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7737   MF->insert(It, loopMBB);
7738   MF->insert(It, exitMBB);
7739
7740   // Transfer the remainder of BB and its successor edges to exitMBB.
7741   exitMBB->splice(exitMBB->begin(), BB,
7742                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7743   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7744
7745   // Load an immediate to varEnd.
7746   unsigned varEnd = MRI.createVirtualRegister(TRC);
7747   if (Subtarget->useMovt(*MF)) {
7748     unsigned Vtmp = varEnd;
7749     if ((LoopSize & 0xFFFF0000) != 0)
7750       Vtmp = MRI.createVirtualRegister(TRC);
7751     AddDefaultPred(BuildMI(BB, dl,
7752                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7753                            Vtmp).addImm(LoopSize & 0xFFFF));
7754
7755     if ((LoopSize & 0xFFFF0000) != 0)
7756       AddDefaultPred(BuildMI(BB, dl,
7757                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7758                              varEnd)
7759                          .addReg(Vtmp)
7760                          .addImm(LoopSize >> 16));
7761   } else {
7762     MachineConstantPool *ConstantPool = MF->getConstantPool();
7763     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7764     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7765
7766     // MachineConstantPool wants an explicit alignment.
7767     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7768     if (Align == 0)
7769       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7770     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7771
7772     if (IsThumb1)
7773       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7774           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7775     else
7776       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7777           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7778   }
7779   BB->addSuccessor(loopMBB);
7780
7781   // Generate the loop body:
7782   //   varPhi = PHI(varLoop, varEnd)
7783   //   srcPhi = PHI(srcLoop, src)
7784   //   destPhi = PHI(destLoop, dst)
7785   MachineBasicBlock *entryBB = BB;
7786   BB = loopMBB;
7787   unsigned varLoop = MRI.createVirtualRegister(TRC);
7788   unsigned varPhi = MRI.createVirtualRegister(TRC);
7789   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7790   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7791   unsigned destLoop = MRI.createVirtualRegister(TRC);
7792   unsigned destPhi = MRI.createVirtualRegister(TRC);
7793
7794   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7795     .addReg(varLoop).addMBB(loopMBB)
7796     .addReg(varEnd).addMBB(entryBB);
7797   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7798     .addReg(srcLoop).addMBB(loopMBB)
7799     .addReg(src).addMBB(entryBB);
7800   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7801     .addReg(destLoop).addMBB(loopMBB)
7802     .addReg(dest).addMBB(entryBB);
7803
7804   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7805   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7806   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7807   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7808              IsThumb1, IsThumb2);
7809   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7810              IsThumb1, IsThumb2);
7811
7812   // Decrement loop variable by UnitSize.
7813   if (IsThumb1) {
7814     MachineInstrBuilder MIB =
7815         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7816     MIB = AddDefaultT1CC(MIB);
7817     MIB.addReg(varPhi).addImm(UnitSize);
7818     AddDefaultPred(MIB);
7819   } else {
7820     MachineInstrBuilder MIB =
7821         BuildMI(*BB, BB->end(), dl,
7822                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7823     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7824     MIB->getOperand(5).setReg(ARM::CPSR);
7825     MIB->getOperand(5).setIsDef(true);
7826   }
7827   BuildMI(*BB, BB->end(), dl,
7828           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7829       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7830
7831   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7832   BB->addSuccessor(loopMBB);
7833   BB->addSuccessor(exitMBB);
7834
7835   // Add epilogue to handle BytesLeft.
7836   BB = exitMBB;
7837   MachineInstr *StartOfExit = exitMBB->begin();
7838
7839   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7840   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7841   unsigned srcIn = srcLoop;
7842   unsigned destIn = destLoop;
7843   for (unsigned i = 0; i < BytesLeft; i++) {
7844     unsigned srcOut = MRI.createVirtualRegister(TRC);
7845     unsigned destOut = MRI.createVirtualRegister(TRC);
7846     unsigned scratch = MRI.createVirtualRegister(TRC);
7847     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7848                IsThumb1, IsThumb2);
7849     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7850                IsThumb1, IsThumb2);
7851     srcIn = srcOut;
7852     destIn = destOut;
7853   }
7854
7855   MI->eraseFromParent();   // The instruction is gone now.
7856   return BB;
7857 }
7858
7859 MachineBasicBlock *
7860 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7861                                        MachineBasicBlock *MBB) const {
7862   const TargetMachine &TM = getTargetMachine();
7863   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7864   DebugLoc DL = MI->getDebugLoc();
7865
7866   assert(Subtarget->isTargetWindows() &&
7867          "__chkstk is only supported on Windows");
7868   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7869
7870   // __chkstk takes the number of words to allocate on the stack in R4, and
7871   // returns the stack adjustment in number of bytes in R4.  This will not
7872   // clober any other registers (other than the obvious lr).
7873   //
7874   // Although, technically, IP should be considered a register which may be
7875   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7876   // thumb-2 environment, so there is no interworking required.  As a result, we
7877   // do not expect a veneer to be emitted by the linker, clobbering IP.
7878   //
7879   // Each module receives its own copy of __chkstk, so no import thunk is
7880   // required, again, ensuring that IP is not clobbered.
7881   //
7882   // Finally, although some linkers may theoretically provide a trampoline for
7883   // out of range calls (which is quite common due to a 32M range limitation of
7884   // branches for Thumb), we can generate the long-call version via
7885   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7886   // IP.
7887
7888   switch (TM.getCodeModel()) {
7889   case CodeModel::Small:
7890   case CodeModel::Medium:
7891   case CodeModel::Default:
7892   case CodeModel::Kernel:
7893     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7894       .addImm((unsigned)ARMCC::AL).addReg(0)
7895       .addExternalSymbol("__chkstk")
7896       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7897       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7898       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7899     break;
7900   case CodeModel::Large:
7901   case CodeModel::JITDefault: {
7902     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7903     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7904
7905     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7906       .addExternalSymbol("__chkstk");
7907     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7908       .addImm((unsigned)ARMCC::AL).addReg(0)
7909       .addReg(Reg, RegState::Kill)
7910       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7911       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7912       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7913     break;
7914   }
7915   }
7916
7917   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7918                                       ARM::SP)
7919                               .addReg(ARM::SP).addReg(ARM::R4)));
7920
7921   MI->eraseFromParent();
7922   return MBB;
7923 }
7924
7925 MachineBasicBlock *
7926 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7927                                        MachineBasicBlock *MBB) const {
7928   DebugLoc DL = MI->getDebugLoc();
7929   MachineFunction *MF = MBB->getParent();
7930   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7931
7932   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7933   MF->push_back(ContBB);
7934   ContBB->splice(ContBB->begin(), MBB,
7935                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7936   MBB->addSuccessor(ContBB);
7937
7938   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7939   MF->push_back(TrapBB);
7940   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7941   MBB->addSuccessor(TrapBB);
7942
7943   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7944       .addReg(MI->getOperand(0).getReg())
7945       .addMBB(TrapBB);
7946
7947   MI->eraseFromParent();
7948   return ContBB;
7949 }
7950
7951 MachineBasicBlock *
7952 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7953                                                MachineBasicBlock *BB) const {
7954   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7955   DebugLoc dl = MI->getDebugLoc();
7956   bool isThumb2 = Subtarget->isThumb2();
7957   switch (MI->getOpcode()) {
7958   default: {
7959     MI->dump();
7960     llvm_unreachable("Unexpected instr type to insert");
7961   }
7962   // The Thumb2 pre-indexed stores have the same MI operands, they just
7963   // define them differently in the .td files from the isel patterns, so
7964   // they need pseudos.
7965   case ARM::t2STR_preidx:
7966     MI->setDesc(TII->get(ARM::t2STR_PRE));
7967     return BB;
7968   case ARM::t2STRB_preidx:
7969     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7970     return BB;
7971   case ARM::t2STRH_preidx:
7972     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7973     return BB;
7974
7975   case ARM::STRi_preidx:
7976   case ARM::STRBi_preidx: {
7977     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7978       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7979     // Decode the offset.
7980     unsigned Offset = MI->getOperand(4).getImm();
7981     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7982     Offset = ARM_AM::getAM2Offset(Offset);
7983     if (isSub)
7984       Offset = -Offset;
7985
7986     MachineMemOperand *MMO = *MI->memoperands_begin();
7987     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7988       .addOperand(MI->getOperand(0))  // Rn_wb
7989       .addOperand(MI->getOperand(1))  // Rt
7990       .addOperand(MI->getOperand(2))  // Rn
7991       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7992       .addOperand(MI->getOperand(5))  // pred
7993       .addOperand(MI->getOperand(6))
7994       .addMemOperand(MMO);
7995     MI->eraseFromParent();
7996     return BB;
7997   }
7998   case ARM::STRr_preidx:
7999   case ARM::STRBr_preidx:
8000   case ARM::STRH_preidx: {
8001     unsigned NewOpc;
8002     switch (MI->getOpcode()) {
8003     default: llvm_unreachable("unexpected opcode!");
8004     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8005     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8006     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8007     }
8008     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8009     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
8010       MIB.addOperand(MI->getOperand(i));
8011     MI->eraseFromParent();
8012     return BB;
8013   }
8014
8015   case ARM::tMOVCCr_pseudo: {
8016     // To "insert" a SELECT_CC instruction, we actually have to insert the
8017     // diamond control-flow pattern.  The incoming instruction knows the
8018     // destination vreg to set, the condition code register to branch on, the
8019     // true/false values to select between, and a branch opcode to use.
8020     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8021     MachineFunction::iterator It = ++BB->getIterator();
8022
8023     //  thisMBB:
8024     //  ...
8025     //   TrueVal = ...
8026     //   cmpTY ccX, r1, r2
8027     //   bCC copy1MBB
8028     //   fallthrough --> copy0MBB
8029     MachineBasicBlock *thisMBB  = BB;
8030     MachineFunction *F = BB->getParent();
8031     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8032     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8033     F->insert(It, copy0MBB);
8034     F->insert(It, sinkMBB);
8035
8036     // Transfer the remainder of BB and its successor edges to sinkMBB.
8037     sinkMBB->splice(sinkMBB->begin(), BB,
8038                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8039     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8040
8041     BB->addSuccessor(copy0MBB);
8042     BB->addSuccessor(sinkMBB);
8043
8044     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
8045       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
8046
8047     //  copy0MBB:
8048     //   %FalseValue = ...
8049     //   # fallthrough to sinkMBB
8050     BB = copy0MBB;
8051
8052     // Update machine-CFG edges
8053     BB->addSuccessor(sinkMBB);
8054
8055     //  sinkMBB:
8056     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8057     //  ...
8058     BB = sinkMBB;
8059     BuildMI(*BB, BB->begin(), dl,
8060             TII->get(ARM::PHI), MI->getOperand(0).getReg())
8061       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8062       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8063
8064     MI->eraseFromParent();   // The pseudo instruction is gone now.
8065     return BB;
8066   }
8067
8068   case ARM::BCCi64:
8069   case ARM::BCCZi64: {
8070     // If there is an unconditional branch to the other successor, remove it.
8071     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8072
8073     // Compare both parts that make up the double comparison separately for
8074     // equality.
8075     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
8076
8077     unsigned LHS1 = MI->getOperand(1).getReg();
8078     unsigned LHS2 = MI->getOperand(2).getReg();
8079     if (RHSisZero) {
8080       AddDefaultPred(BuildMI(BB, dl,
8081                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8082                      .addReg(LHS1).addImm(0));
8083       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8084         .addReg(LHS2).addImm(0)
8085         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8086     } else {
8087       unsigned RHS1 = MI->getOperand(3).getReg();
8088       unsigned RHS2 = MI->getOperand(4).getReg();
8089       AddDefaultPred(BuildMI(BB, dl,
8090                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8091                      .addReg(LHS1).addReg(RHS1));
8092       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8093         .addReg(LHS2).addReg(RHS2)
8094         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8095     }
8096
8097     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
8098     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8099     if (MI->getOperand(0).getImm() == ARMCC::NE)
8100       std::swap(destMBB, exitMBB);
8101
8102     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8103       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8104     if (isThumb2)
8105       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8106     else
8107       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8108
8109     MI->eraseFromParent();   // The pseudo instruction is gone now.
8110     return BB;
8111   }
8112
8113   case ARM::Int_eh_sjlj_setjmp:
8114   case ARM::Int_eh_sjlj_setjmp_nofp:
8115   case ARM::tInt_eh_sjlj_setjmp:
8116   case ARM::t2Int_eh_sjlj_setjmp:
8117   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8118     return BB;
8119
8120   case ARM::Int_eh_sjlj_setup_dispatch:
8121     EmitSjLjDispatchBlock(MI, BB);
8122     return BB;
8123
8124   case ARM::ABS:
8125   case ARM::t2ABS: {
8126     // To insert an ABS instruction, we have to insert the
8127     // diamond control-flow pattern.  The incoming instruction knows the
8128     // source vreg to test against 0, the destination vreg to set,
8129     // the condition code register to branch on, the
8130     // true/false values to select between, and a branch opcode to use.
8131     // It transforms
8132     //     V1 = ABS V0
8133     // into
8134     //     V2 = MOVS V0
8135     //     BCC                      (branch to SinkBB if V0 >= 0)
8136     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8137     //     SinkBB: V1 = PHI(V2, V3)
8138     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8139     MachineFunction::iterator BBI = ++BB->getIterator();
8140     MachineFunction *Fn = BB->getParent();
8141     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8142     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8143     Fn->insert(BBI, RSBBB);
8144     Fn->insert(BBI, SinkBB);
8145
8146     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8147     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8148     bool ABSSrcKIll = MI->getOperand(1).isKill();
8149     bool isThumb2 = Subtarget->isThumb2();
8150     MachineRegisterInfo &MRI = Fn->getRegInfo();
8151     // In Thumb mode S must not be specified if source register is the SP or
8152     // PC and if destination register is the SP, so restrict register class
8153     unsigned NewRsbDstReg =
8154       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8155
8156     // Transfer the remainder of BB and its successor edges to sinkMBB.
8157     SinkBB->splice(SinkBB->begin(), BB,
8158                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8159     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8160
8161     BB->addSuccessor(RSBBB);
8162     BB->addSuccessor(SinkBB);
8163
8164     // fall through to SinkMBB
8165     RSBBB->addSuccessor(SinkBB);
8166
8167     // insert a cmp at the end of BB
8168     AddDefaultPred(BuildMI(BB, dl,
8169                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8170                    .addReg(ABSSrcReg).addImm(0));
8171
8172     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8173     BuildMI(BB, dl,
8174       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8175       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8176
8177     // insert rsbri in RSBBB
8178     // Note: BCC and rsbri will be converted into predicated rsbmi
8179     // by if-conversion pass
8180     BuildMI(*RSBBB, RSBBB->begin(), dl,
8181       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8182       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8183       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8184
8185     // insert PHI in SinkBB,
8186     // reuse ABSDstReg to not change uses of ABS instruction
8187     BuildMI(*SinkBB, SinkBB->begin(), dl,
8188       TII->get(ARM::PHI), ABSDstReg)
8189       .addReg(NewRsbDstReg).addMBB(RSBBB)
8190       .addReg(ABSSrcReg).addMBB(BB);
8191
8192     // remove ABS instruction
8193     MI->eraseFromParent();
8194
8195     // return last added BB
8196     return SinkBB;
8197   }
8198   case ARM::COPY_STRUCT_BYVAL_I32:
8199     ++NumLoopByVals;
8200     return EmitStructByval(MI, BB);
8201   case ARM::WIN__CHKSTK:
8202     return EmitLowered__chkstk(MI, BB);
8203   case ARM::WIN__DBZCHK:
8204     return EmitLowered__dbzchk(MI, BB);
8205   }
8206 }
8207
8208 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8209 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8210 /// instead of as a custom inserter because we need the use list from the SDNode.
8211 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8212                                    MachineInstr *MI, const SDNode *Node) {
8213   bool isThumb1 = Subtarget->isThumb1Only();
8214
8215   DebugLoc DL = MI->getDebugLoc();
8216   MachineFunction *MF = MI->getParent()->getParent();
8217   MachineRegisterInfo &MRI = MF->getRegInfo();
8218   MachineInstrBuilder MIB(*MF, MI);
8219
8220   // If the new dst/src is unused mark it as dead.
8221   if (!Node->hasAnyUseOfValue(0)) {
8222     MI->getOperand(0).setIsDead(true);
8223   }
8224   if (!Node->hasAnyUseOfValue(1)) {
8225     MI->getOperand(1).setIsDead(true);
8226   }
8227
8228   // The MEMCPY both defines and kills the scratch registers.
8229   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8230     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8231                                                          : &ARM::GPRRegClass);
8232     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8233   }
8234 }
8235
8236 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8237                                                       SDNode *Node) const {
8238   if (MI->getOpcode() == ARM::MEMCPY) {
8239     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8240     return;
8241   }
8242
8243   const MCInstrDesc *MCID = &MI->getDesc();
8244   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8245   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8246   // operand is still set to noreg. If needed, set the optional operand's
8247   // register to CPSR, and remove the redundant implicit def.
8248   //
8249   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8250
8251   // Rename pseudo opcodes.
8252   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8253   if (NewOpc) {
8254     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8255     MCID = &TII->get(NewOpc);
8256
8257     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8258            "converted opcode should be the same except for cc_out");
8259
8260     MI->setDesc(*MCID);
8261
8262     // Add the optional cc_out operand
8263     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8264   }
8265   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8266
8267   // Any ARM instruction that sets the 's' bit should specify an optional
8268   // "cc_out" operand in the last operand position.
8269   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8270     assert(!NewOpc && "Optional cc_out operand required");
8271     return;
8272   }
8273   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8274   // since we already have an optional CPSR def.
8275   bool definesCPSR = false;
8276   bool deadCPSR = false;
8277   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8278        i != e; ++i) {
8279     const MachineOperand &MO = MI->getOperand(i);
8280     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8281       definesCPSR = true;
8282       if (MO.isDead())
8283         deadCPSR = true;
8284       MI->RemoveOperand(i);
8285       break;
8286     }
8287   }
8288   if (!definesCPSR) {
8289     assert(!NewOpc && "Optional cc_out operand required");
8290     return;
8291   }
8292   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8293   if (deadCPSR) {
8294     assert(!MI->getOperand(ccOutIdx).getReg() &&
8295            "expect uninitialized optional cc_out operand");
8296     return;
8297   }
8298
8299   // If this instruction was defined with an optional CPSR def and its dag node
8300   // had a live implicit CPSR def, then activate the optional CPSR def.
8301   MachineOperand &MO = MI->getOperand(ccOutIdx);
8302   MO.setReg(ARM::CPSR);
8303   MO.setIsDef(true);
8304 }
8305
8306 //===----------------------------------------------------------------------===//
8307 //                           ARM Optimization Hooks
8308 //===----------------------------------------------------------------------===//
8309
8310 // Helper function that checks if N is a null or all ones constant.
8311 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8312   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8313 }
8314
8315 // Return true if N is conditionally 0 or all ones.
8316 // Detects these expressions where cc is an i1 value:
8317 //
8318 //   (select cc 0, y)   [AllOnes=0]
8319 //   (select cc y, 0)   [AllOnes=0]
8320 //   (zext cc)          [AllOnes=0]
8321 //   (sext cc)          [AllOnes=0/1]
8322 //   (select cc -1, y)  [AllOnes=1]
8323 //   (select cc y, -1)  [AllOnes=1]
8324 //
8325 // Invert is set when N is the null/all ones constant when CC is false.
8326 // OtherOp is set to the alternative value of N.
8327 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8328                                        SDValue &CC, bool &Invert,
8329                                        SDValue &OtherOp,
8330                                        SelectionDAG &DAG) {
8331   switch (N->getOpcode()) {
8332   default: return false;
8333   case ISD::SELECT: {
8334     CC = N->getOperand(0);
8335     SDValue N1 = N->getOperand(1);
8336     SDValue N2 = N->getOperand(2);
8337     if (isZeroOrAllOnes(N1, AllOnes)) {
8338       Invert = false;
8339       OtherOp = N2;
8340       return true;
8341     }
8342     if (isZeroOrAllOnes(N2, AllOnes)) {
8343       Invert = true;
8344       OtherOp = N1;
8345       return true;
8346     }
8347     return false;
8348   }
8349   case ISD::ZERO_EXTEND:
8350     // (zext cc) can never be the all ones value.
8351     if (AllOnes)
8352       return false;
8353     // Fall through.
8354   case ISD::SIGN_EXTEND: {
8355     SDLoc dl(N);
8356     EVT VT = N->getValueType(0);
8357     CC = N->getOperand(0);
8358     if (CC.getValueType() != MVT::i1)
8359       return false;
8360     Invert = !AllOnes;
8361     if (AllOnes)
8362       // When looking for an AllOnes constant, N is an sext, and the 'other'
8363       // value is 0.
8364       OtherOp = DAG.getConstant(0, dl, VT);
8365     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8366       // When looking for a 0 constant, N can be zext or sext.
8367       OtherOp = DAG.getConstant(1, dl, VT);
8368     else
8369       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8370                                 VT);
8371     return true;
8372   }
8373   }
8374 }
8375
8376 // Combine a constant select operand into its use:
8377 //
8378 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8379 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8380 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8381 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8382 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8383 //
8384 // The transform is rejected if the select doesn't have a constant operand that
8385 // is null, or all ones when AllOnes is set.
8386 //
8387 // Also recognize sext/zext from i1:
8388 //
8389 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8390 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8391 //
8392 // These transformations eventually create predicated instructions.
8393 //
8394 // @param N       The node to transform.
8395 // @param Slct    The N operand that is a select.
8396 // @param OtherOp The other N operand (x above).
8397 // @param DCI     Context.
8398 // @param AllOnes Require the select constant to be all ones instead of null.
8399 // @returns The new node, or SDValue() on failure.
8400 static
8401 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8402                             TargetLowering::DAGCombinerInfo &DCI,
8403                             bool AllOnes = false) {
8404   SelectionDAG &DAG = DCI.DAG;
8405   EVT VT = N->getValueType(0);
8406   SDValue NonConstantVal;
8407   SDValue CCOp;
8408   bool SwapSelectOps;
8409   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8410                                   NonConstantVal, DAG))
8411     return SDValue();
8412
8413   // Slct is now know to be the desired identity constant when CC is true.
8414   SDValue TrueVal = OtherOp;
8415   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8416                                  OtherOp, NonConstantVal);
8417   // Unless SwapSelectOps says CC should be false.
8418   if (SwapSelectOps)
8419     std::swap(TrueVal, FalseVal);
8420
8421   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8422                      CCOp, TrueVal, FalseVal);
8423 }
8424
8425 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8426 static
8427 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8428                                        TargetLowering::DAGCombinerInfo &DCI) {
8429   SDValue N0 = N->getOperand(0);
8430   SDValue N1 = N->getOperand(1);
8431   if (N0.getNode()->hasOneUse()) {
8432     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8433     if (Result.getNode())
8434       return Result;
8435   }
8436   if (N1.getNode()->hasOneUse()) {
8437     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8438     if (Result.getNode())
8439       return Result;
8440   }
8441   return SDValue();
8442 }
8443
8444 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8445 // (only after legalization).
8446 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8447                                  TargetLowering::DAGCombinerInfo &DCI,
8448                                  const ARMSubtarget *Subtarget) {
8449
8450   // Only perform optimization if after legalize, and if NEON is available. We
8451   // also expected both operands to be BUILD_VECTORs.
8452   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8453       || N0.getOpcode() != ISD::BUILD_VECTOR
8454       || N1.getOpcode() != ISD::BUILD_VECTOR)
8455     return SDValue();
8456
8457   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8458   EVT VT = N->getValueType(0);
8459   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8460     return SDValue();
8461
8462   // Check that the vector operands are of the right form.
8463   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8464   // operands, where N is the size of the formed vector.
8465   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8466   // index such that we have a pair wise add pattern.
8467
8468   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8469   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8470     return SDValue();
8471   SDValue Vec = N0->getOperand(0)->getOperand(0);
8472   SDNode *V = Vec.getNode();
8473   unsigned nextIndex = 0;
8474
8475   // For each operands to the ADD which are BUILD_VECTORs,
8476   // check to see if each of their operands are an EXTRACT_VECTOR with
8477   // the same vector and appropriate index.
8478   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8479     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8480         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8481
8482       SDValue ExtVec0 = N0->getOperand(i);
8483       SDValue ExtVec1 = N1->getOperand(i);
8484
8485       // First operand is the vector, verify its the same.
8486       if (V != ExtVec0->getOperand(0).getNode() ||
8487           V != ExtVec1->getOperand(0).getNode())
8488         return SDValue();
8489
8490       // Second is the constant, verify its correct.
8491       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8492       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8493
8494       // For the constant, we want to see all the even or all the odd.
8495       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8496           || C1->getZExtValue() != nextIndex+1)
8497         return SDValue();
8498
8499       // Increment index.
8500       nextIndex+=2;
8501     } else
8502       return SDValue();
8503   }
8504
8505   // Create VPADDL node.
8506   SelectionDAG &DAG = DCI.DAG;
8507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8508
8509   SDLoc dl(N);
8510
8511   // Build operand list.
8512   SmallVector<SDValue, 8> Ops;
8513   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8514                                 TLI.getPointerTy(DAG.getDataLayout())));
8515
8516   // Input is the vector.
8517   Ops.push_back(Vec);
8518
8519   // Get widened type and narrowed type.
8520   MVT widenType;
8521   unsigned numElem = VT.getVectorNumElements();
8522   
8523   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8524   switch (inputLaneType.getSimpleVT().SimpleTy) {
8525     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8526     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8527     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8528     default:
8529       llvm_unreachable("Invalid vector element type for padd optimization.");
8530   }
8531
8532   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8533   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8534   return DAG.getNode(ExtOp, dl, VT, tmp);
8535 }
8536
8537 static SDValue findMUL_LOHI(SDValue V) {
8538   if (V->getOpcode() == ISD::UMUL_LOHI ||
8539       V->getOpcode() == ISD::SMUL_LOHI)
8540     return V;
8541   return SDValue();
8542 }
8543
8544 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8545                                      TargetLowering::DAGCombinerInfo &DCI,
8546                                      const ARMSubtarget *Subtarget) {
8547
8548   if (Subtarget->isThumb1Only()) return SDValue();
8549
8550   // Only perform the checks after legalize when the pattern is available.
8551   if (DCI.isBeforeLegalize()) return SDValue();
8552
8553   // Look for multiply add opportunities.
8554   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8555   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8556   // a glue link from the first add to the second add.
8557   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8558   // a S/UMLAL instruction.
8559   //                  UMUL_LOHI
8560   //                 / :lo    \ :hi
8561   //                /          \          [no multiline comment]
8562   //    loAdd ->  ADDE         |
8563   //                 \ :glue  /
8564   //                  \      /
8565   //                    ADDC   <- hiAdd
8566   //
8567   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8568   SDValue AddcOp0 = AddcNode->getOperand(0);
8569   SDValue AddcOp1 = AddcNode->getOperand(1);
8570
8571   // Check if the two operands are from the same mul_lohi node.
8572   if (AddcOp0.getNode() == AddcOp1.getNode())
8573     return SDValue();
8574
8575   assert(AddcNode->getNumValues() == 2 &&
8576          AddcNode->getValueType(0) == MVT::i32 &&
8577          "Expect ADDC with two result values. First: i32");
8578
8579   // Check that we have a glued ADDC node.
8580   if (AddcNode->getValueType(1) != MVT::Glue)
8581     return SDValue();
8582
8583   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8584   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8585       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8586       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8587       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8588     return SDValue();
8589
8590   // Look for the glued ADDE.
8591   SDNode* AddeNode = AddcNode->getGluedUser();
8592   if (!AddeNode)
8593     return SDValue();
8594
8595   // Make sure it is really an ADDE.
8596   if (AddeNode->getOpcode() != ISD::ADDE)
8597     return SDValue();
8598
8599   assert(AddeNode->getNumOperands() == 3 &&
8600          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8601          "ADDE node has the wrong inputs");
8602
8603   // Check for the triangle shape.
8604   SDValue AddeOp0 = AddeNode->getOperand(0);
8605   SDValue AddeOp1 = AddeNode->getOperand(1);
8606
8607   // Make sure that the ADDE operands are not coming from the same node.
8608   if (AddeOp0.getNode() == AddeOp1.getNode())
8609     return SDValue();
8610
8611   // Find the MUL_LOHI node walking up ADDE's operands.
8612   bool IsLeftOperandMUL = false;
8613   SDValue MULOp = findMUL_LOHI(AddeOp0);
8614   if (MULOp == SDValue())
8615    MULOp = findMUL_LOHI(AddeOp1);
8616   else
8617     IsLeftOperandMUL = true;
8618   if (MULOp == SDValue())
8619     return SDValue();
8620
8621   // Figure out the right opcode.
8622   unsigned Opc = MULOp->getOpcode();
8623   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8624
8625   // Figure out the high and low input values to the MLAL node.
8626   SDValue* HiAdd = nullptr;
8627   SDValue* LoMul = nullptr;
8628   SDValue* LowAdd = nullptr;
8629
8630   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8631   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8632     return SDValue();
8633
8634   if (IsLeftOperandMUL)
8635     HiAdd = &AddeOp1;
8636   else
8637     HiAdd = &AddeOp0;
8638
8639
8640   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8641   // whose low result is fed to the ADDC we are checking.
8642
8643   if (AddcOp0 == MULOp.getValue(0)) {
8644     LoMul = &AddcOp0;
8645     LowAdd = &AddcOp1;
8646   }
8647   if (AddcOp1 == MULOp.getValue(0)) {
8648     LoMul = &AddcOp1;
8649     LowAdd = &AddcOp0;
8650   }
8651
8652   if (!LoMul)
8653     return SDValue();
8654
8655   // Create the merged node.
8656   SelectionDAG &DAG = DCI.DAG;
8657
8658   // Build operand list.
8659   SmallVector<SDValue, 8> Ops;
8660   Ops.push_back(LoMul->getOperand(0));
8661   Ops.push_back(LoMul->getOperand(1));
8662   Ops.push_back(*LowAdd);
8663   Ops.push_back(*HiAdd);
8664
8665   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8666                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8667
8668   // Replace the ADDs' nodes uses by the MLA node's values.
8669   SDValue HiMLALResult(MLALNode.getNode(), 1);
8670   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8671
8672   SDValue LoMLALResult(MLALNode.getNode(), 0);
8673   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8674
8675   // Return original node to notify the driver to stop replacing.
8676   SDValue resNode(AddcNode, 0);
8677   return resNode;
8678 }
8679
8680 /// PerformADDCCombine - Target-specific dag combine transform from
8681 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8682 static SDValue PerformADDCCombine(SDNode *N,
8683                                  TargetLowering::DAGCombinerInfo &DCI,
8684                                  const ARMSubtarget *Subtarget) {
8685
8686   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8687
8688 }
8689
8690 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8691 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8692 /// called with the default operands, and if that fails, with commuted
8693 /// operands.
8694 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8695                                           TargetLowering::DAGCombinerInfo &DCI,
8696                                           const ARMSubtarget *Subtarget){
8697
8698   // Attempt to create vpaddl for this add.
8699   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8700   if (Result.getNode())
8701     return Result;
8702
8703   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8704   if (N0.getNode()->hasOneUse()) {
8705     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8706     if (Result.getNode()) return Result;
8707   }
8708   return SDValue();
8709 }
8710
8711 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8712 ///
8713 static SDValue PerformADDCombine(SDNode *N,
8714                                  TargetLowering::DAGCombinerInfo &DCI,
8715                                  const ARMSubtarget *Subtarget) {
8716   SDValue N0 = N->getOperand(0);
8717   SDValue N1 = N->getOperand(1);
8718
8719   // First try with the default operand order.
8720   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8721   if (Result.getNode())
8722     return Result;
8723
8724   // If that didn't work, try again with the operands commuted.
8725   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8726 }
8727
8728 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8729 ///
8730 static SDValue PerformSUBCombine(SDNode *N,
8731                                  TargetLowering::DAGCombinerInfo &DCI) {
8732   SDValue N0 = N->getOperand(0);
8733   SDValue N1 = N->getOperand(1);
8734
8735   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8736   if (N1.getNode()->hasOneUse()) {
8737     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8738     if (Result.getNode()) return Result;
8739   }
8740
8741   return SDValue();
8742 }
8743
8744 /// PerformVMULCombine
8745 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8746 /// special multiplier accumulator forwarding.
8747 ///   vmul d3, d0, d2
8748 ///   vmla d3, d1, d2
8749 /// is faster than
8750 ///   vadd d3, d0, d1
8751 ///   vmul d3, d3, d2
8752 //  However, for (A + B) * (A + B),
8753 //    vadd d2, d0, d1
8754 //    vmul d3, d0, d2
8755 //    vmla d3, d1, d2
8756 //  is slower than
8757 //    vadd d2, d0, d1
8758 //    vmul d3, d2, d2
8759 static SDValue PerformVMULCombine(SDNode *N,
8760                                   TargetLowering::DAGCombinerInfo &DCI,
8761                                   const ARMSubtarget *Subtarget) {
8762   if (!Subtarget->hasVMLxForwarding())
8763     return SDValue();
8764
8765   SelectionDAG &DAG = DCI.DAG;
8766   SDValue N0 = N->getOperand(0);
8767   SDValue N1 = N->getOperand(1);
8768   unsigned Opcode = N0.getOpcode();
8769   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8770       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8771     Opcode = N1.getOpcode();
8772     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8773         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8774       return SDValue();
8775     std::swap(N0, N1);
8776   }
8777
8778   if (N0 == N1)
8779     return SDValue();
8780
8781   EVT VT = N->getValueType(0);
8782   SDLoc DL(N);
8783   SDValue N00 = N0->getOperand(0);
8784   SDValue N01 = N0->getOperand(1);
8785   return DAG.getNode(Opcode, DL, VT,
8786                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8787                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8788 }
8789
8790 static SDValue PerformMULCombine(SDNode *N,
8791                                  TargetLowering::DAGCombinerInfo &DCI,
8792                                  const ARMSubtarget *Subtarget) {
8793   SelectionDAG &DAG = DCI.DAG;
8794
8795   if (Subtarget->isThumb1Only())
8796     return SDValue();
8797
8798   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8799     return SDValue();
8800
8801   EVT VT = N->getValueType(0);
8802   if (VT.is64BitVector() || VT.is128BitVector())
8803     return PerformVMULCombine(N, DCI, Subtarget);
8804   if (VT != MVT::i32)
8805     return SDValue();
8806
8807   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8808   if (!C)
8809     return SDValue();
8810
8811   int64_t MulAmt = C->getSExtValue();
8812   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8813
8814   ShiftAmt = ShiftAmt & (32 - 1);
8815   SDValue V = N->getOperand(0);
8816   SDLoc DL(N);
8817
8818   SDValue Res;
8819   MulAmt >>= ShiftAmt;
8820
8821   if (MulAmt >= 0) {
8822     if (isPowerOf2_32(MulAmt - 1)) {
8823       // (mul x, 2^N + 1) => (add (shl x, N), x)
8824       Res = DAG.getNode(ISD::ADD, DL, VT,
8825                         V,
8826                         DAG.getNode(ISD::SHL, DL, VT,
8827                                     V,
8828                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8829                                                     MVT::i32)));
8830     } else if (isPowerOf2_32(MulAmt + 1)) {
8831       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8832       Res = DAG.getNode(ISD::SUB, DL, VT,
8833                         DAG.getNode(ISD::SHL, DL, VT,
8834                                     V,
8835                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8836                                                     MVT::i32)),
8837                         V);
8838     } else
8839       return SDValue();
8840   } else {
8841     uint64_t MulAmtAbs = -MulAmt;
8842     if (isPowerOf2_32(MulAmtAbs + 1)) {
8843       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8844       Res = DAG.getNode(ISD::SUB, DL, VT,
8845                         V,
8846                         DAG.getNode(ISD::SHL, DL, VT,
8847                                     V,
8848                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8849                                                     MVT::i32)));
8850     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8851       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8852       Res = DAG.getNode(ISD::ADD, DL, VT,
8853                         V,
8854                         DAG.getNode(ISD::SHL, DL, VT,
8855                                     V,
8856                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8857                                                     MVT::i32)));
8858       Res = DAG.getNode(ISD::SUB, DL, VT,
8859                         DAG.getConstant(0, DL, MVT::i32), Res);
8860
8861     } else
8862       return SDValue();
8863   }
8864
8865   if (ShiftAmt != 0)
8866     Res = DAG.getNode(ISD::SHL, DL, VT,
8867                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8868
8869   // Do not add new nodes to DAG combiner worklist.
8870   DCI.CombineTo(N, Res, false);
8871   return SDValue();
8872 }
8873
8874 static SDValue PerformANDCombine(SDNode *N,
8875                                  TargetLowering::DAGCombinerInfo &DCI,
8876                                  const ARMSubtarget *Subtarget) {
8877
8878   // Attempt to use immediate-form VBIC
8879   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8880   SDLoc dl(N);
8881   EVT VT = N->getValueType(0);
8882   SelectionDAG &DAG = DCI.DAG;
8883
8884   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8885     return SDValue();
8886
8887   APInt SplatBits, SplatUndef;
8888   unsigned SplatBitSize;
8889   bool HasAnyUndefs;
8890   if (BVN &&
8891       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8892     if (SplatBitSize <= 64) {
8893       EVT VbicVT;
8894       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8895                                       SplatUndef.getZExtValue(), SplatBitSize,
8896                                       DAG, dl, VbicVT, VT.is128BitVector(),
8897                                       OtherModImm);
8898       if (Val.getNode()) {
8899         SDValue Input =
8900           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8901         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8902         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8903       }
8904     }
8905   }
8906
8907   if (!Subtarget->isThumb1Only()) {
8908     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8909     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8910     if (Result.getNode())
8911       return Result;
8912   }
8913
8914   return SDValue();
8915 }
8916
8917 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8918 static SDValue PerformORCombine(SDNode *N,
8919                                 TargetLowering::DAGCombinerInfo &DCI,
8920                                 const ARMSubtarget *Subtarget) {
8921   // Attempt to use immediate-form VORR
8922   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8923   SDLoc dl(N);
8924   EVT VT = N->getValueType(0);
8925   SelectionDAG &DAG = DCI.DAG;
8926
8927   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8928     return SDValue();
8929
8930   APInt SplatBits, SplatUndef;
8931   unsigned SplatBitSize;
8932   bool HasAnyUndefs;
8933   if (BVN && Subtarget->hasNEON() &&
8934       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8935     if (SplatBitSize <= 64) {
8936       EVT VorrVT;
8937       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8938                                       SplatUndef.getZExtValue(), SplatBitSize,
8939                                       DAG, dl, VorrVT, VT.is128BitVector(),
8940                                       OtherModImm);
8941       if (Val.getNode()) {
8942         SDValue Input =
8943           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8944         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8945         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8946       }
8947     }
8948   }
8949
8950   if (!Subtarget->isThumb1Only()) {
8951     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8952     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8953     if (Result.getNode())
8954       return Result;
8955   }
8956
8957   // The code below optimizes (or (and X, Y), Z).
8958   // The AND operand needs to have a single user to make these optimizations
8959   // profitable.
8960   SDValue N0 = N->getOperand(0);
8961   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8962     return SDValue();
8963   SDValue N1 = N->getOperand(1);
8964
8965   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8966   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8967       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8968     APInt SplatUndef;
8969     unsigned SplatBitSize;
8970     bool HasAnyUndefs;
8971
8972     APInt SplatBits0, SplatBits1;
8973     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8974     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8975     // Ensure that the second operand of both ands are constants
8976     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8977                                       HasAnyUndefs) && !HasAnyUndefs) {
8978         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8979                                           HasAnyUndefs) && !HasAnyUndefs) {
8980             // Ensure that the bit width of the constants are the same and that
8981             // the splat arguments are logical inverses as per the pattern we
8982             // are trying to simplify.
8983             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8984                 SplatBits0 == ~SplatBits1) {
8985                 // Canonicalize the vector type to make instruction selection
8986                 // simpler.
8987                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8988                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8989                                              N0->getOperand(1),
8990                                              N0->getOperand(0),
8991                                              N1->getOperand(0));
8992                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8993             }
8994         }
8995     }
8996   }
8997
8998   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8999   // reasonable.
9000
9001   // BFI is only available on V6T2+
9002   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9003     return SDValue();
9004
9005   SDLoc DL(N);
9006   // 1) or (and A, mask), val => ARMbfi A, val, mask
9007   //      iff (val & mask) == val
9008   //
9009   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9010   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9011   //          && mask == ~mask2
9012   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9013   //          && ~mask == mask2
9014   //  (i.e., copy a bitfield value into another bitfield of the same width)
9015
9016   if (VT != MVT::i32)
9017     return SDValue();
9018
9019   SDValue N00 = N0.getOperand(0);
9020
9021   // The value and the mask need to be constants so we can verify this is
9022   // actually a bitfield set. If the mask is 0xffff, we can do better
9023   // via a movt instruction, so don't use BFI in that case.
9024   SDValue MaskOp = N0.getOperand(1);
9025   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9026   if (!MaskC)
9027     return SDValue();
9028   unsigned Mask = MaskC->getZExtValue();
9029   if (Mask == 0xffff)
9030     return SDValue();
9031   SDValue Res;
9032   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9033   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9034   if (N1C) {
9035     unsigned Val = N1C->getZExtValue();
9036     if ((Val & ~Mask) != Val)
9037       return SDValue();
9038
9039     if (ARM::isBitFieldInvertedMask(Mask)) {
9040       Val >>= countTrailingZeros(~Mask);
9041
9042       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9043                         DAG.getConstant(Val, DL, MVT::i32),
9044                         DAG.getConstant(Mask, DL, MVT::i32));
9045
9046       // Do not add new nodes to DAG combiner worklist.
9047       DCI.CombineTo(N, Res, false);
9048       return SDValue();
9049     }
9050   } else if (N1.getOpcode() == ISD::AND) {
9051     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9052     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9053     if (!N11C)
9054       return SDValue();
9055     unsigned Mask2 = N11C->getZExtValue();
9056
9057     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9058     // as is to match.
9059     if (ARM::isBitFieldInvertedMask(Mask) &&
9060         (Mask == ~Mask2)) {
9061       // The pack halfword instruction works better for masks that fit it,
9062       // so use that when it's available.
9063       if (Subtarget->hasT2ExtractPack() &&
9064           (Mask == 0xffff || Mask == 0xffff0000))
9065         return SDValue();
9066       // 2a
9067       unsigned amt = countTrailingZeros(Mask2);
9068       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9069                         DAG.getConstant(amt, DL, MVT::i32));
9070       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9071                         DAG.getConstant(Mask, DL, MVT::i32));
9072       // Do not add new nodes to DAG combiner worklist.
9073       DCI.CombineTo(N, Res, false);
9074       return SDValue();
9075     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9076                (~Mask == Mask2)) {
9077       // The pack halfword instruction works better for masks that fit it,
9078       // so use that when it's available.
9079       if (Subtarget->hasT2ExtractPack() &&
9080           (Mask2 == 0xffff || Mask2 == 0xffff0000))
9081         return SDValue();
9082       // 2b
9083       unsigned lsb = countTrailingZeros(Mask);
9084       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9085                         DAG.getConstant(lsb, DL, MVT::i32));
9086       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9087                         DAG.getConstant(Mask2, DL, MVT::i32));
9088       // Do not add new nodes to DAG combiner worklist.
9089       DCI.CombineTo(N, Res, false);
9090       return SDValue();
9091     }
9092   }
9093
9094   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9095       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9096       ARM::isBitFieldInvertedMask(~Mask)) {
9097     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9098     // where lsb(mask) == #shamt and masked bits of B are known zero.
9099     SDValue ShAmt = N00.getOperand(1);
9100     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9101     unsigned LSB = countTrailingZeros(Mask);
9102     if (ShAmtC != LSB)
9103       return SDValue();
9104
9105     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9106                       DAG.getConstant(~Mask, DL, MVT::i32));
9107
9108     // Do not add new nodes to DAG combiner worklist.
9109     DCI.CombineTo(N, Res, false);
9110   }
9111
9112   return SDValue();
9113 }
9114
9115 static SDValue PerformXORCombine(SDNode *N,
9116                                  TargetLowering::DAGCombinerInfo &DCI,
9117                                  const ARMSubtarget *Subtarget) {
9118   EVT VT = N->getValueType(0);
9119   SelectionDAG &DAG = DCI.DAG;
9120
9121   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9122     return SDValue();
9123
9124   if (!Subtarget->isThumb1Only()) {
9125     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9126     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9127     if (Result.getNode())
9128       return Result;
9129   }
9130
9131   return SDValue();
9132 }
9133
9134 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9135 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9136 // their position in "to" (Rd).
9137 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9138   assert(N->getOpcode() == ARMISD::BFI);
9139
9140   SDValue From = N->getOperand(1);
9141   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9142   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9143
9144   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9145   // #C in the base of the SHR.
9146   if (From->getOpcode() == ISD::SRL &&
9147       isa<ConstantSDNode>(From->getOperand(1))) {
9148     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9149     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9150     FromMask <<= Shift.getLimitedValue(31);
9151     From = From->getOperand(0);
9152   }
9153
9154   return From;
9155 }
9156
9157 // If A and B contain one contiguous set of bits, does A | B == A . B?
9158 //
9159 // Neither A nor B must be zero.
9160 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9161   unsigned LastActiveBitInA =  A.countTrailingZeros();
9162   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9163   return LastActiveBitInA - 1 == FirstActiveBitInB;
9164 }
9165
9166 static SDValue FindBFIToCombineWith(SDNode *N) {
9167   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9168   // if one exists.
9169   APInt ToMask, FromMask;
9170   SDValue From = ParseBFI(N, ToMask, FromMask);
9171   SDValue To = N->getOperand(0);
9172
9173   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9174   // aren't compatible, but not if they set the same bit in their destination as
9175   // we do (or that of any BFI we're going to combine with).
9176   SDValue V = To;
9177   APInt CombinedToMask = ToMask;
9178   while (V.getOpcode() == ARMISD::BFI) {
9179     APInt NewToMask, NewFromMask;
9180     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9181     if (NewFrom != From) {
9182       // This BFI has a different base. Keep going.
9183       CombinedToMask |= NewToMask;
9184       V = V.getOperand(0);
9185       continue;
9186     }
9187
9188     // Do the written bits conflict with any we've seen so far?
9189     if ((NewToMask & CombinedToMask).getBoolValue())
9190       // Conflicting bits - bail out because going further is unsafe.
9191       return SDValue();
9192
9193     // Are the new bits contiguous when combined with the old bits?
9194     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9195         BitsProperlyConcatenate(FromMask, NewFromMask))
9196       return V;
9197     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9198         BitsProperlyConcatenate(NewFromMask, FromMask))
9199       return V;
9200
9201     // We've seen a write to some bits, so track it.
9202     CombinedToMask |= NewToMask;
9203     // Keep going...
9204     V = V.getOperand(0);
9205   }
9206
9207   return SDValue();
9208 }
9209
9210 static SDValue PerformBFICombine(SDNode *N,
9211                                  TargetLowering::DAGCombinerInfo &DCI) {
9212   SDValue N1 = N->getOperand(1);
9213   if (N1.getOpcode() == ISD::AND) {
9214     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9215     // the bits being cleared by the AND are not demanded by the BFI.
9216     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9217     if (!N11C)
9218       return SDValue();
9219     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9220     unsigned LSB = countTrailingZeros(~InvMask);
9221     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9222     assert(Width <
9223                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9224            "undefined behavior");
9225     unsigned Mask = (1u << Width) - 1;
9226     unsigned Mask2 = N11C->getZExtValue();
9227     if ((Mask & (~Mask2)) == 0)
9228       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9229                              N->getOperand(0), N1.getOperand(0),
9230                              N->getOperand(2));
9231   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9232     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9233     // Keep track of any consecutive bits set that all come from the same base
9234     // value. We can combine these together into a single BFI.
9235     SDValue CombineBFI = FindBFIToCombineWith(N);
9236     if (CombineBFI == SDValue())
9237       return SDValue();
9238
9239     // We've found a BFI.
9240     APInt ToMask1, FromMask1;
9241     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9242
9243     APInt ToMask2, FromMask2;
9244     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9245     assert(From1 == From2);
9246     (void)From2;
9247
9248     // First, unlink CombineBFI.
9249     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9250     // Then create a new BFI, combining the two together.
9251     APInt NewFromMask = FromMask1 | FromMask2;
9252     APInt NewToMask = ToMask1 | ToMask2;
9253
9254     EVT VT = N->getValueType(0);
9255     SDLoc dl(N);
9256
9257     if (NewFromMask[0] == 0)
9258       From1 = DCI.DAG.getNode(
9259         ISD::SRL, dl, VT, From1,
9260         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9261     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9262                            DCI.DAG.getConstant(~NewToMask, dl, VT));
9263   }
9264   return SDValue();
9265 }
9266
9267 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9268 /// ARMISD::VMOVRRD.
9269 static SDValue PerformVMOVRRDCombine(SDNode *N,
9270                                      TargetLowering::DAGCombinerInfo &DCI,
9271                                      const ARMSubtarget *Subtarget) {
9272   // vmovrrd(vmovdrr x, y) -> x,y
9273   SDValue InDouble = N->getOperand(0);
9274   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9275     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9276
9277   // vmovrrd(load f64) -> (load i32), (load i32)
9278   SDNode *InNode = InDouble.getNode();
9279   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9280       InNode->getValueType(0) == MVT::f64 &&
9281       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9282       !cast<LoadSDNode>(InNode)->isVolatile()) {
9283     // TODO: Should this be done for non-FrameIndex operands?
9284     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9285
9286     SelectionDAG &DAG = DCI.DAG;
9287     SDLoc DL(LD);
9288     SDValue BasePtr = LD->getBasePtr();
9289     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9290                                  LD->getPointerInfo(), LD->isVolatile(),
9291                                  LD->isNonTemporal(), LD->isInvariant(),
9292                                  LD->getAlignment());
9293
9294     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9295                                     DAG.getConstant(4, DL, MVT::i32));
9296     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9297                                  LD->getPointerInfo(), LD->isVolatile(),
9298                                  LD->isNonTemporal(), LD->isInvariant(),
9299                                  std::min(4U, LD->getAlignment() / 2));
9300
9301     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9302     if (DCI.DAG.getDataLayout().isBigEndian())
9303       std::swap (NewLD1, NewLD2);
9304     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9305     return Result;
9306   }
9307
9308   return SDValue();
9309 }
9310
9311 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9312 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9313 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9314   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9315   SDValue Op0 = N->getOperand(0);
9316   SDValue Op1 = N->getOperand(1);
9317   if (Op0.getOpcode() == ISD::BITCAST)
9318     Op0 = Op0.getOperand(0);
9319   if (Op1.getOpcode() == ISD::BITCAST)
9320     Op1 = Op1.getOperand(0);
9321   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9322       Op0.getNode() == Op1.getNode() &&
9323       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9324     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9325                        N->getValueType(0), Op0.getOperand(0));
9326   return SDValue();
9327 }
9328
9329 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9330 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9331 /// i64 vector to have f64 elements, since the value can then be loaded
9332 /// directly into a VFP register.
9333 static bool hasNormalLoadOperand(SDNode *N) {
9334   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9335   for (unsigned i = 0; i < NumElts; ++i) {
9336     SDNode *Elt = N->getOperand(i).getNode();
9337     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9338       return true;
9339   }
9340   return false;
9341 }
9342
9343 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9344 /// ISD::BUILD_VECTOR.
9345 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9346                                           TargetLowering::DAGCombinerInfo &DCI,
9347                                           const ARMSubtarget *Subtarget) {
9348   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9349   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9350   // into a pair of GPRs, which is fine when the value is used as a scalar,
9351   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9352   SelectionDAG &DAG = DCI.DAG;
9353   if (N->getNumOperands() == 2) {
9354     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9355     if (RV.getNode())
9356       return RV;
9357   }
9358
9359   // Load i64 elements as f64 values so that type legalization does not split
9360   // them up into i32 values.
9361   EVT VT = N->getValueType(0);
9362   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9363     return SDValue();
9364   SDLoc dl(N);
9365   SmallVector<SDValue, 8> Ops;
9366   unsigned NumElts = VT.getVectorNumElements();
9367   for (unsigned i = 0; i < NumElts; ++i) {
9368     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9369     Ops.push_back(V);
9370     // Make the DAGCombiner fold the bitcast.
9371     DCI.AddToWorklist(V.getNode());
9372   }
9373   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9374   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9375   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9376 }
9377
9378 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9379 static SDValue
9380 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9381   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9382   // At that time, we may have inserted bitcasts from integer to float.
9383   // If these bitcasts have survived DAGCombine, change the lowering of this
9384   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9385   // force to use floating point types.
9386
9387   // Make sure we can change the type of the vector.
9388   // This is possible iff:
9389   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9390   //    1.1. Vector is used only once.
9391   //    1.2. Use is a bit convert to an integer type.
9392   // 2. The size of its operands are 32-bits (64-bits are not legal).
9393   EVT VT = N->getValueType(0);
9394   EVT EltVT = VT.getVectorElementType();
9395
9396   // Check 1.1. and 2.
9397   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9398     return SDValue();
9399
9400   // By construction, the input type must be float.
9401   assert(EltVT == MVT::f32 && "Unexpected type!");
9402
9403   // Check 1.2.
9404   SDNode *Use = *N->use_begin();
9405   if (Use->getOpcode() != ISD::BITCAST ||
9406       Use->getValueType(0).isFloatingPoint())
9407     return SDValue();
9408
9409   // Check profitability.
9410   // Model is, if more than half of the relevant operands are bitcast from
9411   // i32, turn the build_vector into a sequence of insert_vector_elt.
9412   // Relevant operands are everything that is not statically
9413   // (i.e., at compile time) bitcasted.
9414   unsigned NumOfBitCastedElts = 0;
9415   unsigned NumElts = VT.getVectorNumElements();
9416   unsigned NumOfRelevantElts = NumElts;
9417   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9418     SDValue Elt = N->getOperand(Idx);
9419     if (Elt->getOpcode() == ISD::BITCAST) {
9420       // Assume only bit cast to i32 will go away.
9421       if (Elt->getOperand(0).getValueType() == MVT::i32)
9422         ++NumOfBitCastedElts;
9423     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9424       // Constants are statically casted, thus do not count them as
9425       // relevant operands.
9426       --NumOfRelevantElts;
9427   }
9428
9429   // Check if more than half of the elements require a non-free bitcast.
9430   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9431     return SDValue();
9432
9433   SelectionDAG &DAG = DCI.DAG;
9434   // Create the new vector type.
9435   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9436   // Check if the type is legal.
9437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9438   if (!TLI.isTypeLegal(VecVT))
9439     return SDValue();
9440
9441   // Combine:
9442   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9443   // => BITCAST INSERT_VECTOR_ELT
9444   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9445   //                      (BITCAST EN), N.
9446   SDValue Vec = DAG.getUNDEF(VecVT);
9447   SDLoc dl(N);
9448   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9449     SDValue V = N->getOperand(Idx);
9450     if (V.getOpcode() == ISD::UNDEF)
9451       continue;
9452     if (V.getOpcode() == ISD::BITCAST &&
9453         V->getOperand(0).getValueType() == MVT::i32)
9454       // Fold obvious case.
9455       V = V.getOperand(0);
9456     else {
9457       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9458       // Make the DAGCombiner fold the bitcasts.
9459       DCI.AddToWorklist(V.getNode());
9460     }
9461     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9462     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9463   }
9464   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9465   // Make the DAGCombiner fold the bitcasts.
9466   DCI.AddToWorklist(Vec.getNode());
9467   return Vec;
9468 }
9469
9470 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9471 /// ISD::INSERT_VECTOR_ELT.
9472 static SDValue PerformInsertEltCombine(SDNode *N,
9473                                        TargetLowering::DAGCombinerInfo &DCI) {
9474   // Bitcast an i64 load inserted into a vector to f64.
9475   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9476   EVT VT = N->getValueType(0);
9477   SDNode *Elt = N->getOperand(1).getNode();
9478   if (VT.getVectorElementType() != MVT::i64 ||
9479       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9480     return SDValue();
9481
9482   SelectionDAG &DAG = DCI.DAG;
9483   SDLoc dl(N);
9484   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9485                                  VT.getVectorNumElements());
9486   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9487   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9488   // Make the DAGCombiner fold the bitcasts.
9489   DCI.AddToWorklist(Vec.getNode());
9490   DCI.AddToWorklist(V.getNode());
9491   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9492                                Vec, V, N->getOperand(2));
9493   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9494 }
9495
9496 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9497 /// ISD::VECTOR_SHUFFLE.
9498 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9499   // The LLVM shufflevector instruction does not require the shuffle mask
9500   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9501   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9502   // operands do not match the mask length, they are extended by concatenating
9503   // them with undef vectors.  That is probably the right thing for other
9504   // targets, but for NEON it is better to concatenate two double-register
9505   // size vector operands into a single quad-register size vector.  Do that
9506   // transformation here:
9507   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9508   //   shuffle(concat(v1, v2), undef)
9509   SDValue Op0 = N->getOperand(0);
9510   SDValue Op1 = N->getOperand(1);
9511   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9512       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9513       Op0.getNumOperands() != 2 ||
9514       Op1.getNumOperands() != 2)
9515     return SDValue();
9516   SDValue Concat0Op1 = Op0.getOperand(1);
9517   SDValue Concat1Op1 = Op1.getOperand(1);
9518   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9519       Concat1Op1.getOpcode() != ISD::UNDEF)
9520     return SDValue();
9521   // Skip the transformation if any of the types are illegal.
9522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9523   EVT VT = N->getValueType(0);
9524   if (!TLI.isTypeLegal(VT) ||
9525       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9526       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9527     return SDValue();
9528
9529   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9530                                   Op0.getOperand(0), Op1.getOperand(0));
9531   // Translate the shuffle mask.
9532   SmallVector<int, 16> NewMask;
9533   unsigned NumElts = VT.getVectorNumElements();
9534   unsigned HalfElts = NumElts/2;
9535   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9536   for (unsigned n = 0; n < NumElts; ++n) {
9537     int MaskElt = SVN->getMaskElt(n);
9538     int NewElt = -1;
9539     if (MaskElt < (int)HalfElts)
9540       NewElt = MaskElt;
9541     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9542       NewElt = HalfElts + MaskElt - NumElts;
9543     NewMask.push_back(NewElt);
9544   }
9545   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9546                               DAG.getUNDEF(VT), NewMask.data());
9547 }
9548
9549 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9550 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9551 /// base address updates.
9552 /// For generic load/stores, the memory type is assumed to be a vector.
9553 /// The caller is assumed to have checked legality.
9554 static SDValue CombineBaseUpdate(SDNode *N,
9555                                  TargetLowering::DAGCombinerInfo &DCI) {
9556   SelectionDAG &DAG = DCI.DAG;
9557   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9558                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9559   const bool isStore = N->getOpcode() == ISD::STORE;
9560   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9561   SDValue Addr = N->getOperand(AddrOpIdx);
9562   MemSDNode *MemN = cast<MemSDNode>(N);
9563   SDLoc dl(N);
9564
9565   // Search for a use of the address operand that is an increment.
9566   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9567          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9568     SDNode *User = *UI;
9569     if (User->getOpcode() != ISD::ADD ||
9570         UI.getUse().getResNo() != Addr.getResNo())
9571       continue;
9572
9573     // Check that the add is independent of the load/store.  Otherwise, folding
9574     // it would create a cycle.
9575     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9576       continue;
9577
9578     // Find the new opcode for the updating load/store.
9579     bool isLoadOp = true;
9580     bool isLaneOp = false;
9581     unsigned NewOpc = 0;
9582     unsigned NumVecs = 0;
9583     if (isIntrinsic) {
9584       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9585       switch (IntNo) {
9586       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9587       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9588         NumVecs = 1; break;
9589       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9590         NumVecs = 2; break;
9591       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9592         NumVecs = 3; break;
9593       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9594         NumVecs = 4; break;
9595       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9596         NumVecs = 2; isLaneOp = true; break;
9597       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9598         NumVecs = 3; isLaneOp = true; break;
9599       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9600         NumVecs = 4; isLaneOp = true; break;
9601       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9602         NumVecs = 1; isLoadOp = false; break;
9603       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9604         NumVecs = 2; isLoadOp = false; break;
9605       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9606         NumVecs = 3; isLoadOp = false; break;
9607       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9608         NumVecs = 4; isLoadOp = false; break;
9609       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9610         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9611       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9612         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9613       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9614         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9615       }
9616     } else {
9617       isLaneOp = true;
9618       switch (N->getOpcode()) {
9619       default: llvm_unreachable("unexpected opcode for Neon base update");
9620       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9621       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9622       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9623       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9624         NumVecs = 1; isLaneOp = false; break;
9625       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9626         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9627       }
9628     }
9629
9630     // Find the size of memory referenced by the load/store.
9631     EVT VecTy;
9632     if (isLoadOp) {
9633       VecTy = N->getValueType(0);
9634     } else if (isIntrinsic) {
9635       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9636     } else {
9637       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9638       VecTy = N->getOperand(1).getValueType();
9639     }
9640
9641     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9642     if (isLaneOp)
9643       NumBytes /= VecTy.getVectorNumElements();
9644
9645     // If the increment is a constant, it must match the memory ref size.
9646     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9647     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9648       uint64_t IncVal = CInc->getZExtValue();
9649       if (IncVal != NumBytes)
9650         continue;
9651     } else if (NumBytes >= 3 * 16) {
9652       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9653       // separate instructions that make it harder to use a non-constant update.
9654       continue;
9655     }
9656
9657     // OK, we found an ADD we can fold into the base update.
9658     // Now, create a _UPD node, taking care of not breaking alignment.
9659
9660     EVT AlignedVecTy = VecTy;
9661     unsigned Alignment = MemN->getAlignment();
9662
9663     // If this is a less-than-standard-aligned load/store, change the type to
9664     // match the standard alignment.
9665     // The alignment is overlooked when selecting _UPD variants; and it's
9666     // easier to introduce bitcasts here than fix that.
9667     // There are 3 ways to get to this base-update combine:
9668     // - intrinsics: they are assumed to be properly aligned (to the standard
9669     //   alignment of the memory type), so we don't need to do anything.
9670     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9671     //   intrinsics, so, likewise, there's nothing to do.
9672     // - generic load/store instructions: the alignment is specified as an
9673     //   explicit operand, rather than implicitly as the standard alignment
9674     //   of the memory type (like the intrisics).  We need to change the
9675     //   memory type to match the explicit alignment.  That way, we don't
9676     //   generate non-standard-aligned ARMISD::VLDx nodes.
9677     if (isa<LSBaseSDNode>(N)) {
9678       if (Alignment == 0)
9679         Alignment = 1;
9680       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9681         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9682         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9683         assert(!isLaneOp && "Unexpected generic load/store lane.");
9684         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9685         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9686       }
9687       // Don't set an explicit alignment on regular load/stores that we want
9688       // to transform to VLD/VST 1_UPD nodes.
9689       // This matches the behavior of regular load/stores, which only get an
9690       // explicit alignment if the MMO alignment is larger than the standard
9691       // alignment of the memory type.
9692       // Intrinsics, however, always get an explicit alignment, set to the
9693       // alignment of the MMO.
9694       Alignment = 1;
9695     }
9696
9697     // Create the new updating load/store node.
9698     // First, create an SDVTList for the new updating node's results.
9699     EVT Tys[6];
9700     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9701     unsigned n;
9702     for (n = 0; n < NumResultVecs; ++n)
9703       Tys[n] = AlignedVecTy;
9704     Tys[n++] = MVT::i32;
9705     Tys[n] = MVT::Other;
9706     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9707
9708     // Then, gather the new node's operands.
9709     SmallVector<SDValue, 8> Ops;
9710     Ops.push_back(N->getOperand(0)); // incoming chain
9711     Ops.push_back(N->getOperand(AddrOpIdx));
9712     Ops.push_back(Inc);
9713
9714     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9715       // Try to match the intrinsic's signature
9716       Ops.push_back(StN->getValue());
9717     } else {
9718       // Loads (and of course intrinsics) match the intrinsics' signature,
9719       // so just add all but the alignment operand.
9720       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9721         Ops.push_back(N->getOperand(i));
9722     }
9723
9724     // For all node types, the alignment operand is always the last one.
9725     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9726
9727     // If this is a non-standard-aligned STORE, the penultimate operand is the
9728     // stored value.  Bitcast it to the aligned type.
9729     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9730       SDValue &StVal = Ops[Ops.size()-2];
9731       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9732     }
9733
9734     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9735                                            Ops, AlignedVecTy,
9736                                            MemN->getMemOperand());
9737
9738     // Update the uses.
9739     SmallVector<SDValue, 5> NewResults;
9740     for (unsigned i = 0; i < NumResultVecs; ++i)
9741       NewResults.push_back(SDValue(UpdN.getNode(), i));
9742
9743     // If this is an non-standard-aligned LOAD, the first result is the loaded
9744     // value.  Bitcast it to the expected result type.
9745     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9746       SDValue &LdVal = NewResults[0];
9747       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9748     }
9749
9750     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9751     DCI.CombineTo(N, NewResults);
9752     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9753
9754     break;
9755   }
9756   return SDValue();
9757 }
9758
9759 static SDValue PerformVLDCombine(SDNode *N,
9760                                  TargetLowering::DAGCombinerInfo &DCI) {
9761   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9762     return SDValue();
9763
9764   return CombineBaseUpdate(N, DCI);
9765 }
9766
9767 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9768 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9769 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9770 /// return true.
9771 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9772   SelectionDAG &DAG = DCI.DAG;
9773   EVT VT = N->getValueType(0);
9774   // vldN-dup instructions only support 64-bit vectors for N > 1.
9775   if (!VT.is64BitVector())
9776     return false;
9777
9778   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9779   SDNode *VLD = N->getOperand(0).getNode();
9780   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9781     return false;
9782   unsigned NumVecs = 0;
9783   unsigned NewOpc = 0;
9784   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9785   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9786     NumVecs = 2;
9787     NewOpc = ARMISD::VLD2DUP;
9788   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9789     NumVecs = 3;
9790     NewOpc = ARMISD::VLD3DUP;
9791   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9792     NumVecs = 4;
9793     NewOpc = ARMISD::VLD4DUP;
9794   } else {
9795     return false;
9796   }
9797
9798   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9799   // numbers match the load.
9800   unsigned VLDLaneNo =
9801     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9802   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9803        UI != UE; ++UI) {
9804     // Ignore uses of the chain result.
9805     if (UI.getUse().getResNo() == NumVecs)
9806       continue;
9807     SDNode *User = *UI;
9808     if (User->getOpcode() != ARMISD::VDUPLANE ||
9809         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9810       return false;
9811   }
9812
9813   // Create the vldN-dup node.
9814   EVT Tys[5];
9815   unsigned n;
9816   for (n = 0; n < NumVecs; ++n)
9817     Tys[n] = VT;
9818   Tys[n] = MVT::Other;
9819   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9820   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9821   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9822   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9823                                            Ops, VLDMemInt->getMemoryVT(),
9824                                            VLDMemInt->getMemOperand());
9825
9826   // Update the uses.
9827   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9828        UI != UE; ++UI) {
9829     unsigned ResNo = UI.getUse().getResNo();
9830     // Ignore uses of the chain result.
9831     if (ResNo == NumVecs)
9832       continue;
9833     SDNode *User = *UI;
9834     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9835   }
9836
9837   // Now the vldN-lane intrinsic is dead except for its chain result.
9838   // Update uses of the chain.
9839   std::vector<SDValue> VLDDupResults;
9840   for (unsigned n = 0; n < NumVecs; ++n)
9841     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9842   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9843   DCI.CombineTo(VLD, VLDDupResults);
9844
9845   return true;
9846 }
9847
9848 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9849 /// ARMISD::VDUPLANE.
9850 static SDValue PerformVDUPLANECombine(SDNode *N,
9851                                       TargetLowering::DAGCombinerInfo &DCI) {
9852   SDValue Op = N->getOperand(0);
9853
9854   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9855   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9856   if (CombineVLDDUP(N, DCI))
9857     return SDValue(N, 0);
9858
9859   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9860   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9861   while (Op.getOpcode() == ISD::BITCAST)
9862     Op = Op.getOperand(0);
9863   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9864     return SDValue();
9865
9866   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9867   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9868   // The canonical VMOV for a zero vector uses a 32-bit element size.
9869   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9870   unsigned EltBits;
9871   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9872     EltSize = 8;
9873   EVT VT = N->getValueType(0);
9874   if (EltSize > VT.getVectorElementType().getSizeInBits())
9875     return SDValue();
9876
9877   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9878 }
9879
9880 static SDValue PerformLOADCombine(SDNode *N,
9881                                   TargetLowering::DAGCombinerInfo &DCI) {
9882   EVT VT = N->getValueType(0);
9883
9884   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9885   if (ISD::isNormalLoad(N) && VT.isVector() &&
9886       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9887     return CombineBaseUpdate(N, DCI);
9888
9889   return SDValue();
9890 }
9891
9892 /// PerformSTORECombine - Target-specific dag combine xforms for
9893 /// ISD::STORE.
9894 static SDValue PerformSTORECombine(SDNode *N,
9895                                    TargetLowering::DAGCombinerInfo &DCI) {
9896   StoreSDNode *St = cast<StoreSDNode>(N);
9897   if (St->isVolatile())
9898     return SDValue();
9899
9900   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9901   // pack all of the elements in one place.  Next, store to memory in fewer
9902   // chunks.
9903   SDValue StVal = St->getValue();
9904   EVT VT = StVal.getValueType();
9905   if (St->isTruncatingStore() && VT.isVector()) {
9906     SelectionDAG &DAG = DCI.DAG;
9907     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9908     EVT StVT = St->getMemoryVT();
9909     unsigned NumElems = VT.getVectorNumElements();
9910     assert(StVT != VT && "Cannot truncate to the same type");
9911     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9912     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9913
9914     // From, To sizes and ElemCount must be pow of two
9915     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9916
9917     // We are going to use the original vector elt for storing.
9918     // Accumulated smaller vector elements must be a multiple of the store size.
9919     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9920
9921     unsigned SizeRatio  = FromEltSz / ToEltSz;
9922     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9923
9924     // Create a type on which we perform the shuffle.
9925     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9926                                      NumElems*SizeRatio);
9927     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9928
9929     SDLoc DL(St);
9930     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9931     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9932     for (unsigned i = 0; i < NumElems; ++i)
9933       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9934                           ? (i + 1) * SizeRatio - 1
9935                           : i * SizeRatio;
9936
9937     // Can't shuffle using an illegal type.
9938     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9939
9940     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9941                                 DAG.getUNDEF(WideVec.getValueType()),
9942                                 ShuffleVec.data());
9943     // At this point all of the data is stored at the bottom of the
9944     // register. We now need to save it to mem.
9945
9946     // Find the largest store unit
9947     MVT StoreType = MVT::i8;
9948     for (MVT Tp : MVT::integer_valuetypes()) {
9949       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9950         StoreType = Tp;
9951     }
9952     // Didn't find a legal store type.
9953     if (!TLI.isTypeLegal(StoreType))
9954       return SDValue();
9955
9956     // Bitcast the original vector into a vector of store-size units
9957     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9958             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9959     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9960     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9961     SmallVector<SDValue, 8> Chains;
9962     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9963                                         TLI.getPointerTy(DAG.getDataLayout()));
9964     SDValue BasePtr = St->getBasePtr();
9965
9966     // Perform one or more big stores into memory.
9967     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9968     for (unsigned I = 0; I < E; I++) {
9969       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9970                                    StoreType, ShuffWide,
9971                                    DAG.getIntPtrConstant(I, DL));
9972       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9973                                 St->getPointerInfo(), St->isVolatile(),
9974                                 St->isNonTemporal(), St->getAlignment());
9975       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9976                             Increment);
9977       Chains.push_back(Ch);
9978     }
9979     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9980   }
9981
9982   if (!ISD::isNormalStore(St))
9983     return SDValue();
9984
9985   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9986   // ARM stores of arguments in the same cache line.
9987   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9988       StVal.getNode()->hasOneUse()) {
9989     SelectionDAG  &DAG = DCI.DAG;
9990     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9991     SDLoc DL(St);
9992     SDValue BasePtr = St->getBasePtr();
9993     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9994                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9995                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9996                                   St->isNonTemporal(), St->getAlignment());
9997
9998     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9999                                     DAG.getConstant(4, DL, MVT::i32));
10000     return DAG.getStore(NewST1.getValue(0), DL,
10001                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10002                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
10003                         St->isNonTemporal(),
10004                         std::min(4U, St->getAlignment() / 2));
10005   }
10006
10007   if (StVal.getValueType() == MVT::i64 &&
10008       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10009
10010     // Bitcast an i64 store extracted from a vector to f64.
10011     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10012     SelectionDAG &DAG = DCI.DAG;
10013     SDLoc dl(StVal);
10014     SDValue IntVec = StVal.getOperand(0);
10015     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10016                                    IntVec.getValueType().getVectorNumElements());
10017     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10018     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10019                                  Vec, StVal.getOperand(1));
10020     dl = SDLoc(N);
10021     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10022     // Make the DAGCombiner fold the bitcasts.
10023     DCI.AddToWorklist(Vec.getNode());
10024     DCI.AddToWorklist(ExtElt.getNode());
10025     DCI.AddToWorklist(V.getNode());
10026     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10027                         St->getPointerInfo(), St->isVolatile(),
10028                         St->isNonTemporal(), St->getAlignment(),
10029                         St->getAAInfo());
10030   }
10031
10032   // If this is a legal vector store, try to combine it into a VST1_UPD.
10033   if (ISD::isNormalStore(N) && VT.isVector() &&
10034       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10035     return CombineBaseUpdate(N, DCI);
10036
10037   return SDValue();
10038 }
10039
10040 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10041 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10042 /// when the VMUL has a constant operand that is a power of 2.
10043 ///
10044 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10045 ///  vmul.f32        d16, d17, d16
10046 ///  vcvt.s32.f32    d16, d16
10047 /// becomes:
10048 ///  vcvt.s32.f32    d16, d16, #3
10049 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10050                                   const ARMSubtarget *Subtarget) {
10051   if (!Subtarget->hasNEON())
10052     return SDValue();
10053
10054   SDValue Op = N->getOperand(0);
10055   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
10056     return SDValue();
10057
10058   SDValue ConstVec = Op->getOperand(1);
10059   if (!isa<BuildVectorSDNode>(ConstVec))
10060     return SDValue();
10061
10062   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10063   uint32_t FloatBits = FloatTy.getSizeInBits();
10064   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10065   uint32_t IntBits = IntTy.getSizeInBits();
10066   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10067   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10068     // These instructions only exist converting from f32 to i32. We can handle
10069     // smaller integers by generating an extra truncate, but larger ones would
10070     // be lossy. We also can't handle more then 4 lanes, since these intructions
10071     // only support v2i32/v4i32 types.
10072     return SDValue();
10073   }
10074
10075   BitVector UndefElements;
10076   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10077   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10078   if (C == -1 || C == 0 || C > 32)
10079     return SDValue();
10080
10081   SDLoc dl(N);
10082   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10083   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10084     Intrinsic::arm_neon_vcvtfp2fxu;
10085   SDValue FixConv = DAG.getNode(
10086       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10087       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10088       DAG.getConstant(C, dl, MVT::i32));
10089
10090   if (IntBits < FloatBits)
10091     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10092
10093   return FixConv;
10094 }
10095
10096 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10097 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10098 /// when the VDIV has a constant operand that is a power of 2.
10099 ///
10100 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10101 ///  vcvt.f32.s32    d16, d16
10102 ///  vdiv.f32        d16, d17, d16
10103 /// becomes:
10104 ///  vcvt.f32.s32    d16, d16, #3
10105 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10106                                   const ARMSubtarget *Subtarget) {
10107   if (!Subtarget->hasNEON())
10108     return SDValue();
10109
10110   SDValue Op = N->getOperand(0);
10111   unsigned OpOpcode = Op.getNode()->getOpcode();
10112   if (!N->getValueType(0).isVector() ||
10113       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10114     return SDValue();
10115
10116   SDValue ConstVec = N->getOperand(1);
10117   if (!isa<BuildVectorSDNode>(ConstVec))
10118     return SDValue();
10119
10120   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10121   uint32_t FloatBits = FloatTy.getSizeInBits();
10122   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10123   uint32_t IntBits = IntTy.getSizeInBits();
10124   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10125   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10126     // These instructions only exist converting from i32 to f32. We can handle
10127     // smaller integers by generating an extra extend, but larger ones would
10128     // be lossy. We also can't handle more then 4 lanes, since these intructions
10129     // only support v2i32/v4i32 types.
10130     return SDValue();
10131   }
10132
10133   BitVector UndefElements;
10134   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10135   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10136   if (C == -1 || C == 0 || C > 32)
10137     return SDValue();
10138
10139   SDLoc dl(N);
10140   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10141   SDValue ConvInput = Op.getOperand(0);
10142   if (IntBits < FloatBits)
10143     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10144                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10145                             ConvInput);
10146
10147   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10148     Intrinsic::arm_neon_vcvtfxu2fp;
10149   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10150                      Op.getValueType(),
10151                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10152                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10153 }
10154
10155 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10156 /// operand of a vector shift operation, where all the elements of the
10157 /// build_vector must have the same constant integer value.
10158 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10159   // Ignore bit_converts.
10160   while (Op.getOpcode() == ISD::BITCAST)
10161     Op = Op.getOperand(0);
10162   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10163   APInt SplatBits, SplatUndef;
10164   unsigned SplatBitSize;
10165   bool HasAnyUndefs;
10166   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10167                                       HasAnyUndefs, ElementBits) ||
10168       SplatBitSize > ElementBits)
10169     return false;
10170   Cnt = SplatBits.getSExtValue();
10171   return true;
10172 }
10173
10174 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10175 /// operand of a vector shift left operation.  That value must be in the range:
10176 ///   0 <= Value < ElementBits for a left shift; or
10177 ///   0 <= Value <= ElementBits for a long left shift.
10178 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10179   assert(VT.isVector() && "vector shift count is not a vector type");
10180   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10181   if (! getVShiftImm(Op, ElementBits, Cnt))
10182     return false;
10183   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10184 }
10185
10186 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10187 /// operand of a vector shift right operation.  For a shift opcode, the value
10188 /// is positive, but for an intrinsic the value count must be negative. The
10189 /// absolute value must be in the range:
10190 ///   1 <= |Value| <= ElementBits for a right shift; or
10191 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10192 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10193                          int64_t &Cnt) {
10194   assert(VT.isVector() && "vector shift count is not a vector type");
10195   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10196   if (! getVShiftImm(Op, ElementBits, Cnt))
10197     return false;
10198   if (!isIntrinsic)
10199     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10200   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10201     Cnt = -Cnt;
10202     return true;
10203   }
10204   return false;
10205 }
10206
10207 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10208 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10209   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10210   switch (IntNo) {
10211   default:
10212     // Don't do anything for most intrinsics.
10213     break;
10214
10215   // Vector shifts: check for immediate versions and lower them.
10216   // Note: This is done during DAG combining instead of DAG legalizing because
10217   // the build_vectors for 64-bit vector element shift counts are generally
10218   // not legal, and it is hard to see their values after they get legalized to
10219   // loads from a constant pool.
10220   case Intrinsic::arm_neon_vshifts:
10221   case Intrinsic::arm_neon_vshiftu:
10222   case Intrinsic::arm_neon_vrshifts:
10223   case Intrinsic::arm_neon_vrshiftu:
10224   case Intrinsic::arm_neon_vrshiftn:
10225   case Intrinsic::arm_neon_vqshifts:
10226   case Intrinsic::arm_neon_vqshiftu:
10227   case Intrinsic::arm_neon_vqshiftsu:
10228   case Intrinsic::arm_neon_vqshiftns:
10229   case Intrinsic::arm_neon_vqshiftnu:
10230   case Intrinsic::arm_neon_vqshiftnsu:
10231   case Intrinsic::arm_neon_vqrshiftns:
10232   case Intrinsic::arm_neon_vqrshiftnu:
10233   case Intrinsic::arm_neon_vqrshiftnsu: {
10234     EVT VT = N->getOperand(1).getValueType();
10235     int64_t Cnt;
10236     unsigned VShiftOpc = 0;
10237
10238     switch (IntNo) {
10239     case Intrinsic::arm_neon_vshifts:
10240     case Intrinsic::arm_neon_vshiftu:
10241       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10242         VShiftOpc = ARMISD::VSHL;
10243         break;
10244       }
10245       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10246         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10247                      ARMISD::VSHRs : ARMISD::VSHRu);
10248         break;
10249       }
10250       return SDValue();
10251
10252     case Intrinsic::arm_neon_vrshifts:
10253     case Intrinsic::arm_neon_vrshiftu:
10254       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10255         break;
10256       return SDValue();
10257
10258     case Intrinsic::arm_neon_vqshifts:
10259     case Intrinsic::arm_neon_vqshiftu:
10260       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10261         break;
10262       return SDValue();
10263
10264     case Intrinsic::arm_neon_vqshiftsu:
10265       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10266         break;
10267       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10268
10269     case Intrinsic::arm_neon_vrshiftn:
10270     case Intrinsic::arm_neon_vqshiftns:
10271     case Intrinsic::arm_neon_vqshiftnu:
10272     case Intrinsic::arm_neon_vqshiftnsu:
10273     case Intrinsic::arm_neon_vqrshiftns:
10274     case Intrinsic::arm_neon_vqrshiftnu:
10275     case Intrinsic::arm_neon_vqrshiftnsu:
10276       // Narrowing shifts require an immediate right shift.
10277       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10278         break;
10279       llvm_unreachable("invalid shift count for narrowing vector shift "
10280                        "intrinsic");
10281
10282     default:
10283       llvm_unreachable("unhandled vector shift");
10284     }
10285
10286     switch (IntNo) {
10287     case Intrinsic::arm_neon_vshifts:
10288     case Intrinsic::arm_neon_vshiftu:
10289       // Opcode already set above.
10290       break;
10291     case Intrinsic::arm_neon_vrshifts:
10292       VShiftOpc = ARMISD::VRSHRs; break;
10293     case Intrinsic::arm_neon_vrshiftu:
10294       VShiftOpc = ARMISD::VRSHRu; break;
10295     case Intrinsic::arm_neon_vrshiftn:
10296       VShiftOpc = ARMISD::VRSHRN; break;
10297     case Intrinsic::arm_neon_vqshifts:
10298       VShiftOpc = ARMISD::VQSHLs; break;
10299     case Intrinsic::arm_neon_vqshiftu:
10300       VShiftOpc = ARMISD::VQSHLu; break;
10301     case Intrinsic::arm_neon_vqshiftsu:
10302       VShiftOpc = ARMISD::VQSHLsu; break;
10303     case Intrinsic::arm_neon_vqshiftns:
10304       VShiftOpc = ARMISD::VQSHRNs; break;
10305     case Intrinsic::arm_neon_vqshiftnu:
10306       VShiftOpc = ARMISD::VQSHRNu; break;
10307     case Intrinsic::arm_neon_vqshiftnsu:
10308       VShiftOpc = ARMISD::VQSHRNsu; break;
10309     case Intrinsic::arm_neon_vqrshiftns:
10310       VShiftOpc = ARMISD::VQRSHRNs; break;
10311     case Intrinsic::arm_neon_vqrshiftnu:
10312       VShiftOpc = ARMISD::VQRSHRNu; break;
10313     case Intrinsic::arm_neon_vqrshiftnsu:
10314       VShiftOpc = ARMISD::VQRSHRNsu; break;
10315     }
10316
10317     SDLoc dl(N);
10318     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10319                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10320   }
10321
10322   case Intrinsic::arm_neon_vshiftins: {
10323     EVT VT = N->getOperand(1).getValueType();
10324     int64_t Cnt;
10325     unsigned VShiftOpc = 0;
10326
10327     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10328       VShiftOpc = ARMISD::VSLI;
10329     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10330       VShiftOpc = ARMISD::VSRI;
10331     else {
10332       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10333     }
10334
10335     SDLoc dl(N);
10336     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10337                        N->getOperand(1), N->getOperand(2),
10338                        DAG.getConstant(Cnt, dl, MVT::i32));
10339   }
10340
10341   case Intrinsic::arm_neon_vqrshifts:
10342   case Intrinsic::arm_neon_vqrshiftu:
10343     // No immediate versions of these to check for.
10344     break;
10345   }
10346
10347   return SDValue();
10348 }
10349
10350 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10351 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10352 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10353 /// vector element shift counts are generally not legal, and it is hard to see
10354 /// their values after they get legalized to loads from a constant pool.
10355 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10356                                    const ARMSubtarget *ST) {
10357   EVT VT = N->getValueType(0);
10358   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10359     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10360     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10361     SDValue N1 = N->getOperand(1);
10362     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10363       SDValue N0 = N->getOperand(0);
10364       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10365           DAG.MaskedValueIsZero(N0.getOperand(0),
10366                                 APInt::getHighBitsSet(32, 16)))
10367         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10368     }
10369   }
10370
10371   // Nothing to be done for scalar shifts.
10372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10373   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10374     return SDValue();
10375
10376   assert(ST->hasNEON() && "unexpected vector shift");
10377   int64_t Cnt;
10378
10379   switch (N->getOpcode()) {
10380   default: llvm_unreachable("unexpected shift opcode");
10381
10382   case ISD::SHL:
10383     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10384       SDLoc dl(N);
10385       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10386                          DAG.getConstant(Cnt, dl, MVT::i32));
10387     }
10388     break;
10389
10390   case ISD::SRA:
10391   case ISD::SRL:
10392     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10393       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10394                             ARMISD::VSHRs : ARMISD::VSHRu);
10395       SDLoc dl(N);
10396       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10397                          DAG.getConstant(Cnt, dl, MVT::i32));
10398     }
10399   }
10400   return SDValue();
10401 }
10402
10403 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10404 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10405 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10406                                     const ARMSubtarget *ST) {
10407   SDValue N0 = N->getOperand(0);
10408
10409   // Check for sign- and zero-extensions of vector extract operations of 8-
10410   // and 16-bit vector elements.  NEON supports these directly.  They are
10411   // handled during DAG combining because type legalization will promote them
10412   // to 32-bit types and it is messy to recognize the operations after that.
10413   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10414     SDValue Vec = N0.getOperand(0);
10415     SDValue Lane = N0.getOperand(1);
10416     EVT VT = N->getValueType(0);
10417     EVT EltVT = N0.getValueType();
10418     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10419
10420     if (VT == MVT::i32 &&
10421         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10422         TLI.isTypeLegal(Vec.getValueType()) &&
10423         isa<ConstantSDNode>(Lane)) {
10424
10425       unsigned Opc = 0;
10426       switch (N->getOpcode()) {
10427       default: llvm_unreachable("unexpected opcode");
10428       case ISD::SIGN_EXTEND:
10429         Opc = ARMISD::VGETLANEs;
10430         break;
10431       case ISD::ZERO_EXTEND:
10432       case ISD::ANY_EXTEND:
10433         Opc = ARMISD::VGETLANEu;
10434         break;
10435       }
10436       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10437     }
10438   }
10439
10440   return SDValue();
10441 }
10442
10443 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10444                              APInt &KnownOne) {
10445   if (Op.getOpcode() == ARMISD::BFI) {
10446     // Conservatively, we can recurse down the first operand
10447     // and just mask out all affected bits.
10448     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10449
10450     // The operand to BFI is already a mask suitable for removing the bits it
10451     // sets.
10452     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10453     APInt Mask = CI->getAPIntValue();
10454     KnownZero &= Mask;
10455     KnownOne &= Mask;
10456     return;
10457   }
10458   if (Op.getOpcode() == ARMISD::CMOV) {
10459     APInt KZ2(KnownZero.getBitWidth(), 0);
10460     APInt KO2(KnownOne.getBitWidth(), 0);
10461     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10462     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10463
10464     KnownZero &= KZ2;
10465     KnownOne &= KO2;
10466     return;
10467   }
10468   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10469 }
10470
10471 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10472   // If we have a CMOV, OR and AND combination such as:
10473   //   if (x & CN)
10474   //     y |= CM;
10475   //
10476   // And:
10477   //   * CN is a single bit;
10478   //   * All bits covered by CM are known zero in y
10479   //
10480   // Then we can convert this into a sequence of BFI instructions. This will
10481   // always be a win if CM is a single bit, will always be no worse than the
10482   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10483   // three bits (due to the extra IT instruction).
10484
10485   SDValue Op0 = CMOV->getOperand(0);
10486   SDValue Op1 = CMOV->getOperand(1);
10487   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10488   auto CC = CCNode->getAPIntValue().getLimitedValue();
10489   SDValue CmpZ = CMOV->getOperand(4);
10490
10491   // The compare must be against zero.
10492   if (!isNullConstant(CmpZ->getOperand(1)))
10493     return SDValue();
10494
10495   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10496   SDValue And = CmpZ->getOperand(0);
10497   if (And->getOpcode() != ISD::AND)
10498     return SDValue();
10499   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10500   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10501     return SDValue();
10502   SDValue X = And->getOperand(0);
10503
10504   if (CC == ARMCC::EQ) {
10505     // We're performing an "equal to zero" compare. Swap the operands so we
10506     // canonicalize on a "not equal to zero" compare.
10507     std::swap(Op0, Op1);
10508   } else {
10509     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10510   }
10511   
10512   if (Op1->getOpcode() != ISD::OR)
10513     return SDValue();
10514
10515   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10516   if (!OrC)
10517     return SDValue();
10518   SDValue Y = Op1->getOperand(0);
10519
10520   if (Op0 != Y)
10521     return SDValue();
10522
10523   // Now, is it profitable to continue?
10524   APInt OrCI = OrC->getAPIntValue();
10525   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10526   if (OrCI.countPopulation() > Heuristic)
10527     return SDValue();
10528
10529   // Lastly, can we determine that the bits defined by OrCI
10530   // are zero in Y?
10531   APInt KnownZero, KnownOne;
10532   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10533   if ((OrCI & KnownZero) != OrCI)
10534     return SDValue();
10535
10536   // OK, we can do the combine.
10537   SDValue V = Y;
10538   SDLoc dl(X);
10539   EVT VT = X.getValueType();
10540   unsigned BitInX = AndC->getAPIntValue().logBase2();
10541   
10542   if (BitInX != 0) {
10543     // We must shift X first.
10544     X = DAG.getNode(ISD::SRL, dl, VT, X,
10545                     DAG.getConstant(BitInX, dl, VT));
10546   }
10547
10548   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10549        BitInY < NumActiveBits; ++BitInY) {
10550     if (OrCI[BitInY] == 0)
10551       continue;
10552     APInt Mask(VT.getSizeInBits(), 0);
10553     Mask.setBit(BitInY);
10554     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10555                     // Confusingly, the operand is an *inverted* mask.
10556                     DAG.getConstant(~Mask, dl, VT));
10557   }
10558
10559   return V;
10560 }
10561
10562 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10563 SDValue
10564 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10565   SDValue Cmp = N->getOperand(4);
10566   if (Cmp.getOpcode() != ARMISD::CMPZ)
10567     // Only looking at EQ and NE cases.
10568     return SDValue();
10569
10570   EVT VT = N->getValueType(0);
10571   SDLoc dl(N);
10572   SDValue LHS = Cmp.getOperand(0);
10573   SDValue RHS = Cmp.getOperand(1);
10574   SDValue FalseVal = N->getOperand(0);
10575   SDValue TrueVal = N->getOperand(1);
10576   SDValue ARMcc = N->getOperand(2);
10577   ARMCC::CondCodes CC =
10578     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10579
10580   // BFI is only available on V6T2+.
10581   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10582     SDValue R = PerformCMOVToBFICombine(N, DAG);
10583     if (R)
10584       return R;
10585   }
10586
10587   // Simplify
10588   //   mov     r1, r0
10589   //   cmp     r1, x
10590   //   mov     r0, y
10591   //   moveq   r0, x
10592   // to
10593   //   cmp     r0, x
10594   //   movne   r0, y
10595   //
10596   //   mov     r1, r0
10597   //   cmp     r1, x
10598   //   mov     r0, x
10599   //   movne   r0, y
10600   // to
10601   //   cmp     r0, x
10602   //   movne   r0, y
10603   /// FIXME: Turn this into a target neutral optimization?
10604   SDValue Res;
10605   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10606     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10607                       N->getOperand(3), Cmp);
10608   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10609     SDValue ARMcc;
10610     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10611     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10612                       N->getOperand(3), NewCmp);
10613   }
10614
10615   if (Res.getNode()) {
10616     APInt KnownZero, KnownOne;
10617     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10618     // Capture demanded bits information that would be otherwise lost.
10619     if (KnownZero == 0xfffffffe)
10620       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10621                         DAG.getValueType(MVT::i1));
10622     else if (KnownZero == 0xffffff00)
10623       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10624                         DAG.getValueType(MVT::i8));
10625     else if (KnownZero == 0xffff0000)
10626       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10627                         DAG.getValueType(MVT::i16));
10628   }
10629
10630   return Res;
10631 }
10632
10633 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10634                                              DAGCombinerInfo &DCI) const {
10635   switch (N->getOpcode()) {
10636   default: break;
10637   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10638   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10639   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10640   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10641   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10642   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10643   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10644   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10645   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10646   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10647   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10648   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10649   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10650   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10651   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10652   case ISD::FP_TO_SINT:
10653   case ISD::FP_TO_UINT:
10654     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10655   case ISD::FDIV:
10656     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10657   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10658   case ISD::SHL:
10659   case ISD::SRA:
10660   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10661   case ISD::SIGN_EXTEND:
10662   case ISD::ZERO_EXTEND:
10663   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10664   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10665   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10666   case ARMISD::VLD2DUP:
10667   case ARMISD::VLD3DUP:
10668   case ARMISD::VLD4DUP:
10669     return PerformVLDCombine(N, DCI);
10670   case ARMISD::BUILD_VECTOR:
10671     return PerformARMBUILD_VECTORCombine(N, DCI);
10672   case ISD::INTRINSIC_VOID:
10673   case ISD::INTRINSIC_W_CHAIN:
10674     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10675     case Intrinsic::arm_neon_vld1:
10676     case Intrinsic::arm_neon_vld2:
10677     case Intrinsic::arm_neon_vld3:
10678     case Intrinsic::arm_neon_vld4:
10679     case Intrinsic::arm_neon_vld2lane:
10680     case Intrinsic::arm_neon_vld3lane:
10681     case Intrinsic::arm_neon_vld4lane:
10682     case Intrinsic::arm_neon_vst1:
10683     case Intrinsic::arm_neon_vst2:
10684     case Intrinsic::arm_neon_vst3:
10685     case Intrinsic::arm_neon_vst4:
10686     case Intrinsic::arm_neon_vst2lane:
10687     case Intrinsic::arm_neon_vst3lane:
10688     case Intrinsic::arm_neon_vst4lane:
10689       return PerformVLDCombine(N, DCI);
10690     default: break;
10691     }
10692     break;
10693   }
10694   return SDValue();
10695 }
10696
10697 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10698                                                           EVT VT) const {
10699   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10700 }
10701
10702 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10703                                                        unsigned,
10704                                                        unsigned,
10705                                                        bool *Fast) const {
10706   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10707   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10708
10709   switch (VT.getSimpleVT().SimpleTy) {
10710   default:
10711     return false;
10712   case MVT::i8:
10713   case MVT::i16:
10714   case MVT::i32: {
10715     // Unaligned access can use (for example) LRDB, LRDH, LDR
10716     if (AllowsUnaligned) {
10717       if (Fast)
10718         *Fast = Subtarget->hasV7Ops();
10719       return true;
10720     }
10721     return false;
10722   }
10723   case MVT::f64:
10724   case MVT::v2f64: {
10725     // For any little-endian targets with neon, we can support unaligned ld/st
10726     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10727     // A big-endian target may also explicitly support unaligned accesses
10728     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10729       if (Fast)
10730         *Fast = true;
10731       return true;
10732     }
10733     return false;
10734   }
10735   }
10736 }
10737
10738 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10739                        unsigned AlignCheck) {
10740   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10741           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10742 }
10743
10744 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10745                                            unsigned DstAlign, unsigned SrcAlign,
10746                                            bool IsMemset, bool ZeroMemset,
10747                                            bool MemcpyStrSrc,
10748                                            MachineFunction &MF) const {
10749   const Function *F = MF.getFunction();
10750
10751   // See if we can use NEON instructions for this...
10752   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10753       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10754     bool Fast;
10755     if (Size >= 16 &&
10756         (memOpAlign(SrcAlign, DstAlign, 16) ||
10757          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10758       return MVT::v2f64;
10759     } else if (Size >= 8 &&
10760                (memOpAlign(SrcAlign, DstAlign, 8) ||
10761                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10762                  Fast))) {
10763       return MVT::f64;
10764     }
10765   }
10766
10767   // Lowering to i32/i16 if the size permits.
10768   if (Size >= 4)
10769     return MVT::i32;
10770   else if (Size >= 2)
10771     return MVT::i16;
10772
10773   // Let the target-independent logic figure it out.
10774   return MVT::Other;
10775 }
10776
10777 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10778   if (Val.getOpcode() != ISD::LOAD)
10779     return false;
10780
10781   EVT VT1 = Val.getValueType();
10782   if (!VT1.isSimple() || !VT1.isInteger() ||
10783       !VT2.isSimple() || !VT2.isInteger())
10784     return false;
10785
10786   switch (VT1.getSimpleVT().SimpleTy) {
10787   default: break;
10788   case MVT::i1:
10789   case MVT::i8:
10790   case MVT::i16:
10791     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10792     return true;
10793   }
10794
10795   return false;
10796 }
10797
10798 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10799   EVT VT = ExtVal.getValueType();
10800
10801   if (!isTypeLegal(VT))
10802     return false;
10803
10804   // Don't create a loadext if we can fold the extension into a wide/long
10805   // instruction.
10806   // If there's more than one user instruction, the loadext is desirable no
10807   // matter what.  There can be two uses by the same instruction.
10808   if (ExtVal->use_empty() ||
10809       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10810     return true;
10811
10812   SDNode *U = *ExtVal->use_begin();
10813   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10814        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10815     return false;
10816
10817   return true;
10818 }
10819
10820 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10821   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10822     return false;
10823
10824   if (!isTypeLegal(EVT::getEVT(Ty1)))
10825     return false;
10826
10827   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10828
10829   // Assuming the caller doesn't have a zeroext or signext return parameter,
10830   // truncation all the way down to i1 is valid.
10831   return true;
10832 }
10833
10834
10835 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10836   if (V < 0)
10837     return false;
10838
10839   unsigned Scale = 1;
10840   switch (VT.getSimpleVT().SimpleTy) {
10841   default: return false;
10842   case MVT::i1:
10843   case MVT::i8:
10844     // Scale == 1;
10845     break;
10846   case MVT::i16:
10847     // Scale == 2;
10848     Scale = 2;
10849     break;
10850   case MVT::i32:
10851     // Scale == 4;
10852     Scale = 4;
10853     break;
10854   }
10855
10856   if ((V & (Scale - 1)) != 0)
10857     return false;
10858   V /= Scale;
10859   return V == (V & ((1LL << 5) - 1));
10860 }
10861
10862 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10863                                       const ARMSubtarget *Subtarget) {
10864   bool isNeg = false;
10865   if (V < 0) {
10866     isNeg = true;
10867     V = - V;
10868   }
10869
10870   switch (VT.getSimpleVT().SimpleTy) {
10871   default: return false;
10872   case MVT::i1:
10873   case MVT::i8:
10874   case MVT::i16:
10875   case MVT::i32:
10876     // + imm12 or - imm8
10877     if (isNeg)
10878       return V == (V & ((1LL << 8) - 1));
10879     return V == (V & ((1LL << 12) - 1));
10880   case MVT::f32:
10881   case MVT::f64:
10882     // Same as ARM mode. FIXME: NEON?
10883     if (!Subtarget->hasVFP2())
10884       return false;
10885     if ((V & 3) != 0)
10886       return false;
10887     V >>= 2;
10888     return V == (V & ((1LL << 8) - 1));
10889   }
10890 }
10891
10892 /// isLegalAddressImmediate - Return true if the integer value can be used
10893 /// as the offset of the target addressing mode for load / store of the
10894 /// given type.
10895 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10896                                     const ARMSubtarget *Subtarget) {
10897   if (V == 0)
10898     return true;
10899
10900   if (!VT.isSimple())
10901     return false;
10902
10903   if (Subtarget->isThumb1Only())
10904     return isLegalT1AddressImmediate(V, VT);
10905   else if (Subtarget->isThumb2())
10906     return isLegalT2AddressImmediate(V, VT, Subtarget);
10907
10908   // ARM mode.
10909   if (V < 0)
10910     V = - V;
10911   switch (VT.getSimpleVT().SimpleTy) {
10912   default: return false;
10913   case MVT::i1:
10914   case MVT::i8:
10915   case MVT::i32:
10916     // +- imm12
10917     return V == (V & ((1LL << 12) - 1));
10918   case MVT::i16:
10919     // +- imm8
10920     return V == (V & ((1LL << 8) - 1));
10921   case MVT::f32:
10922   case MVT::f64:
10923     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10924       return false;
10925     if ((V & 3) != 0)
10926       return false;
10927     V >>= 2;
10928     return V == (V & ((1LL << 8) - 1));
10929   }
10930 }
10931
10932 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10933                                                       EVT VT) const {
10934   int Scale = AM.Scale;
10935   if (Scale < 0)
10936     return false;
10937
10938   switch (VT.getSimpleVT().SimpleTy) {
10939   default: return false;
10940   case MVT::i1:
10941   case MVT::i8:
10942   case MVT::i16:
10943   case MVT::i32:
10944     if (Scale == 1)
10945       return true;
10946     // r + r << imm
10947     Scale = Scale & ~1;
10948     return Scale == 2 || Scale == 4 || Scale == 8;
10949   case MVT::i64:
10950     // r + r
10951     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10952       return true;
10953     return false;
10954   case MVT::isVoid:
10955     // Note, we allow "void" uses (basically, uses that aren't loads or
10956     // stores), because arm allows folding a scale into many arithmetic
10957     // operations.  This should be made more precise and revisited later.
10958
10959     // Allow r << imm, but the imm has to be a multiple of two.
10960     if (Scale & 1) return false;
10961     return isPowerOf2_32(Scale);
10962   }
10963 }
10964
10965 /// isLegalAddressingMode - Return true if the addressing mode represented
10966 /// by AM is legal for this target, for a load/store of the specified type.
10967 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10968                                               const AddrMode &AM, Type *Ty,
10969                                               unsigned AS) const {
10970   EVT VT = getValueType(DL, Ty, true);
10971   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10972     return false;
10973
10974   // Can never fold addr of global into load/store.
10975   if (AM.BaseGV)
10976     return false;
10977
10978   switch (AM.Scale) {
10979   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10980     break;
10981   case 1:
10982     if (Subtarget->isThumb1Only())
10983       return false;
10984     // FALL THROUGH.
10985   default:
10986     // ARM doesn't support any R+R*scale+imm addr modes.
10987     if (AM.BaseOffs)
10988       return false;
10989
10990     if (!VT.isSimple())
10991       return false;
10992
10993     if (Subtarget->isThumb2())
10994       return isLegalT2ScaledAddressingMode(AM, VT);
10995
10996     int Scale = AM.Scale;
10997     switch (VT.getSimpleVT().SimpleTy) {
10998     default: return false;
10999     case MVT::i1:
11000     case MVT::i8:
11001     case MVT::i32:
11002       if (Scale < 0) Scale = -Scale;
11003       if (Scale == 1)
11004         return true;
11005       // r + r << imm
11006       return isPowerOf2_32(Scale & ~1);
11007     case MVT::i16:
11008     case MVT::i64:
11009       // r + r
11010       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11011         return true;
11012       return false;
11013
11014     case MVT::isVoid:
11015       // Note, we allow "void" uses (basically, uses that aren't loads or
11016       // stores), because arm allows folding a scale into many arithmetic
11017       // operations.  This should be made more precise and revisited later.
11018
11019       // Allow r << imm, but the imm has to be a multiple of two.
11020       if (Scale & 1) return false;
11021       return isPowerOf2_32(Scale);
11022     }
11023   }
11024   return true;
11025 }
11026
11027 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11028 /// icmp immediate, that is the target has icmp instructions which can compare
11029 /// a register against the immediate without having to materialize the
11030 /// immediate into a register.
11031 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11032   // Thumb2 and ARM modes can use cmn for negative immediates.
11033   if (!Subtarget->isThumb())
11034     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11035   if (Subtarget->isThumb2())
11036     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11037   // Thumb1 doesn't have cmn, and only 8-bit immediates.
11038   return Imm >= 0 && Imm <= 255;
11039 }
11040
11041 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11042 /// *or sub* immediate, that is the target has add or sub instructions which can
11043 /// add a register with the immediate without having to materialize the
11044 /// immediate into a register.
11045 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11046   // Same encoding for add/sub, just flip the sign.
11047   int64_t AbsImm = std::abs(Imm);
11048   if (!Subtarget->isThumb())
11049     return ARM_AM::getSOImmVal(AbsImm) != -1;
11050   if (Subtarget->isThumb2())
11051     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11052   // Thumb1 only has 8-bit unsigned immediate.
11053   return AbsImm >= 0 && AbsImm <= 255;
11054 }
11055
11056 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11057                                       bool isSEXTLoad, SDValue &Base,
11058                                       SDValue &Offset, bool &isInc,
11059                                       SelectionDAG &DAG) {
11060   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11061     return false;
11062
11063   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11064     // AddressingMode 3
11065     Base = Ptr->getOperand(0);
11066     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11067       int RHSC = (int)RHS->getZExtValue();
11068       if (RHSC < 0 && RHSC > -256) {
11069         assert(Ptr->getOpcode() == ISD::ADD);
11070         isInc = false;
11071         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11072         return true;
11073       }
11074     }
11075     isInc = (Ptr->getOpcode() == ISD::ADD);
11076     Offset = Ptr->getOperand(1);
11077     return true;
11078   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11079     // AddressingMode 2
11080     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11081       int RHSC = (int)RHS->getZExtValue();
11082       if (RHSC < 0 && RHSC > -0x1000) {
11083         assert(Ptr->getOpcode() == ISD::ADD);
11084         isInc = false;
11085         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11086         Base = Ptr->getOperand(0);
11087         return true;
11088       }
11089     }
11090
11091     if (Ptr->getOpcode() == ISD::ADD) {
11092       isInc = true;
11093       ARM_AM::ShiftOpc ShOpcVal=
11094         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11095       if (ShOpcVal != ARM_AM::no_shift) {
11096         Base = Ptr->getOperand(1);
11097         Offset = Ptr->getOperand(0);
11098       } else {
11099         Base = Ptr->getOperand(0);
11100         Offset = Ptr->getOperand(1);
11101       }
11102       return true;
11103     }
11104
11105     isInc = (Ptr->getOpcode() == ISD::ADD);
11106     Base = Ptr->getOperand(0);
11107     Offset = Ptr->getOperand(1);
11108     return true;
11109   }
11110
11111   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11112   return false;
11113 }
11114
11115 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11116                                      bool isSEXTLoad, SDValue &Base,
11117                                      SDValue &Offset, bool &isInc,
11118                                      SelectionDAG &DAG) {
11119   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11120     return false;
11121
11122   Base = Ptr->getOperand(0);
11123   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11124     int RHSC = (int)RHS->getZExtValue();
11125     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11126       assert(Ptr->getOpcode() == ISD::ADD);
11127       isInc = false;
11128       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11129       return true;
11130     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11131       isInc = Ptr->getOpcode() == ISD::ADD;
11132       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11133       return true;
11134     }
11135   }
11136
11137   return false;
11138 }
11139
11140 /// getPreIndexedAddressParts - returns true by value, base pointer and
11141 /// offset pointer and addressing mode by reference if the node's address
11142 /// can be legally represented as pre-indexed load / store address.
11143 bool
11144 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11145                                              SDValue &Offset,
11146                                              ISD::MemIndexedMode &AM,
11147                                              SelectionDAG &DAG) const {
11148   if (Subtarget->isThumb1Only())
11149     return false;
11150
11151   EVT VT;
11152   SDValue Ptr;
11153   bool isSEXTLoad = false;
11154   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11155     Ptr = LD->getBasePtr();
11156     VT  = LD->getMemoryVT();
11157     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11158   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11159     Ptr = ST->getBasePtr();
11160     VT  = ST->getMemoryVT();
11161   } else
11162     return false;
11163
11164   bool isInc;
11165   bool isLegal = false;
11166   if (Subtarget->isThumb2())
11167     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11168                                        Offset, isInc, DAG);
11169   else
11170     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11171                                         Offset, isInc, DAG);
11172   if (!isLegal)
11173     return false;
11174
11175   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11176   return true;
11177 }
11178
11179 /// getPostIndexedAddressParts - returns true by value, base pointer and
11180 /// offset pointer and addressing mode by reference if this node can be
11181 /// combined with a load / store to form a post-indexed load / store.
11182 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11183                                                    SDValue &Base,
11184                                                    SDValue &Offset,
11185                                                    ISD::MemIndexedMode &AM,
11186                                                    SelectionDAG &DAG) const {
11187   if (Subtarget->isThumb1Only())
11188     return false;
11189
11190   EVT VT;
11191   SDValue Ptr;
11192   bool isSEXTLoad = false;
11193   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11194     VT  = LD->getMemoryVT();
11195     Ptr = LD->getBasePtr();
11196     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11197   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11198     VT  = ST->getMemoryVT();
11199     Ptr = ST->getBasePtr();
11200   } else
11201     return false;
11202
11203   bool isInc;
11204   bool isLegal = false;
11205   if (Subtarget->isThumb2())
11206     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11207                                        isInc, DAG);
11208   else
11209     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11210                                         isInc, DAG);
11211   if (!isLegal)
11212     return false;
11213
11214   if (Ptr != Base) {
11215     // Swap base ptr and offset to catch more post-index load / store when
11216     // it's legal. In Thumb2 mode, offset must be an immediate.
11217     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11218         !Subtarget->isThumb2())
11219       std::swap(Base, Offset);
11220
11221     // Post-indexed load / store update the base pointer.
11222     if (Ptr != Base)
11223       return false;
11224   }
11225
11226   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11227   return true;
11228 }
11229
11230 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11231                                                       APInt &KnownZero,
11232                                                       APInt &KnownOne,
11233                                                       const SelectionDAG &DAG,
11234                                                       unsigned Depth) const {
11235   unsigned BitWidth = KnownOne.getBitWidth();
11236   KnownZero = KnownOne = APInt(BitWidth, 0);
11237   switch (Op.getOpcode()) {
11238   default: break;
11239   case ARMISD::ADDC:
11240   case ARMISD::ADDE:
11241   case ARMISD::SUBC:
11242   case ARMISD::SUBE:
11243     // These nodes' second result is a boolean
11244     if (Op.getResNo() == 0)
11245       break;
11246     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11247     break;
11248   case ARMISD::CMOV: {
11249     // Bits are known zero/one if known on the LHS and RHS.
11250     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11251     if (KnownZero == 0 && KnownOne == 0) return;
11252
11253     APInt KnownZeroRHS, KnownOneRHS;
11254     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11255     KnownZero &= KnownZeroRHS;
11256     KnownOne  &= KnownOneRHS;
11257     return;
11258   }
11259   case ISD::INTRINSIC_W_CHAIN: {
11260     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11261     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11262     switch (IntID) {
11263     default: return;
11264     case Intrinsic::arm_ldaex:
11265     case Intrinsic::arm_ldrex: {
11266       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11267       unsigned MemBits = VT.getScalarType().getSizeInBits();
11268       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11269       return;
11270     }
11271     }
11272   }
11273   }
11274 }
11275
11276 //===----------------------------------------------------------------------===//
11277 //                           ARM Inline Assembly Support
11278 //===----------------------------------------------------------------------===//
11279
11280 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11281   // Looking for "rev" which is V6+.
11282   if (!Subtarget->hasV6Ops())
11283     return false;
11284
11285   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11286   std::string AsmStr = IA->getAsmString();
11287   SmallVector<StringRef, 4> AsmPieces;
11288   SplitString(AsmStr, AsmPieces, ";\n");
11289
11290   switch (AsmPieces.size()) {
11291   default: return false;
11292   case 1:
11293     AsmStr = AsmPieces[0];
11294     AsmPieces.clear();
11295     SplitString(AsmStr, AsmPieces, " \t,");
11296
11297     // rev $0, $1
11298     if (AsmPieces.size() == 3 &&
11299         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11300         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11301       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11302       if (Ty && Ty->getBitWidth() == 32)
11303         return IntrinsicLowering::LowerToByteSwap(CI);
11304     }
11305     break;
11306   }
11307
11308   return false;
11309 }
11310
11311 /// getConstraintType - Given a constraint letter, return the type of
11312 /// constraint it is for this target.
11313 ARMTargetLowering::ConstraintType
11314 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11315   if (Constraint.size() == 1) {
11316     switch (Constraint[0]) {
11317     default:  break;
11318     case 'l': return C_RegisterClass;
11319     case 'w': return C_RegisterClass;
11320     case 'h': return C_RegisterClass;
11321     case 'x': return C_RegisterClass;
11322     case 't': return C_RegisterClass;
11323     case 'j': return C_Other; // Constant for movw.
11324       // An address with a single base register. Due to the way we
11325       // currently handle addresses it is the same as an 'r' memory constraint.
11326     case 'Q': return C_Memory;
11327     }
11328   } else if (Constraint.size() == 2) {
11329     switch (Constraint[0]) {
11330     default: break;
11331     // All 'U+' constraints are addresses.
11332     case 'U': return C_Memory;
11333     }
11334   }
11335   return TargetLowering::getConstraintType(Constraint);
11336 }
11337
11338 /// Examine constraint type and operand type and determine a weight value.
11339 /// This object must already have been set up with the operand type
11340 /// and the current alternative constraint selected.
11341 TargetLowering::ConstraintWeight
11342 ARMTargetLowering::getSingleConstraintMatchWeight(
11343     AsmOperandInfo &info, const char *constraint) const {
11344   ConstraintWeight weight = CW_Invalid;
11345   Value *CallOperandVal = info.CallOperandVal;
11346     // If we don't have a value, we can't do a match,
11347     // but allow it at the lowest weight.
11348   if (!CallOperandVal)
11349     return CW_Default;
11350   Type *type = CallOperandVal->getType();
11351   // Look at the constraint type.
11352   switch (*constraint) {
11353   default:
11354     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11355     break;
11356   case 'l':
11357     if (type->isIntegerTy()) {
11358       if (Subtarget->isThumb())
11359         weight = CW_SpecificReg;
11360       else
11361         weight = CW_Register;
11362     }
11363     break;
11364   case 'w':
11365     if (type->isFloatingPointTy())
11366       weight = CW_Register;
11367     break;
11368   }
11369   return weight;
11370 }
11371
11372 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11373 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11374     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11375   if (Constraint.size() == 1) {
11376     // GCC ARM Constraint Letters
11377     switch (Constraint[0]) {
11378     case 'l': // Low regs or general regs.
11379       if (Subtarget->isThumb())
11380         return RCPair(0U, &ARM::tGPRRegClass);
11381       return RCPair(0U, &ARM::GPRRegClass);
11382     case 'h': // High regs or no regs.
11383       if (Subtarget->isThumb())
11384         return RCPair(0U, &ARM::hGPRRegClass);
11385       break;
11386     case 'r':
11387       if (Subtarget->isThumb1Only())
11388         return RCPair(0U, &ARM::tGPRRegClass);
11389       return RCPair(0U, &ARM::GPRRegClass);
11390     case 'w':
11391       if (VT == MVT::Other)
11392         break;
11393       if (VT == MVT::f32)
11394         return RCPair(0U, &ARM::SPRRegClass);
11395       if (VT.getSizeInBits() == 64)
11396         return RCPair(0U, &ARM::DPRRegClass);
11397       if (VT.getSizeInBits() == 128)
11398         return RCPair(0U, &ARM::QPRRegClass);
11399       break;
11400     case 'x':
11401       if (VT == MVT::Other)
11402         break;
11403       if (VT == MVT::f32)
11404         return RCPair(0U, &ARM::SPR_8RegClass);
11405       if (VT.getSizeInBits() == 64)
11406         return RCPair(0U, &ARM::DPR_8RegClass);
11407       if (VT.getSizeInBits() == 128)
11408         return RCPair(0U, &ARM::QPR_8RegClass);
11409       break;
11410     case 't':
11411       if (VT == MVT::f32)
11412         return RCPair(0U, &ARM::SPRRegClass);
11413       break;
11414     }
11415   }
11416   if (StringRef("{cc}").equals_lower(Constraint))
11417     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11418
11419   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11420 }
11421
11422 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11423 /// vector.  If it is invalid, don't add anything to Ops.
11424 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11425                                                      std::string &Constraint,
11426                                                      std::vector<SDValue>&Ops,
11427                                                      SelectionDAG &DAG) const {
11428   SDValue Result;
11429
11430   // Currently only support length 1 constraints.
11431   if (Constraint.length() != 1) return;
11432
11433   char ConstraintLetter = Constraint[0];
11434   switch (ConstraintLetter) {
11435   default: break;
11436   case 'j':
11437   case 'I': case 'J': case 'K': case 'L':
11438   case 'M': case 'N': case 'O':
11439     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11440     if (!C)
11441       return;
11442
11443     int64_t CVal64 = C->getSExtValue();
11444     int CVal = (int) CVal64;
11445     // None of these constraints allow values larger than 32 bits.  Check
11446     // that the value fits in an int.
11447     if (CVal != CVal64)
11448       return;
11449
11450     switch (ConstraintLetter) {
11451       case 'j':
11452         // Constant suitable for movw, must be between 0 and
11453         // 65535.
11454         if (Subtarget->hasV6T2Ops())
11455           if (CVal >= 0 && CVal <= 65535)
11456             break;
11457         return;
11458       case 'I':
11459         if (Subtarget->isThumb1Only()) {
11460           // This must be a constant between 0 and 255, for ADD
11461           // immediates.
11462           if (CVal >= 0 && CVal <= 255)
11463             break;
11464         } else if (Subtarget->isThumb2()) {
11465           // A constant that can be used as an immediate value in a
11466           // data-processing instruction.
11467           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11468             break;
11469         } else {
11470           // A constant that can be used as an immediate value in a
11471           // data-processing instruction.
11472           if (ARM_AM::getSOImmVal(CVal) != -1)
11473             break;
11474         }
11475         return;
11476
11477       case 'J':
11478         if (Subtarget->isThumb()) {  // FIXME thumb2
11479           // This must be a constant between -255 and -1, for negated ADD
11480           // immediates. This can be used in GCC with an "n" modifier that
11481           // prints the negated value, for use with SUB instructions. It is
11482           // not useful otherwise but is implemented for compatibility.
11483           if (CVal >= -255 && CVal <= -1)
11484             break;
11485         } else {
11486           // This must be a constant between -4095 and 4095. It is not clear
11487           // what this constraint is intended for. Implemented for
11488           // compatibility with GCC.
11489           if (CVal >= -4095 && CVal <= 4095)
11490             break;
11491         }
11492         return;
11493
11494       case 'K':
11495         if (Subtarget->isThumb1Only()) {
11496           // A 32-bit value where only one byte has a nonzero value. Exclude
11497           // zero to match GCC. This constraint is used by GCC internally for
11498           // constants that can be loaded with a move/shift combination.
11499           // It is not useful otherwise but is implemented for compatibility.
11500           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11501             break;
11502         } else if (Subtarget->isThumb2()) {
11503           // A constant whose bitwise inverse can be used as an immediate
11504           // value in a data-processing instruction. This can be used in GCC
11505           // with a "B" modifier that prints the inverted value, for use with
11506           // BIC and MVN instructions. It is not useful otherwise but is
11507           // implemented for compatibility.
11508           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11509             break;
11510         } else {
11511           // A constant whose bitwise inverse can be used as an immediate
11512           // value in a data-processing instruction. This can be used in GCC
11513           // with a "B" modifier that prints the inverted value, for use with
11514           // BIC and MVN instructions. It is not useful otherwise but is
11515           // implemented for compatibility.
11516           if (ARM_AM::getSOImmVal(~CVal) != -1)
11517             break;
11518         }
11519         return;
11520
11521       case 'L':
11522         if (Subtarget->isThumb1Only()) {
11523           // This must be a constant between -7 and 7,
11524           // for 3-operand ADD/SUB immediate instructions.
11525           if (CVal >= -7 && CVal < 7)
11526             break;
11527         } else if (Subtarget->isThumb2()) {
11528           // A constant whose negation can be used as an immediate value in a
11529           // data-processing instruction. This can be used in GCC with an "n"
11530           // modifier that prints the negated value, for use with SUB
11531           // instructions. It is not useful otherwise but is implemented for
11532           // compatibility.
11533           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11534             break;
11535         } else {
11536           // A constant whose negation can be used as an immediate value in a
11537           // data-processing instruction. This can be used in GCC with an "n"
11538           // modifier that prints the negated value, for use with SUB
11539           // instructions. It is not useful otherwise but is implemented for
11540           // compatibility.
11541           if (ARM_AM::getSOImmVal(-CVal) != -1)
11542             break;
11543         }
11544         return;
11545
11546       case 'M':
11547         if (Subtarget->isThumb()) { // FIXME thumb2
11548           // This must be a multiple of 4 between 0 and 1020, for
11549           // ADD sp + immediate.
11550           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11551             break;
11552         } else {
11553           // A power of two or a constant between 0 and 32.  This is used in
11554           // GCC for the shift amount on shifted register operands, but it is
11555           // useful in general for any shift amounts.
11556           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11557             break;
11558         }
11559         return;
11560
11561       case 'N':
11562         if (Subtarget->isThumb()) {  // FIXME thumb2
11563           // This must be a constant between 0 and 31, for shift amounts.
11564           if (CVal >= 0 && CVal <= 31)
11565             break;
11566         }
11567         return;
11568
11569       case 'O':
11570         if (Subtarget->isThumb()) {  // FIXME thumb2
11571           // This must be a multiple of 4 between -508 and 508, for
11572           // ADD/SUB sp = sp + immediate.
11573           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11574             break;
11575         }
11576         return;
11577     }
11578     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11579     break;
11580   }
11581
11582   if (Result.getNode()) {
11583     Ops.push_back(Result);
11584     return;
11585   }
11586   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11587 }
11588
11589 static RTLIB::Libcall getDivRemLibcall(
11590     const SDNode *N, MVT::SimpleValueType SVT) {
11591   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11592           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11593          "Unhandled Opcode in getDivRemLibcall");
11594   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11595                   N->getOpcode() == ISD::SREM;
11596   RTLIB::Libcall LC;
11597   switch (SVT) {
11598   default: llvm_unreachable("Unexpected request for libcall!");
11599   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11600   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11601   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11602   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11603   }
11604   return LC;
11605 }
11606
11607 static TargetLowering::ArgListTy getDivRemArgList(
11608     const SDNode *N, LLVMContext *Context) {
11609   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11610           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11611          "Unhandled Opcode in getDivRemArgList");
11612   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11613                   N->getOpcode() == ISD::SREM;
11614   TargetLowering::ArgListTy Args;
11615   TargetLowering::ArgListEntry Entry;
11616   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11617     EVT ArgVT = N->getOperand(i).getValueType();
11618     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11619     Entry.Node = N->getOperand(i);
11620     Entry.Ty = ArgTy;
11621     Entry.isSExt = isSigned;
11622     Entry.isZExt = !isSigned;
11623     Args.push_back(Entry);
11624   }
11625   return Args;
11626 }
11627
11628 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11629   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11630          "Register-based DivRem lowering only");
11631   unsigned Opcode = Op->getOpcode();
11632   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11633          "Invalid opcode for Div/Rem lowering");
11634   bool isSigned = (Opcode == ISD::SDIVREM);
11635   EVT VT = Op->getValueType(0);
11636   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11637
11638   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11639                                        VT.getSimpleVT().SimpleTy);
11640   SDValue InChain = DAG.getEntryNode();
11641
11642   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11643                                                     DAG.getContext());
11644
11645   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11646                                          getPointerTy(DAG.getDataLayout()));
11647
11648   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11649
11650   SDLoc dl(Op);
11651   TargetLowering::CallLoweringInfo CLI(DAG);
11652   CLI.setDebugLoc(dl).setChain(InChain)
11653     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11654     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11655
11656   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11657   return CallInfo.first;
11658 }
11659
11660 // Lowers REM using divmod helpers
11661 // see RTABI section 4.2/4.3
11662 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11663   // Build return types (div and rem)
11664   std::vector<Type*> RetTyParams;
11665   Type *RetTyElement;
11666
11667   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11668   default: llvm_unreachable("Unexpected request for libcall!");
11669   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11670   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11671   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11672   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11673   }
11674
11675   RetTyParams.push_back(RetTyElement);
11676   RetTyParams.push_back(RetTyElement);
11677   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11678   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11679
11680   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11681                                                              SimpleTy);
11682   SDValue InChain = DAG.getEntryNode();
11683   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11684   bool isSigned = N->getOpcode() == ISD::SREM;
11685   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11686                                          getPointerTy(DAG.getDataLayout()));
11687
11688   // Lower call
11689   CallLoweringInfo CLI(DAG);
11690   CLI.setChain(InChain)
11691      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11692      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11693   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11694
11695   // Return second (rem) result operand (first contains div)
11696   SDNode *ResNode = CallResult.first.getNode();
11697   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11698   return ResNode->getOperand(1);
11699 }
11700
11701 SDValue
11702 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11703   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11704   SDLoc DL(Op);
11705
11706   // Get the inputs.
11707   SDValue Chain = Op.getOperand(0);
11708   SDValue Size  = Op.getOperand(1);
11709
11710   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11711                               DAG.getConstant(2, DL, MVT::i32));
11712
11713   SDValue Flag;
11714   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11715   Flag = Chain.getValue(1);
11716
11717   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11718   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11719
11720   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11721   Chain = NewSP.getValue(1);
11722
11723   SDValue Ops[2] = { NewSP, Chain };
11724   return DAG.getMergeValues(Ops, DL);
11725 }
11726
11727 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11728   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11729          "Unexpected type for custom-lowering FP_EXTEND");
11730
11731   RTLIB::Libcall LC;
11732   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11733
11734   SDValue SrcVal = Op.getOperand(0);
11735   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11736                      SDLoc(Op)).first;
11737 }
11738
11739 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11740   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11741          Subtarget->isFPOnlySP() &&
11742          "Unexpected type for custom-lowering FP_ROUND");
11743
11744   RTLIB::Libcall LC;
11745   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11746
11747   SDValue SrcVal = Op.getOperand(0);
11748   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11749                      SDLoc(Op)).first;
11750 }
11751
11752 bool
11753 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11754   // The ARM target isn't yet aware of offsets.
11755   return false;
11756 }
11757
11758 bool ARM::isBitFieldInvertedMask(unsigned v) {
11759   if (v == 0xffffffff)
11760     return false;
11761
11762   // there can be 1's on either or both "outsides", all the "inside"
11763   // bits must be 0's
11764   return isShiftedMask_32(~v);
11765 }
11766
11767 /// isFPImmLegal - Returns true if the target can instruction select the
11768 /// specified FP immediate natively. If false, the legalizer will
11769 /// materialize the FP immediate as a load from a constant pool.
11770 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11771   if (!Subtarget->hasVFP3())
11772     return false;
11773   if (VT == MVT::f32)
11774     return ARM_AM::getFP32Imm(Imm) != -1;
11775   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11776     return ARM_AM::getFP64Imm(Imm) != -1;
11777   return false;
11778 }
11779
11780 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11781 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11782 /// specified in the intrinsic calls.
11783 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11784                                            const CallInst &I,
11785                                            unsigned Intrinsic) const {
11786   switch (Intrinsic) {
11787   case Intrinsic::arm_neon_vld1:
11788   case Intrinsic::arm_neon_vld2:
11789   case Intrinsic::arm_neon_vld3:
11790   case Intrinsic::arm_neon_vld4:
11791   case Intrinsic::arm_neon_vld2lane:
11792   case Intrinsic::arm_neon_vld3lane:
11793   case Intrinsic::arm_neon_vld4lane: {
11794     Info.opc = ISD::INTRINSIC_W_CHAIN;
11795     // Conservatively set memVT to the entire set of vectors loaded.
11796     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11797     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11798     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11799     Info.ptrVal = I.getArgOperand(0);
11800     Info.offset = 0;
11801     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11802     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11803     Info.vol = false; // volatile loads with NEON intrinsics not supported
11804     Info.readMem = true;
11805     Info.writeMem = false;
11806     return true;
11807   }
11808   case Intrinsic::arm_neon_vst1:
11809   case Intrinsic::arm_neon_vst2:
11810   case Intrinsic::arm_neon_vst3:
11811   case Intrinsic::arm_neon_vst4:
11812   case Intrinsic::arm_neon_vst2lane:
11813   case Intrinsic::arm_neon_vst3lane:
11814   case Intrinsic::arm_neon_vst4lane: {
11815     Info.opc = ISD::INTRINSIC_VOID;
11816     // Conservatively set memVT to the entire set of vectors stored.
11817     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11818     unsigned NumElts = 0;
11819     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11820       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11821       if (!ArgTy->isVectorTy())
11822         break;
11823       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11824     }
11825     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11826     Info.ptrVal = I.getArgOperand(0);
11827     Info.offset = 0;
11828     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11829     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11830     Info.vol = false; // volatile stores with NEON intrinsics not supported
11831     Info.readMem = false;
11832     Info.writeMem = true;
11833     return true;
11834   }
11835   case Intrinsic::arm_ldaex:
11836   case Intrinsic::arm_ldrex: {
11837     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11838     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11839     Info.opc = ISD::INTRINSIC_W_CHAIN;
11840     Info.memVT = MVT::getVT(PtrTy->getElementType());
11841     Info.ptrVal = I.getArgOperand(0);
11842     Info.offset = 0;
11843     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11844     Info.vol = true;
11845     Info.readMem = true;
11846     Info.writeMem = false;
11847     return true;
11848   }
11849   case Intrinsic::arm_stlex:
11850   case Intrinsic::arm_strex: {
11851     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11852     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11853     Info.opc = ISD::INTRINSIC_W_CHAIN;
11854     Info.memVT = MVT::getVT(PtrTy->getElementType());
11855     Info.ptrVal = I.getArgOperand(1);
11856     Info.offset = 0;
11857     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11858     Info.vol = true;
11859     Info.readMem = false;
11860     Info.writeMem = true;
11861     return true;
11862   }
11863   case Intrinsic::arm_stlexd:
11864   case Intrinsic::arm_strexd: {
11865     Info.opc = ISD::INTRINSIC_W_CHAIN;
11866     Info.memVT = MVT::i64;
11867     Info.ptrVal = I.getArgOperand(2);
11868     Info.offset = 0;
11869     Info.align = 8;
11870     Info.vol = true;
11871     Info.readMem = false;
11872     Info.writeMem = true;
11873     return true;
11874   }
11875   case Intrinsic::arm_ldaexd:
11876   case Intrinsic::arm_ldrexd: {
11877     Info.opc = ISD::INTRINSIC_W_CHAIN;
11878     Info.memVT = MVT::i64;
11879     Info.ptrVal = I.getArgOperand(0);
11880     Info.offset = 0;
11881     Info.align = 8;
11882     Info.vol = true;
11883     Info.readMem = true;
11884     Info.writeMem = false;
11885     return true;
11886   }
11887   default:
11888     break;
11889   }
11890
11891   return false;
11892 }
11893
11894 /// \brief Returns true if it is beneficial to convert a load of a constant
11895 /// to just the constant itself.
11896 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11897                                                           Type *Ty) const {
11898   assert(Ty->isIntegerTy());
11899
11900   unsigned Bits = Ty->getPrimitiveSizeInBits();
11901   if (Bits == 0 || Bits > 32)
11902     return false;
11903   return true;
11904 }
11905
11906 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11907                                         ARM_MB::MemBOpt Domain) const {
11908   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11909
11910   // First, if the target has no DMB, see what fallback we can use.
11911   if (!Subtarget->hasDataBarrier()) {
11912     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11913     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11914     // here.
11915     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11916       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11917       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11918                         Builder.getInt32(0), Builder.getInt32(7),
11919                         Builder.getInt32(10), Builder.getInt32(5)};
11920       return Builder.CreateCall(MCR, args);
11921     } else {
11922       // Instead of using barriers, atomic accesses on these subtargets use
11923       // libcalls.
11924       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11925     }
11926   } else {
11927     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11928     // Only a full system barrier exists in the M-class architectures.
11929     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11930     Constant *CDomain = Builder.getInt32(Domain);
11931     return Builder.CreateCall(DMB, CDomain);
11932   }
11933 }
11934
11935 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11936 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11937                                          AtomicOrdering Ord, bool IsStore,
11938                                          bool IsLoad) const {
11939   if (!getInsertFencesForAtomic())
11940     return nullptr;
11941
11942   switch (Ord) {
11943   case NotAtomic:
11944   case Unordered:
11945     llvm_unreachable("Invalid fence: unordered/non-atomic");
11946   case Monotonic:
11947   case Acquire:
11948     return nullptr; // Nothing to do
11949   case SequentiallyConsistent:
11950     if (!IsStore)
11951       return nullptr; // Nothing to do
11952     /*FALLTHROUGH*/
11953   case Release:
11954   case AcquireRelease:
11955     if (Subtarget->isSwift())
11956       return makeDMB(Builder, ARM_MB::ISHST);
11957     // FIXME: add a comment with a link to documentation justifying this.
11958     else
11959       return makeDMB(Builder, ARM_MB::ISH);
11960   }
11961   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11962 }
11963
11964 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11965                                           AtomicOrdering Ord, bool IsStore,
11966                                           bool IsLoad) const {
11967   if (!getInsertFencesForAtomic())
11968     return nullptr;
11969
11970   switch (Ord) {
11971   case NotAtomic:
11972   case Unordered:
11973     llvm_unreachable("Invalid fence: unordered/not-atomic");
11974   case Monotonic:
11975   case Release:
11976     return nullptr; // Nothing to do
11977   case Acquire:
11978   case AcquireRelease:
11979   case SequentiallyConsistent:
11980     return makeDMB(Builder, ARM_MB::ISH);
11981   }
11982   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11983 }
11984
11985 // Loads and stores less than 64-bits are already atomic; ones above that
11986 // are doomed anyway, so defer to the default libcall and blame the OS when
11987 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11988 // anything for those.
11989 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11990   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11991   return (Size == 64) && !Subtarget->isMClass();
11992 }
11993
11994 // Loads and stores less than 64-bits are already atomic; ones above that
11995 // are doomed anyway, so defer to the default libcall and blame the OS when
11996 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11997 // anything for those.
11998 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11999 // guarantee, see DDI0406C ARM architecture reference manual,
12000 // sections A8.8.72-74 LDRD)
12001 TargetLowering::AtomicExpansionKind
12002 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12003   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12004   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12005                                                   : AtomicExpansionKind::None;
12006 }
12007
12008 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12009 // and up to 64 bits on the non-M profiles
12010 TargetLowering::AtomicExpansionKind
12011 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12012   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12013   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12014              ? AtomicExpansionKind::LLSC
12015              : AtomicExpansionKind::None;
12016 }
12017
12018 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12019     AtomicCmpXchgInst *AI) const {
12020   return true;
12021 }
12022
12023 // This has so far only been implemented for MachO.
12024 bool ARMTargetLowering::useLoadStackGuardNode() const {
12025   return Subtarget->isTargetMachO();
12026 }
12027
12028 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12029                                                   unsigned &Cost) const {
12030   // If we do not have NEON, vector types are not natively supported.
12031   if (!Subtarget->hasNEON())
12032     return false;
12033
12034   // Floating point values and vector values map to the same register file.
12035   // Therefore, although we could do a store extract of a vector type, this is
12036   // better to leave at float as we have more freedom in the addressing mode for
12037   // those.
12038   if (VectorTy->isFPOrFPVectorTy())
12039     return false;
12040
12041   // If the index is unknown at compile time, this is very expensive to lower
12042   // and it is not possible to combine the store with the extract.
12043   if (!isa<ConstantInt>(Idx))
12044     return false;
12045
12046   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12047   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12048   // We can do a store + vector extract on any vector that fits perfectly in a D
12049   // or Q register.
12050   if (BitWidth == 64 || BitWidth == 128) {
12051     Cost = 0;
12052     return true;
12053   }
12054   return false;
12055 }
12056
12057 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12058   return Subtarget->hasV6T2Ops();
12059 }
12060
12061 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12062   return Subtarget->hasV6T2Ops();
12063 }
12064
12065 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12066                                          AtomicOrdering Ord) const {
12067   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12068   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12069   bool IsAcquire = isAtLeastAcquire(Ord);
12070
12071   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12072   // intrinsic must return {i32, i32} and we have to recombine them into a
12073   // single i64 here.
12074   if (ValTy->getPrimitiveSizeInBits() == 64) {
12075     Intrinsic::ID Int =
12076         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12077     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12078
12079     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12080     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12081
12082     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12083     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12084     if (!Subtarget->isLittle())
12085       std::swap (Lo, Hi);
12086     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12087     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12088     return Builder.CreateOr(
12089         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12090   }
12091
12092   Type *Tys[] = { Addr->getType() };
12093   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12094   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12095
12096   return Builder.CreateTruncOrBitCast(
12097       Builder.CreateCall(Ldrex, Addr),
12098       cast<PointerType>(Addr->getType())->getElementType());
12099 }
12100
12101 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12102     IRBuilder<> &Builder) const {
12103   if (!Subtarget->hasV7Ops())
12104     return;
12105   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12106   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12107 }
12108
12109 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12110                                                Value *Addr,
12111                                                AtomicOrdering Ord) const {
12112   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12113   bool IsRelease = isAtLeastRelease(Ord);
12114
12115   // Since the intrinsics must have legal type, the i64 intrinsics take two
12116   // parameters: "i32, i32". We must marshal Val into the appropriate form
12117   // before the call.
12118   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12119     Intrinsic::ID Int =
12120         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12121     Function *Strex = Intrinsic::getDeclaration(M, Int);
12122     Type *Int32Ty = Type::getInt32Ty(M->getContext());
12123
12124     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12125     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12126     if (!Subtarget->isLittle())
12127       std::swap (Lo, Hi);
12128     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12129     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12130   }
12131
12132   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12133   Type *Tys[] = { Addr->getType() };
12134   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12135
12136   return Builder.CreateCall(
12137       Strex, {Builder.CreateZExtOrBitCast(
12138                   Val, Strex->getFunctionType()->getParamType(0)),
12139               Addr});
12140 }
12141
12142 /// \brief Lower an interleaved load into a vldN intrinsic.
12143 ///
12144 /// E.g. Lower an interleaved load (Factor = 2):
12145 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12146 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12147 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12148 ///
12149 ///      Into:
12150 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12151 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12152 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12153 bool ARMTargetLowering::lowerInterleavedLoad(
12154     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12155     ArrayRef<unsigned> Indices, unsigned Factor) const {
12156   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12157          "Invalid interleave factor");
12158   assert(!Shuffles.empty() && "Empty shufflevector input");
12159   assert(Shuffles.size() == Indices.size() &&
12160          "Unmatched number of shufflevectors and indices");
12161
12162   VectorType *VecTy = Shuffles[0]->getType();
12163   Type *EltTy = VecTy->getVectorElementType();
12164
12165   const DataLayout &DL = LI->getModule()->getDataLayout();
12166   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12167   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12168
12169   // Skip if we do not have NEON and skip illegal vector types and vector types
12170   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12171   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12172     return false;
12173
12174   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12175   // load integer vectors first and then convert to pointer vectors.
12176   if (EltTy->isPointerTy())
12177     VecTy =
12178         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12179
12180   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12181                                             Intrinsic::arm_neon_vld3,
12182                                             Intrinsic::arm_neon_vld4};
12183
12184   IRBuilder<> Builder(LI);
12185   SmallVector<Value *, 2> Ops;
12186
12187   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12188   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12189   Ops.push_back(Builder.getInt32(LI->getAlignment()));
12190
12191   Type *Tys[] = { VecTy, Int8Ptr };
12192   Function *VldnFunc =
12193       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12194   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12195
12196   // Replace uses of each shufflevector with the corresponding vector loaded
12197   // by ldN.
12198   for (unsigned i = 0; i < Shuffles.size(); i++) {
12199     ShuffleVectorInst *SV = Shuffles[i];
12200     unsigned Index = Indices[i];
12201
12202     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12203
12204     // Convert the integer vector to pointer vector if the element is pointer.
12205     if (EltTy->isPointerTy())
12206       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12207
12208     SV->replaceAllUsesWith(SubVec);
12209   }
12210
12211   return true;
12212 }
12213
12214 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12215 ///
12216 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12217 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12218                                    unsigned NumElts) {
12219   SmallVector<Constant *, 16> Mask;
12220   for (unsigned i = 0; i < NumElts; i++)
12221     Mask.push_back(Builder.getInt32(Start + i));
12222
12223   return ConstantVector::get(Mask);
12224 }
12225
12226 /// \brief Lower an interleaved store into a vstN intrinsic.
12227 ///
12228 /// E.g. Lower an interleaved store (Factor = 3):
12229 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12230 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12231 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12232 ///
12233 ///      Into:
12234 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12235 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12236 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12237 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12238 ///
12239 /// Note that the new shufflevectors will be removed and we'll only generate one
12240 /// vst3 instruction in CodeGen.
12241 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12242                                               ShuffleVectorInst *SVI,
12243                                               unsigned Factor) const {
12244   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12245          "Invalid interleave factor");
12246
12247   VectorType *VecTy = SVI->getType();
12248   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12249          "Invalid interleaved store");
12250
12251   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12252   Type *EltTy = VecTy->getVectorElementType();
12253   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12254
12255   const DataLayout &DL = SI->getModule()->getDataLayout();
12256   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12257   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12258
12259   // Skip if we do not have NEON and skip illegal vector types and vector types
12260   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12261   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12262       EltIs64Bits)
12263     return false;
12264
12265   Value *Op0 = SVI->getOperand(0);
12266   Value *Op1 = SVI->getOperand(1);
12267   IRBuilder<> Builder(SI);
12268
12269   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12270   // vectors to integer vectors.
12271   if (EltTy->isPointerTy()) {
12272     Type *IntTy = DL.getIntPtrType(EltTy);
12273
12274     // Convert to the corresponding integer vector.
12275     Type *IntVecTy =
12276         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12277     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12278     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12279
12280     SubVecTy = VectorType::get(IntTy, NumSubElts);
12281   }
12282
12283   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12284                                              Intrinsic::arm_neon_vst3,
12285                                              Intrinsic::arm_neon_vst4};
12286   SmallVector<Value *, 6> Ops;
12287
12288   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12289   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12290
12291   Type *Tys[] = { Int8Ptr, SubVecTy };
12292   Function *VstNFunc = Intrinsic::getDeclaration(
12293       SI->getModule(), StoreInts[Factor - 2], Tys);
12294
12295   // Split the shufflevector operands into sub vectors for the new vstN call.
12296   for (unsigned i = 0; i < Factor; i++)
12297     Ops.push_back(Builder.CreateShuffleVector(
12298         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12299
12300   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12301   Builder.CreateCall(VstNFunc, Ops);
12302   return true;
12303 }
12304
12305 enum HABaseType {
12306   HA_UNKNOWN = 0,
12307   HA_FLOAT,
12308   HA_DOUBLE,
12309   HA_VECT64,
12310   HA_VECT128
12311 };
12312
12313 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12314                                    uint64_t &Members) {
12315   if (auto *ST = dyn_cast<StructType>(Ty)) {
12316     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12317       uint64_t SubMembers = 0;
12318       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12319         return false;
12320       Members += SubMembers;
12321     }
12322   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12323     uint64_t SubMembers = 0;
12324     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12325       return false;
12326     Members += SubMembers * AT->getNumElements();
12327   } else if (Ty->isFloatTy()) {
12328     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12329       return false;
12330     Members = 1;
12331     Base = HA_FLOAT;
12332   } else if (Ty->isDoubleTy()) {
12333     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12334       return false;
12335     Members = 1;
12336     Base = HA_DOUBLE;
12337   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12338     Members = 1;
12339     switch (Base) {
12340     case HA_FLOAT:
12341     case HA_DOUBLE:
12342       return false;
12343     case HA_VECT64:
12344       return VT->getBitWidth() == 64;
12345     case HA_VECT128:
12346       return VT->getBitWidth() == 128;
12347     case HA_UNKNOWN:
12348       switch (VT->getBitWidth()) {
12349       case 64:
12350         Base = HA_VECT64;
12351         return true;
12352       case 128:
12353         Base = HA_VECT128;
12354         return true;
12355       default:
12356         return false;
12357       }
12358     }
12359   }
12360
12361   return (Members > 0 && Members <= 4);
12362 }
12363
12364 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12365 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12366 /// passing according to AAPCS rules.
12367 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12368     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12369   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12370       CallingConv::ARM_AAPCS_VFP)
12371     return false;
12372
12373   HABaseType Base = HA_UNKNOWN;
12374   uint64_t Members = 0;
12375   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12376   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12377
12378   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12379   return IsHA || IsIntArray;
12380 }
12381
12382 unsigned ARMTargetLowering::getExceptionPointerRegister(
12383     const Constant *PersonalityFn) const {
12384   // Platforms which do not use SjLj EH may return values in these registers
12385   // via the personality function.
12386   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12387 }
12388
12389 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12390     const Constant *PersonalityFn) const {
12391   // Platforms which do not use SjLj EH may return values in these registers
12392   // via the personality function.
12393   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12394 }