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->isTargetWatchABI()) {
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() && Subtarget->hasV6T2Ops())
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   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
777                                         : Subtarget->hasDivideInARMMode();
778   if (!hasDivide) {
779     // These are expanded into libcalls if the cpu doesn't have HW divider.
780     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
781     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
782   }
783 
784   setOperationAction(ISD::SREM,  MVT::i32, Expand);
785   setOperationAction(ISD::UREM,  MVT::i32, Expand);
786   // Register based DivRem for AEABI (RTABI 4.2)
787   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
788       Subtarget->isTargetGNUAEABI()) {
789     setOperationAction(ISD::SREM, MVT::i64, Custom);
790     setOperationAction(ISD::UREM, MVT::i64, Custom);
791 
792     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
793     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
794     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
795     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
796     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
797     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
798     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
799     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
800 
801     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
802     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
803     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
804     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
805     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
806     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
807     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
808     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
809 
810     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
811     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
812     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
813     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
814   } else {
815     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
816     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
817   }
818 
819   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
820   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
821   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
822   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
823 
824   setOperationAction(ISD::TRAP, MVT::Other, Legal);
825 
826   // Use the default implementation.
827   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
828   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
829   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
830   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
831   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
832   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
833 
834   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
835     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
836   else
837     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
838 
839   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
840   // the default expansion. If we are targeting a single threaded system,
841   // then set them all for expand so we can lower them later into their
842   // non-atomic form.
843   if (TM.Options.ThreadModel == ThreadModel::Single)
844     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
845   else if (Subtarget->hasAnyDataBarrier() && (!Subtarget->isThumb() ||
846                                               Subtarget->hasV8MBaselineOps())) {
847     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
848     // to ldrex/strex loops already.
849     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
850 
851     // On v8, we have particularly efficient implementations of atomic fences
852     // if they can be combined with nearby atomic loads and stores.
853     if (!Subtarget->hasV8Ops()) {
854       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
855       setInsertFencesForAtomic(true);
856     }
857   } else {
858     // If there's anything we can use as a barrier, go through custom lowering
859     // for ATOMIC_FENCE.
860     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
861                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
862 
863     // Set them all for expansion, which will force libcalls.
864     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
865     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
866     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
867     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
868     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
869     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
870     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
871     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
872     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
873     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
874     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
875     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
876     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
877     // Unordered/Monotonic case.
878     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
879     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
880   }
881 
882   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
883 
884   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
885   if (!Subtarget->hasV6Ops()) {
886     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
887     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
888   }
889   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
890 
891   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
892       !Subtarget->isThumb1Only()) {
893     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
894     // iff target supports vfp2.
895     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
896     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
897   }
898 
899   // We want to custom lower some of our intrinsics.
900   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
901   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
902   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
903   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
904   if (Subtarget->useSjLjEH())
905     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
906 
907   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
908   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
909   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
910   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
911   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
912   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
913   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
914   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
915   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
916 
917   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
918   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
919   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
920   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
921   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
922 
923   // We don't support sin/cos/fmod/copysign/pow
924   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
925   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
926   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
927   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
928   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
929   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
930   setOperationAction(ISD::FREM,      MVT::f64, Expand);
931   setOperationAction(ISD::FREM,      MVT::f32, Expand);
932   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
933       !Subtarget->isThumb1Only()) {
934     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
935     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
936   }
937   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
938   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
939 
940   if (!Subtarget->hasVFP4()) {
941     setOperationAction(ISD::FMA, MVT::f64, Expand);
942     setOperationAction(ISD::FMA, MVT::f32, Expand);
943   }
944 
945   // Various VFP goodness
946   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
947     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
948     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
949       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
950       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
951     }
952 
953     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
954     if (!Subtarget->hasFP16()) {
955       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
956       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
957     }
958   }
959 
960   // Combine sin / cos into one node or libcall if possible.
961   if (Subtarget->hasSinCos()) {
962     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
963     setLibcallName(RTLIB::SINCOS_F64, "sincos");
964     if (Subtarget->isTargetWatchABI()) {
965       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
966       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
967     }
968     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
969       // For iOS, we don't want to the normal expansion of a libcall to
970       // sincos. We want to issue a libcall to __sincos_stret.
971       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
972       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
973     }
974   }
975 
976   // FP-ARMv8 implements a lot of rounding-like FP operations.
977   if (Subtarget->hasFPARMv8()) {
978     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
979     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
980     setOperationAction(ISD::FROUND, MVT::f32, Legal);
981     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
982     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
983     setOperationAction(ISD::FRINT, MVT::f32, Legal);
984     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
985     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
986     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
987     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
988     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
989     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
990 
991     if (!Subtarget->isFPOnlySP()) {
992       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
993       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
994       setOperationAction(ISD::FROUND, MVT::f64, Legal);
995       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
996       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
997       setOperationAction(ISD::FRINT, MVT::f64, Legal);
998       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
999       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1000     }
1001   }
1002 
1003   if (Subtarget->hasNEON()) {
1004     // vmin and vmax aren't available in a scalar form, so we use
1005     // a NEON instruction with an undef lane instead.
1006     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1007     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1008     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1009     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1010     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1011     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1012   }
1013 
1014   // We have target-specific dag combine patterns for the following nodes:
1015   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1016   setTargetDAGCombine(ISD::ADD);
1017   setTargetDAGCombine(ISD::SUB);
1018   setTargetDAGCombine(ISD::MUL);
1019   setTargetDAGCombine(ISD::AND);
1020   setTargetDAGCombine(ISD::OR);
1021   setTargetDAGCombine(ISD::XOR);
1022 
1023   if (Subtarget->hasV6Ops())
1024     setTargetDAGCombine(ISD::SRL);
1025 
1026   setStackPointerRegisterToSaveRestore(ARM::SP);
1027 
1028   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1029       !Subtarget->hasVFP2())
1030     setSchedulingPreference(Sched::RegPressure);
1031   else
1032     setSchedulingPreference(Sched::Hybrid);
1033 
1034   //// temporary - rewrite interface to use type
1035   MaxStoresPerMemset = 8;
1036   MaxStoresPerMemsetOptSize = 4;
1037   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1038   MaxStoresPerMemcpyOptSize = 2;
1039   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1040   MaxStoresPerMemmoveOptSize = 2;
1041 
1042   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1043   // are at least 4 bytes aligned.
1044   setMinStackArgumentAlignment(4);
1045 
1046   // Prefer likely predicted branches to selects on out-of-order cores.
1047   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1048 
1049   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1050 }
1051 
1052 bool ARMTargetLowering::useSoftFloat() const {
1053   return Subtarget->useSoftFloat();
1054 }
1055 
1056 // FIXME: It might make sense to define the representative register class as the
1057 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1058 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1059 // SPR's representative would be DPR_VFP2. This should work well if register
1060 // pressure tracking were modified such that a register use would increment the
1061 // pressure of the register class's representative and all of it's super
1062 // classes' representatives transitively. We have not implemented this because
1063 // of the difficulty prior to coalescing of modeling operand register classes
1064 // due to the common occurrence of cross class copies and subregister insertions
1065 // and extractions.
1066 std::pair<const TargetRegisterClass *, uint8_t>
1067 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1068                                            MVT VT) const {
1069   const TargetRegisterClass *RRC = nullptr;
1070   uint8_t Cost = 1;
1071   switch (VT.SimpleTy) {
1072   default:
1073     return TargetLowering::findRepresentativeClass(TRI, VT);
1074   // Use DPR as representative register class for all floating point
1075   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1076   // the cost is 1 for both f32 and f64.
1077   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1078   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1079     RRC = &ARM::DPRRegClass;
1080     // When NEON is used for SP, only half of the register file is available
1081     // because operations that define both SP and DP results will be constrained
1082     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1083     // coalescing by double-counting the SP regs. See the FIXME above.
1084     if (Subtarget->useNEONForSinglePrecisionFP())
1085       Cost = 2;
1086     break;
1087   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1088   case MVT::v4f32: case MVT::v2f64:
1089     RRC = &ARM::DPRRegClass;
1090     Cost = 2;
1091     break;
1092   case MVT::v4i64:
1093     RRC = &ARM::DPRRegClass;
1094     Cost = 4;
1095     break;
1096   case MVT::v8i64:
1097     RRC = &ARM::DPRRegClass;
1098     Cost = 8;
1099     break;
1100   }
1101   return std::make_pair(RRC, Cost);
1102 }
1103 
1104 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1105   switch ((ARMISD::NodeType)Opcode) {
1106   case ARMISD::FIRST_NUMBER:  break;
1107   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1108   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1109   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1110   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1111   case ARMISD::CALL:          return "ARMISD::CALL";
1112   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1113   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1114   case ARMISD::tCALL:         return "ARMISD::tCALL";
1115   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1116   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1117   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1118   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1119   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1120   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1121   case ARMISD::CMP:           return "ARMISD::CMP";
1122   case ARMISD::CMN:           return "ARMISD::CMN";
1123   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1124   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1125   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1126   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1127   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1128 
1129   case ARMISD::CMOV:          return "ARMISD::CMOV";
1130 
1131   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1132   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1133   case ARMISD::RRX:           return "ARMISD::RRX";
1134 
1135   case ARMISD::ADDC:          return "ARMISD::ADDC";
1136   case ARMISD::ADDE:          return "ARMISD::ADDE";
1137   case ARMISD::SUBC:          return "ARMISD::SUBC";
1138   case ARMISD::SUBE:          return "ARMISD::SUBE";
1139 
1140   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1141   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1142 
1143   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1144   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1145   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1146 
1147   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1148 
1149   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1150 
1151   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1152 
1153   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1154 
1155   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1156 
1157   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1158   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1159 
1160   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1161   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1162   case ARMISD::VCGE:          return "ARMISD::VCGE";
1163   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1164   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1165   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1166   case ARMISD::VCGT:          return "ARMISD::VCGT";
1167   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1168   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1169   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1170   case ARMISD::VTST:          return "ARMISD::VTST";
1171 
1172   case ARMISD::VSHL:          return "ARMISD::VSHL";
1173   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1174   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1175   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1176   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1177   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1178   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1179   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1180   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1181   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1182   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1183   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1184   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1185   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1186   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1187   case ARMISD::VSLI:          return "ARMISD::VSLI";
1188   case ARMISD::VSRI:          return "ARMISD::VSRI";
1189   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1190   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1191   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1192   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1193   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1194   case ARMISD::VDUP:          return "ARMISD::VDUP";
1195   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1196   case ARMISD::VEXT:          return "ARMISD::VEXT";
1197   case ARMISD::VREV64:        return "ARMISD::VREV64";
1198   case ARMISD::VREV32:        return "ARMISD::VREV32";
1199   case ARMISD::VREV16:        return "ARMISD::VREV16";
1200   case ARMISD::VZIP:          return "ARMISD::VZIP";
1201   case ARMISD::VUZP:          return "ARMISD::VUZP";
1202   case ARMISD::VTRN:          return "ARMISD::VTRN";
1203   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1204   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1205   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1206   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1207   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1208   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1209   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1210   case ARMISD::BFI:           return "ARMISD::BFI";
1211   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1212   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1213   case ARMISD::VBSL:          return "ARMISD::VBSL";
1214   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1215   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1216   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1217   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1218   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1219   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1220   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1221   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1222   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1223   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1224   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1225   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1226   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1227   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1228   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1229   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1230   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1231   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1232   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1233   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1234   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1235   }
1236   return nullptr;
1237 }
1238 
1239 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1240                                           EVT VT) const {
1241   if (!VT.isVector())
1242     return getPointerTy(DL);
1243   return VT.changeVectorElementTypeToInteger();
1244 }
1245 
1246 /// getRegClassFor - Return the register class that should be used for the
1247 /// specified value type.
1248 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1249   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1250   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1251   // load / store 4 to 8 consecutive D registers.
1252   if (Subtarget->hasNEON()) {
1253     if (VT == MVT::v4i64)
1254       return &ARM::QQPRRegClass;
1255     if (VT == MVT::v8i64)
1256       return &ARM::QQQQPRRegClass;
1257   }
1258   return TargetLowering::getRegClassFor(VT);
1259 }
1260 
1261 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1262 // source/dest is aligned and the copy size is large enough. We therefore want
1263 // to align such objects passed to memory intrinsics.
1264 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1265                                                unsigned &PrefAlign) const {
1266   if (!isa<MemIntrinsic>(CI))
1267     return false;
1268   MinSize = 8;
1269   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1270   // cycle faster than 4-byte aligned LDM.
1271   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1272   return true;
1273 }
1274 
1275 // Create a fast isel object.
1276 FastISel *
1277 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1278                                   const TargetLibraryInfo *libInfo) const {
1279   return ARM::createFastISel(funcInfo, libInfo);
1280 }
1281 
1282 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1283   unsigned NumVals = N->getNumValues();
1284   if (!NumVals)
1285     return Sched::RegPressure;
1286 
1287   for (unsigned i = 0; i != NumVals; ++i) {
1288     EVT VT = N->getValueType(i);
1289     if (VT == MVT::Glue || VT == MVT::Other)
1290       continue;
1291     if (VT.isFloatingPoint() || VT.isVector())
1292       return Sched::ILP;
1293   }
1294 
1295   if (!N->isMachineOpcode())
1296     return Sched::RegPressure;
1297 
1298   // Load are scheduled for latency even if there instruction itinerary
1299   // is not available.
1300   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1301   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1302 
1303   if (MCID.getNumDefs() == 0)
1304     return Sched::RegPressure;
1305   if (!Itins->isEmpty() &&
1306       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1307     return Sched::ILP;
1308 
1309   return Sched::RegPressure;
1310 }
1311 
1312 //===----------------------------------------------------------------------===//
1313 // Lowering Code
1314 //===----------------------------------------------------------------------===//
1315 
1316 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1317 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1318   switch (CC) {
1319   default: llvm_unreachable("Unknown condition code!");
1320   case ISD::SETNE:  return ARMCC::NE;
1321   case ISD::SETEQ:  return ARMCC::EQ;
1322   case ISD::SETGT:  return ARMCC::GT;
1323   case ISD::SETGE:  return ARMCC::GE;
1324   case ISD::SETLT:  return ARMCC::LT;
1325   case ISD::SETLE:  return ARMCC::LE;
1326   case ISD::SETUGT: return ARMCC::HI;
1327   case ISD::SETUGE: return ARMCC::HS;
1328   case ISD::SETULT: return ARMCC::LO;
1329   case ISD::SETULE: return ARMCC::LS;
1330   }
1331 }
1332 
1333 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1334 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1335                         ARMCC::CondCodes &CondCode2) {
1336   CondCode2 = ARMCC::AL;
1337   switch (CC) {
1338   default: llvm_unreachable("Unknown FP condition!");
1339   case ISD::SETEQ:
1340   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1341   case ISD::SETGT:
1342   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1343   case ISD::SETGE:
1344   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1345   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1346   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1347   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1348   case ISD::SETO:   CondCode = ARMCC::VC; break;
1349   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1350   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1351   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1352   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1353   case ISD::SETLT:
1354   case ISD::SETULT: CondCode = ARMCC::LT; break;
1355   case ISD::SETLE:
1356   case ISD::SETULE: CondCode = ARMCC::LE; break;
1357   case ISD::SETNE:
1358   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1359   }
1360 }
1361 
1362 //===----------------------------------------------------------------------===//
1363 //                      Calling Convention Implementation
1364 //===----------------------------------------------------------------------===//
1365 
1366 #include "ARMGenCallingConv.inc"
1367 
1368 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1369 /// account presence of floating point hardware and calling convention
1370 /// limitations, such as support for variadic functions.
1371 CallingConv::ID
1372 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1373                                            bool isVarArg) const {
1374   switch (CC) {
1375   default:
1376     llvm_unreachable("Unsupported calling convention");
1377   case CallingConv::ARM_AAPCS:
1378   case CallingConv::ARM_APCS:
1379   case CallingConv::GHC:
1380     return CC;
1381   case CallingConv::ARM_AAPCS_VFP:
1382     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1383   case CallingConv::C:
1384     if (!Subtarget->isAAPCS_ABI())
1385       return CallingConv::ARM_APCS;
1386     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1387              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1388              !isVarArg)
1389       return CallingConv::ARM_AAPCS_VFP;
1390     else
1391       return CallingConv::ARM_AAPCS;
1392   case CallingConv::Fast:
1393   case CallingConv::CXX_FAST_TLS:
1394     if (!Subtarget->isAAPCS_ABI()) {
1395       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1396         return CallingConv::Fast;
1397       return CallingConv::ARM_APCS;
1398     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1399       return CallingConv::ARM_AAPCS_VFP;
1400     else
1401       return CallingConv::ARM_AAPCS;
1402   }
1403 }
1404 
1405 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1406 /// CallingConvention.
1407 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1408                                                  bool Return,
1409                                                  bool isVarArg) const {
1410   switch (getEffectiveCallingConv(CC, isVarArg)) {
1411   default:
1412     llvm_unreachable("Unsupported calling convention");
1413   case CallingConv::ARM_APCS:
1414     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1415   case CallingConv::ARM_AAPCS:
1416     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1417   case CallingConv::ARM_AAPCS_VFP:
1418     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1419   case CallingConv::Fast:
1420     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1421   case CallingConv::GHC:
1422     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1423   }
1424 }
1425 
1426 /// LowerCallResult - Lower the result values of a call into the
1427 /// appropriate copies out of appropriate physical registers.
1428 SDValue
1429 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1430                                    CallingConv::ID CallConv, bool isVarArg,
1431                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1432                                    SDLoc dl, SelectionDAG &DAG,
1433                                    SmallVectorImpl<SDValue> &InVals,
1434                                    bool isThisReturn, SDValue ThisVal) const {
1435 
1436   // Assign locations to each value returned by this call.
1437   SmallVector<CCValAssign, 16> RVLocs;
1438   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1439                     *DAG.getContext(), Call);
1440   CCInfo.AnalyzeCallResult(Ins,
1441                            CCAssignFnForNode(CallConv, /* Return*/ true,
1442                                              isVarArg));
1443 
1444   // Copy all of the result registers out of their specified physreg.
1445   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1446     CCValAssign VA = RVLocs[i];
1447 
1448     // Pass 'this' value directly from the argument to return value, to avoid
1449     // reg unit interference
1450     if (i == 0 && isThisReturn) {
1451       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1452              "unexpected return calling convention register assignment");
1453       InVals.push_back(ThisVal);
1454       continue;
1455     }
1456 
1457     SDValue Val;
1458     if (VA.needsCustom()) {
1459       // Handle f64 or half of a v2f64.
1460       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1461                                       InFlag);
1462       Chain = Lo.getValue(1);
1463       InFlag = Lo.getValue(2);
1464       VA = RVLocs[++i]; // skip ahead to next loc
1465       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1466                                       InFlag);
1467       Chain = Hi.getValue(1);
1468       InFlag = Hi.getValue(2);
1469       if (!Subtarget->isLittle())
1470         std::swap (Lo, Hi);
1471       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1472 
1473       if (VA.getLocVT() == MVT::v2f64) {
1474         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1475         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1476                           DAG.getConstant(0, dl, MVT::i32));
1477 
1478         VA = RVLocs[++i]; // skip ahead to next loc
1479         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1480         Chain = Lo.getValue(1);
1481         InFlag = Lo.getValue(2);
1482         VA = RVLocs[++i]; // skip ahead to next loc
1483         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1484         Chain = Hi.getValue(1);
1485         InFlag = Hi.getValue(2);
1486         if (!Subtarget->isLittle())
1487           std::swap (Lo, Hi);
1488         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1489         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1490                           DAG.getConstant(1, dl, MVT::i32));
1491       }
1492     } else {
1493       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1494                                InFlag);
1495       Chain = Val.getValue(1);
1496       InFlag = Val.getValue(2);
1497     }
1498 
1499     switch (VA.getLocInfo()) {
1500     default: llvm_unreachable("Unknown loc info!");
1501     case CCValAssign::Full: break;
1502     case CCValAssign::BCvt:
1503       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1504       break;
1505     }
1506 
1507     InVals.push_back(Val);
1508   }
1509 
1510   return Chain;
1511 }
1512 
1513 /// LowerMemOpCallTo - Store the argument to the stack.
1514 SDValue
1515 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1516                                     SDValue StackPtr, SDValue Arg,
1517                                     SDLoc dl, SelectionDAG &DAG,
1518                                     const CCValAssign &VA,
1519                                     ISD::ArgFlagsTy Flags) const {
1520   unsigned LocMemOffset = VA.getLocMemOffset();
1521   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1522   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1523                        StackPtr, PtrOff);
1524   return DAG.getStore(
1525       Chain, dl, Arg, PtrOff,
1526       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1527       false, false, 0);
1528 }
1529 
1530 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1531                                          SDValue Chain, SDValue &Arg,
1532                                          RegsToPassVector &RegsToPass,
1533                                          CCValAssign &VA, CCValAssign &NextVA,
1534                                          SDValue &StackPtr,
1535                                          SmallVectorImpl<SDValue> &MemOpChains,
1536                                          ISD::ArgFlagsTy Flags) const {
1537 
1538   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1539                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1540   unsigned id = Subtarget->isLittle() ? 0 : 1;
1541   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1542 
1543   if (NextVA.isRegLoc())
1544     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1545   else {
1546     assert(NextVA.isMemLoc());
1547     if (!StackPtr.getNode())
1548       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1549                                     getPointerTy(DAG.getDataLayout()));
1550 
1551     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1552                                            dl, DAG, NextVA,
1553                                            Flags));
1554   }
1555 }
1556 
1557 /// LowerCall - Lowering a call into a callseq_start <-
1558 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1559 /// nodes.
1560 SDValue
1561 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1562                              SmallVectorImpl<SDValue> &InVals) const {
1563   SelectionDAG &DAG                     = CLI.DAG;
1564   SDLoc &dl                             = CLI.DL;
1565   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1566   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1567   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1568   SDValue Chain                         = CLI.Chain;
1569   SDValue Callee                        = CLI.Callee;
1570   bool &isTailCall                      = CLI.IsTailCall;
1571   CallingConv::ID CallConv              = CLI.CallConv;
1572   bool doesNotRet                       = CLI.DoesNotReturn;
1573   bool isVarArg                         = CLI.IsVarArg;
1574 
1575   MachineFunction &MF = DAG.getMachineFunction();
1576   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1577   bool isThisReturn   = false;
1578   bool isSibCall      = false;
1579   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1580 
1581   // Disable tail calls if they're not supported.
1582   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1583     isTailCall = false;
1584 
1585   if (isTailCall) {
1586     // Check if it's really possible to do a tail call.
1587     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1588                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1589                                                    Outs, OutVals, Ins, DAG);
1590     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1591       report_fatal_error("failed to perform tail call elimination on a call "
1592                          "site marked musttail");
1593     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1594     // detected sibcalls.
1595     if (isTailCall) {
1596       ++NumTailCalls;
1597       isSibCall = true;
1598     }
1599   }
1600 
1601   // Analyze operands of the call, assigning locations to each operand.
1602   SmallVector<CCValAssign, 16> ArgLocs;
1603   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1604                     *DAG.getContext(), Call);
1605   CCInfo.AnalyzeCallOperands(Outs,
1606                              CCAssignFnForNode(CallConv, /* Return*/ false,
1607                                                isVarArg));
1608 
1609   // Get a count of how many bytes are to be pushed on the stack.
1610   unsigned NumBytes = CCInfo.getNextStackOffset();
1611 
1612   // For tail calls, memory operands are available in our caller's stack.
1613   if (isSibCall)
1614     NumBytes = 0;
1615 
1616   // Adjust the stack pointer for the new arguments...
1617   // These operations are automatically eliminated by the prolog/epilog pass
1618   if (!isSibCall)
1619     Chain = DAG.getCALLSEQ_START(Chain,
1620                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1621 
1622   SDValue StackPtr =
1623       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1624 
1625   RegsToPassVector RegsToPass;
1626   SmallVector<SDValue, 8> MemOpChains;
1627 
1628   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1629   // of tail call optimization, arguments are handled later.
1630   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1631        i != e;
1632        ++i, ++realArgIdx) {
1633     CCValAssign &VA = ArgLocs[i];
1634     SDValue Arg = OutVals[realArgIdx];
1635     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1636     bool isByVal = Flags.isByVal();
1637 
1638     // Promote the value if needed.
1639     switch (VA.getLocInfo()) {
1640     default: llvm_unreachable("Unknown loc info!");
1641     case CCValAssign::Full: break;
1642     case CCValAssign::SExt:
1643       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1644       break;
1645     case CCValAssign::ZExt:
1646       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1647       break;
1648     case CCValAssign::AExt:
1649       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1650       break;
1651     case CCValAssign::BCvt:
1652       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1653       break;
1654     }
1655 
1656     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1657     if (VA.needsCustom()) {
1658       if (VA.getLocVT() == MVT::v2f64) {
1659         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1660                                   DAG.getConstant(0, dl, MVT::i32));
1661         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1662                                   DAG.getConstant(1, dl, MVT::i32));
1663 
1664         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1665                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1666 
1667         VA = ArgLocs[++i]; // skip ahead to next loc
1668         if (VA.isRegLoc()) {
1669           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1670                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1671         } else {
1672           assert(VA.isMemLoc());
1673 
1674           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1675                                                  dl, DAG, VA, Flags));
1676         }
1677       } else {
1678         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1679                          StackPtr, MemOpChains, Flags);
1680       }
1681     } else if (VA.isRegLoc()) {
1682       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1683         assert(VA.getLocVT() == MVT::i32 &&
1684                "unexpected calling convention register assignment");
1685         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1686                "unexpected use of 'returned'");
1687         isThisReturn = true;
1688       }
1689       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1690     } else if (isByVal) {
1691       assert(VA.isMemLoc());
1692       unsigned offset = 0;
1693 
1694       // True if this byval aggregate will be split between registers
1695       // and memory.
1696       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1697       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1698 
1699       if (CurByValIdx < ByValArgsCount) {
1700 
1701         unsigned RegBegin, RegEnd;
1702         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1703 
1704         EVT PtrVT =
1705             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1706         unsigned int i, j;
1707         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1708           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1709           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1710           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1711                                      MachinePointerInfo(),
1712                                      false, false, false,
1713                                      DAG.InferPtrAlignment(AddArg));
1714           MemOpChains.push_back(Load.getValue(1));
1715           RegsToPass.push_back(std::make_pair(j, Load));
1716         }
1717 
1718         // If parameter size outsides register area, "offset" value
1719         // helps us to calculate stack slot for remained part properly.
1720         offset = RegEnd - RegBegin;
1721 
1722         CCInfo.nextInRegsParam();
1723       }
1724 
1725       if (Flags.getByValSize() > 4*offset) {
1726         auto PtrVT = getPointerTy(DAG.getDataLayout());
1727         unsigned LocMemOffset = VA.getLocMemOffset();
1728         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1729         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1730         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1731         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1732         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1733                                            MVT::i32);
1734         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1735                                             MVT::i32);
1736 
1737         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1738         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1739         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1740                                           Ops));
1741       }
1742     } else if (!isSibCall) {
1743       assert(VA.isMemLoc());
1744 
1745       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1746                                              dl, DAG, VA, Flags));
1747     }
1748   }
1749 
1750   if (!MemOpChains.empty())
1751     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1752 
1753   // Build a sequence of copy-to-reg nodes chained together with token chain
1754   // and flag operands which copy the outgoing args into the appropriate regs.
1755   SDValue InFlag;
1756   // Tail call byval lowering might overwrite argument registers so in case of
1757   // tail call optimization the copies to registers are lowered later.
1758   if (!isTailCall)
1759     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1760       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1761                                RegsToPass[i].second, InFlag);
1762       InFlag = Chain.getValue(1);
1763     }
1764 
1765   // For tail calls lower the arguments to the 'real' stack slot.
1766   if (isTailCall) {
1767     // Force all the incoming stack arguments to be loaded from the stack
1768     // before any new outgoing arguments are stored to the stack, because the
1769     // outgoing stack slots may alias the incoming argument stack slots, and
1770     // the alias isn't otherwise explicit. This is slightly more conservative
1771     // than necessary, because it means that each store effectively depends
1772     // on every argument instead of just those arguments it would clobber.
1773 
1774     // Do not flag preceding copytoreg stuff together with the following stuff.
1775     InFlag = SDValue();
1776     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1777       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1778                                RegsToPass[i].second, InFlag);
1779       InFlag = Chain.getValue(1);
1780     }
1781     InFlag = SDValue();
1782   }
1783 
1784   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1785   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1786   // node so that legalize doesn't hack it.
1787   bool isDirect = false;
1788   bool isARMFunc = false;
1789   bool isLocalARMFunc = false;
1790   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1791   auto PtrVt = getPointerTy(DAG.getDataLayout());
1792 
1793   if (Subtarget->genLongCalls()) {
1794     assert((Subtarget->isTargetWindows() ||
1795             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1796            "long-calls with non-static relocation model!");
1797     // Handle a global address or an external symbol. If it's not one of
1798     // those, the target's already in a register, so we don't need to do
1799     // anything extra.
1800     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1801       const GlobalValue *GV = G->getGlobal();
1802       // Create a constant pool entry for the callee address
1803       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1804       ARMConstantPoolValue *CPV =
1805         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1806 
1807       // Get the address of the callee into a register
1808       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1809       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1810       Callee = DAG.getLoad(
1811           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1812           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1813           false, false, 0);
1814     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1815       const char *Sym = S->getSymbol();
1816 
1817       // Create a constant pool entry for the callee address
1818       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1819       ARMConstantPoolValue *CPV =
1820         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1821                                       ARMPCLabelIndex, 0);
1822       // Get the address of the callee into a register
1823       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1824       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1825       Callee = DAG.getLoad(
1826           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1827           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1828           false, false, 0);
1829     }
1830   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1831     const GlobalValue *GV = G->getGlobal();
1832     isDirect = true;
1833     bool isDef = GV->isStrongDefinitionForLinker();
1834     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1835                    getTargetMachine().getRelocationModel() != Reloc::Static;
1836     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1837     // ARM call to a local ARM function is predicable.
1838     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1839     // tBX takes a register source operand.
1840     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1841       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1842       Callee = DAG.getNode(
1843           ARMISD::WrapperPIC, dl, PtrVt,
1844           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1845       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1846                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1847                            false, false, true, 0);
1848     } else if (Subtarget->isTargetCOFF()) {
1849       assert(Subtarget->isTargetWindows() &&
1850              "Windows is the only supported COFF target");
1851       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1852                                  ? ARMII::MO_DLLIMPORT
1853                                  : ARMII::MO_NO_FLAG;
1854       Callee =
1855           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1856       if (GV->hasDLLImportStorageClass())
1857         Callee =
1858             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1859                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1860                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1861                         false, false, false, 0);
1862     } else {
1863       // On ELF targets for PIC code, direct calls should go through the PLT
1864       unsigned OpFlags = 0;
1865       if (Subtarget->isTargetELF() &&
1866           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1867         OpFlags = ARMII::MO_PLT;
1868       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1869     }
1870   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1871     isDirect = true;
1872     bool isStub = Subtarget->isTargetMachO() &&
1873                   getTargetMachine().getRelocationModel() != Reloc::Static;
1874     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1875     // tBX takes a register source operand.
1876     const char *Sym = S->getSymbol();
1877     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1878       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1879       ARMConstantPoolValue *CPV =
1880         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1881                                       ARMPCLabelIndex, 4);
1882       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1883       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1884       Callee = DAG.getLoad(
1885           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1886           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1887           false, false, 0);
1888       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1889       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1890     } else {
1891       unsigned OpFlags = 0;
1892       // On ELF targets for PIC code, direct calls should go through the PLT
1893       if (Subtarget->isTargetELF() &&
1894                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1895         OpFlags = ARMII::MO_PLT;
1896       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1897     }
1898   }
1899 
1900   // FIXME: handle tail calls differently.
1901   unsigned CallOpc;
1902   if (Subtarget->isThumb()) {
1903     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1904       CallOpc = ARMISD::CALL_NOLINK;
1905     else
1906       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1907   } else {
1908     if (!isDirect && !Subtarget->hasV5TOps())
1909       CallOpc = ARMISD::CALL_NOLINK;
1910     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1911              // Emit regular call when code size is the priority
1912              !MF.getFunction()->optForMinSize())
1913       // "mov lr, pc; b _foo" to avoid confusing the RSP
1914       CallOpc = ARMISD::CALL_NOLINK;
1915     else
1916       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1917   }
1918 
1919   std::vector<SDValue> Ops;
1920   Ops.push_back(Chain);
1921   Ops.push_back(Callee);
1922 
1923   // Add argument registers to the end of the list so that they are known live
1924   // into the call.
1925   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1926     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1927                                   RegsToPass[i].second.getValueType()));
1928 
1929   // Add a register mask operand representing the call-preserved registers.
1930   if (!isTailCall) {
1931     const uint32_t *Mask;
1932     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1933     if (isThisReturn) {
1934       // For 'this' returns, use the R0-preserving mask if applicable
1935       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1936       if (!Mask) {
1937         // Set isThisReturn to false if the calling convention is not one that
1938         // allows 'returned' to be modeled in this way, so LowerCallResult does
1939         // not try to pass 'this' straight through
1940         isThisReturn = false;
1941         Mask = ARI->getCallPreservedMask(MF, CallConv);
1942       }
1943     } else
1944       Mask = ARI->getCallPreservedMask(MF, CallConv);
1945 
1946     assert(Mask && "Missing call preserved mask for calling convention");
1947     Ops.push_back(DAG.getRegisterMask(Mask));
1948   }
1949 
1950   if (InFlag.getNode())
1951     Ops.push_back(InFlag);
1952 
1953   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1954   if (isTailCall) {
1955     MF.getFrameInfo()->setHasTailCall();
1956     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1957   }
1958 
1959   // Returns a chain and a flag for retval copy to use.
1960   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1961   InFlag = Chain.getValue(1);
1962 
1963   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1964                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1965   if (!Ins.empty())
1966     InFlag = Chain.getValue(1);
1967 
1968   // Handle result values, copying them out of physregs into vregs that we
1969   // return.
1970   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1971                          InVals, isThisReturn,
1972                          isThisReturn ? OutVals[0] : SDValue());
1973 }
1974 
1975 /// HandleByVal - Every parameter *after* a byval parameter is passed
1976 /// on the stack.  Remember the next parameter register to allocate,
1977 /// and then confiscate the rest of the parameter registers to insure
1978 /// this.
1979 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1980                                     unsigned Align) const {
1981   assert((State->getCallOrPrologue() == Prologue ||
1982           State->getCallOrPrologue() == Call) &&
1983          "unhandled ParmContext");
1984 
1985   // Byval (as with any stack) slots are always at least 4 byte aligned.
1986   Align = std::max(Align, 4U);
1987 
1988   unsigned Reg = State->AllocateReg(GPRArgRegs);
1989   if (!Reg)
1990     return;
1991 
1992   unsigned AlignInRegs = Align / 4;
1993   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1994   for (unsigned i = 0; i < Waste; ++i)
1995     Reg = State->AllocateReg(GPRArgRegs);
1996 
1997   if (!Reg)
1998     return;
1999 
2000   unsigned Excess = 4 * (ARM::R4 - Reg);
2001 
2002   // Special case when NSAA != SP and parameter size greater than size of
2003   // all remained GPR regs. In that case we can't split parameter, we must
2004   // send it to stack. We also must set NCRN to R4, so waste all
2005   // remained registers.
2006   const unsigned NSAAOffset = State->getNextStackOffset();
2007   if (NSAAOffset != 0 && Size > Excess) {
2008     while (State->AllocateReg(GPRArgRegs))
2009       ;
2010     return;
2011   }
2012 
2013   // First register for byval parameter is the first register that wasn't
2014   // allocated before this method call, so it would be "reg".
2015   // If parameter is small enough to be saved in range [reg, r4), then
2016   // the end (first after last) register would be reg + param-size-in-regs,
2017   // else parameter would be splitted between registers and stack,
2018   // end register would be r4 in this case.
2019   unsigned ByValRegBegin = Reg;
2020   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2021   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2022   // Note, first register is allocated in the beginning of function already,
2023   // allocate remained amount of registers we need.
2024   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2025     State->AllocateReg(GPRArgRegs);
2026   // A byval parameter that is split between registers and memory needs its
2027   // size truncated here.
2028   // In the case where the entire structure fits in registers, we set the
2029   // size in memory to zero.
2030   Size = std::max<int>(Size - Excess, 0);
2031 }
2032 
2033 /// MatchingStackOffset - Return true if the given stack call argument is
2034 /// already available in the same position (relatively) of the caller's
2035 /// incoming argument stack.
2036 static
2037 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2038                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2039                          const TargetInstrInfo *TII) {
2040   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2041   int FI = INT_MAX;
2042   if (Arg.getOpcode() == ISD::CopyFromReg) {
2043     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2044     if (!TargetRegisterInfo::isVirtualRegister(VR))
2045       return false;
2046     MachineInstr *Def = MRI->getVRegDef(VR);
2047     if (!Def)
2048       return false;
2049     if (!Flags.isByVal()) {
2050       if (!TII->isLoadFromStackSlot(Def, FI))
2051         return false;
2052     } else {
2053       return false;
2054     }
2055   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2056     if (Flags.isByVal())
2057       // ByVal argument is passed in as a pointer but it's now being
2058       // dereferenced. e.g.
2059       // define @foo(%struct.X* %A) {
2060       //   tail call @bar(%struct.X* byval %A)
2061       // }
2062       return false;
2063     SDValue Ptr = Ld->getBasePtr();
2064     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2065     if (!FINode)
2066       return false;
2067     FI = FINode->getIndex();
2068   } else
2069     return false;
2070 
2071   assert(FI != INT_MAX);
2072   if (!MFI->isFixedObjectIndex(FI))
2073     return false;
2074   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2075 }
2076 
2077 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2078 /// for tail call optimization. Targets which want to do tail call
2079 /// optimization should implement this function.
2080 bool
2081 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2082                                                      CallingConv::ID CalleeCC,
2083                                                      bool isVarArg,
2084                                                      bool isCalleeStructRet,
2085                                                      bool isCallerStructRet,
2086                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2087                                     const SmallVectorImpl<SDValue> &OutVals,
2088                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2089                                                      SelectionDAG& DAG) const {
2090   const Function *CallerF = DAG.getMachineFunction().getFunction();
2091   CallingConv::ID CallerCC = CallerF->getCallingConv();
2092   bool CCMatch = CallerCC == CalleeCC;
2093 
2094   assert(Subtarget->supportsTailCall());
2095 
2096   // Look for obvious safe cases to perform tail call optimization that do not
2097   // require ABI changes. This is what gcc calls sibcall.
2098 
2099   // Do not sibcall optimize vararg calls unless the call site is not passing
2100   // any arguments.
2101   if (isVarArg && !Outs.empty())
2102     return false;
2103 
2104   // Exception-handling functions need a special set of instructions to indicate
2105   // a return to the hardware. Tail-calling another function would probably
2106   // break this.
2107   if (CallerF->hasFnAttribute("interrupt"))
2108     return false;
2109 
2110   // Also avoid sibcall optimization if either caller or callee uses struct
2111   // return semantics.
2112   if (isCalleeStructRet || isCallerStructRet)
2113     return false;
2114 
2115   // Externally-defined functions with weak linkage should not be
2116   // tail-called on ARM when the OS does not support dynamic
2117   // pre-emption of symbols, as the AAELF spec requires normal calls
2118   // to undefined weak functions to be replaced with a NOP or jump to the
2119   // next instruction. The behaviour of branch instructions in this
2120   // situation (as used for tail calls) is implementation-defined, so we
2121   // cannot rely on the linker replacing the tail call with a return.
2122   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2123     const GlobalValue *GV = G->getGlobal();
2124     const Triple &TT = getTargetMachine().getTargetTriple();
2125     if (GV->hasExternalWeakLinkage() &&
2126         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2127       return false;
2128   }
2129 
2130   // If the calling conventions do not match, then we'd better make sure the
2131   // results are returned in the same way as what the caller expects.
2132   if (!CCMatch) {
2133     SmallVector<CCValAssign, 16> RVLocs1;
2134     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2135                        *DAG.getContext(), Call);
2136     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2137 
2138     SmallVector<CCValAssign, 16> RVLocs2;
2139     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2140                        *DAG.getContext(), Call);
2141     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2142 
2143     if (RVLocs1.size() != RVLocs2.size())
2144       return false;
2145     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2146       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2147         return false;
2148       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2149         return false;
2150       if (RVLocs1[i].isRegLoc()) {
2151         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2152           return false;
2153       } else {
2154         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2155           return false;
2156       }
2157     }
2158   }
2159 
2160   // If Caller's vararg or byval argument has been split between registers and
2161   // stack, do not perform tail call, since part of the argument is in caller's
2162   // local frame.
2163   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2164                                       getInfo<ARMFunctionInfo>();
2165   if (AFI_Caller->getArgRegsSaveSize())
2166     return false;
2167 
2168   // If the callee takes no arguments then go on to check the results of the
2169   // call.
2170   if (!Outs.empty()) {
2171     // Check if stack adjustment is needed. For now, do not do this if any
2172     // argument is passed on the stack.
2173     SmallVector<CCValAssign, 16> ArgLocs;
2174     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2175                       *DAG.getContext(), Call);
2176     CCInfo.AnalyzeCallOperands(Outs,
2177                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2178     if (CCInfo.getNextStackOffset()) {
2179       MachineFunction &MF = DAG.getMachineFunction();
2180 
2181       // Check if the arguments are already laid out in the right way as
2182       // the caller's fixed stack objects.
2183       MachineFrameInfo *MFI = MF.getFrameInfo();
2184       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2185       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2186       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2187            i != e;
2188            ++i, ++realArgIdx) {
2189         CCValAssign &VA = ArgLocs[i];
2190         EVT RegVT = VA.getLocVT();
2191         SDValue Arg = OutVals[realArgIdx];
2192         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2193         if (VA.getLocInfo() == CCValAssign::Indirect)
2194           return false;
2195         if (VA.needsCustom()) {
2196           // f64 and vector types are split into multiple registers or
2197           // register/stack-slot combinations.  The types will not match
2198           // the registers; give up on memory f64 refs until we figure
2199           // out what to do about this.
2200           if (!VA.isRegLoc())
2201             return false;
2202           if (!ArgLocs[++i].isRegLoc())
2203             return false;
2204           if (RegVT == MVT::v2f64) {
2205             if (!ArgLocs[++i].isRegLoc())
2206               return false;
2207             if (!ArgLocs[++i].isRegLoc())
2208               return false;
2209           }
2210         } else if (!VA.isRegLoc()) {
2211           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2212                                    MFI, MRI, TII))
2213             return false;
2214         }
2215       }
2216     }
2217   }
2218 
2219   return true;
2220 }
2221 
2222 bool
2223 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2224                                   MachineFunction &MF, bool isVarArg,
2225                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2226                                   LLVMContext &Context) const {
2227   SmallVector<CCValAssign, 16> RVLocs;
2228   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2229   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2230                                                     isVarArg));
2231 }
2232 
2233 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2234                                     SDLoc DL, SelectionDAG &DAG) {
2235   const MachineFunction &MF = DAG.getMachineFunction();
2236   const Function *F = MF.getFunction();
2237 
2238   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2239 
2240   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2241   // version of the "preferred return address". These offsets affect the return
2242   // instruction if this is a return from PL1 without hypervisor extensions.
2243   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2244   //    SWI:     0      "subs pc, lr, #0"
2245   //    ABORT:   +4     "subs pc, lr, #4"
2246   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2247   // UNDEF varies depending on where the exception came from ARM or Thumb
2248   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2249 
2250   int64_t LROffset;
2251   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2252       IntKind == "ABORT")
2253     LROffset = 4;
2254   else if (IntKind == "SWI" || IntKind == "UNDEF")
2255     LROffset = 0;
2256   else
2257     report_fatal_error("Unsupported interrupt attribute. If present, value "
2258                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2259 
2260   RetOps.insert(RetOps.begin() + 1,
2261                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2262 
2263   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2264 }
2265 
2266 SDValue
2267 ARMTargetLowering::LowerReturn(SDValue Chain,
2268                                CallingConv::ID CallConv, bool isVarArg,
2269                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2270                                const SmallVectorImpl<SDValue> &OutVals,
2271                                SDLoc dl, SelectionDAG &DAG) const {
2272 
2273   // CCValAssign - represent the assignment of the return value to a location.
2274   SmallVector<CCValAssign, 16> RVLocs;
2275 
2276   // CCState - Info about the registers and stack slots.
2277   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2278                     *DAG.getContext(), Call);
2279 
2280   // Analyze outgoing return values.
2281   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2282                                                isVarArg));
2283 
2284   SDValue Flag;
2285   SmallVector<SDValue, 4> RetOps;
2286   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2287   bool isLittleEndian = Subtarget->isLittle();
2288 
2289   MachineFunction &MF = DAG.getMachineFunction();
2290   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2291   AFI->setReturnRegsCount(RVLocs.size());
2292 
2293   // Copy the result values into the output registers.
2294   for (unsigned i = 0, realRVLocIdx = 0;
2295        i != RVLocs.size();
2296        ++i, ++realRVLocIdx) {
2297     CCValAssign &VA = RVLocs[i];
2298     assert(VA.isRegLoc() && "Can only return in registers!");
2299 
2300     SDValue Arg = OutVals[realRVLocIdx];
2301 
2302     switch (VA.getLocInfo()) {
2303     default: llvm_unreachable("Unknown loc info!");
2304     case CCValAssign::Full: break;
2305     case CCValAssign::BCvt:
2306       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2307       break;
2308     }
2309 
2310     if (VA.needsCustom()) {
2311       if (VA.getLocVT() == MVT::v2f64) {
2312         // Extract the first half and return it in two registers.
2313         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2314                                    DAG.getConstant(0, dl, MVT::i32));
2315         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2316                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2317 
2318         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2319                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
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         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2325                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2326                                  Flag);
2327         Flag = Chain.getValue(1);
2328         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2329         VA = RVLocs[++i]; // skip ahead to next loc
2330 
2331         // Extract the 2nd half and fall through to handle it as an f64 value.
2332         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2333                           DAG.getConstant(1, dl, MVT::i32));
2334       }
2335       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2336       // available.
2337       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2338                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2339       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2340                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2341                                Flag);
2342       Flag = Chain.getValue(1);
2343       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2344       VA = RVLocs[++i]; // skip ahead to next loc
2345       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2346                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2347                                Flag);
2348     } else
2349       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2350 
2351     // Guarantee that all emitted copies are
2352     // stuck together, avoiding something bad.
2353     Flag = Chain.getValue(1);
2354     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2355   }
2356   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2357   const MCPhysReg *I =
2358       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2359   if (I) {
2360     for (; *I; ++I) {
2361       if (ARM::GPRRegClass.contains(*I))
2362         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2363       else if (ARM::DPRRegClass.contains(*I))
2364         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2365       else
2366         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2367     }
2368   }
2369 
2370   // Update chain and glue.
2371   RetOps[0] = Chain;
2372   if (Flag.getNode())
2373     RetOps.push_back(Flag);
2374 
2375   // CPUs which aren't M-class use a special sequence to return from
2376   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2377   // though we use "subs pc, lr, #N").
2378   //
2379   // M-class CPUs actually use a normal return sequence with a special
2380   // (hardware-provided) value in LR, so the normal code path works.
2381   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2382       !Subtarget->isMClass()) {
2383     if (Subtarget->isThumb1Only())
2384       report_fatal_error("interrupt attribute is not supported in Thumb1");
2385     return LowerInterruptReturn(RetOps, dl, DAG);
2386   }
2387 
2388   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2389 }
2390 
2391 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2392   if (N->getNumValues() != 1)
2393     return false;
2394   if (!N->hasNUsesOfValue(1, 0))
2395     return false;
2396 
2397   SDValue TCChain = Chain;
2398   SDNode *Copy = *N->use_begin();
2399   if (Copy->getOpcode() == ISD::CopyToReg) {
2400     // If the copy has a glue operand, we conservatively assume it isn't safe to
2401     // perform a tail call.
2402     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2403       return false;
2404     TCChain = Copy->getOperand(0);
2405   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2406     SDNode *VMov = Copy;
2407     // f64 returned in a pair of GPRs.
2408     SmallPtrSet<SDNode*, 2> Copies;
2409     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2410          UI != UE; ++UI) {
2411       if (UI->getOpcode() != ISD::CopyToReg)
2412         return false;
2413       Copies.insert(*UI);
2414     }
2415     if (Copies.size() > 2)
2416       return false;
2417 
2418     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2419          UI != UE; ++UI) {
2420       SDValue UseChain = UI->getOperand(0);
2421       if (Copies.count(UseChain.getNode()))
2422         // Second CopyToReg
2423         Copy = *UI;
2424       else {
2425         // We are at the top of this chain.
2426         // If the copy has a glue operand, we conservatively assume it
2427         // isn't safe to perform a tail call.
2428         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2429           return false;
2430         // First CopyToReg
2431         TCChain = UseChain;
2432       }
2433     }
2434   } else if (Copy->getOpcode() == ISD::BITCAST) {
2435     // f32 returned in a single GPR.
2436     if (!Copy->hasOneUse())
2437       return false;
2438     Copy = *Copy->use_begin();
2439     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2440       return false;
2441     // If the copy has a glue operand, we conservatively assume it isn't safe to
2442     // perform a tail call.
2443     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2444       return false;
2445     TCChain = Copy->getOperand(0);
2446   } else {
2447     return false;
2448   }
2449 
2450   bool HasRet = false;
2451   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2452        UI != UE; ++UI) {
2453     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2454         UI->getOpcode() != ARMISD::INTRET_FLAG)
2455       return false;
2456     HasRet = true;
2457   }
2458 
2459   if (!HasRet)
2460     return false;
2461 
2462   Chain = TCChain;
2463   return true;
2464 }
2465 
2466 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2467   if (!Subtarget->supportsTailCall())
2468     return false;
2469 
2470   auto Attr =
2471       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2472   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2473     return false;
2474 
2475   return true;
2476 }
2477 
2478 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2479 // and pass the lower and high parts through.
2480 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2481   SDLoc DL(Op);
2482   SDValue WriteValue = Op->getOperand(2);
2483 
2484   // This function is only supposed to be called for i64 type argument.
2485   assert(WriteValue.getValueType() == MVT::i64
2486           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2487 
2488   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2489                            DAG.getConstant(0, DL, MVT::i32));
2490   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2491                            DAG.getConstant(1, DL, MVT::i32));
2492   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2493   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2494 }
2495 
2496 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2497 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2498 // one of the above mentioned nodes. It has to be wrapped because otherwise
2499 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2500 // be used to form addressing mode. These wrapped nodes will be selected
2501 // into MOVi.
2502 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2503   EVT PtrVT = Op.getValueType();
2504   // FIXME there is no actual debug info here
2505   SDLoc dl(Op);
2506   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2507   SDValue Res;
2508   if (CP->isMachineConstantPoolEntry())
2509     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2510                                     CP->getAlignment());
2511   else
2512     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2513                                     CP->getAlignment());
2514   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2515 }
2516 
2517 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2518   return MachineJumpTableInfo::EK_Inline;
2519 }
2520 
2521 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2522                                              SelectionDAG &DAG) const {
2523   MachineFunction &MF = DAG.getMachineFunction();
2524   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2525   unsigned ARMPCLabelIndex = 0;
2526   SDLoc DL(Op);
2527   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2528   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2529   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2530   SDValue CPAddr;
2531   if (RelocM == Reloc::Static) {
2532     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2533   } else {
2534     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2535     ARMPCLabelIndex = AFI->createPICLabelUId();
2536     ARMConstantPoolValue *CPV =
2537       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2538                                       ARMCP::CPBlockAddress, PCAdj);
2539     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2540   }
2541   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2542   SDValue Result =
2543       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2544                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2545                   false, false, false, 0);
2546   if (RelocM == Reloc::Static)
2547     return Result;
2548   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2549   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2550 }
2551 
2552 /// \brief Convert a TLS address reference into the correct sequence of loads
2553 /// and calls to compute the variable's address for Darwin, and return an
2554 /// SDValue containing the final node.
2555 
2556 /// Darwin only has one TLS scheme which must be capable of dealing with the
2557 /// fully general situation, in the worst case. This means:
2558 ///     + "extern __thread" declaration.
2559 ///     + Defined in a possibly unknown dynamic library.
2560 ///
2561 /// The general system is that each __thread variable has a [3 x i32] descriptor
2562 /// which contains information used by the runtime to calculate the address. The
2563 /// only part of this the compiler needs to know about is the first word, which
2564 /// contains a function pointer that must be called with the address of the
2565 /// entire descriptor in "r0".
2566 ///
2567 /// Since this descriptor may be in a different unit, in general access must
2568 /// proceed along the usual ARM rules. A common sequence to produce is:
2569 ///
2570 ///     movw rT1, :lower16:_var$non_lazy_ptr
2571 ///     movt rT1, :upper16:_var$non_lazy_ptr
2572 ///     ldr r0, [rT1]
2573 ///     ldr rT2, [r0]
2574 ///     blx rT2
2575 ///     [...address now in r0...]
2576 SDValue
2577 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2578                                                SelectionDAG &DAG) const {
2579   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2580   SDLoc DL(Op);
2581 
2582   // First step is to get the address of the actua global symbol. This is where
2583   // the TLS descriptor lives.
2584   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2585 
2586   // The first entry in the descriptor is a function pointer that we must call
2587   // to obtain the address of the variable.
2588   SDValue Chain = DAG.getEntryNode();
2589   SDValue FuncTLVGet =
2590       DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2591                   MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2592                   false, true, true, 4);
2593   Chain = FuncTLVGet.getValue(1);
2594 
2595   MachineFunction &F = DAG.getMachineFunction();
2596   MachineFrameInfo *MFI = F.getFrameInfo();
2597   MFI->setAdjustsStack(true);
2598 
2599   // TLS calls preserve all registers except those that absolutely must be
2600   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2601   // silly).
2602   auto TRI =
2603       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2604   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2605   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2606 
2607   // Finally, we can make the call. This is just a degenerate version of a
2608   // normal AArch64 call node: r0 takes the address of the descriptor, and
2609   // returns the address of the variable in this thread.
2610   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2611   Chain =
2612       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2613                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2614                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2615   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2616 }
2617 
2618 SDValue
2619 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2620                                                 SelectionDAG &DAG) const {
2621   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2622   SDValue Chain = DAG.getEntryNode();
2623   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2624   SDLoc DL(Op);
2625 
2626   // Load the current TEB (thread environment block)
2627   SDValue Ops[] = {Chain,
2628                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2629                    DAG.getConstant(15, DL, MVT::i32),
2630                    DAG.getConstant(0, DL, MVT::i32),
2631                    DAG.getConstant(13, DL, MVT::i32),
2632                    DAG.getConstant(0, DL, MVT::i32),
2633                    DAG.getConstant(2, DL, MVT::i32)};
2634   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2635                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2636 
2637   SDValue TEB = CurrentTEB.getValue(0);
2638   Chain = CurrentTEB.getValue(1);
2639 
2640   // Load the ThreadLocalStoragePointer from the TEB
2641   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2642   SDValue TLSArray =
2643       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2644   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo(),
2645                          false, false, false, 0);
2646 
2647   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2648   // offset into the TLSArray.
2649 
2650   // Load the TLS index from the C runtime
2651   SDValue TLSIndex =
2652       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2653   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2654   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo(),
2655                          false, false, false, 0);
2656 
2657   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2658                               DAG.getConstant(2, DL, MVT::i32));
2659   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2660                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2661                             MachinePointerInfo(), false, false, false, 0);
2662 
2663   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS,
2664                      LowerGlobalAddressWindows(Op, DAG));
2665 }
2666 
2667 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2668 SDValue
2669 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2670                                                  SelectionDAG &DAG) const {
2671   SDLoc dl(GA);
2672   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2673   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2674   MachineFunction &MF = DAG.getMachineFunction();
2675   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2676   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2677   ARMConstantPoolValue *CPV =
2678     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2679                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2680   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2681   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2682   Argument =
2683       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2684                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2685                   false, false, false, 0);
2686   SDValue Chain = Argument.getValue(1);
2687 
2688   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2689   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2690 
2691   // call __tls_get_addr.
2692   ArgListTy Args;
2693   ArgListEntry Entry;
2694   Entry.Node = Argument;
2695   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2696   Args.push_back(Entry);
2697 
2698   // FIXME: is there useful debug info available here?
2699   TargetLowering::CallLoweringInfo CLI(DAG);
2700   CLI.setDebugLoc(dl).setChain(Chain)
2701     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2702                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2703                0);
2704 
2705   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2706   return CallResult.first;
2707 }
2708 
2709 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2710 // "local exec" model.
2711 SDValue
2712 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2713                                         SelectionDAG &DAG,
2714                                         TLSModel::Model model) const {
2715   const GlobalValue *GV = GA->getGlobal();
2716   SDLoc dl(GA);
2717   SDValue Offset;
2718   SDValue Chain = DAG.getEntryNode();
2719   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2720   // Get the Thread Pointer
2721   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2722 
2723   if (model == TLSModel::InitialExec) {
2724     MachineFunction &MF = DAG.getMachineFunction();
2725     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2726     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2727     // Initial exec model.
2728     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2729     ARMConstantPoolValue *CPV =
2730       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2731                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2732                                       true);
2733     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2734     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2735     Offset = DAG.getLoad(
2736         PtrVT, dl, Chain, Offset,
2737         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2738         false, false, 0);
2739     Chain = Offset.getValue(1);
2740 
2741     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2742     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2743 
2744     Offset = DAG.getLoad(
2745         PtrVT, dl, Chain, Offset,
2746         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2747         false, false, 0);
2748   } else {
2749     // local exec model
2750     assert(model == TLSModel::LocalExec);
2751     ARMConstantPoolValue *CPV =
2752       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2753     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2754     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2755     Offset = DAG.getLoad(
2756         PtrVT, dl, Chain, Offset,
2757         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2758         false, false, 0);
2759   }
2760 
2761   // The address of the thread local variable is the add of the thread
2762   // pointer with the offset of the variable.
2763   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2764 }
2765 
2766 SDValue
2767 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2768   if (Subtarget->isTargetDarwin())
2769     return LowerGlobalTLSAddressDarwin(Op, DAG);
2770 
2771   if (Subtarget->isTargetWindows())
2772     return LowerGlobalTLSAddressWindows(Op, DAG);
2773 
2774   // TODO: implement the "local dynamic" model
2775   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2776   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2777   if (DAG.getTarget().Options.EmulatedTLS)
2778     return LowerToTLSEmulatedModel(GA, DAG);
2779 
2780   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2781 
2782   switch (model) {
2783     case TLSModel::GeneralDynamic:
2784     case TLSModel::LocalDynamic:
2785       return LowerToTLSGeneralDynamicModel(GA, DAG);
2786     case TLSModel::InitialExec:
2787     case TLSModel::LocalExec:
2788       return LowerToTLSExecModels(GA, DAG, model);
2789   }
2790   llvm_unreachable("bogus TLS model");
2791 }
2792 
2793 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2794                                                  SelectionDAG &DAG) const {
2795   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2796   SDLoc dl(Op);
2797   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2798   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2799     bool UseGOT_PREL =
2800         !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2801 
2802     MachineFunction &MF = DAG.getMachineFunction();
2803     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2804     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2805     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2806     SDLoc dl(Op);
2807     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2808     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2809         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2810         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2811         /*AddCurrentAddress=*/UseGOT_PREL);
2812     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2813     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2814     SDValue Result = DAG.getLoad(
2815         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2816         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2817         false, false, 0);
2818     SDValue Chain = Result.getValue(1);
2819     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2820     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2821     if (UseGOT_PREL)
2822       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2823                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2824                            false, false, false, 0);
2825     return Result;
2826   }
2827 
2828   // If we have T2 ops, we can materialize the address directly via movt/movw
2829   // pair. This is always cheaper.
2830   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2831     ++NumMovwMovt;
2832     // FIXME: Once remat is capable of dealing with instructions with register
2833     // operands, expand this into two nodes.
2834     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2835                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2836   } else {
2837     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2838     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2839     return DAG.getLoad(
2840         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2841         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2842         false, false, 0);
2843   }
2844 }
2845 
2846 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2847                                                     SelectionDAG &DAG) const {
2848   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2849   SDLoc dl(Op);
2850   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2851   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2852 
2853   if (Subtarget->useMovt(DAG.getMachineFunction()))
2854     ++NumMovwMovt;
2855 
2856   // FIXME: Once remat is capable of dealing with instructions with register
2857   // operands, expand this into multiple nodes
2858   unsigned Wrapper =
2859       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2860 
2861   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2862   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2863 
2864   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2865     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2866                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2867                          false, false, false, 0);
2868   return Result;
2869 }
2870 
2871 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2872                                                      SelectionDAG &DAG) const {
2873   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2874   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2875          "Windows on ARM expects to use movw/movt");
2876 
2877   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2878   const ARMII::TOF TargetFlags =
2879     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2880   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2881   SDValue Result;
2882   SDLoc DL(Op);
2883 
2884   ++NumMovwMovt;
2885 
2886   // FIXME: Once remat is capable of dealing with instructions with register
2887   // operands, expand this into two nodes.
2888   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2889                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2890                                                   TargetFlags));
2891   if (GV->hasDLLImportStorageClass())
2892     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2893                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2894                          false, false, false, 0);
2895   return Result;
2896 }
2897 
2898 SDValue
2899 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2900   SDLoc dl(Op);
2901   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2902   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2903                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2904                      Op.getOperand(1), Val);
2905 }
2906 
2907 SDValue
2908 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2909   SDLoc dl(Op);
2910   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2911                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2912 }
2913 
2914 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2915                                                       SelectionDAG &DAG) const {
2916   SDLoc dl(Op);
2917   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2918                      Op.getOperand(0));
2919 }
2920 
2921 SDValue
2922 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2923                                           const ARMSubtarget *Subtarget) const {
2924   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2925   SDLoc dl(Op);
2926   switch (IntNo) {
2927   default: return SDValue();    // Don't custom lower most intrinsics.
2928   case Intrinsic::arm_rbit: {
2929     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2930            "RBIT intrinsic must have i32 type!");
2931     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2932   }
2933   case Intrinsic::arm_thread_pointer: {
2934     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2935     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2936   }
2937   case Intrinsic::eh_sjlj_lsda: {
2938     MachineFunction &MF = DAG.getMachineFunction();
2939     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2940     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2941     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2942     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2943     SDValue CPAddr;
2944     unsigned PCAdj = (RelocM != Reloc::PIC_)
2945       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2946     ARMConstantPoolValue *CPV =
2947       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2948                                       ARMCP::CPLSDA, PCAdj);
2949     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2951     SDValue Result = DAG.getLoad(
2952         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2953         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2954         false, false, 0);
2955 
2956     if (RelocM == Reloc::PIC_) {
2957       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2958       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2959     }
2960     return Result;
2961   }
2962   case Intrinsic::arm_neon_vmulls:
2963   case Intrinsic::arm_neon_vmullu: {
2964     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2965       ? ARMISD::VMULLs : ARMISD::VMULLu;
2966     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2967                        Op.getOperand(1), Op.getOperand(2));
2968   }
2969   case Intrinsic::arm_neon_vminnm:
2970   case Intrinsic::arm_neon_vmaxnm: {
2971     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2972       ? ISD::FMINNUM : ISD::FMAXNUM;
2973     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2974                        Op.getOperand(1), Op.getOperand(2));
2975   }
2976   case Intrinsic::arm_neon_vminu:
2977   case Intrinsic::arm_neon_vmaxu: {
2978     if (Op.getValueType().isFloatingPoint())
2979       return SDValue();
2980     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2981       ? ISD::UMIN : ISD::UMAX;
2982     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2983                          Op.getOperand(1), Op.getOperand(2));
2984   }
2985   case Intrinsic::arm_neon_vmins:
2986   case Intrinsic::arm_neon_vmaxs: {
2987     // v{min,max}s is overloaded between signed integers and floats.
2988     if (!Op.getValueType().isFloatingPoint()) {
2989       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2990         ? ISD::SMIN : ISD::SMAX;
2991       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2992                          Op.getOperand(1), Op.getOperand(2));
2993     }
2994     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2995       ? ISD::FMINNAN : ISD::FMAXNAN;
2996     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2997                        Op.getOperand(1), Op.getOperand(2));
2998   }
2999   }
3000 }
3001 
3002 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3003                                  const ARMSubtarget *Subtarget) {
3004   // FIXME: handle "fence singlethread" more efficiently.
3005   SDLoc dl(Op);
3006   if (!Subtarget->hasDataBarrier()) {
3007     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3008     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3009     // here.
3010     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3011            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3012     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3013                        DAG.getConstant(0, dl, MVT::i32));
3014   }
3015 
3016   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3017   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3018   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3019   if (Subtarget->isMClass()) {
3020     // Only a full system barrier exists in the M-class architectures.
3021     Domain = ARM_MB::SY;
3022   } else if (Subtarget->isSwift() && Ord == Release) {
3023     // Swift happens to implement ISHST barriers in a way that's compatible with
3024     // Release semantics but weaker than ISH so we'd be fools not to use
3025     // it. Beware: other processors probably don't!
3026     Domain = ARM_MB::ISHST;
3027   }
3028 
3029   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3030                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3031                      DAG.getConstant(Domain, dl, MVT::i32));
3032 }
3033 
3034 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3035                              const ARMSubtarget *Subtarget) {
3036   // ARM pre v5TE and Thumb1 does not have preload instructions.
3037   if (!(Subtarget->isThumb2() ||
3038         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3039     // Just preserve the chain.
3040     return Op.getOperand(0);
3041 
3042   SDLoc dl(Op);
3043   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3044   if (!isRead &&
3045       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3046     // ARMv7 with MP extension has PLDW.
3047     return Op.getOperand(0);
3048 
3049   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3050   if (Subtarget->isThumb()) {
3051     // Invert the bits.
3052     isRead = ~isRead & 1;
3053     isData = ~isData & 1;
3054   }
3055 
3056   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3057                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3058                      DAG.getConstant(isData, dl, MVT::i32));
3059 }
3060 
3061 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3062   MachineFunction &MF = DAG.getMachineFunction();
3063   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3064 
3065   // vastart just stores the address of the VarArgsFrameIndex slot into the
3066   // memory location argument.
3067   SDLoc dl(Op);
3068   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3069   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3070   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3071   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3072                       MachinePointerInfo(SV), false, false, 0);
3073 }
3074 
3075 SDValue
3076 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
3077                                         SDValue &Root, SelectionDAG &DAG,
3078                                         SDLoc dl) const {
3079   MachineFunction &MF = DAG.getMachineFunction();
3080   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3081 
3082   const TargetRegisterClass *RC;
3083   if (AFI->isThumb1OnlyFunction())
3084     RC = &ARM::tGPRRegClass;
3085   else
3086     RC = &ARM::GPRRegClass;
3087 
3088   // Transform the arguments stored in physical registers into virtual ones.
3089   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3090   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3091 
3092   SDValue ArgValue2;
3093   if (NextVA.isMemLoc()) {
3094     MachineFrameInfo *MFI = MF.getFrameInfo();
3095     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3096 
3097     // Create load node to retrieve arguments from the stack.
3098     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3099     ArgValue2 = DAG.getLoad(
3100         MVT::i32, dl, Root, FIN,
3101         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3102         false, false, 0);
3103   } else {
3104     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3105     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3106   }
3107   if (!Subtarget->isLittle())
3108     std::swap (ArgValue, ArgValue2);
3109   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3110 }
3111 
3112 // The remaining GPRs hold either the beginning of variable-argument
3113 // data, or the beginning of an aggregate passed by value (usually
3114 // byval).  Either way, we allocate stack slots adjacent to the data
3115 // provided by our caller, and store the unallocated registers there.
3116 // If this is a variadic function, the va_list pointer will begin with
3117 // these values; otherwise, this reassembles a (byval) structure that
3118 // was split between registers and memory.
3119 // Return: The frame index registers were stored into.
3120 int
3121 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3122                                   SDLoc dl, SDValue &Chain,
3123                                   const Value *OrigArg,
3124                                   unsigned InRegsParamRecordIdx,
3125                                   int ArgOffset,
3126                                   unsigned ArgSize) const {
3127   // Currently, two use-cases possible:
3128   // Case #1. Non-var-args function, and we meet first byval parameter.
3129   //          Setup first unallocated register as first byval register;
3130   //          eat all remained registers
3131   //          (these two actions are performed by HandleByVal method).
3132   //          Then, here, we initialize stack frame with
3133   //          "store-reg" instructions.
3134   // Case #2. Var-args function, that doesn't contain byval parameters.
3135   //          The same: eat all remained unallocated registers,
3136   //          initialize stack frame.
3137 
3138   MachineFunction &MF = DAG.getMachineFunction();
3139   MachineFrameInfo *MFI = MF.getFrameInfo();
3140   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3141   unsigned RBegin, REnd;
3142   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3143     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3144   } else {
3145     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3146     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3147     REnd = ARM::R4;
3148   }
3149 
3150   if (REnd != RBegin)
3151     ArgOffset = -4 * (ARM::R4 - RBegin);
3152 
3153   auto PtrVT = getPointerTy(DAG.getDataLayout());
3154   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3155   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3156 
3157   SmallVector<SDValue, 4> MemOps;
3158   const TargetRegisterClass *RC =
3159       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3160 
3161   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3162     unsigned VReg = MF.addLiveIn(Reg, RC);
3163     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3164     SDValue Store =
3165         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3166                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3167     MemOps.push_back(Store);
3168     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3169   }
3170 
3171   if (!MemOps.empty())
3172     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3173   return FrameIndex;
3174 }
3175 
3176 // Setup stack frame, the va_list pointer will start from.
3177 void
3178 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3179                                         SDLoc dl, SDValue &Chain,
3180                                         unsigned ArgOffset,
3181                                         unsigned TotalArgRegsSaveSize,
3182                                         bool ForceMutable) const {
3183   MachineFunction &MF = DAG.getMachineFunction();
3184   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3185 
3186   // Try to store any remaining integer argument regs
3187   // to their spots on the stack so that they may be loaded by deferencing
3188   // the result of va_next.
3189   // If there is no regs to be stored, just point address after last
3190   // argument passed via stack.
3191   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3192                                   CCInfo.getInRegsParamsCount(),
3193                                   CCInfo.getNextStackOffset(), 4);
3194   AFI->setVarArgsFrameIndex(FrameIndex);
3195 }
3196 
3197 SDValue
3198 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3199                                         CallingConv::ID CallConv, bool isVarArg,
3200                                         const SmallVectorImpl<ISD::InputArg>
3201                                           &Ins,
3202                                         SDLoc dl, SelectionDAG &DAG,
3203                                         SmallVectorImpl<SDValue> &InVals)
3204                                           const {
3205   MachineFunction &MF = DAG.getMachineFunction();
3206   MachineFrameInfo *MFI = MF.getFrameInfo();
3207 
3208   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3209 
3210   // Assign locations to all of the incoming arguments.
3211   SmallVector<CCValAssign, 16> ArgLocs;
3212   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3213                     *DAG.getContext(), Prologue);
3214   CCInfo.AnalyzeFormalArguments(Ins,
3215                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3216                                                   isVarArg));
3217 
3218   SmallVector<SDValue, 16> ArgValues;
3219   SDValue ArgValue;
3220   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3221   unsigned CurArgIdx = 0;
3222 
3223   // Initially ArgRegsSaveSize is zero.
3224   // Then we increase this value each time we meet byval parameter.
3225   // We also increase this value in case of varargs function.
3226   AFI->setArgRegsSaveSize(0);
3227 
3228   // Calculate the amount of stack space that we need to allocate to store
3229   // byval and variadic arguments that are passed in registers.
3230   // We need to know this before we allocate the first byval or variadic
3231   // argument, as they will be allocated a stack slot below the CFA (Canonical
3232   // Frame Address, the stack pointer at entry to the function).
3233   unsigned ArgRegBegin = ARM::R4;
3234   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3235     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3236       break;
3237 
3238     CCValAssign &VA = ArgLocs[i];
3239     unsigned Index = VA.getValNo();
3240     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3241     if (!Flags.isByVal())
3242       continue;
3243 
3244     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3245     unsigned RBegin, REnd;
3246     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3247     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3248 
3249     CCInfo.nextInRegsParam();
3250   }
3251   CCInfo.rewindByValRegsInfo();
3252 
3253   int lastInsIndex = -1;
3254   if (isVarArg && MFI->hasVAStart()) {
3255     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3256     if (RegIdx != array_lengthof(GPRArgRegs))
3257       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3258   }
3259 
3260   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3261   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3262   auto PtrVT = getPointerTy(DAG.getDataLayout());
3263 
3264   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3265     CCValAssign &VA = ArgLocs[i];
3266     if (Ins[VA.getValNo()].isOrigArg()) {
3267       std::advance(CurOrigArg,
3268                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3269       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3270     }
3271     // Arguments stored in registers.
3272     if (VA.isRegLoc()) {
3273       EVT RegVT = VA.getLocVT();
3274 
3275       if (VA.needsCustom()) {
3276         // f64 and vector types are split up into multiple registers or
3277         // combinations of registers and stack slots.
3278         if (VA.getLocVT() == MVT::v2f64) {
3279           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3280                                                    Chain, DAG, dl);
3281           VA = ArgLocs[++i]; // skip ahead to next loc
3282           SDValue ArgValue2;
3283           if (VA.isMemLoc()) {
3284             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3285             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3286             ArgValue2 = DAG.getLoad(
3287                 MVT::f64, dl, Chain, FIN,
3288                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3289                 false, false, false, 0);
3290           } else {
3291             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3292                                              Chain, DAG, dl);
3293           }
3294           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3295           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3296                                  ArgValue, ArgValue1,
3297                                  DAG.getIntPtrConstant(0, dl));
3298           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3299                                  ArgValue, ArgValue2,
3300                                  DAG.getIntPtrConstant(1, dl));
3301         } else
3302           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3303 
3304       } else {
3305         const TargetRegisterClass *RC;
3306 
3307         if (RegVT == MVT::f32)
3308           RC = &ARM::SPRRegClass;
3309         else if (RegVT == MVT::f64)
3310           RC = &ARM::DPRRegClass;
3311         else if (RegVT == MVT::v2f64)
3312           RC = &ARM::QPRRegClass;
3313         else if (RegVT == MVT::i32)
3314           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3315                                            : &ARM::GPRRegClass;
3316         else
3317           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3318 
3319         // Transform the arguments in physical registers into virtual ones.
3320         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3321         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3322       }
3323 
3324       // If this is an 8 or 16-bit value, it is really passed promoted
3325       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3326       // truncate to the right size.
3327       switch (VA.getLocInfo()) {
3328       default: llvm_unreachable("Unknown loc info!");
3329       case CCValAssign::Full: break;
3330       case CCValAssign::BCvt:
3331         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3332         break;
3333       case CCValAssign::SExt:
3334         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3335                                DAG.getValueType(VA.getValVT()));
3336         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3337         break;
3338       case CCValAssign::ZExt:
3339         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3340                                DAG.getValueType(VA.getValVT()));
3341         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3342         break;
3343       }
3344 
3345       InVals.push_back(ArgValue);
3346 
3347     } else { // VA.isRegLoc()
3348 
3349       // sanity check
3350       assert(VA.isMemLoc());
3351       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3352 
3353       int index = VA.getValNo();
3354 
3355       // Some Ins[] entries become multiple ArgLoc[] entries.
3356       // Process them only once.
3357       if (index != lastInsIndex)
3358         {
3359           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3360           // FIXME: For now, all byval parameter objects are marked mutable.
3361           // This can be changed with more analysis.
3362           // In case of tail call optimization mark all arguments mutable.
3363           // Since they could be overwritten by lowering of arguments in case of
3364           // a tail call.
3365           if (Flags.isByVal()) {
3366             assert(Ins[index].isOrigArg() &&
3367                    "Byval arguments cannot be implicit");
3368             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3369 
3370             int FrameIndex = StoreByValRegs(
3371                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3372                 VA.getLocMemOffset(), Flags.getByValSize());
3373             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3374             CCInfo.nextInRegsParam();
3375           } else {
3376             unsigned FIOffset = VA.getLocMemOffset();
3377             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3378                                             FIOffset, true);
3379 
3380             // Create load nodes to retrieve arguments from the stack.
3381             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3382             InVals.push_back(DAG.getLoad(
3383                 VA.getValVT(), dl, Chain, FIN,
3384                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3385                 false, false, false, 0));
3386           }
3387           lastInsIndex = index;
3388         }
3389     }
3390   }
3391 
3392   // varargs
3393   if (isVarArg && MFI->hasVAStart())
3394     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3395                          CCInfo.getNextStackOffset(),
3396                          TotalArgRegsSaveSize);
3397 
3398   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3399 
3400   return Chain;
3401 }
3402 
3403 /// isFloatingPointZero - Return true if this is +0.0.
3404 static bool isFloatingPointZero(SDValue Op) {
3405   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3406     return CFP->getValueAPF().isPosZero();
3407   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3408     // Maybe this has already been legalized into the constant pool?
3409     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3410       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3411       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3412         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3413           return CFP->getValueAPF().isPosZero();
3414     }
3415   } else if (Op->getOpcode() == ISD::BITCAST &&
3416              Op->getValueType(0) == MVT::f64) {
3417     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3418     // created by LowerConstantFP().
3419     SDValue BitcastOp = Op->getOperand(0);
3420     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3421         isNullConstant(BitcastOp->getOperand(0)))
3422       return true;
3423   }
3424   return false;
3425 }
3426 
3427 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3428 /// the given operands.
3429 SDValue
3430 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3431                              SDValue &ARMcc, SelectionDAG &DAG,
3432                              SDLoc dl) const {
3433   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3434     unsigned C = RHSC->getZExtValue();
3435     if (!isLegalICmpImmediate(C)) {
3436       // Constant does not fit, try adjusting it by one?
3437       switch (CC) {
3438       default: break;
3439       case ISD::SETLT:
3440       case ISD::SETGE:
3441         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3442           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3443           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3444         }
3445         break;
3446       case ISD::SETULT:
3447       case ISD::SETUGE:
3448         if (C != 0 && isLegalICmpImmediate(C-1)) {
3449           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3450           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3451         }
3452         break;
3453       case ISD::SETLE:
3454       case ISD::SETGT:
3455         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3456           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3457           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3458         }
3459         break;
3460       case ISD::SETULE:
3461       case ISD::SETUGT:
3462         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3463           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3464           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3465         }
3466         break;
3467       }
3468     }
3469   }
3470 
3471   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3472   ARMISD::NodeType CompareType;
3473   switch (CondCode) {
3474   default:
3475     CompareType = ARMISD::CMP;
3476     break;
3477   case ARMCC::EQ:
3478   case ARMCC::NE:
3479     // Uses only Z Flag
3480     CompareType = ARMISD::CMPZ;
3481     break;
3482   }
3483   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3484   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3485 }
3486 
3487 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3488 SDValue
3489 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3490                              SDLoc dl) const {
3491   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3492   SDValue Cmp;
3493   if (!isFloatingPointZero(RHS))
3494     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3495   else
3496     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3497   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3498 }
3499 
3500 /// duplicateCmp - Glue values can have only one use, so this function
3501 /// duplicates a comparison node.
3502 SDValue
3503 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3504   unsigned Opc = Cmp.getOpcode();
3505   SDLoc DL(Cmp);
3506   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3507     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3508 
3509   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3510   Cmp = Cmp.getOperand(0);
3511   Opc = Cmp.getOpcode();
3512   if (Opc == ARMISD::CMPFP)
3513     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3514   else {
3515     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3516     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3517   }
3518   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3519 }
3520 
3521 std::pair<SDValue, SDValue>
3522 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3523                                  SDValue &ARMcc) const {
3524   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3525 
3526   SDValue Value, OverflowCmp;
3527   SDValue LHS = Op.getOperand(0);
3528   SDValue RHS = Op.getOperand(1);
3529   SDLoc dl(Op);
3530 
3531   // FIXME: We are currently always generating CMPs because we don't support
3532   // generating CMN through the backend. This is not as good as the natural
3533   // CMP case because it causes a register dependency and cannot be folded
3534   // later.
3535 
3536   switch (Op.getOpcode()) {
3537   default:
3538     llvm_unreachable("Unknown overflow instruction!");
3539   case ISD::SADDO:
3540     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3541     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3542     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3543     break;
3544   case ISD::UADDO:
3545     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3546     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3547     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3548     break;
3549   case ISD::SSUBO:
3550     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3551     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3552     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3553     break;
3554   case ISD::USUBO:
3555     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3556     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3557     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3558     break;
3559   } // switch (...)
3560 
3561   return std::make_pair(Value, OverflowCmp);
3562 }
3563 
3564 
3565 SDValue
3566 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3567   // Let legalize expand this if it isn't a legal type yet.
3568   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3569     return SDValue();
3570 
3571   SDValue Value, OverflowCmp;
3572   SDValue ARMcc;
3573   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3574   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3575   SDLoc dl(Op);
3576   // We use 0 and 1 as false and true values.
3577   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3578   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3579   EVT VT = Op.getValueType();
3580 
3581   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3582                                  ARMcc, CCR, OverflowCmp);
3583 
3584   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3585   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3586 }
3587 
3588 
3589 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3590   SDValue Cond = Op.getOperand(0);
3591   SDValue SelectTrue = Op.getOperand(1);
3592   SDValue SelectFalse = Op.getOperand(2);
3593   SDLoc dl(Op);
3594   unsigned Opc = Cond.getOpcode();
3595 
3596   if (Cond.getResNo() == 1 &&
3597       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3598        Opc == ISD::USUBO)) {
3599     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3600       return SDValue();
3601 
3602     SDValue Value, OverflowCmp;
3603     SDValue ARMcc;
3604     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3605     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3606     EVT VT = Op.getValueType();
3607 
3608     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3609                    OverflowCmp, DAG);
3610   }
3611 
3612   // Convert:
3613   //
3614   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3615   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3616   //
3617   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3618     const ConstantSDNode *CMOVTrue =
3619       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3620     const ConstantSDNode *CMOVFalse =
3621       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3622 
3623     if (CMOVTrue && CMOVFalse) {
3624       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3625       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3626 
3627       SDValue True;
3628       SDValue False;
3629       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3630         True = SelectTrue;
3631         False = SelectFalse;
3632       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3633         True = SelectFalse;
3634         False = SelectTrue;
3635       }
3636 
3637       if (True.getNode() && False.getNode()) {
3638         EVT VT = Op.getValueType();
3639         SDValue ARMcc = Cond.getOperand(2);
3640         SDValue CCR = Cond.getOperand(3);
3641         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3642         assert(True.getValueType() == VT);
3643         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3644       }
3645     }
3646   }
3647 
3648   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3649   // undefined bits before doing a full-word comparison with zero.
3650   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3651                      DAG.getConstant(1, dl, Cond.getValueType()));
3652 
3653   return DAG.getSelectCC(dl, Cond,
3654                          DAG.getConstant(0, dl, Cond.getValueType()),
3655                          SelectTrue, SelectFalse, ISD::SETNE);
3656 }
3657 
3658 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3659                                  bool &swpCmpOps, bool &swpVselOps) {
3660   // Start by selecting the GE condition code for opcodes that return true for
3661   // 'equality'
3662   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3663       CC == ISD::SETULE)
3664     CondCode = ARMCC::GE;
3665 
3666   // and GT for opcodes that return false for 'equality'.
3667   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3668            CC == ISD::SETULT)
3669     CondCode = ARMCC::GT;
3670 
3671   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3672   // to swap the compare operands.
3673   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3674       CC == ISD::SETULT)
3675     swpCmpOps = true;
3676 
3677   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3678   // If we have an unordered opcode, we need to swap the operands to the VSEL
3679   // instruction (effectively negating the condition).
3680   //
3681   // This also has the effect of swapping which one of 'less' or 'greater'
3682   // returns true, so we also swap the compare operands. It also switches
3683   // whether we return true for 'equality', so we compensate by picking the
3684   // opposite condition code to our original choice.
3685   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3686       CC == ISD::SETUGT) {
3687     swpCmpOps = !swpCmpOps;
3688     swpVselOps = !swpVselOps;
3689     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3690   }
3691 
3692   // 'ordered' is 'anything but unordered', so use the VS condition code and
3693   // swap the VSEL operands.
3694   if (CC == ISD::SETO) {
3695     CondCode = ARMCC::VS;
3696     swpVselOps = true;
3697   }
3698 
3699   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3700   // code and swap the VSEL operands.
3701   if (CC == ISD::SETUNE) {
3702     CondCode = ARMCC::EQ;
3703     swpVselOps = true;
3704   }
3705 }
3706 
3707 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3708                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3709                                    SDValue Cmp, SelectionDAG &DAG) const {
3710   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3711     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3712                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3713     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3714                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3715 
3716     SDValue TrueLow = TrueVal.getValue(0);
3717     SDValue TrueHigh = TrueVal.getValue(1);
3718     SDValue FalseLow = FalseVal.getValue(0);
3719     SDValue FalseHigh = FalseVal.getValue(1);
3720 
3721     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3722                               ARMcc, CCR, Cmp);
3723     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3724                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3725 
3726     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3727   } else {
3728     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3729                        Cmp);
3730   }
3731 }
3732 
3733 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3734   EVT VT = Op.getValueType();
3735   SDValue LHS = Op.getOperand(0);
3736   SDValue RHS = Op.getOperand(1);
3737   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3738   SDValue TrueVal = Op.getOperand(2);
3739   SDValue FalseVal = Op.getOperand(3);
3740   SDLoc dl(Op);
3741 
3742   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3743     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3744                                                     dl);
3745 
3746     // If softenSetCCOperands only returned one value, we should compare it to
3747     // zero.
3748     if (!RHS.getNode()) {
3749       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3750       CC = ISD::SETNE;
3751     }
3752   }
3753 
3754   if (LHS.getValueType() == MVT::i32) {
3755     // Try to generate VSEL on ARMv8.
3756     // The VSEL instruction can't use all the usual ARM condition
3757     // codes: it only has two bits to select the condition code, so it's
3758     // constrained to use only GE, GT, VS and EQ.
3759     //
3760     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3761     // swap the operands of the previous compare instruction (effectively
3762     // inverting the compare condition, swapping 'less' and 'greater') and
3763     // sometimes need to swap the operands to the VSEL (which inverts the
3764     // condition in the sense of firing whenever the previous condition didn't)
3765     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3766                                     TrueVal.getValueType() == MVT::f64)) {
3767       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3768       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3769           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3770         CC = ISD::getSetCCInverse(CC, true);
3771         std::swap(TrueVal, FalseVal);
3772       }
3773     }
3774 
3775     SDValue ARMcc;
3776     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3777     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3778     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3779   }
3780 
3781   ARMCC::CondCodes CondCode, CondCode2;
3782   FPCCToARMCC(CC, CondCode, CondCode2);
3783 
3784   // Try to generate VMAXNM/VMINNM on ARMv8.
3785   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3786                                   TrueVal.getValueType() == MVT::f64)) {
3787     bool swpCmpOps = false;
3788     bool swpVselOps = false;
3789     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3790 
3791     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3792         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3793       if (swpCmpOps)
3794         std::swap(LHS, RHS);
3795       if (swpVselOps)
3796         std::swap(TrueVal, FalseVal);
3797     }
3798   }
3799 
3800   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3801   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3802   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3803   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3804   if (CondCode2 != ARMCC::AL) {
3805     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3806     // FIXME: Needs another CMP because flag can have but one use.
3807     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3808     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3809   }
3810   return Result;
3811 }
3812 
3813 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3814 /// to morph to an integer compare sequence.
3815 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3816                            const ARMSubtarget *Subtarget) {
3817   SDNode *N = Op.getNode();
3818   if (!N->hasOneUse())
3819     // Otherwise it requires moving the value from fp to integer registers.
3820     return false;
3821   if (!N->getNumValues())
3822     return false;
3823   EVT VT = Op.getValueType();
3824   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3825     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3826     // vmrs are very slow, e.g. cortex-a8.
3827     return false;
3828 
3829   if (isFloatingPointZero(Op)) {
3830     SeenZero = true;
3831     return true;
3832   }
3833   return ISD::isNormalLoad(N);
3834 }
3835 
3836 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3837   if (isFloatingPointZero(Op))
3838     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3839 
3840   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3841     return DAG.getLoad(MVT::i32, SDLoc(Op),
3842                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3843                        Ld->isVolatile(), Ld->isNonTemporal(),
3844                        Ld->isInvariant(), Ld->getAlignment());
3845 
3846   llvm_unreachable("Unknown VFP cmp argument!");
3847 }
3848 
3849 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3850                            SDValue &RetVal1, SDValue &RetVal2) {
3851   SDLoc dl(Op);
3852 
3853   if (isFloatingPointZero(Op)) {
3854     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3855     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3856     return;
3857   }
3858 
3859   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3860     SDValue Ptr = Ld->getBasePtr();
3861     RetVal1 = DAG.getLoad(MVT::i32, dl,
3862                           Ld->getChain(), Ptr,
3863                           Ld->getPointerInfo(),
3864                           Ld->isVolatile(), Ld->isNonTemporal(),
3865                           Ld->isInvariant(), Ld->getAlignment());
3866 
3867     EVT PtrType = Ptr.getValueType();
3868     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3869     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3870                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3871     RetVal2 = DAG.getLoad(MVT::i32, dl,
3872                           Ld->getChain(), NewPtr,
3873                           Ld->getPointerInfo().getWithOffset(4),
3874                           Ld->isVolatile(), Ld->isNonTemporal(),
3875                           Ld->isInvariant(), NewAlign);
3876     return;
3877   }
3878 
3879   llvm_unreachable("Unknown VFP cmp argument!");
3880 }
3881 
3882 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3883 /// f32 and even f64 comparisons to integer ones.
3884 SDValue
3885 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3886   SDValue Chain = Op.getOperand(0);
3887   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3888   SDValue LHS = Op.getOperand(2);
3889   SDValue RHS = Op.getOperand(3);
3890   SDValue Dest = Op.getOperand(4);
3891   SDLoc dl(Op);
3892 
3893   bool LHSSeenZero = false;
3894   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3895   bool RHSSeenZero = false;
3896   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3897   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3898     // If unsafe fp math optimization is enabled and there are no other uses of
3899     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3900     // to an integer comparison.
3901     if (CC == ISD::SETOEQ)
3902       CC = ISD::SETEQ;
3903     else if (CC == ISD::SETUNE)
3904       CC = ISD::SETNE;
3905 
3906     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3907     SDValue ARMcc;
3908     if (LHS.getValueType() == MVT::f32) {
3909       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3910                         bitcastf32Toi32(LHS, DAG), Mask);
3911       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3912                         bitcastf32Toi32(RHS, DAG), Mask);
3913       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3914       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3915       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3916                          Chain, Dest, ARMcc, CCR, Cmp);
3917     }
3918 
3919     SDValue LHS1, LHS2;
3920     SDValue RHS1, RHS2;
3921     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3922     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3923     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3924     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3925     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3926     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3927     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3928     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3929     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3930   }
3931 
3932   return SDValue();
3933 }
3934 
3935 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3936   SDValue Chain = Op.getOperand(0);
3937   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3938   SDValue LHS = Op.getOperand(2);
3939   SDValue RHS = Op.getOperand(3);
3940   SDValue Dest = Op.getOperand(4);
3941   SDLoc dl(Op);
3942 
3943   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3944     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3945                                                     dl);
3946 
3947     // If softenSetCCOperands only returned one value, we should compare it to
3948     // zero.
3949     if (!RHS.getNode()) {
3950       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3951       CC = ISD::SETNE;
3952     }
3953   }
3954 
3955   if (LHS.getValueType() == MVT::i32) {
3956     SDValue ARMcc;
3957     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3958     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3959     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3960                        Chain, Dest, ARMcc, CCR, Cmp);
3961   }
3962 
3963   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3964 
3965   if (getTargetMachine().Options.UnsafeFPMath &&
3966       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3967        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3968     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
3969       return Result;
3970   }
3971 
3972   ARMCC::CondCodes CondCode, CondCode2;
3973   FPCCToARMCC(CC, CondCode, CondCode2);
3974 
3975   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3976   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3977   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3978   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3979   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3980   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3981   if (CondCode2 != ARMCC::AL) {
3982     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3983     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3984     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3985   }
3986   return Res;
3987 }
3988 
3989 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3990   SDValue Chain = Op.getOperand(0);
3991   SDValue Table = Op.getOperand(1);
3992   SDValue Index = Op.getOperand(2);
3993   SDLoc dl(Op);
3994 
3995   EVT PTy = getPointerTy(DAG.getDataLayout());
3996   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3997   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3998   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3999   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4000   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4001   if (Subtarget->isThumb2()) {
4002     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
4003     // which does another jump to the destination. This also makes it easier
4004     // to translate it to TBB / TBH later.
4005     // FIXME: This might not work if the function is extremely large.
4006     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4007                        Addr, Op.getOperand(2), JTI);
4008   }
4009   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4010     Addr =
4011         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4012                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
4013                     false, false, false, 0);
4014     Chain = Addr.getValue(1);
4015     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4016     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4017   } else {
4018     Addr =
4019         DAG.getLoad(PTy, dl, Chain, Addr,
4020                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
4021                     false, false, false, 0);
4022     Chain = Addr.getValue(1);
4023     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4024   }
4025 }
4026 
4027 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4028   EVT VT = Op.getValueType();
4029   SDLoc dl(Op);
4030 
4031   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4032     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4033       return Op;
4034     return DAG.UnrollVectorOp(Op.getNode());
4035   }
4036 
4037   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4038          "Invalid type for custom lowering!");
4039   if (VT != MVT::v4i16)
4040     return DAG.UnrollVectorOp(Op.getNode());
4041 
4042   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4043   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4044 }
4045 
4046 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4047   EVT VT = Op.getValueType();
4048   if (VT.isVector())
4049     return LowerVectorFP_TO_INT(Op, DAG);
4050   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4051     RTLIB::Libcall LC;
4052     if (Op.getOpcode() == ISD::FP_TO_SINT)
4053       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4054                               Op.getValueType());
4055     else
4056       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4057                               Op.getValueType());
4058     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4059                        /*isSigned*/ false, SDLoc(Op)).first;
4060   }
4061 
4062   return Op;
4063 }
4064 
4065 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4066   EVT VT = Op.getValueType();
4067   SDLoc dl(Op);
4068 
4069   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4070     if (VT.getVectorElementType() == MVT::f32)
4071       return Op;
4072     return DAG.UnrollVectorOp(Op.getNode());
4073   }
4074 
4075   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4076          "Invalid type for custom lowering!");
4077   if (VT != MVT::v4f32)
4078     return DAG.UnrollVectorOp(Op.getNode());
4079 
4080   unsigned CastOpc;
4081   unsigned Opc;
4082   switch (Op.getOpcode()) {
4083   default: llvm_unreachable("Invalid opcode!");
4084   case ISD::SINT_TO_FP:
4085     CastOpc = ISD::SIGN_EXTEND;
4086     Opc = ISD::SINT_TO_FP;
4087     break;
4088   case ISD::UINT_TO_FP:
4089     CastOpc = ISD::ZERO_EXTEND;
4090     Opc = ISD::UINT_TO_FP;
4091     break;
4092   }
4093 
4094   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4095   return DAG.getNode(Opc, dl, VT, Op);
4096 }
4097 
4098 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4099   EVT VT = Op.getValueType();
4100   if (VT.isVector())
4101     return LowerVectorINT_TO_FP(Op, DAG);
4102   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4103     RTLIB::Libcall LC;
4104     if (Op.getOpcode() == ISD::SINT_TO_FP)
4105       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4106                               Op.getValueType());
4107     else
4108       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4109                               Op.getValueType());
4110     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4111                        /*isSigned*/ false, SDLoc(Op)).first;
4112   }
4113 
4114   return Op;
4115 }
4116 
4117 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4118   // Implement fcopysign with a fabs and a conditional fneg.
4119   SDValue Tmp0 = Op.getOperand(0);
4120   SDValue Tmp1 = Op.getOperand(1);
4121   SDLoc dl(Op);
4122   EVT VT = Op.getValueType();
4123   EVT SrcVT = Tmp1.getValueType();
4124   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4125     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4126   bool UseNEON = !InGPR && Subtarget->hasNEON();
4127 
4128   if (UseNEON) {
4129     // Use VBSL to copy the sign bit.
4130     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4131     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4132                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4133     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4134     if (VT == MVT::f64)
4135       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4136                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4137                          DAG.getConstant(32, dl, MVT::i32));
4138     else /*if (VT == MVT::f32)*/
4139       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4140     if (SrcVT == MVT::f32) {
4141       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4142       if (VT == MVT::f64)
4143         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4144                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4145                            DAG.getConstant(32, dl, MVT::i32));
4146     } else if (VT == MVT::f32)
4147       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4148                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4149                          DAG.getConstant(32, dl, MVT::i32));
4150     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4151     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4152 
4153     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4154                                             dl, MVT::i32);
4155     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4156     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4157                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4158 
4159     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4160                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4161                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4162     if (VT == MVT::f32) {
4163       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4164       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4165                         DAG.getConstant(0, dl, MVT::i32));
4166     } else {
4167       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4168     }
4169 
4170     return Res;
4171   }
4172 
4173   // Bitcast operand 1 to i32.
4174   if (SrcVT == MVT::f64)
4175     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4176                        Tmp1).getValue(1);
4177   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4178 
4179   // Or in the signbit with integer operations.
4180   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4181   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4182   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4183   if (VT == MVT::f32) {
4184     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4185                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4186     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4187                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4188   }
4189 
4190   // f64: Or the high part with signbit and then combine two parts.
4191   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4192                      Tmp0);
4193   SDValue Lo = Tmp0.getValue(0);
4194   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4195   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4196   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4197 }
4198 
4199 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4200   MachineFunction &MF = DAG.getMachineFunction();
4201   MachineFrameInfo *MFI = MF.getFrameInfo();
4202   MFI->setReturnAddressIsTaken(true);
4203 
4204   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4205     return SDValue();
4206 
4207   EVT VT = Op.getValueType();
4208   SDLoc dl(Op);
4209   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4210   if (Depth) {
4211     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4212     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4213     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4214                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4215                        MachinePointerInfo(), false, false, false, 0);
4216   }
4217 
4218   // Return LR, which contains the return address. Mark it an implicit live-in.
4219   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4220   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4221 }
4222 
4223 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4224   const ARMBaseRegisterInfo &ARI =
4225     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4226   MachineFunction &MF = DAG.getMachineFunction();
4227   MachineFrameInfo *MFI = MF.getFrameInfo();
4228   MFI->setFrameAddressIsTaken(true);
4229 
4230   EVT VT = Op.getValueType();
4231   SDLoc dl(Op);  // FIXME probably not meaningful
4232   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4233   unsigned FrameReg = ARI.getFrameRegister(MF);
4234   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4235   while (Depth--)
4236     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4237                             MachinePointerInfo(),
4238                             false, false, false, 0);
4239   return FrameAddr;
4240 }
4241 
4242 // FIXME? Maybe this could be a TableGen attribute on some registers and
4243 // this table could be generated automatically from RegInfo.
4244 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4245                                               SelectionDAG &DAG) const {
4246   unsigned Reg = StringSwitch<unsigned>(RegName)
4247                        .Case("sp", ARM::SP)
4248                        .Default(0);
4249   if (Reg)
4250     return Reg;
4251   report_fatal_error(Twine("Invalid register name \""
4252                               + StringRef(RegName)  + "\"."));
4253 }
4254 
4255 // Result is 64 bit value so split into two 32 bit values and return as a
4256 // pair of values.
4257 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4258                                 SelectionDAG &DAG) {
4259   SDLoc DL(N);
4260 
4261   // This function is only supposed to be called for i64 type destination.
4262   assert(N->getValueType(0) == MVT::i64
4263           && "ExpandREAD_REGISTER called for non-i64 type result.");
4264 
4265   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4266                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4267                              N->getOperand(0),
4268                              N->getOperand(1));
4269 
4270   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4271                     Read.getValue(1)));
4272   Results.push_back(Read.getOperand(0));
4273 }
4274 
4275 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4276 /// When \p DstVT, the destination type of \p BC, is on the vector
4277 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4278 /// it might be possible to combine them, such that everything stays on the
4279 /// vector register bank.
4280 /// \p return The node that would replace \p BT, if the combine
4281 /// is possible.
4282 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4283                                                 SelectionDAG &DAG) {
4284   SDValue Op = BC->getOperand(0);
4285   EVT DstVT = BC->getValueType(0);
4286 
4287   // The only vector instruction that can produce a scalar (remember,
4288   // since the bitcast was about to be turned into VMOVDRR, the source
4289   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4290   // Moreover, we can do this combine only if there is one use.
4291   // Finally, if the destination type is not a vector, there is not
4292   // much point on forcing everything on the vector bank.
4293   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4294       !Op.hasOneUse())
4295     return SDValue();
4296 
4297   // If the index is not constant, we will introduce an additional
4298   // multiply that will stick.
4299   // Give up in that case.
4300   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4301   if (!Index)
4302     return SDValue();
4303   unsigned DstNumElt = DstVT.getVectorNumElements();
4304 
4305   // Compute the new index.
4306   const APInt &APIntIndex = Index->getAPIntValue();
4307   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4308   NewIndex *= APIntIndex;
4309   // Check if the new constant index fits into i32.
4310   if (NewIndex.getBitWidth() > 32)
4311     return SDValue();
4312 
4313   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4314   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4315   SDLoc dl(Op);
4316   SDValue ExtractSrc = Op.getOperand(0);
4317   EVT VecVT = EVT::getVectorVT(
4318       *DAG.getContext(), DstVT.getScalarType(),
4319       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4320   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4321   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4322                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4323 }
4324 
4325 /// ExpandBITCAST - If the target supports VFP, this function is called to
4326 /// expand a bit convert where either the source or destination type is i64 to
4327 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4328 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4329 /// vectors), since the legalizer won't know what to do with that.
4330 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4331   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4332   SDLoc dl(N);
4333   SDValue Op = N->getOperand(0);
4334 
4335   // This function is only supposed to be called for i64 types, either as the
4336   // source or destination of the bit convert.
4337   EVT SrcVT = Op.getValueType();
4338   EVT DstVT = N->getValueType(0);
4339   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4340          "ExpandBITCAST called for non-i64 type");
4341 
4342   // Turn i64->f64 into VMOVDRR.
4343   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4344     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4345     // if we can combine the bitcast with its source.
4346     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4347       return Val;
4348 
4349     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4350                              DAG.getConstant(0, dl, MVT::i32));
4351     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4352                              DAG.getConstant(1, dl, MVT::i32));
4353     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4354                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4355   }
4356 
4357   // Turn f64->i64 into VMOVRRD.
4358   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4359     SDValue Cvt;
4360     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4361         SrcVT.getVectorNumElements() > 1)
4362       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4363                         DAG.getVTList(MVT::i32, MVT::i32),
4364                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4365     else
4366       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4367                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4368     // Merge the pieces into a single i64 value.
4369     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4370   }
4371 
4372   return SDValue();
4373 }
4374 
4375 /// getZeroVector - Returns a vector of specified type with all zero elements.
4376 /// Zero vectors are used to represent vector negation and in those cases
4377 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4378 /// not support i64 elements, so sometimes the zero vectors will need to be
4379 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4380 /// zero vector.
4381 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4382   assert(VT.isVector() && "Expected a vector type");
4383   // The canonical modified immediate encoding of a zero vector is....0!
4384   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4385   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4386   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4387   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4388 }
4389 
4390 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4391 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4392 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4393                                                 SelectionDAG &DAG) const {
4394   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4395   EVT VT = Op.getValueType();
4396   unsigned VTBits = VT.getSizeInBits();
4397   SDLoc dl(Op);
4398   SDValue ShOpLo = Op.getOperand(0);
4399   SDValue ShOpHi = Op.getOperand(1);
4400   SDValue ShAmt  = Op.getOperand(2);
4401   SDValue ARMcc;
4402   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4403 
4404   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4405 
4406   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4407                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4408   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4409   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4410                                    DAG.getConstant(VTBits, dl, MVT::i32));
4411   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4412   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4413   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4414 
4415   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4416   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4417                           ISD::SETGE, ARMcc, DAG, dl);
4418   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4419   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4420                            CCR, Cmp);
4421 
4422   SDValue Ops[2] = { Lo, Hi };
4423   return DAG.getMergeValues(Ops, dl);
4424 }
4425 
4426 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4427 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4428 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4429                                                SelectionDAG &DAG) const {
4430   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4431   EVT VT = Op.getValueType();
4432   unsigned VTBits = VT.getSizeInBits();
4433   SDLoc dl(Op);
4434   SDValue ShOpLo = Op.getOperand(0);
4435   SDValue ShOpHi = Op.getOperand(1);
4436   SDValue ShAmt  = Op.getOperand(2);
4437   SDValue ARMcc;
4438 
4439   assert(Op.getOpcode() == ISD::SHL_PARTS);
4440   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4441                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4442   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4443   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4444                                    DAG.getConstant(VTBits, dl, MVT::i32));
4445   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4446   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4447 
4448   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4449   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4450   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4451                           ISD::SETGE, ARMcc, DAG, dl);
4452   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4453   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4454                            CCR, Cmp);
4455 
4456   SDValue Ops[2] = { Lo, Hi };
4457   return DAG.getMergeValues(Ops, dl);
4458 }
4459 
4460 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4461                                             SelectionDAG &DAG) const {
4462   // The rounding mode is in bits 23:22 of the FPSCR.
4463   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4464   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4465   // so that the shift + and get folded into a bitfield extract.
4466   SDLoc dl(Op);
4467   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4468                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4469                                               MVT::i32));
4470   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4471                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4472   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4473                               DAG.getConstant(22, dl, MVT::i32));
4474   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4475                      DAG.getConstant(3, dl, MVT::i32));
4476 }
4477 
4478 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4479                          const ARMSubtarget *ST) {
4480   SDLoc dl(N);
4481   EVT VT = N->getValueType(0);
4482   if (VT.isVector()) {
4483     assert(ST->hasNEON());
4484 
4485     // Compute the least significant set bit: LSB = X & -X
4486     SDValue X = N->getOperand(0);
4487     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4488     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4489 
4490     EVT ElemTy = VT.getVectorElementType();
4491 
4492     if (ElemTy == MVT::i8) {
4493       // Compute with: cttz(x) = ctpop(lsb - 1)
4494       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4495                                 DAG.getTargetConstant(1, dl, ElemTy));
4496       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4497       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4498     }
4499 
4500     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4501         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4502       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4503       unsigned NumBits = ElemTy.getSizeInBits();
4504       SDValue WidthMinus1 =
4505           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4506                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4507       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4508       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4509     }
4510 
4511     // Compute with: cttz(x) = ctpop(lsb - 1)
4512 
4513     // Since we can only compute the number of bits in a byte with vcnt.8, we
4514     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4515     // and i64.
4516 
4517     // Compute LSB - 1.
4518     SDValue Bits;
4519     if (ElemTy == MVT::i64) {
4520       // Load constant 0xffff'ffff'ffff'ffff to register.
4521       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4522                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4523       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4524     } else {
4525       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4526                                 DAG.getTargetConstant(1, dl, ElemTy));
4527       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4528     }
4529 
4530     // Count #bits with vcnt.8.
4531     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4532     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4533     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4534 
4535     // Gather the #bits with vpaddl (pairwise add.)
4536     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4537     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4538         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4539         Cnt8);
4540     if (ElemTy == MVT::i16)
4541       return Cnt16;
4542 
4543     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4544     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4545         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4546         Cnt16);
4547     if (ElemTy == MVT::i32)
4548       return Cnt32;
4549 
4550     assert(ElemTy == MVT::i64);
4551     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4552         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4553         Cnt32);
4554     return Cnt64;
4555   }
4556 
4557   if (!ST->hasV6T2Ops())
4558     return SDValue();
4559 
4560   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4561   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4562 }
4563 
4564 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4565 /// for each 16-bit element from operand, repeated.  The basic idea is to
4566 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4567 ///
4568 /// Trace for v4i16:
4569 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4570 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4571 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4572 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4573 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4574 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4575 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4576 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4577 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4578   EVT VT = N->getValueType(0);
4579   SDLoc DL(N);
4580 
4581   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4582   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4583   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4584   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4585   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4586   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4587 }
4588 
4589 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4590 /// bit-count for each 16-bit element from the operand.  We need slightly
4591 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4592 /// 64/128-bit registers.
4593 ///
4594 /// Trace for v4i16:
4595 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4596 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4597 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4598 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4599 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4600   EVT VT = N->getValueType(0);
4601   SDLoc DL(N);
4602 
4603   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4604   if (VT.is64BitVector()) {
4605     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4606     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4607                        DAG.getIntPtrConstant(0, DL));
4608   } else {
4609     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4610                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4611     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4612   }
4613 }
4614 
4615 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4616 /// bit-count for each 32-bit element from the operand.  The idea here is
4617 /// to split the vector into 16-bit elements, leverage the 16-bit count
4618 /// routine, and then combine the results.
4619 ///
4620 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4621 /// input    = [v0    v1    ] (vi: 32-bit elements)
4622 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4623 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4624 /// vrev: N0 = [k1 k0 k3 k2 ]
4625 ///            [k0 k1 k2 k3 ]
4626 ///       N1 =+[k1 k0 k3 k2 ]
4627 ///            [k0 k2 k1 k3 ]
4628 ///       N2 =+[k1 k3 k0 k2 ]
4629 ///            [k0    k2    k1    k3    ]
4630 /// Extended =+[k1    k3    k0    k2    ]
4631 ///            [k0    k2    ]
4632 /// Extracted=+[k1    k3    ]
4633 ///
4634 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4635   EVT VT = N->getValueType(0);
4636   SDLoc DL(N);
4637 
4638   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4639 
4640   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4641   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4642   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4643   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4644   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4645 
4646   if (VT.is64BitVector()) {
4647     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4648     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4649                        DAG.getIntPtrConstant(0, DL));
4650   } else {
4651     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4652                                     DAG.getIntPtrConstant(0, DL));
4653     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4654   }
4655 }
4656 
4657 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4658                           const ARMSubtarget *ST) {
4659   EVT VT = N->getValueType(0);
4660 
4661   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4662   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4663           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4664          "Unexpected type for custom ctpop lowering");
4665 
4666   if (VT.getVectorElementType() == MVT::i32)
4667     return lowerCTPOP32BitElements(N, DAG);
4668   else
4669     return lowerCTPOP16BitElements(N, DAG);
4670 }
4671 
4672 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4673                           const ARMSubtarget *ST) {
4674   EVT VT = N->getValueType(0);
4675   SDLoc dl(N);
4676 
4677   if (!VT.isVector())
4678     return SDValue();
4679 
4680   // Lower vector shifts on NEON to use VSHL.
4681   assert(ST->hasNEON() && "unexpected vector shift");
4682 
4683   // Left shifts translate directly to the vshiftu intrinsic.
4684   if (N->getOpcode() == ISD::SHL)
4685     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4686                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4687                                        MVT::i32),
4688                        N->getOperand(0), N->getOperand(1));
4689 
4690   assert((N->getOpcode() == ISD::SRA ||
4691           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4692 
4693   // NEON uses the same intrinsics for both left and right shifts.  For
4694   // right shifts, the shift amounts are negative, so negate the vector of
4695   // shift amounts.
4696   EVT ShiftVT = N->getOperand(1).getValueType();
4697   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4698                                      getZeroVector(ShiftVT, DAG, dl),
4699                                      N->getOperand(1));
4700   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4701                              Intrinsic::arm_neon_vshifts :
4702                              Intrinsic::arm_neon_vshiftu);
4703   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4704                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4705                      N->getOperand(0), NegatedCount);
4706 }
4707 
4708 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4709                                 const ARMSubtarget *ST) {
4710   EVT VT = N->getValueType(0);
4711   SDLoc dl(N);
4712 
4713   // We can get here for a node like i32 = ISD::SHL i32, i64
4714   if (VT != MVT::i64)
4715     return SDValue();
4716 
4717   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4718          "Unknown shift to lower!");
4719 
4720   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4721   if (!isOneConstant(N->getOperand(1)))
4722     return SDValue();
4723 
4724   // If we are in thumb mode, we don't have RRX.
4725   if (ST->isThumb1Only()) return SDValue();
4726 
4727   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4728   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4729                            DAG.getConstant(0, dl, MVT::i32));
4730   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4731                            DAG.getConstant(1, dl, MVT::i32));
4732 
4733   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4734   // captures the result into a carry flag.
4735   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4736   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4737 
4738   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4739   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4740 
4741   // Merge the pieces into a single i64 value.
4742  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4743 }
4744 
4745 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4746   SDValue TmpOp0, TmpOp1;
4747   bool Invert = false;
4748   bool Swap = false;
4749   unsigned Opc = 0;
4750 
4751   SDValue Op0 = Op.getOperand(0);
4752   SDValue Op1 = Op.getOperand(1);
4753   SDValue CC = Op.getOperand(2);
4754   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4755   EVT VT = Op.getValueType();
4756   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4757   SDLoc dl(Op);
4758 
4759   if (CmpVT.getVectorElementType() == MVT::i64)
4760     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4761     // but it's possible that our operands are 64-bit but our result is 32-bit.
4762     // Bail in this case.
4763     return SDValue();
4764 
4765   if (Op1.getValueType().isFloatingPoint()) {
4766     switch (SetCCOpcode) {
4767     default: llvm_unreachable("Illegal FP comparison");
4768     case ISD::SETUNE:
4769     case ISD::SETNE:  Invert = true; // Fallthrough
4770     case ISD::SETOEQ:
4771     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4772     case ISD::SETOLT:
4773     case ISD::SETLT: Swap = true; // Fallthrough
4774     case ISD::SETOGT:
4775     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4776     case ISD::SETOLE:
4777     case ISD::SETLE:  Swap = true; // Fallthrough
4778     case ISD::SETOGE:
4779     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4780     case ISD::SETUGE: Swap = true; // Fallthrough
4781     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4782     case ISD::SETUGT: Swap = true; // Fallthrough
4783     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4784     case ISD::SETUEQ: Invert = true; // Fallthrough
4785     case ISD::SETONE:
4786       // Expand this to (OLT | OGT).
4787       TmpOp0 = Op0;
4788       TmpOp1 = Op1;
4789       Opc = ISD::OR;
4790       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4791       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4792       break;
4793     case ISD::SETUO: Invert = true; // Fallthrough
4794     case ISD::SETO:
4795       // Expand this to (OLT | OGE).
4796       TmpOp0 = Op0;
4797       TmpOp1 = Op1;
4798       Opc = ISD::OR;
4799       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4800       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4801       break;
4802     }
4803   } else {
4804     // Integer comparisons.
4805     switch (SetCCOpcode) {
4806     default: llvm_unreachable("Illegal integer comparison");
4807     case ISD::SETNE:  Invert = true;
4808     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4809     case ISD::SETLT:  Swap = true;
4810     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4811     case ISD::SETLE:  Swap = true;
4812     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4813     case ISD::SETULT: Swap = true;
4814     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4815     case ISD::SETULE: Swap = true;
4816     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4817     }
4818 
4819     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4820     if (Opc == ARMISD::VCEQ) {
4821 
4822       SDValue AndOp;
4823       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4824         AndOp = Op0;
4825       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4826         AndOp = Op1;
4827 
4828       // Ignore bitconvert.
4829       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4830         AndOp = AndOp.getOperand(0);
4831 
4832       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4833         Opc = ARMISD::VTST;
4834         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4835         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4836         Invert = !Invert;
4837       }
4838     }
4839   }
4840 
4841   if (Swap)
4842     std::swap(Op0, Op1);
4843 
4844   // If one of the operands is a constant vector zero, attempt to fold the
4845   // comparison to a specialized compare-against-zero form.
4846   SDValue SingleOp;
4847   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4848     SingleOp = Op0;
4849   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4850     if (Opc == ARMISD::VCGE)
4851       Opc = ARMISD::VCLEZ;
4852     else if (Opc == ARMISD::VCGT)
4853       Opc = ARMISD::VCLTZ;
4854     SingleOp = Op1;
4855   }
4856 
4857   SDValue Result;
4858   if (SingleOp.getNode()) {
4859     switch (Opc) {
4860     case ARMISD::VCEQ:
4861       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4862     case ARMISD::VCGE:
4863       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4864     case ARMISD::VCLEZ:
4865       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4866     case ARMISD::VCGT:
4867       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4868     case ARMISD::VCLTZ:
4869       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4870     default:
4871       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4872     }
4873   } else {
4874      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4875   }
4876 
4877   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4878 
4879   if (Invert)
4880     Result = DAG.getNOT(dl, Result, VT);
4881 
4882   return Result;
4883 }
4884 
4885 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4886 /// valid vector constant for a NEON instruction with a "modified immediate"
4887 /// operand (e.g., VMOV).  If so, return the encoded value.
4888 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4889                                  unsigned SplatBitSize, SelectionDAG &DAG,
4890                                  SDLoc dl, EVT &VT, bool is128Bits,
4891                                  NEONModImmType type) {
4892   unsigned OpCmode, Imm;
4893 
4894   // SplatBitSize is set to the smallest size that splats the vector, so a
4895   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4896   // immediate instructions others than VMOV do not support the 8-bit encoding
4897   // of a zero vector, and the default encoding of zero is supposed to be the
4898   // 32-bit version.
4899   if (SplatBits == 0)
4900     SplatBitSize = 32;
4901 
4902   switch (SplatBitSize) {
4903   case 8:
4904     if (type != VMOVModImm)
4905       return SDValue();
4906     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4907     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4908     OpCmode = 0xe;
4909     Imm = SplatBits;
4910     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4911     break;
4912 
4913   case 16:
4914     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4915     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4916     if ((SplatBits & ~0xff) == 0) {
4917       // Value = 0x00nn: Op=x, Cmode=100x.
4918       OpCmode = 0x8;
4919       Imm = SplatBits;
4920       break;
4921     }
4922     if ((SplatBits & ~0xff00) == 0) {
4923       // Value = 0xnn00: Op=x, Cmode=101x.
4924       OpCmode = 0xa;
4925       Imm = SplatBits >> 8;
4926       break;
4927     }
4928     return SDValue();
4929 
4930   case 32:
4931     // NEON's 32-bit VMOV supports splat values where:
4932     // * only one byte is nonzero, or
4933     // * the least significant byte is 0xff and the second byte is nonzero, or
4934     // * the least significant 2 bytes are 0xff and the third is nonzero.
4935     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4936     if ((SplatBits & ~0xff) == 0) {
4937       // Value = 0x000000nn: Op=x, Cmode=000x.
4938       OpCmode = 0;
4939       Imm = SplatBits;
4940       break;
4941     }
4942     if ((SplatBits & ~0xff00) == 0) {
4943       // Value = 0x0000nn00: Op=x, Cmode=001x.
4944       OpCmode = 0x2;
4945       Imm = SplatBits >> 8;
4946       break;
4947     }
4948     if ((SplatBits & ~0xff0000) == 0) {
4949       // Value = 0x00nn0000: Op=x, Cmode=010x.
4950       OpCmode = 0x4;
4951       Imm = SplatBits >> 16;
4952       break;
4953     }
4954     if ((SplatBits & ~0xff000000) == 0) {
4955       // Value = 0xnn000000: Op=x, Cmode=011x.
4956       OpCmode = 0x6;
4957       Imm = SplatBits >> 24;
4958       break;
4959     }
4960 
4961     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4962     if (type == OtherModImm) return SDValue();
4963 
4964     if ((SplatBits & ~0xffff) == 0 &&
4965         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4966       // Value = 0x0000nnff: Op=x, Cmode=1100.
4967       OpCmode = 0xc;
4968       Imm = SplatBits >> 8;
4969       break;
4970     }
4971 
4972     if ((SplatBits & ~0xffffff) == 0 &&
4973         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4974       // Value = 0x00nnffff: Op=x, Cmode=1101.
4975       OpCmode = 0xd;
4976       Imm = SplatBits >> 16;
4977       break;
4978     }
4979 
4980     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4981     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4982     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4983     // and fall through here to test for a valid 64-bit splat.  But, then the
4984     // caller would also need to check and handle the change in size.
4985     return SDValue();
4986 
4987   case 64: {
4988     if (type != VMOVModImm)
4989       return SDValue();
4990     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4991     uint64_t BitMask = 0xff;
4992     uint64_t Val = 0;
4993     unsigned ImmMask = 1;
4994     Imm = 0;
4995     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4996       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4997         Val |= BitMask;
4998         Imm |= ImmMask;
4999       } else if ((SplatBits & BitMask) != 0) {
5000         return SDValue();
5001       }
5002       BitMask <<= 8;
5003       ImmMask <<= 1;
5004     }
5005 
5006     if (DAG.getDataLayout().isBigEndian())
5007       // swap higher and lower 32 bit word
5008       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5009 
5010     // Op=1, Cmode=1110.
5011     OpCmode = 0x1e;
5012     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5013     break;
5014   }
5015 
5016   default:
5017     llvm_unreachable("unexpected size for isNEONModifiedImm");
5018   }
5019 
5020   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5021   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5022 }
5023 
5024 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5025                                            const ARMSubtarget *ST) const {
5026   if (!ST->hasVFP3())
5027     return SDValue();
5028 
5029   bool IsDouble = Op.getValueType() == MVT::f64;
5030   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5031 
5032   // Use the default (constant pool) lowering for double constants when we have
5033   // an SP-only FPU
5034   if (IsDouble && Subtarget->isFPOnlySP())
5035     return SDValue();
5036 
5037   // Try splatting with a VMOV.f32...
5038   APFloat FPVal = CFP->getValueAPF();
5039   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5040 
5041   if (ImmVal != -1) {
5042     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5043       // We have code in place to select a valid ConstantFP already, no need to
5044       // do any mangling.
5045       return Op;
5046     }
5047 
5048     // It's a float and we are trying to use NEON operations where
5049     // possible. Lower it to a splat followed by an extract.
5050     SDLoc DL(Op);
5051     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5052     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5053                                       NewVal);
5054     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5055                        DAG.getConstant(0, DL, MVT::i32));
5056   }
5057 
5058   // The rest of our options are NEON only, make sure that's allowed before
5059   // proceeding..
5060   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5061     return SDValue();
5062 
5063   EVT VMovVT;
5064   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5065 
5066   // It wouldn't really be worth bothering for doubles except for one very
5067   // important value, which does happen to match: 0.0. So make sure we don't do
5068   // anything stupid.
5069   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5070     return SDValue();
5071 
5072   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5073   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5074                                      VMovVT, false, VMOVModImm);
5075   if (NewVal != SDValue()) {
5076     SDLoc DL(Op);
5077     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5078                                       NewVal);
5079     if (IsDouble)
5080       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5081 
5082     // It's a float: cast and extract a vector element.
5083     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5084                                        VecConstant);
5085     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5086                        DAG.getConstant(0, DL, MVT::i32));
5087   }
5088 
5089   // Finally, try a VMVN.i32
5090   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5091                              false, VMVNModImm);
5092   if (NewVal != SDValue()) {
5093     SDLoc DL(Op);
5094     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5095 
5096     if (IsDouble)
5097       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5098 
5099     // It's a float: cast and extract a vector element.
5100     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5101                                        VecConstant);
5102     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5103                        DAG.getConstant(0, DL, MVT::i32));
5104   }
5105 
5106   return SDValue();
5107 }
5108 
5109 // check if an VEXT instruction can handle the shuffle mask when the
5110 // vector sources of the shuffle are the same.
5111 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5112   unsigned NumElts = VT.getVectorNumElements();
5113 
5114   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5115   if (M[0] < 0)
5116     return false;
5117 
5118   Imm = M[0];
5119 
5120   // If this is a VEXT shuffle, the immediate value is the index of the first
5121   // element.  The other shuffle indices must be the successive elements after
5122   // the first one.
5123   unsigned ExpectedElt = Imm;
5124   for (unsigned i = 1; i < NumElts; ++i) {
5125     // Increment the expected index.  If it wraps around, just follow it
5126     // back to index zero and keep going.
5127     ++ExpectedElt;
5128     if (ExpectedElt == NumElts)
5129       ExpectedElt = 0;
5130 
5131     if (M[i] < 0) continue; // ignore UNDEF indices
5132     if (ExpectedElt != static_cast<unsigned>(M[i]))
5133       return false;
5134   }
5135 
5136   return true;
5137 }
5138 
5139 
5140 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5141                        bool &ReverseVEXT, unsigned &Imm) {
5142   unsigned NumElts = VT.getVectorNumElements();
5143   ReverseVEXT = false;
5144 
5145   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5146   if (M[0] < 0)
5147     return false;
5148 
5149   Imm = M[0];
5150 
5151   // If this is a VEXT shuffle, the immediate value is the index of the first
5152   // element.  The other shuffle indices must be the successive elements after
5153   // the first one.
5154   unsigned ExpectedElt = Imm;
5155   for (unsigned i = 1; i < NumElts; ++i) {
5156     // Increment the expected index.  If it wraps around, it may still be
5157     // a VEXT but the source vectors must be swapped.
5158     ExpectedElt += 1;
5159     if (ExpectedElt == NumElts * 2) {
5160       ExpectedElt = 0;
5161       ReverseVEXT = true;
5162     }
5163 
5164     if (M[i] < 0) continue; // ignore UNDEF indices
5165     if (ExpectedElt != static_cast<unsigned>(M[i]))
5166       return false;
5167   }
5168 
5169   // Adjust the index value if the source operands will be swapped.
5170   if (ReverseVEXT)
5171     Imm -= NumElts;
5172 
5173   return true;
5174 }
5175 
5176 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5177 /// instruction with the specified blocksize.  (The order of the elements
5178 /// within each block of the vector is reversed.)
5179 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5180   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5181          "Only possible block sizes for VREV are: 16, 32, 64");
5182 
5183   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5184   if (EltSz == 64)
5185     return false;
5186 
5187   unsigned NumElts = VT.getVectorNumElements();
5188   unsigned BlockElts = M[0] + 1;
5189   // If the first shuffle index is UNDEF, be optimistic.
5190   if (M[0] < 0)
5191     BlockElts = BlockSize / EltSz;
5192 
5193   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5194     return false;
5195 
5196   for (unsigned i = 0; i < NumElts; ++i) {
5197     if (M[i] < 0) continue; // ignore UNDEF indices
5198     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5199       return false;
5200   }
5201 
5202   return true;
5203 }
5204 
5205 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5206   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5207   // range, then 0 is placed into the resulting vector. So pretty much any mask
5208   // of 8 elements can work here.
5209   return VT == MVT::v8i8 && M.size() == 8;
5210 }
5211 
5212 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5213 // checking that pairs of elements in the shuffle mask represent the same index
5214 // in each vector, incrementing the expected index by 2 at each step.
5215 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5216 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5217 //  v2={e,f,g,h}
5218 // WhichResult gives the offset for each element in the mask based on which
5219 // of the two results it belongs to.
5220 //
5221 // The transpose can be represented either as:
5222 // result1 = shufflevector v1, v2, result1_shuffle_mask
5223 // result2 = shufflevector v1, v2, result2_shuffle_mask
5224 // where v1/v2 and the shuffle masks have the same number of elements
5225 // (here WhichResult (see below) indicates which result is being checked)
5226 //
5227 // or as:
5228 // results = shufflevector v1, v2, shuffle_mask
5229 // where both results are returned in one vector and the shuffle mask has twice
5230 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5231 // want to check the low half and high half of the shuffle mask as if it were
5232 // the other case
5233 static bool isVTRNMask(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   // If the mask is twice as long as the input vector then we need to check the
5243   // upper and lower parts of the mask with a matching value for WhichResult
5244   // FIXME: A mask with only even values will be rejected in case the first
5245   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5246   // M[0] is used to determine WhichResult
5247   for (unsigned i = 0; i < M.size(); i += NumElts) {
5248     if (M.size() == NumElts * 2)
5249       WhichResult = i / NumElts;
5250     else
5251       WhichResult = M[i] == 0 ? 0 : 1;
5252     for (unsigned j = 0; j < NumElts; j += 2) {
5253       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5254           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5255         return false;
5256     }
5257   }
5258 
5259   if (M.size() == NumElts*2)
5260     WhichResult = 0;
5261 
5262   return true;
5263 }
5264 
5265 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5266 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5267 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5268 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5269   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5270   if (EltSz == 64)
5271     return false;
5272 
5273   unsigned NumElts = VT.getVectorNumElements();
5274   if (M.size() != NumElts && M.size() != NumElts*2)
5275     return false;
5276 
5277   for (unsigned i = 0; i < M.size(); i += NumElts) {
5278     if (M.size() == NumElts * 2)
5279       WhichResult = i / NumElts;
5280     else
5281       WhichResult = M[i] == 0 ? 0 : 1;
5282     for (unsigned j = 0; j < NumElts; j += 2) {
5283       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5284           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5285         return false;
5286     }
5287   }
5288 
5289   if (M.size() == NumElts*2)
5290     WhichResult = 0;
5291 
5292   return true;
5293 }
5294 
5295 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5296 // that the mask elements are either all even and in steps of size 2 or all odd
5297 // and in steps of size 2.
5298 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5299 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5300 //  v2={e,f,g,h}
5301 // Requires similar checks to that of isVTRNMask with
5302 // respect the how results are returned.
5303 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5304   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5305   if (EltSz == 64)
5306     return false;
5307 
5308   unsigned NumElts = VT.getVectorNumElements();
5309   if (M.size() != NumElts && M.size() != NumElts*2)
5310     return false;
5311 
5312   for (unsigned i = 0; i < M.size(); i += NumElts) {
5313     WhichResult = M[i] == 0 ? 0 : 1;
5314     for (unsigned j = 0; j < NumElts; ++j) {
5315       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5316         return false;
5317     }
5318   }
5319 
5320   if (M.size() == NumElts*2)
5321     WhichResult = 0;
5322 
5323   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5324   if (VT.is64BitVector() && EltSz == 32)
5325     return false;
5326 
5327   return true;
5328 }
5329 
5330 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5331 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5332 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5333 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5334   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5335   if (EltSz == 64)
5336     return false;
5337 
5338   unsigned NumElts = VT.getVectorNumElements();
5339   if (M.size() != NumElts && M.size() != NumElts*2)
5340     return false;
5341 
5342   unsigned Half = NumElts / 2;
5343   for (unsigned i = 0; i < M.size(); i += NumElts) {
5344     WhichResult = M[i] == 0 ? 0 : 1;
5345     for (unsigned j = 0; j < NumElts; j += Half) {
5346       unsigned Idx = WhichResult;
5347       for (unsigned k = 0; k < Half; ++k) {
5348         int MIdx = M[i + j + k];
5349         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5350           return false;
5351         Idx += 2;
5352       }
5353     }
5354   }
5355 
5356   if (M.size() == NumElts*2)
5357     WhichResult = 0;
5358 
5359   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5360   if (VT.is64BitVector() && EltSz == 32)
5361     return false;
5362 
5363   return true;
5364 }
5365 
5366 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5367 // that pairs of elements of the shufflemask represent the same index in each
5368 // vector incrementing sequentially through the vectors.
5369 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5370 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5371 //  v2={e,f,g,h}
5372 // Requires similar checks to that of isVTRNMask with respect the how results
5373 // are returned.
5374 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5375   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5376   if (EltSz == 64)
5377     return false;
5378 
5379   unsigned NumElts = VT.getVectorNumElements();
5380   if (M.size() != NumElts && M.size() != NumElts*2)
5381     return false;
5382 
5383   for (unsigned i = 0; i < M.size(); i += NumElts) {
5384     WhichResult = M[i] == 0 ? 0 : 1;
5385     unsigned Idx = WhichResult * NumElts / 2;
5386     for (unsigned j = 0; j < NumElts; j += 2) {
5387       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5388           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5389         return false;
5390       Idx += 1;
5391     }
5392   }
5393 
5394   if (M.size() == NumElts*2)
5395     WhichResult = 0;
5396 
5397   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5398   if (VT.is64BitVector() && EltSz == 32)
5399     return false;
5400 
5401   return true;
5402 }
5403 
5404 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5405 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5406 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5407 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5408   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5409   if (EltSz == 64)
5410     return false;
5411 
5412   unsigned NumElts = VT.getVectorNumElements();
5413   if (M.size() != NumElts && M.size() != NumElts*2)
5414     return false;
5415 
5416   for (unsigned i = 0; i < M.size(); i += NumElts) {
5417     WhichResult = M[i] == 0 ? 0 : 1;
5418     unsigned Idx = WhichResult * NumElts / 2;
5419     for (unsigned j = 0; j < NumElts; j += 2) {
5420       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5421           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5422         return false;
5423       Idx += 1;
5424     }
5425   }
5426 
5427   if (M.size() == NumElts*2)
5428     WhichResult = 0;
5429 
5430   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5431   if (VT.is64BitVector() && EltSz == 32)
5432     return false;
5433 
5434   return true;
5435 }
5436 
5437 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5438 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5439 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5440                                            unsigned &WhichResult,
5441                                            bool &isV_UNDEF) {
5442   isV_UNDEF = false;
5443   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5444     return ARMISD::VTRN;
5445   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5446     return ARMISD::VUZP;
5447   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5448     return ARMISD::VZIP;
5449 
5450   isV_UNDEF = true;
5451   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5452     return ARMISD::VTRN;
5453   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5454     return ARMISD::VUZP;
5455   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5456     return ARMISD::VZIP;
5457 
5458   return 0;
5459 }
5460 
5461 /// \return true if this is a reverse operation on an vector.
5462 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5463   unsigned NumElts = VT.getVectorNumElements();
5464   // Make sure the mask has the right size.
5465   if (NumElts != M.size())
5466       return false;
5467 
5468   // Look for <15, ..., 3, -1, 1, 0>.
5469   for (unsigned i = 0; i != NumElts; ++i)
5470     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5471       return false;
5472 
5473   return true;
5474 }
5475 
5476 // If N is an integer constant that can be moved into a register in one
5477 // instruction, return an SDValue of such a constant (will become a MOV
5478 // instruction).  Otherwise return null.
5479 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5480                                      const ARMSubtarget *ST, SDLoc dl) {
5481   uint64_t Val;
5482   if (!isa<ConstantSDNode>(N))
5483     return SDValue();
5484   Val = cast<ConstantSDNode>(N)->getZExtValue();
5485 
5486   if (ST->isThumb1Only()) {
5487     if (Val <= 255 || ~Val <= 255)
5488       return DAG.getConstant(Val, dl, MVT::i32);
5489   } else {
5490     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5491       return DAG.getConstant(Val, dl, MVT::i32);
5492   }
5493   return SDValue();
5494 }
5495 
5496 // If this is a case we can't handle, return null and let the default
5497 // expansion code take care of it.
5498 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5499                                              const ARMSubtarget *ST) const {
5500   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5501   SDLoc dl(Op);
5502   EVT VT = Op.getValueType();
5503 
5504   APInt SplatBits, SplatUndef;
5505   unsigned SplatBitSize;
5506   bool HasAnyUndefs;
5507   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5508     if (SplatBitSize <= 64) {
5509       // Check if an immediate VMOV works.
5510       EVT VmovVT;
5511       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5512                                       SplatUndef.getZExtValue(), SplatBitSize,
5513                                       DAG, dl, VmovVT, VT.is128BitVector(),
5514                                       VMOVModImm);
5515       if (Val.getNode()) {
5516         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5517         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5518       }
5519 
5520       // Try an immediate VMVN.
5521       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5522       Val = isNEONModifiedImm(NegatedImm,
5523                                       SplatUndef.getZExtValue(), SplatBitSize,
5524                                       DAG, dl, VmovVT, VT.is128BitVector(),
5525                                       VMVNModImm);
5526       if (Val.getNode()) {
5527         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5528         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5529       }
5530 
5531       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5532       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5533         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5534         if (ImmVal != -1) {
5535           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5536           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5537         }
5538       }
5539     }
5540   }
5541 
5542   // Scan through the operands to see if only one value is used.
5543   //
5544   // As an optimisation, even if more than one value is used it may be more
5545   // profitable to splat with one value then change some lanes.
5546   //
5547   // Heuristically we decide to do this if the vector has a "dominant" value,
5548   // defined as splatted to more than half of the lanes.
5549   unsigned NumElts = VT.getVectorNumElements();
5550   bool isOnlyLowElement = true;
5551   bool usesOnlyOneValue = true;
5552   bool hasDominantValue = false;
5553   bool isConstant = true;
5554 
5555   // Map of the number of times a particular SDValue appears in the
5556   // element list.
5557   DenseMap<SDValue, unsigned> ValueCounts;
5558   SDValue Value;
5559   for (unsigned i = 0; i < NumElts; ++i) {
5560     SDValue V = Op.getOperand(i);
5561     if (V.getOpcode() == ISD::UNDEF)
5562       continue;
5563     if (i > 0)
5564       isOnlyLowElement = false;
5565     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5566       isConstant = false;
5567 
5568     ValueCounts.insert(std::make_pair(V, 0));
5569     unsigned &Count = ValueCounts[V];
5570 
5571     // Is this value dominant? (takes up more than half of the lanes)
5572     if (++Count > (NumElts / 2)) {
5573       hasDominantValue = true;
5574       Value = V;
5575     }
5576   }
5577   if (ValueCounts.size() != 1)
5578     usesOnlyOneValue = false;
5579   if (!Value.getNode() && ValueCounts.size() > 0)
5580     Value = ValueCounts.begin()->first;
5581 
5582   if (ValueCounts.size() == 0)
5583     return DAG.getUNDEF(VT);
5584 
5585   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5586   // Keep going if we are hitting this case.
5587   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5588     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5589 
5590   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5591 
5592   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5593   // i32 and try again.
5594   if (hasDominantValue && EltSize <= 32) {
5595     if (!isConstant) {
5596       SDValue N;
5597 
5598       // If we are VDUPing a value that comes directly from a vector, that will
5599       // cause an unnecessary move to and from a GPR, where instead we could
5600       // just use VDUPLANE. We can only do this if the lane being extracted
5601       // is at a constant index, as the VDUP from lane instructions only have
5602       // constant-index forms.
5603       ConstantSDNode *constIndex;
5604       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5605           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5606         // We need to create a new undef vector to use for the VDUPLANE if the
5607         // size of the vector from which we get the value is different than the
5608         // size of the vector that we need to create. We will insert the element
5609         // such that the register coalescer will remove unnecessary copies.
5610         if (VT != Value->getOperand(0).getValueType()) {
5611           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5612                              VT.getVectorNumElements();
5613           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5614                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5615                         Value, DAG.getConstant(index, dl, MVT::i32)),
5616                            DAG.getConstant(index, dl, MVT::i32));
5617         } else
5618           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5619                         Value->getOperand(0), Value->getOperand(1));
5620       } else
5621         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5622 
5623       if (!usesOnlyOneValue) {
5624         // The dominant value was splatted as 'N', but we now have to insert
5625         // all differing elements.
5626         for (unsigned I = 0; I < NumElts; ++I) {
5627           if (Op.getOperand(I) == Value)
5628             continue;
5629           SmallVector<SDValue, 3> Ops;
5630           Ops.push_back(N);
5631           Ops.push_back(Op.getOperand(I));
5632           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5633           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5634         }
5635       }
5636       return N;
5637     }
5638     if (VT.getVectorElementType().isFloatingPoint()) {
5639       SmallVector<SDValue, 8> Ops;
5640       for (unsigned i = 0; i < NumElts; ++i)
5641         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5642                                   Op.getOperand(i)));
5643       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5644       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5645       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5646       if (Val.getNode())
5647         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5648     }
5649     if (usesOnlyOneValue) {
5650       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5651       if (isConstant && Val.getNode())
5652         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5653     }
5654   }
5655 
5656   // If all elements are constants and the case above didn't get hit, fall back
5657   // to the default expansion, which will generate a load from the constant
5658   // pool.
5659   if (isConstant)
5660     return SDValue();
5661 
5662   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5663   if (NumElts >= 4) {
5664     SDValue shuffle = ReconstructShuffle(Op, DAG);
5665     if (shuffle != SDValue())
5666       return shuffle;
5667   }
5668 
5669   // Vectors with 32- or 64-bit elements can be built by directly assigning
5670   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5671   // will be legalized.
5672   if (EltSize >= 32) {
5673     // Do the expansion with floating-point types, since that is what the VFP
5674     // registers are defined to use, and since i64 is not legal.
5675     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5676     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5677     SmallVector<SDValue, 8> Ops;
5678     for (unsigned i = 0; i < NumElts; ++i)
5679       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5680     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5681     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5682   }
5683 
5684   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5685   // know the default expansion would otherwise fall back on something even
5686   // worse. For a vector with one or two non-undef values, that's
5687   // scalar_to_vector for the elements followed by a shuffle (provided the
5688   // shuffle is valid for the target) and materialization element by element
5689   // on the stack followed by a load for everything else.
5690   if (!isConstant && !usesOnlyOneValue) {
5691     SDValue Vec = DAG.getUNDEF(VT);
5692     for (unsigned i = 0 ; i < NumElts; ++i) {
5693       SDValue V = Op.getOperand(i);
5694       if (V.getOpcode() == ISD::UNDEF)
5695         continue;
5696       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5697       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5698     }
5699     return Vec;
5700   }
5701 
5702   return SDValue();
5703 }
5704 
5705 // Gather data to see if the operation can be modelled as a
5706 // shuffle in combination with VEXTs.
5707 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5708                                               SelectionDAG &DAG) const {
5709   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5710   SDLoc dl(Op);
5711   EVT VT = Op.getValueType();
5712   unsigned NumElts = VT.getVectorNumElements();
5713 
5714   struct ShuffleSourceInfo {
5715     SDValue Vec;
5716     unsigned MinElt;
5717     unsigned MaxElt;
5718 
5719     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5720     // be compatible with the shuffle we intend to construct. As a result
5721     // ShuffleVec will be some sliding window into the original Vec.
5722     SDValue ShuffleVec;
5723 
5724     // Code should guarantee that element i in Vec starts at element "WindowBase
5725     // + i * WindowScale in ShuffleVec".
5726     int WindowBase;
5727     int WindowScale;
5728 
5729     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5730     ShuffleSourceInfo(SDValue Vec)
5731         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5732           WindowScale(1) {}
5733   };
5734 
5735   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5736   // node.
5737   SmallVector<ShuffleSourceInfo, 2> Sources;
5738   for (unsigned i = 0; i < NumElts; ++i) {
5739     SDValue V = Op.getOperand(i);
5740     if (V.getOpcode() == ISD::UNDEF)
5741       continue;
5742     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5743       // A shuffle can only come from building a vector from various
5744       // elements of other vectors.
5745       return SDValue();
5746     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5747       // Furthermore, shuffles require a constant mask, whereas extractelts
5748       // accept variable indices.
5749       return SDValue();
5750     }
5751 
5752     // Add this element source to the list if it's not already there.
5753     SDValue SourceVec = V.getOperand(0);
5754     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5755     if (Source == Sources.end())
5756       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5757 
5758     // Update the minimum and maximum lane number seen.
5759     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5760     Source->MinElt = std::min(Source->MinElt, EltNo);
5761     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5762   }
5763 
5764   // Currently only do something sane when at most two source vectors
5765   // are involved.
5766   if (Sources.size() > 2)
5767     return SDValue();
5768 
5769   // Find out the smallest element size among result and two sources, and use
5770   // it as element size to build the shuffle_vector.
5771   EVT SmallestEltTy = VT.getVectorElementType();
5772   for (auto &Source : Sources) {
5773     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5774     if (SrcEltTy.bitsLT(SmallestEltTy))
5775       SmallestEltTy = SrcEltTy;
5776   }
5777   unsigned ResMultiplier =
5778       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5779   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5780   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5781 
5782   // If the source vector is too wide or too narrow, we may nevertheless be able
5783   // to construct a compatible shuffle either by concatenating it with UNDEF or
5784   // extracting a suitable range of elements.
5785   for (auto &Src : Sources) {
5786     EVT SrcVT = Src.ShuffleVec.getValueType();
5787 
5788     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5789       continue;
5790 
5791     // This stage of the search produces a source with the same element type as
5792     // the original, but with a total width matching the BUILD_VECTOR output.
5793     EVT EltVT = SrcVT.getVectorElementType();
5794     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5795     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5796 
5797     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5798       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5799         return SDValue();
5800       // We can pad out the smaller vector for free, so if it's part of a
5801       // shuffle...
5802       Src.ShuffleVec =
5803           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5804                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5805       continue;
5806     }
5807 
5808     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5809       return SDValue();
5810 
5811     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5812       // Span too large for a VEXT to cope
5813       return SDValue();
5814     }
5815 
5816     if (Src.MinElt >= NumSrcElts) {
5817       // The extraction can just take the second half
5818       Src.ShuffleVec =
5819           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5820                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5821       Src.WindowBase = -NumSrcElts;
5822     } else if (Src.MaxElt < NumSrcElts) {
5823       // The extraction can just take the first half
5824       Src.ShuffleVec =
5825           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5826                       DAG.getConstant(0, dl, MVT::i32));
5827     } else {
5828       // An actual VEXT is needed
5829       SDValue VEXTSrc1 =
5830           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5831                       DAG.getConstant(0, dl, MVT::i32));
5832       SDValue VEXTSrc2 =
5833           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5834                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5835 
5836       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5837                                    VEXTSrc2,
5838                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5839       Src.WindowBase = -Src.MinElt;
5840     }
5841   }
5842 
5843   // Another possible incompatibility occurs from the vector element types. We
5844   // can fix this by bitcasting the source vectors to the same type we intend
5845   // for the shuffle.
5846   for (auto &Src : Sources) {
5847     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5848     if (SrcEltTy == SmallestEltTy)
5849       continue;
5850     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5851     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5852     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5853     Src.WindowBase *= Src.WindowScale;
5854   }
5855 
5856   // Final sanity check before we try to actually produce a shuffle.
5857   DEBUG(
5858     for (auto Src : Sources)
5859       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5860   );
5861 
5862   // The stars all align, our next step is to produce the mask for the shuffle.
5863   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5864   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5865   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5866     SDValue Entry = Op.getOperand(i);
5867     if (Entry.getOpcode() == ISD::UNDEF)
5868       continue;
5869 
5870     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5871     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5872 
5873     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5874     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5875     // segment.
5876     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5877     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5878                                VT.getVectorElementType().getSizeInBits());
5879     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5880 
5881     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5882     // starting at the appropriate offset.
5883     int *LaneMask = &Mask[i * ResMultiplier];
5884 
5885     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5886     ExtractBase += NumElts * (Src - Sources.begin());
5887     for (int j = 0; j < LanesDefined; ++j)
5888       LaneMask[j] = ExtractBase + j;
5889   }
5890 
5891   // Final check before we try to produce nonsense...
5892   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5893     return SDValue();
5894 
5895   // We can't handle more than two sources. This should have already
5896   // been checked before this point.
5897   assert(Sources.size() <= 2 && "Too many sources!");
5898 
5899   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5900   for (unsigned i = 0; i < Sources.size(); ++i)
5901     ShuffleOps[i] = Sources[i].ShuffleVec;
5902 
5903   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5904                                          ShuffleOps[1], &Mask[0]);
5905   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5906 }
5907 
5908 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5909 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5910 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5911 /// are assumed to be legal.
5912 bool
5913 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5914                                       EVT VT) const {
5915   if (VT.getVectorNumElements() == 4 &&
5916       (VT.is128BitVector() || VT.is64BitVector())) {
5917     unsigned PFIndexes[4];
5918     for (unsigned i = 0; i != 4; ++i) {
5919       if (M[i] < 0)
5920         PFIndexes[i] = 8;
5921       else
5922         PFIndexes[i] = M[i];
5923     }
5924 
5925     // Compute the index in the perfect shuffle table.
5926     unsigned PFTableIndex =
5927       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5928     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5929     unsigned Cost = (PFEntry >> 30);
5930 
5931     if (Cost <= 4)
5932       return true;
5933   }
5934 
5935   bool ReverseVEXT, isV_UNDEF;
5936   unsigned Imm, WhichResult;
5937 
5938   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5939   return (EltSize >= 32 ||
5940           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5941           isVREVMask(M, VT, 64) ||
5942           isVREVMask(M, VT, 32) ||
5943           isVREVMask(M, VT, 16) ||
5944           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5945           isVTBLMask(M, VT) ||
5946           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5947           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5948 }
5949 
5950 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5951 /// the specified operations to build the shuffle.
5952 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5953                                       SDValue RHS, SelectionDAG &DAG,
5954                                       SDLoc dl) {
5955   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5956   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5957   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5958 
5959   enum {
5960     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5961     OP_VREV,
5962     OP_VDUP0,
5963     OP_VDUP1,
5964     OP_VDUP2,
5965     OP_VDUP3,
5966     OP_VEXT1,
5967     OP_VEXT2,
5968     OP_VEXT3,
5969     OP_VUZPL, // VUZP, left result
5970     OP_VUZPR, // VUZP, right result
5971     OP_VZIPL, // VZIP, left result
5972     OP_VZIPR, // VZIP, right result
5973     OP_VTRNL, // VTRN, left result
5974     OP_VTRNR  // VTRN, right result
5975   };
5976 
5977   if (OpNum == OP_COPY) {
5978     if (LHSID == (1*9+2)*9+3) return LHS;
5979     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5980     return RHS;
5981   }
5982 
5983   SDValue OpLHS, OpRHS;
5984   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5985   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5986   EVT VT = OpLHS.getValueType();
5987 
5988   switch (OpNum) {
5989   default: llvm_unreachable("Unknown shuffle opcode!");
5990   case OP_VREV:
5991     // VREV divides the vector in half and swaps within the half.
5992     if (VT.getVectorElementType() == MVT::i32 ||
5993         VT.getVectorElementType() == MVT::f32)
5994       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5995     // vrev <4 x i16> -> VREV32
5996     if (VT.getVectorElementType() == MVT::i16)
5997       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5998     // vrev <4 x i8> -> VREV16
5999     assert(VT.getVectorElementType() == MVT::i8);
6000     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6001   case OP_VDUP0:
6002   case OP_VDUP1:
6003   case OP_VDUP2:
6004   case OP_VDUP3:
6005     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6006                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6007   case OP_VEXT1:
6008   case OP_VEXT2:
6009   case OP_VEXT3:
6010     return DAG.getNode(ARMISD::VEXT, dl, VT,
6011                        OpLHS, OpRHS,
6012                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6013   case OP_VUZPL:
6014   case OP_VUZPR:
6015     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6016                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6017   case OP_VZIPL:
6018   case OP_VZIPR:
6019     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6020                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6021   case OP_VTRNL:
6022   case OP_VTRNR:
6023     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6024                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6025   }
6026 }
6027 
6028 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6029                                        ArrayRef<int> ShuffleMask,
6030                                        SelectionDAG &DAG) {
6031   // Check to see if we can use the VTBL instruction.
6032   SDValue V1 = Op.getOperand(0);
6033   SDValue V2 = Op.getOperand(1);
6034   SDLoc DL(Op);
6035 
6036   SmallVector<SDValue, 8> VTBLMask;
6037   for (ArrayRef<int>::iterator
6038          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6039     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6040 
6041   if (V2.getNode()->getOpcode() == ISD::UNDEF)
6042     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6043                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
6044 
6045   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6046                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
6047 }
6048 
6049 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6050                                                       SelectionDAG &DAG) {
6051   SDLoc DL(Op);
6052   SDValue OpLHS = Op.getOperand(0);
6053   EVT VT = OpLHS.getValueType();
6054 
6055   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6056          "Expect an v8i16/v16i8 type");
6057   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6058   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6059   // extract the first 8 bytes into the top double word and the last 8 bytes
6060   // into the bottom double word. The v8i16 case is similar.
6061   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6062   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6063                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6064 }
6065 
6066 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6067   SDValue V1 = Op.getOperand(0);
6068   SDValue V2 = Op.getOperand(1);
6069   SDLoc dl(Op);
6070   EVT VT = Op.getValueType();
6071   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6072 
6073   // Convert shuffles that are directly supported on NEON to target-specific
6074   // DAG nodes, instead of keeping them as shuffles and matching them again
6075   // during code selection.  This is more efficient and avoids the possibility
6076   // of inconsistencies between legalization and selection.
6077   // FIXME: floating-point vectors should be canonicalized to integer vectors
6078   // of the same time so that they get CSEd properly.
6079   ArrayRef<int> ShuffleMask = SVN->getMask();
6080 
6081   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6082   if (EltSize <= 32) {
6083     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
6084       int Lane = SVN->getSplatIndex();
6085       // If this is undef splat, generate it via "just" vdup, if possible.
6086       if (Lane == -1) Lane = 0;
6087 
6088       // Test if V1 is a SCALAR_TO_VECTOR.
6089       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6090         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6091       }
6092       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6093       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6094       // reaches it).
6095       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6096           !isa<ConstantSDNode>(V1.getOperand(0))) {
6097         bool IsScalarToVector = true;
6098         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6099           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
6100             IsScalarToVector = false;
6101             break;
6102           }
6103         if (IsScalarToVector)
6104           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6105       }
6106       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6107                          DAG.getConstant(Lane, dl, MVT::i32));
6108     }
6109 
6110     bool ReverseVEXT;
6111     unsigned Imm;
6112     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6113       if (ReverseVEXT)
6114         std::swap(V1, V2);
6115       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6116                          DAG.getConstant(Imm, dl, MVT::i32));
6117     }
6118 
6119     if (isVREVMask(ShuffleMask, VT, 64))
6120       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6121     if (isVREVMask(ShuffleMask, VT, 32))
6122       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6123     if (isVREVMask(ShuffleMask, VT, 16))
6124       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6125 
6126     if (V2->getOpcode() == ISD::UNDEF &&
6127         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6128       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6129                          DAG.getConstant(Imm, dl, MVT::i32));
6130     }
6131 
6132     // Check for Neon shuffles that modify both input vectors in place.
6133     // If both results are used, i.e., if there are two shuffles with the same
6134     // source operands and with masks corresponding to both results of one of
6135     // these operations, DAG memoization will ensure that a single node is
6136     // used for both shuffles.
6137     unsigned WhichResult;
6138     bool isV_UNDEF;
6139     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6140             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6141       if (isV_UNDEF)
6142         V2 = V1;
6143       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6144           .getValue(WhichResult);
6145     }
6146 
6147     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6148     // shuffles that produce a result larger than their operands with:
6149     //   shuffle(concat(v1, undef), concat(v2, undef))
6150     // ->
6151     //   shuffle(concat(v1, v2), undef)
6152     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6153     //
6154     // This is useful in the general case, but there are special cases where
6155     // native shuffles produce larger results: the two-result ops.
6156     //
6157     // Look through the concat when lowering them:
6158     //   shuffle(concat(v1, v2), undef)
6159     // ->
6160     //   concat(VZIP(v1, v2):0, :1)
6161     //
6162     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6163         V2->getOpcode() == ISD::UNDEF) {
6164       SDValue SubV1 = V1->getOperand(0);
6165       SDValue SubV2 = V1->getOperand(1);
6166       EVT SubVT = SubV1.getValueType();
6167 
6168       // We expect these to have been canonicalized to -1.
6169       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6170         return i < (int)VT.getVectorNumElements();
6171       }) && "Unexpected shuffle index into UNDEF operand!");
6172 
6173       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6174               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6175         if (isV_UNDEF)
6176           SubV2 = SubV1;
6177         assert((WhichResult == 0) &&
6178                "In-place shuffle of concat can only have one result!");
6179         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6180                                   SubV1, SubV2);
6181         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6182                            Res.getValue(1));
6183       }
6184     }
6185   }
6186 
6187   // If the shuffle is not directly supported and it has 4 elements, use
6188   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6189   unsigned NumElts = VT.getVectorNumElements();
6190   if (NumElts == 4) {
6191     unsigned PFIndexes[4];
6192     for (unsigned i = 0; i != 4; ++i) {
6193       if (ShuffleMask[i] < 0)
6194         PFIndexes[i] = 8;
6195       else
6196         PFIndexes[i] = ShuffleMask[i];
6197     }
6198 
6199     // Compute the index in the perfect shuffle table.
6200     unsigned PFTableIndex =
6201       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6202     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6203     unsigned Cost = (PFEntry >> 30);
6204 
6205     if (Cost <= 4)
6206       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6207   }
6208 
6209   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6210   if (EltSize >= 32) {
6211     // Do the expansion with floating-point types, since that is what the VFP
6212     // registers are defined to use, and since i64 is not legal.
6213     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6214     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6215     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6216     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6217     SmallVector<SDValue, 8> Ops;
6218     for (unsigned i = 0; i < NumElts; ++i) {
6219       if (ShuffleMask[i] < 0)
6220         Ops.push_back(DAG.getUNDEF(EltVT));
6221       else
6222         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6223                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6224                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6225                                                   dl, MVT::i32)));
6226     }
6227     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6228     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6229   }
6230 
6231   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6232     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6233 
6234   if (VT == MVT::v8i8)
6235     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6236       return NewOp;
6237 
6238   return SDValue();
6239 }
6240 
6241 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6242   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6243   SDValue Lane = Op.getOperand(2);
6244   if (!isa<ConstantSDNode>(Lane))
6245     return SDValue();
6246 
6247   return Op;
6248 }
6249 
6250 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6251   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6252   SDValue Lane = Op.getOperand(1);
6253   if (!isa<ConstantSDNode>(Lane))
6254     return SDValue();
6255 
6256   SDValue Vec = Op.getOperand(0);
6257   if (Op.getValueType() == MVT::i32 &&
6258       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6259     SDLoc dl(Op);
6260     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6261   }
6262 
6263   return Op;
6264 }
6265 
6266 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6267   // The only time a CONCAT_VECTORS operation can have legal types is when
6268   // two 64-bit vectors are concatenated to a 128-bit vector.
6269   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6270          "unexpected CONCAT_VECTORS");
6271   SDLoc dl(Op);
6272   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6273   SDValue Op0 = Op.getOperand(0);
6274   SDValue Op1 = Op.getOperand(1);
6275   if (Op0.getOpcode() != ISD::UNDEF)
6276     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6277                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6278                       DAG.getIntPtrConstant(0, dl));
6279   if (Op1.getOpcode() != ISD::UNDEF)
6280     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6281                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6282                       DAG.getIntPtrConstant(1, dl));
6283   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6284 }
6285 
6286 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6287 /// element has been zero/sign-extended, depending on the isSigned parameter,
6288 /// from an integer type half its size.
6289 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6290                                    bool isSigned) {
6291   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6292   EVT VT = N->getValueType(0);
6293   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6294     SDNode *BVN = N->getOperand(0).getNode();
6295     if (BVN->getValueType(0) != MVT::v4i32 ||
6296         BVN->getOpcode() != ISD::BUILD_VECTOR)
6297       return false;
6298     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6299     unsigned HiElt = 1 - LoElt;
6300     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6301     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6302     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6303     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6304     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6305       return false;
6306     if (isSigned) {
6307       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6308           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6309         return true;
6310     } else {
6311       if (Hi0->isNullValue() && Hi1->isNullValue())
6312         return true;
6313     }
6314     return false;
6315   }
6316 
6317   if (N->getOpcode() != ISD::BUILD_VECTOR)
6318     return false;
6319 
6320   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6321     SDNode *Elt = N->getOperand(i).getNode();
6322     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6323       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6324       unsigned HalfSize = EltSize / 2;
6325       if (isSigned) {
6326         if (!isIntN(HalfSize, C->getSExtValue()))
6327           return false;
6328       } else {
6329         if (!isUIntN(HalfSize, C->getZExtValue()))
6330           return false;
6331       }
6332       continue;
6333     }
6334     return false;
6335   }
6336 
6337   return true;
6338 }
6339 
6340 /// isSignExtended - Check if a node is a vector value that is sign-extended
6341 /// or a constant BUILD_VECTOR with sign-extended elements.
6342 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6343   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6344     return true;
6345   if (isExtendedBUILD_VECTOR(N, DAG, true))
6346     return true;
6347   return false;
6348 }
6349 
6350 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6351 /// or a constant BUILD_VECTOR with zero-extended elements.
6352 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6353   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6354     return true;
6355   if (isExtendedBUILD_VECTOR(N, DAG, false))
6356     return true;
6357   return false;
6358 }
6359 
6360 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6361   if (OrigVT.getSizeInBits() >= 64)
6362     return OrigVT;
6363 
6364   assert(OrigVT.isSimple() && "Expecting a simple value type");
6365 
6366   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6367   switch (OrigSimpleTy) {
6368   default: llvm_unreachable("Unexpected Vector Type");
6369   case MVT::v2i8:
6370   case MVT::v2i16:
6371      return MVT::v2i32;
6372   case MVT::v4i8:
6373     return  MVT::v4i16;
6374   }
6375 }
6376 
6377 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6378 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6379 /// We insert the required extension here to get the vector to fill a D register.
6380 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6381                                             const EVT &OrigTy,
6382                                             const EVT &ExtTy,
6383                                             unsigned ExtOpcode) {
6384   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6385   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6386   // 64-bits we need to insert a new extension so that it will be 64-bits.
6387   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6388   if (OrigTy.getSizeInBits() >= 64)
6389     return N;
6390 
6391   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6392   EVT NewVT = getExtensionTo64Bits(OrigTy);
6393 
6394   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6395 }
6396 
6397 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6398 /// does not do any sign/zero extension. If the original vector is less
6399 /// than 64 bits, an appropriate extension will be added after the load to
6400 /// reach a total size of 64 bits. We have to add the extension separately
6401 /// because ARM does not have a sign/zero extending load for vectors.
6402 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6403   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6404 
6405   // The load already has the right type.
6406   if (ExtendedTy == LD->getMemoryVT())
6407     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6408                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6409                 LD->isNonTemporal(), LD->isInvariant(),
6410                 LD->getAlignment());
6411 
6412   // We need to create a zextload/sextload. We cannot just create a load
6413   // followed by a zext/zext node because LowerMUL is also run during normal
6414   // operation legalization where we can't create illegal types.
6415   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6416                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6417                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6418                         LD->isNonTemporal(), LD->getAlignment());
6419 }
6420 
6421 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6422 /// extending load, or BUILD_VECTOR with extended elements, return the
6423 /// unextended value. The unextended vector should be 64 bits so that it can
6424 /// be used as an operand to a VMULL instruction. If the original vector size
6425 /// before extension is less than 64 bits we add a an extension to resize
6426 /// the vector to 64 bits.
6427 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6428   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6429     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6430                                         N->getOperand(0)->getValueType(0),
6431                                         N->getValueType(0),
6432                                         N->getOpcode());
6433 
6434   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6435     return SkipLoadExtensionForVMULL(LD, DAG);
6436 
6437   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6438   // have been legalized as a BITCAST from v4i32.
6439   if (N->getOpcode() == ISD::BITCAST) {
6440     SDNode *BVN = N->getOperand(0).getNode();
6441     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6442            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6443     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6444     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6445                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6446   }
6447   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6448   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6449   EVT VT = N->getValueType(0);
6450   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6451   unsigned NumElts = VT.getVectorNumElements();
6452   MVT TruncVT = MVT::getIntegerVT(EltSize);
6453   SmallVector<SDValue, 8> Ops;
6454   SDLoc dl(N);
6455   for (unsigned i = 0; i != NumElts; ++i) {
6456     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6457     const APInt &CInt = C->getAPIntValue();
6458     // Element types smaller than 32 bits are not legal, so use i32 elements.
6459     // The values are implicitly truncated so sext vs. zext doesn't matter.
6460     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6461   }
6462   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6463                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6464 }
6465 
6466 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6467   unsigned Opcode = N->getOpcode();
6468   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6469     SDNode *N0 = N->getOperand(0).getNode();
6470     SDNode *N1 = N->getOperand(1).getNode();
6471     return N0->hasOneUse() && N1->hasOneUse() &&
6472       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6473   }
6474   return false;
6475 }
6476 
6477 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6478   unsigned Opcode = N->getOpcode();
6479   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6480     SDNode *N0 = N->getOperand(0).getNode();
6481     SDNode *N1 = N->getOperand(1).getNode();
6482     return N0->hasOneUse() && N1->hasOneUse() &&
6483       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6484   }
6485   return false;
6486 }
6487 
6488 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6489   // Multiplications are only custom-lowered for 128-bit vectors so that
6490   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6491   EVT VT = Op.getValueType();
6492   assert(VT.is128BitVector() && VT.isInteger() &&
6493          "unexpected type for custom-lowering ISD::MUL");
6494   SDNode *N0 = Op.getOperand(0).getNode();
6495   SDNode *N1 = Op.getOperand(1).getNode();
6496   unsigned NewOpc = 0;
6497   bool isMLA = false;
6498   bool isN0SExt = isSignExtended(N0, DAG);
6499   bool isN1SExt = isSignExtended(N1, DAG);
6500   if (isN0SExt && isN1SExt)
6501     NewOpc = ARMISD::VMULLs;
6502   else {
6503     bool isN0ZExt = isZeroExtended(N0, DAG);
6504     bool isN1ZExt = isZeroExtended(N1, DAG);
6505     if (isN0ZExt && isN1ZExt)
6506       NewOpc = ARMISD::VMULLu;
6507     else if (isN1SExt || isN1ZExt) {
6508       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6509       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6510       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6511         NewOpc = ARMISD::VMULLs;
6512         isMLA = true;
6513       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6514         NewOpc = ARMISD::VMULLu;
6515         isMLA = true;
6516       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6517         std::swap(N0, N1);
6518         NewOpc = ARMISD::VMULLu;
6519         isMLA = true;
6520       }
6521     }
6522 
6523     if (!NewOpc) {
6524       if (VT == MVT::v2i64)
6525         // Fall through to expand this.  It is not legal.
6526         return SDValue();
6527       else
6528         // Other vector multiplications are legal.
6529         return Op;
6530     }
6531   }
6532 
6533   // Legalize to a VMULL instruction.
6534   SDLoc DL(Op);
6535   SDValue Op0;
6536   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6537   if (!isMLA) {
6538     Op0 = SkipExtensionForVMULL(N0, DAG);
6539     assert(Op0.getValueType().is64BitVector() &&
6540            Op1.getValueType().is64BitVector() &&
6541            "unexpected types for extended operands to VMULL");
6542     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6543   }
6544 
6545   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6546   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6547   //   vmull q0, d4, d6
6548   //   vmlal q0, d5, d6
6549   // is faster than
6550   //   vaddl q0, d4, d5
6551   //   vmovl q1, d6
6552   //   vmul  q0, q0, q1
6553   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6554   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6555   EVT Op1VT = Op1.getValueType();
6556   return DAG.getNode(N0->getOpcode(), DL, VT,
6557                      DAG.getNode(NewOpc, DL, VT,
6558                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6559                      DAG.getNode(NewOpc, DL, VT,
6560                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6561 }
6562 
6563 static SDValue
6564 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6565   // TODO: Should this propagate fast-math-flags?
6566 
6567   // Convert to float
6568   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6569   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6570   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6571   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6572   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6573   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6574   // Get reciprocal estimate.
6575   // float4 recip = vrecpeq_f32(yf);
6576   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6577                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6578                    Y);
6579   // Because char has a smaller range than uchar, we can actually get away
6580   // without any newton steps.  This requires that we use a weird bias
6581   // of 0xb000, however (again, this has been exhaustively tested).
6582   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6583   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6584   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6585   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
6586   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6587   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6588   // Convert back to short.
6589   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6590   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6591   return X;
6592 }
6593 
6594 static SDValue
6595 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6596   // TODO: Should this propagate fast-math-flags?
6597 
6598   SDValue N2;
6599   // Convert to float.
6600   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6601   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6602   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6603   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6604   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6605   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6606 
6607   // Use reciprocal estimate and one refinement step.
6608   // float4 recip = vrecpeq_f32(yf);
6609   // recip *= vrecpsq_f32(yf, recip);
6610   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6611                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6612                    N1);
6613   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6614                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6615                    N1, N2);
6616   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6617   // Because short has a smaller range than ushort, we can actually get away
6618   // with only a single newton step.  This requires that we use a weird bias
6619   // of 89, however (again, this has been exhaustively tested).
6620   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6621   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6622   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6623   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
6624   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6625   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6626   // Convert back to integer and return.
6627   // return vmovn_s32(vcvt_s32_f32(result));
6628   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6629   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6630   return N0;
6631 }
6632 
6633 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6634   EVT VT = Op.getValueType();
6635   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6636          "unexpected type for custom-lowering ISD::SDIV");
6637 
6638   SDLoc dl(Op);
6639   SDValue N0 = Op.getOperand(0);
6640   SDValue N1 = Op.getOperand(1);
6641   SDValue N2, N3;
6642 
6643   if (VT == MVT::v8i8) {
6644     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6645     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6646 
6647     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6648                      DAG.getIntPtrConstant(4, dl));
6649     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6650                      DAG.getIntPtrConstant(4, dl));
6651     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6652                      DAG.getIntPtrConstant(0, dl));
6653     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6654                      DAG.getIntPtrConstant(0, dl));
6655 
6656     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6657     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6658 
6659     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6660     N0 = LowerCONCAT_VECTORS(N0, DAG);
6661 
6662     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6663     return N0;
6664   }
6665   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6666 }
6667 
6668 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6669   // TODO: Should this propagate fast-math-flags?
6670   EVT VT = Op.getValueType();
6671   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6672          "unexpected type for custom-lowering ISD::UDIV");
6673 
6674   SDLoc dl(Op);
6675   SDValue N0 = Op.getOperand(0);
6676   SDValue N1 = Op.getOperand(1);
6677   SDValue N2, N3;
6678 
6679   if (VT == MVT::v8i8) {
6680     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6681     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6682 
6683     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6684                      DAG.getIntPtrConstant(4, dl));
6685     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6686                      DAG.getIntPtrConstant(4, dl));
6687     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6688                      DAG.getIntPtrConstant(0, dl));
6689     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6690                      DAG.getIntPtrConstant(0, dl));
6691 
6692     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6693     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6694 
6695     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6696     N0 = LowerCONCAT_VECTORS(N0, DAG);
6697 
6698     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6699                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6700                                      MVT::i32),
6701                      N0);
6702     return N0;
6703   }
6704 
6705   // v4i16 sdiv ... Convert to float.
6706   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6707   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6708   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6709   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6710   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6711   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6712 
6713   // Use reciprocal estimate and two refinement steps.
6714   // float4 recip = vrecpeq_f32(yf);
6715   // recip *= vrecpsq_f32(yf, recip);
6716   // recip *= vrecpsq_f32(yf, recip);
6717   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6718                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6719                    BN1);
6720   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6721                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6722                    BN1, N2);
6723   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6724   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6725                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6726                    BN1, N2);
6727   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6728   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6729   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6730   // and that it will never cause us to return an answer too large).
6731   // float4 result = as_float4(as_int4(xf*recip) + 2);
6732   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6733   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6734   N1 = DAG.getConstant(2, dl, MVT::v4i32);
6735   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6736   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6737   // Convert back to integer and return.
6738   // return vmovn_u32(vcvt_s32_f32(result));
6739   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6740   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6741   return N0;
6742 }
6743 
6744 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6745   EVT VT = Op.getNode()->getValueType(0);
6746   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6747 
6748   unsigned Opc;
6749   bool ExtraOp = false;
6750   switch (Op.getOpcode()) {
6751   default: llvm_unreachable("Invalid code");
6752   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6753   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6754   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6755   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6756   }
6757 
6758   if (!ExtraOp)
6759     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6760                        Op.getOperand(1));
6761   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6762                      Op.getOperand(1), Op.getOperand(2));
6763 }
6764 
6765 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6766   assert(Subtarget->isTargetDarwin());
6767 
6768   // For iOS, we want to call an alternative entry point: __sincos_stret,
6769   // return values are passed via sret.
6770   SDLoc dl(Op);
6771   SDValue Arg = Op.getOperand(0);
6772   EVT ArgVT = Arg.getValueType();
6773   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6774   auto PtrVT = getPointerTy(DAG.getDataLayout());
6775 
6776   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6778 
6779   // Pair of floats / doubles used to pass the result.
6780   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6781   auto &DL = DAG.getDataLayout();
6782 
6783   ArgListTy Args;
6784   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6785   SDValue SRet;
6786   if (ShouldUseSRet) {
6787     // Create stack object for sret.
6788     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6789     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6790     int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6791     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6792 
6793     ArgListEntry Entry;
6794     Entry.Node = SRet;
6795     Entry.Ty = RetTy->getPointerTo();
6796     Entry.isSExt = false;
6797     Entry.isZExt = false;
6798     Entry.isSRet = true;
6799     Args.push_back(Entry);
6800     RetTy = Type::getVoidTy(*DAG.getContext());
6801   }
6802 
6803   ArgListEntry Entry;
6804   Entry.Node = Arg;
6805   Entry.Ty = ArgTy;
6806   Entry.isSExt = false;
6807   Entry.isZExt = false;
6808   Args.push_back(Entry);
6809 
6810   const char *LibcallName =
6811       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6812   RTLIB::Libcall LC =
6813       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6814   CallingConv::ID CC = getLibcallCallingConv(LC);
6815   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6816 
6817   TargetLowering::CallLoweringInfo CLI(DAG);
6818   CLI.setDebugLoc(dl)
6819       .setChain(DAG.getEntryNode())
6820       .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6821       .setDiscardResult(ShouldUseSRet);
6822   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6823 
6824   if (!ShouldUseSRet)
6825     return CallResult.first;
6826 
6827   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6828                                 MachinePointerInfo(), false, false, false, 0);
6829 
6830   // Address of cos field.
6831   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6832                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6833   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6834                                 MachinePointerInfo(), false, false, false, 0);
6835 
6836   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6837   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6838                      LoadSin.getValue(0), LoadCos.getValue(0));
6839 }
6840 
6841 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6842                                                   bool Signed,
6843                                                   SDValue &Chain) const {
6844   EVT VT = Op.getValueType();
6845   assert((VT == MVT::i32 || VT == MVT::i64) &&
6846          "unexpected type for custom lowering DIV");
6847   SDLoc dl(Op);
6848 
6849   const auto &DL = DAG.getDataLayout();
6850   const auto &TLI = DAG.getTargetLoweringInfo();
6851 
6852   const char *Name = nullptr;
6853   if (Signed)
6854     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6855   else
6856     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6857 
6858   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6859 
6860   ARMTargetLowering::ArgListTy Args;
6861 
6862   for (auto AI : {1, 0}) {
6863     ArgListEntry Arg;
6864     Arg.Node = Op.getOperand(AI);
6865     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6866     Args.push_back(Arg);
6867   }
6868 
6869   CallLoweringInfo CLI(DAG);
6870   CLI.setDebugLoc(dl)
6871     .setChain(Chain)
6872     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6873                ES, std::move(Args), 0);
6874 
6875   return LowerCallTo(CLI).first;
6876 }
6877 
6878 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6879                                             bool Signed) const {
6880   assert(Op.getValueType() == MVT::i32 &&
6881          "unexpected type for custom lowering DIV");
6882   SDLoc dl(Op);
6883 
6884   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6885                                DAG.getEntryNode(), Op.getOperand(1));
6886 
6887   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6888 }
6889 
6890 void ARMTargetLowering::ExpandDIV_Windows(
6891     SDValue Op, SelectionDAG &DAG, bool Signed,
6892     SmallVectorImpl<SDValue> &Results) const {
6893   const auto &DL = DAG.getDataLayout();
6894   const auto &TLI = DAG.getTargetLoweringInfo();
6895 
6896   assert(Op.getValueType() == MVT::i64 &&
6897          "unexpected type for custom lowering DIV");
6898   SDLoc dl(Op);
6899 
6900   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6901                            DAG.getConstant(0, dl, MVT::i32));
6902   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6903                            DAG.getConstant(1, dl, MVT::i32));
6904   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6905 
6906   SDValue DBZCHK =
6907       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6908 
6909   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6910 
6911   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6912   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6913                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6914   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6915 
6916   Results.push_back(Lower);
6917   Results.push_back(Upper);
6918 }
6919 
6920 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6921   // Monotonic load/store is legal for all targets
6922   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6923     return Op;
6924 
6925   // Acquire/Release load/store is not legal for targets without a
6926   // dmb or equivalent available.
6927   return SDValue();
6928 }
6929 
6930 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6931                                     SmallVectorImpl<SDValue> &Results,
6932                                     SelectionDAG &DAG,
6933                                     const ARMSubtarget *Subtarget) {
6934   SDLoc DL(N);
6935   // Under Power Management extensions, the cycle-count is:
6936   //    mrc p15, #0, <Rt>, c9, c13, #0
6937   SDValue Ops[] = { N->getOperand(0), // Chain
6938                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6939                     DAG.getConstant(15, DL, MVT::i32),
6940                     DAG.getConstant(0, DL, MVT::i32),
6941                     DAG.getConstant(9, DL, MVT::i32),
6942                     DAG.getConstant(13, DL, MVT::i32),
6943                     DAG.getConstant(0, DL, MVT::i32)
6944   };
6945 
6946   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6947                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6948   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6949                                 DAG.getConstant(0, DL, MVT::i32)));
6950   Results.push_back(Cycles32.getValue(1));
6951 }
6952 
6953 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6954   switch (Op.getOpcode()) {
6955   default: llvm_unreachable("Don't know how to custom lower this!");
6956   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6957   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6958   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6959   case ISD::GlobalAddress:
6960     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6961     default: llvm_unreachable("unknown object format");
6962     case Triple::COFF:
6963       return LowerGlobalAddressWindows(Op, DAG);
6964     case Triple::ELF:
6965       return LowerGlobalAddressELF(Op, DAG);
6966     case Triple::MachO:
6967       return LowerGlobalAddressDarwin(Op, DAG);
6968     }
6969   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6970   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6971   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6972   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6973   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6974   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6975   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6976   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6977   case ISD::SINT_TO_FP:
6978   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6979   case ISD::FP_TO_SINT:
6980   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6981   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6982   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6983   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6984   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6985   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6986   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6987   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6988                                                                Subtarget);
6989   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6990   case ISD::SHL:
6991   case ISD::SRL:
6992   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6993   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6994   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6995   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6996   case ISD::SRL_PARTS:
6997   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6998   case ISD::CTTZ:
6999   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7000   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7001   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7002   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7003   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7004   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7005   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7006   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7007   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7008   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7009   case ISD::MUL:           return LowerMUL(Op, DAG);
7010   case ISD::SDIV:          return LowerSDIV(Op, DAG);
7011   case ISD::UDIV:          return LowerUDIV(Op, DAG);
7012   case ISD::ADDC:
7013   case ISD::ADDE:
7014   case ISD::SUBC:
7015   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7016   case ISD::SADDO:
7017   case ISD::UADDO:
7018   case ISD::SSUBO:
7019   case ISD::USUBO:
7020     return LowerXALUO(Op, DAG);
7021   case ISD::ATOMIC_LOAD:
7022   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7023   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7024   case ISD::SDIVREM:
7025   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7026   case ISD::DYNAMIC_STACKALLOC:
7027     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7028       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7029     llvm_unreachable("Don't know how to custom lower this!");
7030   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7031   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7032   case ARMISD::WIN__DBZCHK: return SDValue();
7033   }
7034 }
7035 
7036 /// ReplaceNodeResults - Replace the results of node with an illegal result
7037 /// type with new values built out of custom code.
7038 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7039                                            SmallVectorImpl<SDValue> &Results,
7040                                            SelectionDAG &DAG) const {
7041   SDValue Res;
7042   switch (N->getOpcode()) {
7043   default:
7044     llvm_unreachable("Don't know how to custom expand this!");
7045   case ISD::READ_REGISTER:
7046     ExpandREAD_REGISTER(N, Results, DAG);
7047     break;
7048   case ISD::BITCAST:
7049     Res = ExpandBITCAST(N, DAG);
7050     break;
7051   case ISD::SRL:
7052   case ISD::SRA:
7053     Res = Expand64BitShift(N, DAG, Subtarget);
7054     break;
7055   case ISD::SREM:
7056   case ISD::UREM:
7057     Res = LowerREM(N, DAG);
7058     break;
7059   case ISD::SDIVREM:
7060   case ISD::UDIVREM:
7061     Res = LowerDivRem(SDValue(N, 0), DAG);
7062     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7063     Results.push_back(Res.getValue(0));
7064     Results.push_back(Res.getValue(1));
7065     return;
7066   case ISD::READCYCLECOUNTER:
7067     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7068     return;
7069   case ISD::UDIV:
7070   case ISD::SDIV:
7071     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7072     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7073                              Results);
7074   }
7075   if (Res.getNode())
7076     Results.push_back(Res);
7077 }
7078 
7079 //===----------------------------------------------------------------------===//
7080 //                           ARM Scheduler Hooks
7081 //===----------------------------------------------------------------------===//
7082 
7083 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7084 /// registers the function context.
7085 void ARMTargetLowering::
7086 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
7087                        MachineBasicBlock *DispatchBB, int FI) const {
7088   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7089   DebugLoc dl = MI->getDebugLoc();
7090   MachineFunction *MF = MBB->getParent();
7091   MachineRegisterInfo *MRI = &MF->getRegInfo();
7092   MachineConstantPool *MCP = MF->getConstantPool();
7093   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7094   const Function *F = MF->getFunction();
7095 
7096   bool isThumb = Subtarget->isThumb();
7097   bool isThumb2 = Subtarget->isThumb2();
7098 
7099   unsigned PCLabelId = AFI->createPICLabelUId();
7100   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7101   ARMConstantPoolValue *CPV =
7102     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7103   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7104 
7105   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7106                                            : &ARM::GPRRegClass;
7107 
7108   // Grab constant pool and fixed stack memory operands.
7109   MachineMemOperand *CPMMO =
7110       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7111                                MachineMemOperand::MOLoad, 4, 4);
7112 
7113   MachineMemOperand *FIMMOSt =
7114       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7115                                MachineMemOperand::MOStore, 4, 4);
7116 
7117   // Load the address of the dispatch MBB into the jump buffer.
7118   if (isThumb2) {
7119     // Incoming value: jbuf
7120     //   ldr.n  r5, LCPI1_1
7121     //   orr    r5, r5, #1
7122     //   add    r5, pc
7123     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7124     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7125     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7126                    .addConstantPoolIndex(CPI)
7127                    .addMemOperand(CPMMO));
7128     // Set the low bit because of thumb mode.
7129     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7130     AddDefaultCC(
7131       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7132                      .addReg(NewVReg1, RegState::Kill)
7133                      .addImm(0x01)));
7134     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7135     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7136       .addReg(NewVReg2, RegState::Kill)
7137       .addImm(PCLabelId);
7138     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7139                    .addReg(NewVReg3, RegState::Kill)
7140                    .addFrameIndex(FI)
7141                    .addImm(36)  // &jbuf[1] :: pc
7142                    .addMemOperand(FIMMOSt));
7143   } else if (isThumb) {
7144     // Incoming value: jbuf
7145     //   ldr.n  r1, LCPI1_4
7146     //   add    r1, pc
7147     //   mov    r2, #1
7148     //   orrs   r1, r2
7149     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7150     //   str    r1, [r2]
7151     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7152     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7153                    .addConstantPoolIndex(CPI)
7154                    .addMemOperand(CPMMO));
7155     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7156     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7157       .addReg(NewVReg1, RegState::Kill)
7158       .addImm(PCLabelId);
7159     // Set the low bit because of thumb mode.
7160     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7161     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7162                    .addReg(ARM::CPSR, RegState::Define)
7163                    .addImm(1));
7164     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7165     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7166                    .addReg(ARM::CPSR, RegState::Define)
7167                    .addReg(NewVReg2, RegState::Kill)
7168                    .addReg(NewVReg3, RegState::Kill));
7169     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7170     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7171             .addFrameIndex(FI)
7172             .addImm(36); // &jbuf[1] :: pc
7173     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7174                    .addReg(NewVReg4, RegState::Kill)
7175                    .addReg(NewVReg5, RegState::Kill)
7176                    .addImm(0)
7177                    .addMemOperand(FIMMOSt));
7178   } else {
7179     // Incoming value: jbuf
7180     //   ldr  r1, LCPI1_1
7181     //   add  r1, pc, r1
7182     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7183     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7184     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7185                    .addConstantPoolIndex(CPI)
7186                    .addImm(0)
7187                    .addMemOperand(CPMMO));
7188     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7189     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7190                    .addReg(NewVReg1, RegState::Kill)
7191                    .addImm(PCLabelId));
7192     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7193                    .addReg(NewVReg2, RegState::Kill)
7194                    .addFrameIndex(FI)
7195                    .addImm(36)  // &jbuf[1] :: pc
7196                    .addMemOperand(FIMMOSt));
7197   }
7198 }
7199 
7200 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7201                                               MachineBasicBlock *MBB) const {
7202   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7203   DebugLoc dl = MI->getDebugLoc();
7204   MachineFunction *MF = MBB->getParent();
7205   MachineRegisterInfo *MRI = &MF->getRegInfo();
7206   MachineFrameInfo *MFI = MF->getFrameInfo();
7207   int FI = MFI->getFunctionContextIndex();
7208 
7209   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7210                                                         : &ARM::GPRnopcRegClass;
7211 
7212   // Get a mapping of the call site numbers to all of the landing pads they're
7213   // associated with.
7214   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7215   unsigned MaxCSNum = 0;
7216   MachineModuleInfo &MMI = MF->getMMI();
7217   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7218        ++BB) {
7219     if (!BB->isEHPad()) continue;
7220 
7221     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7222     // pad.
7223     for (MachineBasicBlock::iterator
7224            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7225       if (!II->isEHLabel()) continue;
7226 
7227       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7228       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7229 
7230       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7231       for (SmallVectorImpl<unsigned>::iterator
7232              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7233            CSI != CSE; ++CSI) {
7234         CallSiteNumToLPad[*CSI].push_back(&*BB);
7235         MaxCSNum = std::max(MaxCSNum, *CSI);
7236       }
7237       break;
7238     }
7239   }
7240 
7241   // Get an ordered list of the machine basic blocks for the jump table.
7242   std::vector<MachineBasicBlock*> LPadList;
7243   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7244   LPadList.reserve(CallSiteNumToLPad.size());
7245   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7246     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7247     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7248            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7249       LPadList.push_back(*II);
7250       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7251     }
7252   }
7253 
7254   assert(!LPadList.empty() &&
7255          "No landing pad destinations for the dispatch jump table!");
7256 
7257   // Create the jump table and associated information.
7258   MachineJumpTableInfo *JTI =
7259     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7260   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7261   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7262 
7263   // Create the MBBs for the dispatch code.
7264 
7265   // Shove the dispatch's address into the return slot in the function context.
7266   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7267   DispatchBB->setIsEHPad();
7268 
7269   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7270   unsigned trap_opcode;
7271   if (Subtarget->isThumb())
7272     trap_opcode = ARM::tTRAP;
7273   else
7274     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7275 
7276   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7277   DispatchBB->addSuccessor(TrapBB);
7278 
7279   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7280   DispatchBB->addSuccessor(DispContBB);
7281 
7282   // Insert and MBBs.
7283   MF->insert(MF->end(), DispatchBB);
7284   MF->insert(MF->end(), DispContBB);
7285   MF->insert(MF->end(), TrapBB);
7286 
7287   // Insert code into the entry block that creates and registers the function
7288   // context.
7289   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7290 
7291   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7292       MachinePointerInfo::getFixedStack(*MF, FI),
7293       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7294 
7295   MachineInstrBuilder MIB;
7296   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7297 
7298   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7299   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7300 
7301   // Add a register mask with no preserved registers.  This results in all
7302   // registers being marked as clobbered.
7303   MIB.addRegMask(RI.getNoPreservedMask());
7304 
7305   unsigned NumLPads = LPadList.size();
7306   if (Subtarget->isThumb2()) {
7307     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7308     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7309                    .addFrameIndex(FI)
7310                    .addImm(4)
7311                    .addMemOperand(FIMMOLd));
7312 
7313     if (NumLPads < 256) {
7314       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7315                      .addReg(NewVReg1)
7316                      .addImm(LPadList.size()));
7317     } else {
7318       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7319       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7320                      .addImm(NumLPads & 0xFFFF));
7321 
7322       unsigned VReg2 = VReg1;
7323       if ((NumLPads & 0xFFFF0000) != 0) {
7324         VReg2 = MRI->createVirtualRegister(TRC);
7325         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7326                        .addReg(VReg1)
7327                        .addImm(NumLPads >> 16));
7328       }
7329 
7330       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7331                      .addReg(NewVReg1)
7332                      .addReg(VReg2));
7333     }
7334 
7335     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7336       .addMBB(TrapBB)
7337       .addImm(ARMCC::HI)
7338       .addReg(ARM::CPSR);
7339 
7340     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7341     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7342                    .addJumpTableIndex(MJTI));
7343 
7344     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7345     AddDefaultCC(
7346       AddDefaultPred(
7347         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7348         .addReg(NewVReg3, RegState::Kill)
7349         .addReg(NewVReg1)
7350         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7351 
7352     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7353       .addReg(NewVReg4, RegState::Kill)
7354       .addReg(NewVReg1)
7355       .addJumpTableIndex(MJTI);
7356   } else if (Subtarget->isThumb()) {
7357     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7358     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7359                    .addFrameIndex(FI)
7360                    .addImm(1)
7361                    .addMemOperand(FIMMOLd));
7362 
7363     if (NumLPads < 256) {
7364       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7365                      .addReg(NewVReg1)
7366                      .addImm(NumLPads));
7367     } else {
7368       MachineConstantPool *ConstantPool = MF->getConstantPool();
7369       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7370       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7371 
7372       // MachineConstantPool wants an explicit alignment.
7373       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7374       if (Align == 0)
7375         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7376       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7377 
7378       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7379       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7380                      .addReg(VReg1, RegState::Define)
7381                      .addConstantPoolIndex(Idx));
7382       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7383                      .addReg(NewVReg1)
7384                      .addReg(VReg1));
7385     }
7386 
7387     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7388       .addMBB(TrapBB)
7389       .addImm(ARMCC::HI)
7390       .addReg(ARM::CPSR);
7391 
7392     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7393     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7394                    .addReg(ARM::CPSR, RegState::Define)
7395                    .addReg(NewVReg1)
7396                    .addImm(2));
7397 
7398     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7399     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7400                    .addJumpTableIndex(MJTI));
7401 
7402     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7403     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7404                    .addReg(ARM::CPSR, RegState::Define)
7405                    .addReg(NewVReg2, RegState::Kill)
7406                    .addReg(NewVReg3));
7407 
7408     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7409         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7410 
7411     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7412     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7413                    .addReg(NewVReg4, RegState::Kill)
7414                    .addImm(0)
7415                    .addMemOperand(JTMMOLd));
7416 
7417     unsigned NewVReg6 = NewVReg5;
7418     if (RelocM == Reloc::PIC_) {
7419       NewVReg6 = MRI->createVirtualRegister(TRC);
7420       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7421                      .addReg(ARM::CPSR, RegState::Define)
7422                      .addReg(NewVReg5, RegState::Kill)
7423                      .addReg(NewVReg3));
7424     }
7425 
7426     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7427       .addReg(NewVReg6, RegState::Kill)
7428       .addJumpTableIndex(MJTI);
7429   } else {
7430     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7431     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7432                    .addFrameIndex(FI)
7433                    .addImm(4)
7434                    .addMemOperand(FIMMOLd));
7435 
7436     if (NumLPads < 256) {
7437       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7438                      .addReg(NewVReg1)
7439                      .addImm(NumLPads));
7440     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7441       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7442       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7443                      .addImm(NumLPads & 0xFFFF));
7444 
7445       unsigned VReg2 = VReg1;
7446       if ((NumLPads & 0xFFFF0000) != 0) {
7447         VReg2 = MRI->createVirtualRegister(TRC);
7448         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7449                        .addReg(VReg1)
7450                        .addImm(NumLPads >> 16));
7451       }
7452 
7453       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7454                      .addReg(NewVReg1)
7455                      .addReg(VReg2));
7456     } else {
7457       MachineConstantPool *ConstantPool = MF->getConstantPool();
7458       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7459       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7460 
7461       // MachineConstantPool wants an explicit alignment.
7462       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7463       if (Align == 0)
7464         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7465       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7466 
7467       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7468       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7469                      .addReg(VReg1, RegState::Define)
7470                      .addConstantPoolIndex(Idx)
7471                      .addImm(0));
7472       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7473                      .addReg(NewVReg1)
7474                      .addReg(VReg1, RegState::Kill));
7475     }
7476 
7477     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7478       .addMBB(TrapBB)
7479       .addImm(ARMCC::HI)
7480       .addReg(ARM::CPSR);
7481 
7482     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7483     AddDefaultCC(
7484       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7485                      .addReg(NewVReg1)
7486                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7487     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7488     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7489                    .addJumpTableIndex(MJTI));
7490 
7491     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7492         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7493     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7494     AddDefaultPred(
7495       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7496       .addReg(NewVReg3, RegState::Kill)
7497       .addReg(NewVReg4)
7498       .addImm(0)
7499       .addMemOperand(JTMMOLd));
7500 
7501     if (RelocM == Reloc::PIC_) {
7502       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7503         .addReg(NewVReg5, RegState::Kill)
7504         .addReg(NewVReg4)
7505         .addJumpTableIndex(MJTI);
7506     } else {
7507       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7508         .addReg(NewVReg5, RegState::Kill)
7509         .addJumpTableIndex(MJTI);
7510     }
7511   }
7512 
7513   // Add the jump table entries as successors to the MBB.
7514   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7515   for (std::vector<MachineBasicBlock*>::iterator
7516          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7517     MachineBasicBlock *CurMBB = *I;
7518     if (SeenMBBs.insert(CurMBB).second)
7519       DispContBB->addSuccessor(CurMBB);
7520   }
7521 
7522   // N.B. the order the invoke BBs are processed in doesn't matter here.
7523   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7524   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7525   for (MachineBasicBlock *BB : InvokeBBs) {
7526 
7527     // Remove the landing pad successor from the invoke block and replace it
7528     // with the new dispatch block.
7529     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7530                                                   BB->succ_end());
7531     while (!Successors.empty()) {
7532       MachineBasicBlock *SMBB = Successors.pop_back_val();
7533       if (SMBB->isEHPad()) {
7534         BB->removeSuccessor(SMBB);
7535         MBBLPads.push_back(SMBB);
7536       }
7537     }
7538 
7539     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7540     BB->normalizeSuccProbs();
7541 
7542     // Find the invoke call and mark all of the callee-saved registers as
7543     // 'implicit defined' so that they're spilled. This prevents code from
7544     // moving instructions to before the EH block, where they will never be
7545     // executed.
7546     for (MachineBasicBlock::reverse_iterator
7547            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7548       if (!II->isCall()) continue;
7549 
7550       DenseMap<unsigned, bool> DefRegs;
7551       for (MachineInstr::mop_iterator
7552              OI = II->operands_begin(), OE = II->operands_end();
7553            OI != OE; ++OI) {
7554         if (!OI->isReg()) continue;
7555         DefRegs[OI->getReg()] = true;
7556       }
7557 
7558       MachineInstrBuilder MIB(*MF, &*II);
7559 
7560       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7561         unsigned Reg = SavedRegs[i];
7562         if (Subtarget->isThumb2() &&
7563             !ARM::tGPRRegClass.contains(Reg) &&
7564             !ARM::hGPRRegClass.contains(Reg))
7565           continue;
7566         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7567           continue;
7568         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7569           continue;
7570         if (!DefRegs[Reg])
7571           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7572       }
7573 
7574       break;
7575     }
7576   }
7577 
7578   // Mark all former landing pads as non-landing pads. The dispatch is the only
7579   // landing pad now.
7580   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7581          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7582     (*I)->setIsEHPad(false);
7583 
7584   // The instruction is gone now.
7585   MI->eraseFromParent();
7586 }
7587 
7588 static
7589 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7590   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7591        E = MBB->succ_end(); I != E; ++I)
7592     if (*I != Succ)
7593       return *I;
7594   llvm_unreachable("Expecting a BB with two successors!");
7595 }
7596 
7597 /// Return the load opcode for a given load size. If load size >= 8,
7598 /// neon opcode will be returned.
7599 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7600   if (LdSize >= 8)
7601     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7602                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7603   if (IsThumb1)
7604     return LdSize == 4 ? ARM::tLDRi
7605                        : LdSize == 2 ? ARM::tLDRHi
7606                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7607   if (IsThumb2)
7608     return LdSize == 4 ? ARM::t2LDR_POST
7609                        : LdSize == 2 ? ARM::t2LDRH_POST
7610                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7611   return LdSize == 4 ? ARM::LDR_POST_IMM
7612                      : LdSize == 2 ? ARM::LDRH_POST
7613                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7614 }
7615 
7616 /// Return the store opcode for a given store size. If store size >= 8,
7617 /// neon opcode will be returned.
7618 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7619   if (StSize >= 8)
7620     return StSize == 16 ? ARM::VST1q32wb_fixed
7621                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7622   if (IsThumb1)
7623     return StSize == 4 ? ARM::tSTRi
7624                        : StSize == 2 ? ARM::tSTRHi
7625                                      : StSize == 1 ? ARM::tSTRBi : 0;
7626   if (IsThumb2)
7627     return StSize == 4 ? ARM::t2STR_POST
7628                        : StSize == 2 ? ARM::t2STRH_POST
7629                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7630   return StSize == 4 ? ARM::STR_POST_IMM
7631                      : StSize == 2 ? ARM::STRH_POST
7632                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7633 }
7634 
7635 /// Emit a post-increment load operation with given size. The instructions
7636 /// will be added to BB at Pos.
7637 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7638                        const TargetInstrInfo *TII, DebugLoc dl,
7639                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7640                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7641   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7642   assert(LdOpc != 0 && "Should have a load opcode");
7643   if (LdSize >= 8) {
7644     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7645                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7646                        .addImm(0));
7647   } else if (IsThumb1) {
7648     // load + update AddrIn
7649     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7650                        .addReg(AddrIn).addImm(0));
7651     MachineInstrBuilder MIB =
7652         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7653     MIB = AddDefaultT1CC(MIB);
7654     MIB.addReg(AddrIn).addImm(LdSize);
7655     AddDefaultPred(MIB);
7656   } else if (IsThumb2) {
7657     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7658                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7659                        .addImm(LdSize));
7660   } else { // arm
7661     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7662                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7663                        .addReg(0).addImm(LdSize));
7664   }
7665 }
7666 
7667 /// Emit a post-increment store operation with given size. The instructions
7668 /// will be added to BB at Pos.
7669 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7670                        const TargetInstrInfo *TII, DebugLoc dl,
7671                        unsigned StSize, unsigned Data, unsigned AddrIn,
7672                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7673   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7674   assert(StOpc != 0 && "Should have a store opcode");
7675   if (StSize >= 8) {
7676     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7677                        .addReg(AddrIn).addImm(0).addReg(Data));
7678   } else if (IsThumb1) {
7679     // store + update AddrIn
7680     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7681                        .addReg(AddrIn).addImm(0));
7682     MachineInstrBuilder MIB =
7683         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7684     MIB = AddDefaultT1CC(MIB);
7685     MIB.addReg(AddrIn).addImm(StSize);
7686     AddDefaultPred(MIB);
7687   } else if (IsThumb2) {
7688     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7689                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7690   } else { // arm
7691     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7692                        .addReg(Data).addReg(AddrIn).addReg(0)
7693                        .addImm(StSize));
7694   }
7695 }
7696 
7697 MachineBasicBlock *
7698 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7699                                    MachineBasicBlock *BB) const {
7700   // This pseudo instruction has 3 operands: dst, src, size
7701   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7702   // Otherwise, we will generate unrolled scalar copies.
7703   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7704   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7705   MachineFunction::iterator It = ++BB->getIterator();
7706 
7707   unsigned dest = MI->getOperand(0).getReg();
7708   unsigned src = MI->getOperand(1).getReg();
7709   unsigned SizeVal = MI->getOperand(2).getImm();
7710   unsigned Align = MI->getOperand(3).getImm();
7711   DebugLoc dl = MI->getDebugLoc();
7712 
7713   MachineFunction *MF = BB->getParent();
7714   MachineRegisterInfo &MRI = MF->getRegInfo();
7715   unsigned UnitSize = 0;
7716   const TargetRegisterClass *TRC = nullptr;
7717   const TargetRegisterClass *VecTRC = nullptr;
7718 
7719   bool IsThumb1 = Subtarget->isThumb1Only();
7720   bool IsThumb2 = Subtarget->isThumb2();
7721 
7722   if (Align & 1) {
7723     UnitSize = 1;
7724   } else if (Align & 2) {
7725     UnitSize = 2;
7726   } else {
7727     // Check whether we can use NEON instructions.
7728     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7729         Subtarget->hasNEON()) {
7730       if ((Align % 16 == 0) && SizeVal >= 16)
7731         UnitSize = 16;
7732       else if ((Align % 8 == 0) && SizeVal >= 8)
7733         UnitSize = 8;
7734     }
7735     // Can't use NEON instructions.
7736     if (UnitSize == 0)
7737       UnitSize = 4;
7738   }
7739 
7740   // Select the correct opcode and register class for unit size load/store
7741   bool IsNeon = UnitSize >= 8;
7742   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7743   if (IsNeon)
7744     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7745                             : UnitSize == 8 ? &ARM::DPRRegClass
7746                                             : nullptr;
7747 
7748   unsigned BytesLeft = SizeVal % UnitSize;
7749   unsigned LoopSize = SizeVal - BytesLeft;
7750 
7751   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7752     // Use LDR and STR to copy.
7753     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7754     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7755     unsigned srcIn = src;
7756     unsigned destIn = dest;
7757     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7758       unsigned srcOut = MRI.createVirtualRegister(TRC);
7759       unsigned destOut = MRI.createVirtualRegister(TRC);
7760       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7761       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7762                  IsThumb1, IsThumb2);
7763       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7764                  IsThumb1, IsThumb2);
7765       srcIn = srcOut;
7766       destIn = destOut;
7767     }
7768 
7769     // Handle the leftover bytes with LDRB and STRB.
7770     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7771     // [destOut] = STRB_POST(scratch, destIn, 1)
7772     for (unsigned i = 0; i < BytesLeft; i++) {
7773       unsigned srcOut = MRI.createVirtualRegister(TRC);
7774       unsigned destOut = MRI.createVirtualRegister(TRC);
7775       unsigned scratch = MRI.createVirtualRegister(TRC);
7776       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7777                  IsThumb1, IsThumb2);
7778       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7779                  IsThumb1, IsThumb2);
7780       srcIn = srcOut;
7781       destIn = destOut;
7782     }
7783     MI->eraseFromParent();   // The instruction is gone now.
7784     return BB;
7785   }
7786 
7787   // Expand the pseudo op to a loop.
7788   // thisMBB:
7789   //   ...
7790   //   movw varEnd, # --> with thumb2
7791   //   movt varEnd, #
7792   //   ldrcp varEnd, idx --> without thumb2
7793   //   fallthrough --> loopMBB
7794   // loopMBB:
7795   //   PHI varPhi, varEnd, varLoop
7796   //   PHI srcPhi, src, srcLoop
7797   //   PHI destPhi, dst, destLoop
7798   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7799   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7800   //   subs varLoop, varPhi, #UnitSize
7801   //   bne loopMBB
7802   //   fallthrough --> exitMBB
7803   // exitMBB:
7804   //   epilogue to handle left-over bytes
7805   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7806   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7807   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7808   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7809   MF->insert(It, loopMBB);
7810   MF->insert(It, exitMBB);
7811 
7812   // Transfer the remainder of BB and its successor edges to exitMBB.
7813   exitMBB->splice(exitMBB->begin(), BB,
7814                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7815   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7816 
7817   // Load an immediate to varEnd.
7818   unsigned varEnd = MRI.createVirtualRegister(TRC);
7819   if (Subtarget->useMovt(*MF)) {
7820     unsigned Vtmp = varEnd;
7821     if ((LoopSize & 0xFFFF0000) != 0)
7822       Vtmp = MRI.createVirtualRegister(TRC);
7823     AddDefaultPred(BuildMI(BB, dl,
7824                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7825                            Vtmp).addImm(LoopSize & 0xFFFF));
7826 
7827     if ((LoopSize & 0xFFFF0000) != 0)
7828       AddDefaultPred(BuildMI(BB, dl,
7829                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7830                              varEnd)
7831                          .addReg(Vtmp)
7832                          .addImm(LoopSize >> 16));
7833   } else {
7834     MachineConstantPool *ConstantPool = MF->getConstantPool();
7835     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7836     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7837 
7838     // MachineConstantPool wants an explicit alignment.
7839     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7840     if (Align == 0)
7841       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7842     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7843 
7844     if (IsThumb1)
7845       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7846           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7847     else
7848       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7849           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7850   }
7851   BB->addSuccessor(loopMBB);
7852 
7853   // Generate the loop body:
7854   //   varPhi = PHI(varLoop, varEnd)
7855   //   srcPhi = PHI(srcLoop, src)
7856   //   destPhi = PHI(destLoop, dst)
7857   MachineBasicBlock *entryBB = BB;
7858   BB = loopMBB;
7859   unsigned varLoop = MRI.createVirtualRegister(TRC);
7860   unsigned varPhi = MRI.createVirtualRegister(TRC);
7861   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7862   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7863   unsigned destLoop = MRI.createVirtualRegister(TRC);
7864   unsigned destPhi = MRI.createVirtualRegister(TRC);
7865 
7866   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7867     .addReg(varLoop).addMBB(loopMBB)
7868     .addReg(varEnd).addMBB(entryBB);
7869   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7870     .addReg(srcLoop).addMBB(loopMBB)
7871     .addReg(src).addMBB(entryBB);
7872   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7873     .addReg(destLoop).addMBB(loopMBB)
7874     .addReg(dest).addMBB(entryBB);
7875 
7876   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7877   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7878   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7879   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7880              IsThumb1, IsThumb2);
7881   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7882              IsThumb1, IsThumb2);
7883 
7884   // Decrement loop variable by UnitSize.
7885   if (IsThumb1) {
7886     MachineInstrBuilder MIB =
7887         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7888     MIB = AddDefaultT1CC(MIB);
7889     MIB.addReg(varPhi).addImm(UnitSize);
7890     AddDefaultPred(MIB);
7891   } else {
7892     MachineInstrBuilder MIB =
7893         BuildMI(*BB, BB->end(), dl,
7894                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7895     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7896     MIB->getOperand(5).setReg(ARM::CPSR);
7897     MIB->getOperand(5).setIsDef(true);
7898   }
7899   BuildMI(*BB, BB->end(), dl,
7900           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7901       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7902 
7903   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7904   BB->addSuccessor(loopMBB);
7905   BB->addSuccessor(exitMBB);
7906 
7907   // Add epilogue to handle BytesLeft.
7908   BB = exitMBB;
7909   MachineInstr *StartOfExit = exitMBB->begin();
7910 
7911   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7912   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7913   unsigned srcIn = srcLoop;
7914   unsigned destIn = destLoop;
7915   for (unsigned i = 0; i < BytesLeft; i++) {
7916     unsigned srcOut = MRI.createVirtualRegister(TRC);
7917     unsigned destOut = MRI.createVirtualRegister(TRC);
7918     unsigned scratch = MRI.createVirtualRegister(TRC);
7919     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7920                IsThumb1, IsThumb2);
7921     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7922                IsThumb1, IsThumb2);
7923     srcIn = srcOut;
7924     destIn = destOut;
7925   }
7926 
7927   MI->eraseFromParent();   // The instruction is gone now.
7928   return BB;
7929 }
7930 
7931 MachineBasicBlock *
7932 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7933                                        MachineBasicBlock *MBB) const {
7934   const TargetMachine &TM = getTargetMachine();
7935   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7936   DebugLoc DL = MI->getDebugLoc();
7937 
7938   assert(Subtarget->isTargetWindows() &&
7939          "__chkstk is only supported on Windows");
7940   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7941 
7942   // __chkstk takes the number of words to allocate on the stack in R4, and
7943   // returns the stack adjustment in number of bytes in R4.  This will not
7944   // clober any other registers (other than the obvious lr).
7945   //
7946   // Although, technically, IP should be considered a register which may be
7947   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7948   // thumb-2 environment, so there is no interworking required.  As a result, we
7949   // do not expect a veneer to be emitted by the linker, clobbering IP.
7950   //
7951   // Each module receives its own copy of __chkstk, so no import thunk is
7952   // required, again, ensuring that IP is not clobbered.
7953   //
7954   // Finally, although some linkers may theoretically provide a trampoline for
7955   // out of range calls (which is quite common due to a 32M range limitation of
7956   // branches for Thumb), we can generate the long-call version via
7957   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7958   // IP.
7959 
7960   switch (TM.getCodeModel()) {
7961   case CodeModel::Small:
7962   case CodeModel::Medium:
7963   case CodeModel::Default:
7964   case CodeModel::Kernel:
7965     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7966       .addImm((unsigned)ARMCC::AL).addReg(0)
7967       .addExternalSymbol("__chkstk")
7968       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7969       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7970       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7971     break;
7972   case CodeModel::Large:
7973   case CodeModel::JITDefault: {
7974     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7975     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7976 
7977     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7978       .addExternalSymbol("__chkstk");
7979     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7980       .addImm((unsigned)ARMCC::AL).addReg(0)
7981       .addReg(Reg, RegState::Kill)
7982       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7983       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7984       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7985     break;
7986   }
7987   }
7988 
7989   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7990                                       ARM::SP)
7991                               .addReg(ARM::SP).addReg(ARM::R4)));
7992 
7993   MI->eraseFromParent();
7994   return MBB;
7995 }
7996 
7997 MachineBasicBlock *
7998 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7999                                        MachineBasicBlock *MBB) const {
8000   DebugLoc DL = MI->getDebugLoc();
8001   MachineFunction *MF = MBB->getParent();
8002   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8003 
8004   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8005   MF->push_back(ContBB);
8006   ContBB->splice(ContBB->begin(), MBB,
8007                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8008   MBB->addSuccessor(ContBB);
8009 
8010   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8011   MF->push_back(TrapBB);
8012   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
8013   MBB->addSuccessor(TrapBB);
8014 
8015   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
8016       .addReg(MI->getOperand(0).getReg())
8017       .addMBB(TrapBB);
8018 
8019   MI->eraseFromParent();
8020   return ContBB;
8021 }
8022 
8023 MachineBasicBlock *
8024 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8025                                                MachineBasicBlock *BB) const {
8026   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8027   DebugLoc dl = MI->getDebugLoc();
8028   bool isThumb2 = Subtarget->isThumb2();
8029   switch (MI->getOpcode()) {
8030   default: {
8031     MI->dump();
8032     llvm_unreachable("Unexpected instr type to insert");
8033   }
8034   // The Thumb2 pre-indexed stores have the same MI operands, they just
8035   // define them differently in the .td files from the isel patterns, so
8036   // they need pseudos.
8037   case ARM::t2STR_preidx:
8038     MI->setDesc(TII->get(ARM::t2STR_PRE));
8039     return BB;
8040   case ARM::t2STRB_preidx:
8041     MI->setDesc(TII->get(ARM::t2STRB_PRE));
8042     return BB;
8043   case ARM::t2STRH_preidx:
8044     MI->setDesc(TII->get(ARM::t2STRH_PRE));
8045     return BB;
8046 
8047   case ARM::STRi_preidx:
8048   case ARM::STRBi_preidx: {
8049     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
8050       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
8051     // Decode the offset.
8052     unsigned Offset = MI->getOperand(4).getImm();
8053     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8054     Offset = ARM_AM::getAM2Offset(Offset);
8055     if (isSub)
8056       Offset = -Offset;
8057 
8058     MachineMemOperand *MMO = *MI->memoperands_begin();
8059     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8060       .addOperand(MI->getOperand(0))  // Rn_wb
8061       .addOperand(MI->getOperand(1))  // Rt
8062       .addOperand(MI->getOperand(2))  // Rn
8063       .addImm(Offset)                 // offset (skip GPR==zero_reg)
8064       .addOperand(MI->getOperand(5))  // pred
8065       .addOperand(MI->getOperand(6))
8066       .addMemOperand(MMO);
8067     MI->eraseFromParent();
8068     return BB;
8069   }
8070   case ARM::STRr_preidx:
8071   case ARM::STRBr_preidx:
8072   case ARM::STRH_preidx: {
8073     unsigned NewOpc;
8074     switch (MI->getOpcode()) {
8075     default: llvm_unreachable("unexpected opcode!");
8076     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8077     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8078     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8079     }
8080     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8081     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
8082       MIB.addOperand(MI->getOperand(i));
8083     MI->eraseFromParent();
8084     return BB;
8085   }
8086 
8087   case ARM::tMOVCCr_pseudo: {
8088     // To "insert" a SELECT_CC instruction, we actually have to insert the
8089     // diamond control-flow pattern.  The incoming instruction knows the
8090     // destination vreg to set, the condition code register to branch on, the
8091     // true/false values to select between, and a branch opcode to use.
8092     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8093     MachineFunction::iterator It = ++BB->getIterator();
8094 
8095     //  thisMBB:
8096     //  ...
8097     //   TrueVal = ...
8098     //   cmpTY ccX, r1, r2
8099     //   bCC copy1MBB
8100     //   fallthrough --> copy0MBB
8101     MachineBasicBlock *thisMBB  = BB;
8102     MachineFunction *F = BB->getParent();
8103     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8104     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8105     F->insert(It, copy0MBB);
8106     F->insert(It, sinkMBB);
8107 
8108     // Transfer the remainder of BB and its successor edges to sinkMBB.
8109     sinkMBB->splice(sinkMBB->begin(), BB,
8110                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8111     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8112 
8113     BB->addSuccessor(copy0MBB);
8114     BB->addSuccessor(sinkMBB);
8115 
8116     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
8117       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
8118 
8119     //  copy0MBB:
8120     //   %FalseValue = ...
8121     //   # fallthrough to sinkMBB
8122     BB = copy0MBB;
8123 
8124     // Update machine-CFG edges
8125     BB->addSuccessor(sinkMBB);
8126 
8127     //  sinkMBB:
8128     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8129     //  ...
8130     BB = sinkMBB;
8131     BuildMI(*BB, BB->begin(), dl,
8132             TII->get(ARM::PHI), MI->getOperand(0).getReg())
8133       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8134       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8135 
8136     MI->eraseFromParent();   // The pseudo instruction is gone now.
8137     return BB;
8138   }
8139 
8140   case ARM::BCCi64:
8141   case ARM::BCCZi64: {
8142     // If there is an unconditional branch to the other successor, remove it.
8143     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8144 
8145     // Compare both parts that make up the double comparison separately for
8146     // equality.
8147     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
8148 
8149     unsigned LHS1 = MI->getOperand(1).getReg();
8150     unsigned LHS2 = MI->getOperand(2).getReg();
8151     if (RHSisZero) {
8152       AddDefaultPred(BuildMI(BB, dl,
8153                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8154                      .addReg(LHS1).addImm(0));
8155       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8156         .addReg(LHS2).addImm(0)
8157         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8158     } else {
8159       unsigned RHS1 = MI->getOperand(3).getReg();
8160       unsigned RHS2 = MI->getOperand(4).getReg();
8161       AddDefaultPred(BuildMI(BB, dl,
8162                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8163                      .addReg(LHS1).addReg(RHS1));
8164       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8165         .addReg(LHS2).addReg(RHS2)
8166         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8167     }
8168 
8169     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
8170     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8171     if (MI->getOperand(0).getImm() == ARMCC::NE)
8172       std::swap(destMBB, exitMBB);
8173 
8174     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8175       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8176     if (isThumb2)
8177       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8178     else
8179       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8180 
8181     MI->eraseFromParent();   // The pseudo instruction is gone now.
8182     return BB;
8183   }
8184 
8185   case ARM::Int_eh_sjlj_setjmp:
8186   case ARM::Int_eh_sjlj_setjmp_nofp:
8187   case ARM::tInt_eh_sjlj_setjmp:
8188   case ARM::t2Int_eh_sjlj_setjmp:
8189   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8190     return BB;
8191 
8192   case ARM::Int_eh_sjlj_setup_dispatch:
8193     EmitSjLjDispatchBlock(MI, BB);
8194     return BB;
8195 
8196   case ARM::ABS:
8197   case ARM::t2ABS: {
8198     // To insert an ABS instruction, we have to insert the
8199     // diamond control-flow pattern.  The incoming instruction knows the
8200     // source vreg to test against 0, the destination vreg to set,
8201     // the condition code register to branch on, the
8202     // true/false values to select between, and a branch opcode to use.
8203     // It transforms
8204     //     V1 = ABS V0
8205     // into
8206     //     V2 = MOVS V0
8207     //     BCC                      (branch to SinkBB if V0 >= 0)
8208     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8209     //     SinkBB: V1 = PHI(V2, V3)
8210     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8211     MachineFunction::iterator BBI = ++BB->getIterator();
8212     MachineFunction *Fn = BB->getParent();
8213     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8214     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8215     Fn->insert(BBI, RSBBB);
8216     Fn->insert(BBI, SinkBB);
8217 
8218     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8219     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8220     bool ABSSrcKIll = MI->getOperand(1).isKill();
8221     bool isThumb2 = Subtarget->isThumb2();
8222     MachineRegisterInfo &MRI = Fn->getRegInfo();
8223     // In Thumb mode S must not be specified if source register is the SP or
8224     // PC and if destination register is the SP, so restrict register class
8225     unsigned NewRsbDstReg =
8226       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8227 
8228     // Transfer the remainder of BB and its successor edges to sinkMBB.
8229     SinkBB->splice(SinkBB->begin(), BB,
8230                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8231     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8232 
8233     BB->addSuccessor(RSBBB);
8234     BB->addSuccessor(SinkBB);
8235 
8236     // fall through to SinkMBB
8237     RSBBB->addSuccessor(SinkBB);
8238 
8239     // insert a cmp at the end of BB
8240     AddDefaultPred(BuildMI(BB, dl,
8241                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8242                    .addReg(ABSSrcReg).addImm(0));
8243 
8244     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8245     BuildMI(BB, dl,
8246       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8247       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8248 
8249     // insert rsbri in RSBBB
8250     // Note: BCC and rsbri will be converted into predicated rsbmi
8251     // by if-conversion pass
8252     BuildMI(*RSBBB, RSBBB->begin(), dl,
8253       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8254       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8255       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8256 
8257     // insert PHI in SinkBB,
8258     // reuse ABSDstReg to not change uses of ABS instruction
8259     BuildMI(*SinkBB, SinkBB->begin(), dl,
8260       TII->get(ARM::PHI), ABSDstReg)
8261       .addReg(NewRsbDstReg).addMBB(RSBBB)
8262       .addReg(ABSSrcReg).addMBB(BB);
8263 
8264     // remove ABS instruction
8265     MI->eraseFromParent();
8266 
8267     // return last added BB
8268     return SinkBB;
8269   }
8270   case ARM::COPY_STRUCT_BYVAL_I32:
8271     ++NumLoopByVals;
8272     return EmitStructByval(MI, BB);
8273   case ARM::WIN__CHKSTK:
8274     return EmitLowered__chkstk(MI, BB);
8275   case ARM::WIN__DBZCHK:
8276     return EmitLowered__dbzchk(MI, BB);
8277   }
8278 }
8279 
8280 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8281 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8282 /// instead of as a custom inserter because we need the use list from the SDNode.
8283 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8284                                    MachineInstr *MI, const SDNode *Node) {
8285   bool isThumb1 = Subtarget->isThumb1Only();
8286 
8287   DebugLoc DL = MI->getDebugLoc();
8288   MachineFunction *MF = MI->getParent()->getParent();
8289   MachineRegisterInfo &MRI = MF->getRegInfo();
8290   MachineInstrBuilder MIB(*MF, MI);
8291 
8292   // If the new dst/src is unused mark it as dead.
8293   if (!Node->hasAnyUseOfValue(0)) {
8294     MI->getOperand(0).setIsDead(true);
8295   }
8296   if (!Node->hasAnyUseOfValue(1)) {
8297     MI->getOperand(1).setIsDead(true);
8298   }
8299 
8300   // The MEMCPY both defines and kills the scratch registers.
8301   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8302     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8303                                                          : &ARM::GPRRegClass);
8304     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8305   }
8306 }
8307 
8308 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8309                                                       SDNode *Node) const {
8310   if (MI->getOpcode() == ARM::MEMCPY) {
8311     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8312     return;
8313   }
8314 
8315   const MCInstrDesc *MCID = &MI->getDesc();
8316   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8317   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8318   // operand is still set to noreg. If needed, set the optional operand's
8319   // register to CPSR, and remove the redundant implicit def.
8320   //
8321   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8322 
8323   // Rename pseudo opcodes.
8324   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8325   if (NewOpc) {
8326     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8327     MCID = &TII->get(NewOpc);
8328 
8329     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8330            "converted opcode should be the same except for cc_out");
8331 
8332     MI->setDesc(*MCID);
8333 
8334     // Add the optional cc_out operand
8335     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8336   }
8337   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8338 
8339   // Any ARM instruction that sets the 's' bit should specify an optional
8340   // "cc_out" operand in the last operand position.
8341   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8342     assert(!NewOpc && "Optional cc_out operand required");
8343     return;
8344   }
8345   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8346   // since we already have an optional CPSR def.
8347   bool definesCPSR = false;
8348   bool deadCPSR = false;
8349   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8350        i != e; ++i) {
8351     const MachineOperand &MO = MI->getOperand(i);
8352     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8353       definesCPSR = true;
8354       if (MO.isDead())
8355         deadCPSR = true;
8356       MI->RemoveOperand(i);
8357       break;
8358     }
8359   }
8360   if (!definesCPSR) {
8361     assert(!NewOpc && "Optional cc_out operand required");
8362     return;
8363   }
8364   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8365   if (deadCPSR) {
8366     assert(!MI->getOperand(ccOutIdx).getReg() &&
8367            "expect uninitialized optional cc_out operand");
8368     return;
8369   }
8370 
8371   // If this instruction was defined with an optional CPSR def and its dag node
8372   // had a live implicit CPSR def, then activate the optional CPSR def.
8373   MachineOperand &MO = MI->getOperand(ccOutIdx);
8374   MO.setReg(ARM::CPSR);
8375   MO.setIsDef(true);
8376 }
8377 
8378 //===----------------------------------------------------------------------===//
8379 //                           ARM Optimization Hooks
8380 //===----------------------------------------------------------------------===//
8381 
8382 // Helper function that checks if N is a null or all ones constant.
8383 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8384   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8385 }
8386 
8387 // Return true if N is conditionally 0 or all ones.
8388 // Detects these expressions where cc is an i1 value:
8389 //
8390 //   (select cc 0, y)   [AllOnes=0]
8391 //   (select cc y, 0)   [AllOnes=0]
8392 //   (zext cc)          [AllOnes=0]
8393 //   (sext cc)          [AllOnes=0/1]
8394 //   (select cc -1, y)  [AllOnes=1]
8395 //   (select cc y, -1)  [AllOnes=1]
8396 //
8397 // Invert is set when N is the null/all ones constant when CC is false.
8398 // OtherOp is set to the alternative value of N.
8399 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8400                                        SDValue &CC, bool &Invert,
8401                                        SDValue &OtherOp,
8402                                        SelectionDAG &DAG) {
8403   switch (N->getOpcode()) {
8404   default: return false;
8405   case ISD::SELECT: {
8406     CC = N->getOperand(0);
8407     SDValue N1 = N->getOperand(1);
8408     SDValue N2 = N->getOperand(2);
8409     if (isZeroOrAllOnes(N1, AllOnes)) {
8410       Invert = false;
8411       OtherOp = N2;
8412       return true;
8413     }
8414     if (isZeroOrAllOnes(N2, AllOnes)) {
8415       Invert = true;
8416       OtherOp = N1;
8417       return true;
8418     }
8419     return false;
8420   }
8421   case ISD::ZERO_EXTEND:
8422     // (zext cc) can never be the all ones value.
8423     if (AllOnes)
8424       return false;
8425     // Fall through.
8426   case ISD::SIGN_EXTEND: {
8427     SDLoc dl(N);
8428     EVT VT = N->getValueType(0);
8429     CC = N->getOperand(0);
8430     if (CC.getValueType() != MVT::i1)
8431       return false;
8432     Invert = !AllOnes;
8433     if (AllOnes)
8434       // When looking for an AllOnes constant, N is an sext, and the 'other'
8435       // value is 0.
8436       OtherOp = DAG.getConstant(0, dl, VT);
8437     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8438       // When looking for a 0 constant, N can be zext or sext.
8439       OtherOp = DAG.getConstant(1, dl, VT);
8440     else
8441       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8442                                 VT);
8443     return true;
8444   }
8445   }
8446 }
8447 
8448 // Combine a constant select operand into its use:
8449 //
8450 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8451 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8452 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8453 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8454 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8455 //
8456 // The transform is rejected if the select doesn't have a constant operand that
8457 // is null, or all ones when AllOnes is set.
8458 //
8459 // Also recognize sext/zext from i1:
8460 //
8461 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8462 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8463 //
8464 // These transformations eventually create predicated instructions.
8465 //
8466 // @param N       The node to transform.
8467 // @param Slct    The N operand that is a select.
8468 // @param OtherOp The other N operand (x above).
8469 // @param DCI     Context.
8470 // @param AllOnes Require the select constant to be all ones instead of null.
8471 // @returns The new node, or SDValue() on failure.
8472 static
8473 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8474                             TargetLowering::DAGCombinerInfo &DCI,
8475                             bool AllOnes = false) {
8476   SelectionDAG &DAG = DCI.DAG;
8477   EVT VT = N->getValueType(0);
8478   SDValue NonConstantVal;
8479   SDValue CCOp;
8480   bool SwapSelectOps;
8481   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8482                                   NonConstantVal, DAG))
8483     return SDValue();
8484 
8485   // Slct is now know to be the desired identity constant when CC is true.
8486   SDValue TrueVal = OtherOp;
8487   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8488                                  OtherOp, NonConstantVal);
8489   // Unless SwapSelectOps says CC should be false.
8490   if (SwapSelectOps)
8491     std::swap(TrueVal, FalseVal);
8492 
8493   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8494                      CCOp, TrueVal, FalseVal);
8495 }
8496 
8497 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8498 static
8499 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8500                                        TargetLowering::DAGCombinerInfo &DCI) {
8501   SDValue N0 = N->getOperand(0);
8502   SDValue N1 = N->getOperand(1);
8503   if (N0.getNode()->hasOneUse())
8504     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
8505       return Result;
8506   if (N1.getNode()->hasOneUse())
8507     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
8508       return Result;
8509   return SDValue();
8510 }
8511 
8512 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8513 // (only after legalization).
8514 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8515                                  TargetLowering::DAGCombinerInfo &DCI,
8516                                  const ARMSubtarget *Subtarget) {
8517 
8518   // Only perform optimization if after legalize, and if NEON is available. We
8519   // also expected both operands to be BUILD_VECTORs.
8520   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8521       || N0.getOpcode() != ISD::BUILD_VECTOR
8522       || N1.getOpcode() != ISD::BUILD_VECTOR)
8523     return SDValue();
8524 
8525   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8526   EVT VT = N->getValueType(0);
8527   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8528     return SDValue();
8529 
8530   // Check that the vector operands are of the right form.
8531   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8532   // operands, where N is the size of the formed vector.
8533   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8534   // index such that we have a pair wise add pattern.
8535 
8536   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8537   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8538     return SDValue();
8539   SDValue Vec = N0->getOperand(0)->getOperand(0);
8540   SDNode *V = Vec.getNode();
8541   unsigned nextIndex = 0;
8542 
8543   // For each operands to the ADD which are BUILD_VECTORs,
8544   // check to see if each of their operands are an EXTRACT_VECTOR with
8545   // the same vector and appropriate index.
8546   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8547     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8548         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8549 
8550       SDValue ExtVec0 = N0->getOperand(i);
8551       SDValue ExtVec1 = N1->getOperand(i);
8552 
8553       // First operand is the vector, verify its the same.
8554       if (V != ExtVec0->getOperand(0).getNode() ||
8555           V != ExtVec1->getOperand(0).getNode())
8556         return SDValue();
8557 
8558       // Second is the constant, verify its correct.
8559       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8560       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8561 
8562       // For the constant, we want to see all the even or all the odd.
8563       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8564           || C1->getZExtValue() != nextIndex+1)
8565         return SDValue();
8566 
8567       // Increment index.
8568       nextIndex+=2;
8569     } else
8570       return SDValue();
8571   }
8572 
8573   // Create VPADDL node.
8574   SelectionDAG &DAG = DCI.DAG;
8575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8576 
8577   SDLoc dl(N);
8578 
8579   // Build operand list.
8580   SmallVector<SDValue, 8> Ops;
8581   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8582                                 TLI.getPointerTy(DAG.getDataLayout())));
8583 
8584   // Input is the vector.
8585   Ops.push_back(Vec);
8586 
8587   // Get widened type and narrowed type.
8588   MVT widenType;
8589   unsigned numElem = VT.getVectorNumElements();
8590 
8591   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8592   switch (inputLaneType.getSimpleVT().SimpleTy) {
8593     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8594     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8595     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8596     default:
8597       llvm_unreachable("Invalid vector element type for padd optimization.");
8598   }
8599 
8600   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8601   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8602   return DAG.getNode(ExtOp, dl, VT, tmp);
8603 }
8604 
8605 static SDValue findMUL_LOHI(SDValue V) {
8606   if (V->getOpcode() == ISD::UMUL_LOHI ||
8607       V->getOpcode() == ISD::SMUL_LOHI)
8608     return V;
8609   return SDValue();
8610 }
8611 
8612 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8613                                      TargetLowering::DAGCombinerInfo &DCI,
8614                                      const ARMSubtarget *Subtarget) {
8615 
8616   if (Subtarget->isThumb1Only()) return SDValue();
8617 
8618   // Only perform the checks after legalize when the pattern is available.
8619   if (DCI.isBeforeLegalize()) return SDValue();
8620 
8621   // Look for multiply add opportunities.
8622   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8623   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8624   // a glue link from the first add to the second add.
8625   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8626   // a S/UMLAL instruction.
8627   //                  UMUL_LOHI
8628   //                 / :lo    \ :hi
8629   //                /          \          [no multiline comment]
8630   //    loAdd ->  ADDE         |
8631   //                 \ :glue  /
8632   //                  \      /
8633   //                    ADDC   <- hiAdd
8634   //
8635   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8636   SDValue AddcOp0 = AddcNode->getOperand(0);
8637   SDValue AddcOp1 = AddcNode->getOperand(1);
8638 
8639   // Check if the two operands are from the same mul_lohi node.
8640   if (AddcOp0.getNode() == AddcOp1.getNode())
8641     return SDValue();
8642 
8643   assert(AddcNode->getNumValues() == 2 &&
8644          AddcNode->getValueType(0) == MVT::i32 &&
8645          "Expect ADDC with two result values. First: i32");
8646 
8647   // Check that we have a glued ADDC node.
8648   if (AddcNode->getValueType(1) != MVT::Glue)
8649     return SDValue();
8650 
8651   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8652   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8653       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8654       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8655       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8656     return SDValue();
8657 
8658   // Look for the glued ADDE.
8659   SDNode* AddeNode = AddcNode->getGluedUser();
8660   if (!AddeNode)
8661     return SDValue();
8662 
8663   // Make sure it is really an ADDE.
8664   if (AddeNode->getOpcode() != ISD::ADDE)
8665     return SDValue();
8666 
8667   assert(AddeNode->getNumOperands() == 3 &&
8668          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8669          "ADDE node has the wrong inputs");
8670 
8671   // Check for the triangle shape.
8672   SDValue AddeOp0 = AddeNode->getOperand(0);
8673   SDValue AddeOp1 = AddeNode->getOperand(1);
8674 
8675   // Make sure that the ADDE operands are not coming from the same node.
8676   if (AddeOp0.getNode() == AddeOp1.getNode())
8677     return SDValue();
8678 
8679   // Find the MUL_LOHI node walking up ADDE's operands.
8680   bool IsLeftOperandMUL = false;
8681   SDValue MULOp = findMUL_LOHI(AddeOp0);
8682   if (MULOp == SDValue())
8683    MULOp = findMUL_LOHI(AddeOp1);
8684   else
8685     IsLeftOperandMUL = true;
8686   if (MULOp == SDValue())
8687     return SDValue();
8688 
8689   // Figure out the right opcode.
8690   unsigned Opc = MULOp->getOpcode();
8691   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8692 
8693   // Figure out the high and low input values to the MLAL node.
8694   SDValue* HiAdd = nullptr;
8695   SDValue* LoMul = nullptr;
8696   SDValue* LowAdd = nullptr;
8697 
8698   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8699   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8700     return SDValue();
8701 
8702   if (IsLeftOperandMUL)
8703     HiAdd = &AddeOp1;
8704   else
8705     HiAdd = &AddeOp0;
8706 
8707 
8708   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8709   // whose low result is fed to the ADDC we are checking.
8710 
8711   if (AddcOp0 == MULOp.getValue(0)) {
8712     LoMul = &AddcOp0;
8713     LowAdd = &AddcOp1;
8714   }
8715   if (AddcOp1 == MULOp.getValue(0)) {
8716     LoMul = &AddcOp1;
8717     LowAdd = &AddcOp0;
8718   }
8719 
8720   if (!LoMul)
8721     return SDValue();
8722 
8723   // Create the merged node.
8724   SelectionDAG &DAG = DCI.DAG;
8725 
8726   // Build operand list.
8727   SmallVector<SDValue, 8> Ops;
8728   Ops.push_back(LoMul->getOperand(0));
8729   Ops.push_back(LoMul->getOperand(1));
8730   Ops.push_back(*LowAdd);
8731   Ops.push_back(*HiAdd);
8732 
8733   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8734                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8735 
8736   // Replace the ADDs' nodes uses by the MLA node's values.
8737   SDValue HiMLALResult(MLALNode.getNode(), 1);
8738   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8739 
8740   SDValue LoMLALResult(MLALNode.getNode(), 0);
8741   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8742 
8743   // Return original node to notify the driver to stop replacing.
8744   SDValue resNode(AddcNode, 0);
8745   return resNode;
8746 }
8747 
8748 /// PerformADDCCombine - Target-specific dag combine transform from
8749 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8750 static SDValue PerformADDCCombine(SDNode *N,
8751                                  TargetLowering::DAGCombinerInfo &DCI,
8752                                  const ARMSubtarget *Subtarget) {
8753 
8754   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8755 
8756 }
8757 
8758 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8759 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8760 /// called with the default operands, and if that fails, with commuted
8761 /// operands.
8762 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8763                                           TargetLowering::DAGCombinerInfo &DCI,
8764                                           const ARMSubtarget *Subtarget){
8765 
8766   // Attempt to create vpaddl for this add.
8767   if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget))
8768     return Result;
8769 
8770   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8771   if (N0.getNode()->hasOneUse())
8772     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
8773       return Result;
8774   return SDValue();
8775 }
8776 
8777 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8778 ///
8779 static SDValue PerformADDCombine(SDNode *N,
8780                                  TargetLowering::DAGCombinerInfo &DCI,
8781                                  const ARMSubtarget *Subtarget) {
8782   SDValue N0 = N->getOperand(0);
8783   SDValue N1 = N->getOperand(1);
8784 
8785   // First try with the default operand order.
8786   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
8787     return Result;
8788 
8789   // If that didn't work, try again with the operands commuted.
8790   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8791 }
8792 
8793 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8794 ///
8795 static SDValue PerformSUBCombine(SDNode *N,
8796                                  TargetLowering::DAGCombinerInfo &DCI) {
8797   SDValue N0 = N->getOperand(0);
8798   SDValue N1 = N->getOperand(1);
8799 
8800   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8801   if (N1.getNode()->hasOneUse())
8802     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
8803       return Result;
8804 
8805   return SDValue();
8806 }
8807 
8808 /// PerformVMULCombine
8809 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8810 /// special multiplier accumulator forwarding.
8811 ///   vmul d3, d0, d2
8812 ///   vmla d3, d1, d2
8813 /// is faster than
8814 ///   vadd d3, d0, d1
8815 ///   vmul d3, d3, d2
8816 //  However, for (A + B) * (A + B),
8817 //    vadd d2, d0, d1
8818 //    vmul d3, d0, d2
8819 //    vmla d3, d1, d2
8820 //  is slower than
8821 //    vadd d2, d0, d1
8822 //    vmul d3, d2, d2
8823 static SDValue PerformVMULCombine(SDNode *N,
8824                                   TargetLowering::DAGCombinerInfo &DCI,
8825                                   const ARMSubtarget *Subtarget) {
8826   if (!Subtarget->hasVMLxForwarding())
8827     return SDValue();
8828 
8829   SelectionDAG &DAG = DCI.DAG;
8830   SDValue N0 = N->getOperand(0);
8831   SDValue N1 = N->getOperand(1);
8832   unsigned Opcode = N0.getOpcode();
8833   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8834       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8835     Opcode = N1.getOpcode();
8836     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8837         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8838       return SDValue();
8839     std::swap(N0, N1);
8840   }
8841 
8842   if (N0 == N1)
8843     return SDValue();
8844 
8845   EVT VT = N->getValueType(0);
8846   SDLoc DL(N);
8847   SDValue N00 = N0->getOperand(0);
8848   SDValue N01 = N0->getOperand(1);
8849   return DAG.getNode(Opcode, DL, VT,
8850                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8851                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8852 }
8853 
8854 static SDValue PerformMULCombine(SDNode *N,
8855                                  TargetLowering::DAGCombinerInfo &DCI,
8856                                  const ARMSubtarget *Subtarget) {
8857   SelectionDAG &DAG = DCI.DAG;
8858 
8859   if (Subtarget->isThumb1Only())
8860     return SDValue();
8861 
8862   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8863     return SDValue();
8864 
8865   EVT VT = N->getValueType(0);
8866   if (VT.is64BitVector() || VT.is128BitVector())
8867     return PerformVMULCombine(N, DCI, Subtarget);
8868   if (VT != MVT::i32)
8869     return SDValue();
8870 
8871   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8872   if (!C)
8873     return SDValue();
8874 
8875   int64_t MulAmt = C->getSExtValue();
8876   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8877 
8878   ShiftAmt = ShiftAmt & (32 - 1);
8879   SDValue V = N->getOperand(0);
8880   SDLoc DL(N);
8881 
8882   SDValue Res;
8883   MulAmt >>= ShiftAmt;
8884 
8885   if (MulAmt >= 0) {
8886     if (isPowerOf2_32(MulAmt - 1)) {
8887       // (mul x, 2^N + 1) => (add (shl x, N), x)
8888       Res = DAG.getNode(ISD::ADD, DL, VT,
8889                         V,
8890                         DAG.getNode(ISD::SHL, DL, VT,
8891                                     V,
8892                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8893                                                     MVT::i32)));
8894     } else if (isPowerOf2_32(MulAmt + 1)) {
8895       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8896       Res = DAG.getNode(ISD::SUB, DL, VT,
8897                         DAG.getNode(ISD::SHL, DL, VT,
8898                                     V,
8899                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8900                                                     MVT::i32)),
8901                         V);
8902     } else
8903       return SDValue();
8904   } else {
8905     uint64_t MulAmtAbs = -MulAmt;
8906     if (isPowerOf2_32(MulAmtAbs + 1)) {
8907       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8908       Res = DAG.getNode(ISD::SUB, DL, VT,
8909                         V,
8910                         DAG.getNode(ISD::SHL, DL, VT,
8911                                     V,
8912                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8913                                                     MVT::i32)));
8914     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8915       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8916       Res = DAG.getNode(ISD::ADD, DL, VT,
8917                         V,
8918                         DAG.getNode(ISD::SHL, DL, VT,
8919                                     V,
8920                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8921                                                     MVT::i32)));
8922       Res = DAG.getNode(ISD::SUB, DL, VT,
8923                         DAG.getConstant(0, DL, MVT::i32), Res);
8924 
8925     } else
8926       return SDValue();
8927   }
8928 
8929   if (ShiftAmt != 0)
8930     Res = DAG.getNode(ISD::SHL, DL, VT,
8931                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8932 
8933   // Do not add new nodes to DAG combiner worklist.
8934   DCI.CombineTo(N, Res, false);
8935   return SDValue();
8936 }
8937 
8938 static SDValue PerformANDCombine(SDNode *N,
8939                                  TargetLowering::DAGCombinerInfo &DCI,
8940                                  const ARMSubtarget *Subtarget) {
8941 
8942   // Attempt to use immediate-form VBIC
8943   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8944   SDLoc dl(N);
8945   EVT VT = N->getValueType(0);
8946   SelectionDAG &DAG = DCI.DAG;
8947 
8948   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8949     return SDValue();
8950 
8951   APInt SplatBits, SplatUndef;
8952   unsigned SplatBitSize;
8953   bool HasAnyUndefs;
8954   if (BVN &&
8955       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8956     if (SplatBitSize <= 64) {
8957       EVT VbicVT;
8958       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8959                                       SplatUndef.getZExtValue(), SplatBitSize,
8960                                       DAG, dl, VbicVT, VT.is128BitVector(),
8961                                       OtherModImm);
8962       if (Val.getNode()) {
8963         SDValue Input =
8964           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8965         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8966         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8967       }
8968     }
8969   }
8970 
8971   if (!Subtarget->isThumb1Only()) {
8972     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8973     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
8974       return Result;
8975   }
8976 
8977   return SDValue();
8978 }
8979 
8980 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8981 static SDValue PerformORCombine(SDNode *N,
8982                                 TargetLowering::DAGCombinerInfo &DCI,
8983                                 const ARMSubtarget *Subtarget) {
8984   // Attempt to use immediate-form VORR
8985   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8986   SDLoc dl(N);
8987   EVT VT = N->getValueType(0);
8988   SelectionDAG &DAG = DCI.DAG;
8989 
8990   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8991     return SDValue();
8992 
8993   APInt SplatBits, SplatUndef;
8994   unsigned SplatBitSize;
8995   bool HasAnyUndefs;
8996   if (BVN && Subtarget->hasNEON() &&
8997       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8998     if (SplatBitSize <= 64) {
8999       EVT VorrVT;
9000       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9001                                       SplatUndef.getZExtValue(), SplatBitSize,
9002                                       DAG, dl, VorrVT, VT.is128BitVector(),
9003                                       OtherModImm);
9004       if (Val.getNode()) {
9005         SDValue Input =
9006           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9007         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9008         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9009       }
9010     }
9011   }
9012 
9013   if (!Subtarget->isThumb1Only()) {
9014     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9015     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9016       return Result;
9017   }
9018 
9019   // The code below optimizes (or (and X, Y), Z).
9020   // The AND operand needs to have a single user to make these optimizations
9021   // profitable.
9022   SDValue N0 = N->getOperand(0);
9023   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9024     return SDValue();
9025   SDValue N1 = N->getOperand(1);
9026 
9027   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9028   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9029       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9030     APInt SplatUndef;
9031     unsigned SplatBitSize;
9032     bool HasAnyUndefs;
9033 
9034     APInt SplatBits0, SplatBits1;
9035     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9036     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9037     // Ensure that the second operand of both ands are constants
9038     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9039                                       HasAnyUndefs) && !HasAnyUndefs) {
9040         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9041                                           HasAnyUndefs) && !HasAnyUndefs) {
9042             // Ensure that the bit width of the constants are the same and that
9043             // the splat arguments are logical inverses as per the pattern we
9044             // are trying to simplify.
9045             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9046                 SplatBits0 == ~SplatBits1) {
9047                 // Canonicalize the vector type to make instruction selection
9048                 // simpler.
9049                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9050                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9051                                              N0->getOperand(1),
9052                                              N0->getOperand(0),
9053                                              N1->getOperand(0));
9054                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9055             }
9056         }
9057     }
9058   }
9059 
9060   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9061   // reasonable.
9062 
9063   // BFI is only available on V6T2+
9064   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9065     return SDValue();
9066 
9067   SDLoc DL(N);
9068   // 1) or (and A, mask), val => ARMbfi A, val, mask
9069   //      iff (val & mask) == val
9070   //
9071   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9072   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9073   //          && mask == ~mask2
9074   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9075   //          && ~mask == mask2
9076   //  (i.e., copy a bitfield value into another bitfield of the same width)
9077 
9078   if (VT != MVT::i32)
9079     return SDValue();
9080 
9081   SDValue N00 = N0.getOperand(0);
9082 
9083   // The value and the mask need to be constants so we can verify this is
9084   // actually a bitfield set. If the mask is 0xffff, we can do better
9085   // via a movt instruction, so don't use BFI in that case.
9086   SDValue MaskOp = N0.getOperand(1);
9087   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9088   if (!MaskC)
9089     return SDValue();
9090   unsigned Mask = MaskC->getZExtValue();
9091   if (Mask == 0xffff)
9092     return SDValue();
9093   SDValue Res;
9094   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9095   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9096   if (N1C) {
9097     unsigned Val = N1C->getZExtValue();
9098     if ((Val & ~Mask) != Val)
9099       return SDValue();
9100 
9101     if (ARM::isBitFieldInvertedMask(Mask)) {
9102       Val >>= countTrailingZeros(~Mask);
9103 
9104       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9105                         DAG.getConstant(Val, DL, MVT::i32),
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       return SDValue();
9111     }
9112   } else if (N1.getOpcode() == ISD::AND) {
9113     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9114     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9115     if (!N11C)
9116       return SDValue();
9117     unsigned Mask2 = N11C->getZExtValue();
9118 
9119     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9120     // as is to match.
9121     if (ARM::isBitFieldInvertedMask(Mask) &&
9122         (Mask == ~Mask2)) {
9123       // The pack halfword instruction works better for masks that fit it,
9124       // so use that when it's available.
9125       if (Subtarget->hasT2ExtractPack() &&
9126           (Mask == 0xffff || Mask == 0xffff0000))
9127         return SDValue();
9128       // 2a
9129       unsigned amt = countTrailingZeros(Mask2);
9130       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9131                         DAG.getConstant(amt, DL, MVT::i32));
9132       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9133                         DAG.getConstant(Mask, DL, MVT::i32));
9134       // Do not add new nodes to DAG combiner worklist.
9135       DCI.CombineTo(N, Res, false);
9136       return SDValue();
9137     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9138                (~Mask == Mask2)) {
9139       // The pack halfword instruction works better for masks that fit it,
9140       // so use that when it's available.
9141       if (Subtarget->hasT2ExtractPack() &&
9142           (Mask2 == 0xffff || Mask2 == 0xffff0000))
9143         return SDValue();
9144       // 2b
9145       unsigned lsb = countTrailingZeros(Mask);
9146       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9147                         DAG.getConstant(lsb, DL, MVT::i32));
9148       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9149                         DAG.getConstant(Mask2, DL, MVT::i32));
9150       // Do not add new nodes to DAG combiner worklist.
9151       DCI.CombineTo(N, Res, false);
9152       return SDValue();
9153     }
9154   }
9155 
9156   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9157       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9158       ARM::isBitFieldInvertedMask(~Mask)) {
9159     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9160     // where lsb(mask) == #shamt and masked bits of B are known zero.
9161     SDValue ShAmt = N00.getOperand(1);
9162     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9163     unsigned LSB = countTrailingZeros(Mask);
9164     if (ShAmtC != LSB)
9165       return SDValue();
9166 
9167     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9168                       DAG.getConstant(~Mask, DL, MVT::i32));
9169 
9170     // Do not add new nodes to DAG combiner worklist.
9171     DCI.CombineTo(N, Res, false);
9172   }
9173 
9174   return SDValue();
9175 }
9176 
9177 static SDValue PerformXORCombine(SDNode *N,
9178                                  TargetLowering::DAGCombinerInfo &DCI,
9179                                  const ARMSubtarget *Subtarget) {
9180   EVT VT = N->getValueType(0);
9181   SelectionDAG &DAG = DCI.DAG;
9182 
9183   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9184     return SDValue();
9185 
9186   if (!Subtarget->isThumb1Only()) {
9187     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9188     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9189       return Result;
9190   }
9191 
9192   return SDValue();
9193 }
9194 
9195 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9196 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9197 // their position in "to" (Rd).
9198 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9199   assert(N->getOpcode() == ARMISD::BFI);
9200 
9201   SDValue From = N->getOperand(1);
9202   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9203   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9204 
9205   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9206   // #C in the base of the SHR.
9207   if (From->getOpcode() == ISD::SRL &&
9208       isa<ConstantSDNode>(From->getOperand(1))) {
9209     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9210     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9211     FromMask <<= Shift.getLimitedValue(31);
9212     From = From->getOperand(0);
9213   }
9214 
9215   return From;
9216 }
9217 
9218 // If A and B contain one contiguous set of bits, does A | B == A . B?
9219 //
9220 // Neither A nor B must be zero.
9221 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9222   unsigned LastActiveBitInA =  A.countTrailingZeros();
9223   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9224   return LastActiveBitInA - 1 == FirstActiveBitInB;
9225 }
9226 
9227 static SDValue FindBFIToCombineWith(SDNode *N) {
9228   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9229   // if one exists.
9230   APInt ToMask, FromMask;
9231   SDValue From = ParseBFI(N, ToMask, FromMask);
9232   SDValue To = N->getOperand(0);
9233 
9234   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9235   // aren't compatible, but not if they set the same bit in their destination as
9236   // we do (or that of any BFI we're going to combine with).
9237   SDValue V = To;
9238   APInt CombinedToMask = ToMask;
9239   while (V.getOpcode() == ARMISD::BFI) {
9240     APInt NewToMask, NewFromMask;
9241     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9242     if (NewFrom != From) {
9243       // This BFI has a different base. Keep going.
9244       CombinedToMask |= NewToMask;
9245       V = V.getOperand(0);
9246       continue;
9247     }
9248 
9249     // Do the written bits conflict with any we've seen so far?
9250     if ((NewToMask & CombinedToMask).getBoolValue())
9251       // Conflicting bits - bail out because going further is unsafe.
9252       return SDValue();
9253 
9254     // Are the new bits contiguous when combined with the old bits?
9255     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9256         BitsProperlyConcatenate(FromMask, NewFromMask))
9257       return V;
9258     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9259         BitsProperlyConcatenate(NewFromMask, FromMask))
9260       return V;
9261 
9262     // We've seen a write to some bits, so track it.
9263     CombinedToMask |= NewToMask;
9264     // Keep going...
9265     V = V.getOperand(0);
9266   }
9267 
9268   return SDValue();
9269 }
9270 
9271 static SDValue PerformBFICombine(SDNode *N,
9272                                  TargetLowering::DAGCombinerInfo &DCI) {
9273   SDValue N1 = N->getOperand(1);
9274   if (N1.getOpcode() == ISD::AND) {
9275     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9276     // the bits being cleared by the AND are not demanded by the BFI.
9277     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9278     if (!N11C)
9279       return SDValue();
9280     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9281     unsigned LSB = countTrailingZeros(~InvMask);
9282     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9283     assert(Width <
9284                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9285            "undefined behavior");
9286     unsigned Mask = (1u << Width) - 1;
9287     unsigned Mask2 = N11C->getZExtValue();
9288     if ((Mask & (~Mask2)) == 0)
9289       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9290                              N->getOperand(0), N1.getOperand(0),
9291                              N->getOperand(2));
9292   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9293     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9294     // Keep track of any consecutive bits set that all come from the same base
9295     // value. We can combine these together into a single BFI.
9296     SDValue CombineBFI = FindBFIToCombineWith(N);
9297     if (CombineBFI == SDValue())
9298       return SDValue();
9299 
9300     // We've found a BFI.
9301     APInt ToMask1, FromMask1;
9302     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9303 
9304     APInt ToMask2, FromMask2;
9305     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9306     assert(From1 == From2);
9307     (void)From2;
9308 
9309     // First, unlink CombineBFI.
9310     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9311     // Then create a new BFI, combining the two together.
9312     APInt NewFromMask = FromMask1 | FromMask2;
9313     APInt NewToMask = ToMask1 | ToMask2;
9314 
9315     EVT VT = N->getValueType(0);
9316     SDLoc dl(N);
9317 
9318     if (NewFromMask[0] == 0)
9319       From1 = DCI.DAG.getNode(
9320         ISD::SRL, dl, VT, From1,
9321         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9322     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9323                            DCI.DAG.getConstant(~NewToMask, dl, VT));
9324   }
9325   return SDValue();
9326 }
9327 
9328 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9329 /// ARMISD::VMOVRRD.
9330 static SDValue PerformVMOVRRDCombine(SDNode *N,
9331                                      TargetLowering::DAGCombinerInfo &DCI,
9332                                      const ARMSubtarget *Subtarget) {
9333   // vmovrrd(vmovdrr x, y) -> x,y
9334   SDValue InDouble = N->getOperand(0);
9335   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9336     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9337 
9338   // vmovrrd(load f64) -> (load i32), (load i32)
9339   SDNode *InNode = InDouble.getNode();
9340   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9341       InNode->getValueType(0) == MVT::f64 &&
9342       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9343       !cast<LoadSDNode>(InNode)->isVolatile()) {
9344     // TODO: Should this be done for non-FrameIndex operands?
9345     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9346 
9347     SelectionDAG &DAG = DCI.DAG;
9348     SDLoc DL(LD);
9349     SDValue BasePtr = LD->getBasePtr();
9350     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9351                                  LD->getPointerInfo(), LD->isVolatile(),
9352                                  LD->isNonTemporal(), LD->isInvariant(),
9353                                  LD->getAlignment());
9354 
9355     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9356                                     DAG.getConstant(4, DL, MVT::i32));
9357     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9358                                  LD->getPointerInfo(), LD->isVolatile(),
9359                                  LD->isNonTemporal(), LD->isInvariant(),
9360                                  std::min(4U, LD->getAlignment() / 2));
9361 
9362     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9363     if (DCI.DAG.getDataLayout().isBigEndian())
9364       std::swap (NewLD1, NewLD2);
9365     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9366     return Result;
9367   }
9368 
9369   return SDValue();
9370 }
9371 
9372 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9373 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9374 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9375   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9376   SDValue Op0 = N->getOperand(0);
9377   SDValue Op1 = N->getOperand(1);
9378   if (Op0.getOpcode() == ISD::BITCAST)
9379     Op0 = Op0.getOperand(0);
9380   if (Op1.getOpcode() == ISD::BITCAST)
9381     Op1 = Op1.getOperand(0);
9382   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9383       Op0.getNode() == Op1.getNode() &&
9384       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9385     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9386                        N->getValueType(0), Op0.getOperand(0));
9387   return SDValue();
9388 }
9389 
9390 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9391 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9392 /// i64 vector to have f64 elements, since the value can then be loaded
9393 /// directly into a VFP register.
9394 static bool hasNormalLoadOperand(SDNode *N) {
9395   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9396   for (unsigned i = 0; i < NumElts; ++i) {
9397     SDNode *Elt = N->getOperand(i).getNode();
9398     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9399       return true;
9400   }
9401   return false;
9402 }
9403 
9404 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9405 /// ISD::BUILD_VECTOR.
9406 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9407                                           TargetLowering::DAGCombinerInfo &DCI,
9408                                           const ARMSubtarget *Subtarget) {
9409   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9410   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9411   // into a pair of GPRs, which is fine when the value is used as a scalar,
9412   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9413   SelectionDAG &DAG = DCI.DAG;
9414   if (N->getNumOperands() == 2)
9415     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
9416       return RV;
9417 
9418   // Load i64 elements as f64 values so that type legalization does not split
9419   // them up into i32 values.
9420   EVT VT = N->getValueType(0);
9421   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9422     return SDValue();
9423   SDLoc dl(N);
9424   SmallVector<SDValue, 8> Ops;
9425   unsigned NumElts = VT.getVectorNumElements();
9426   for (unsigned i = 0; i < NumElts; ++i) {
9427     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9428     Ops.push_back(V);
9429     // Make the DAGCombiner fold the bitcast.
9430     DCI.AddToWorklist(V.getNode());
9431   }
9432   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9433   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9434   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9435 }
9436 
9437 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9438 static SDValue
9439 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9440   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9441   // At that time, we may have inserted bitcasts from integer to float.
9442   // If these bitcasts have survived DAGCombine, change the lowering of this
9443   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9444   // force to use floating point types.
9445 
9446   // Make sure we can change the type of the vector.
9447   // This is possible iff:
9448   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9449   //    1.1. Vector is used only once.
9450   //    1.2. Use is a bit convert to an integer type.
9451   // 2. The size of its operands are 32-bits (64-bits are not legal).
9452   EVT VT = N->getValueType(0);
9453   EVT EltVT = VT.getVectorElementType();
9454 
9455   // Check 1.1. and 2.
9456   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9457     return SDValue();
9458 
9459   // By construction, the input type must be float.
9460   assert(EltVT == MVT::f32 && "Unexpected type!");
9461 
9462   // Check 1.2.
9463   SDNode *Use = *N->use_begin();
9464   if (Use->getOpcode() != ISD::BITCAST ||
9465       Use->getValueType(0).isFloatingPoint())
9466     return SDValue();
9467 
9468   // Check profitability.
9469   // Model is, if more than half of the relevant operands are bitcast from
9470   // i32, turn the build_vector into a sequence of insert_vector_elt.
9471   // Relevant operands are everything that is not statically
9472   // (i.e., at compile time) bitcasted.
9473   unsigned NumOfBitCastedElts = 0;
9474   unsigned NumElts = VT.getVectorNumElements();
9475   unsigned NumOfRelevantElts = NumElts;
9476   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9477     SDValue Elt = N->getOperand(Idx);
9478     if (Elt->getOpcode() == ISD::BITCAST) {
9479       // Assume only bit cast to i32 will go away.
9480       if (Elt->getOperand(0).getValueType() == MVT::i32)
9481         ++NumOfBitCastedElts;
9482     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9483       // Constants are statically casted, thus do not count them as
9484       // relevant operands.
9485       --NumOfRelevantElts;
9486   }
9487 
9488   // Check if more than half of the elements require a non-free bitcast.
9489   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9490     return SDValue();
9491 
9492   SelectionDAG &DAG = DCI.DAG;
9493   // Create the new vector type.
9494   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9495   // Check if the type is legal.
9496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9497   if (!TLI.isTypeLegal(VecVT))
9498     return SDValue();
9499 
9500   // Combine:
9501   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9502   // => BITCAST INSERT_VECTOR_ELT
9503   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9504   //                      (BITCAST EN), N.
9505   SDValue Vec = DAG.getUNDEF(VecVT);
9506   SDLoc dl(N);
9507   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9508     SDValue V = N->getOperand(Idx);
9509     if (V.getOpcode() == ISD::UNDEF)
9510       continue;
9511     if (V.getOpcode() == ISD::BITCAST &&
9512         V->getOperand(0).getValueType() == MVT::i32)
9513       // Fold obvious case.
9514       V = V.getOperand(0);
9515     else {
9516       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9517       // Make the DAGCombiner fold the bitcasts.
9518       DCI.AddToWorklist(V.getNode());
9519     }
9520     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9521     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9522   }
9523   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9524   // Make the DAGCombiner fold the bitcasts.
9525   DCI.AddToWorklist(Vec.getNode());
9526   return Vec;
9527 }
9528 
9529 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9530 /// ISD::INSERT_VECTOR_ELT.
9531 static SDValue PerformInsertEltCombine(SDNode *N,
9532                                        TargetLowering::DAGCombinerInfo &DCI) {
9533   // Bitcast an i64 load inserted into a vector to f64.
9534   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9535   EVT VT = N->getValueType(0);
9536   SDNode *Elt = N->getOperand(1).getNode();
9537   if (VT.getVectorElementType() != MVT::i64 ||
9538       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9539     return SDValue();
9540 
9541   SelectionDAG &DAG = DCI.DAG;
9542   SDLoc dl(N);
9543   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9544                                  VT.getVectorNumElements());
9545   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9546   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9547   // Make the DAGCombiner fold the bitcasts.
9548   DCI.AddToWorklist(Vec.getNode());
9549   DCI.AddToWorklist(V.getNode());
9550   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9551                                Vec, V, N->getOperand(2));
9552   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9553 }
9554 
9555 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9556 /// ISD::VECTOR_SHUFFLE.
9557 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9558   // The LLVM shufflevector instruction does not require the shuffle mask
9559   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9560   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9561   // operands do not match the mask length, they are extended by concatenating
9562   // them with undef vectors.  That is probably the right thing for other
9563   // targets, but for NEON it is better to concatenate two double-register
9564   // size vector operands into a single quad-register size vector.  Do that
9565   // transformation here:
9566   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9567   //   shuffle(concat(v1, v2), undef)
9568   SDValue Op0 = N->getOperand(0);
9569   SDValue Op1 = N->getOperand(1);
9570   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9571       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9572       Op0.getNumOperands() != 2 ||
9573       Op1.getNumOperands() != 2)
9574     return SDValue();
9575   SDValue Concat0Op1 = Op0.getOperand(1);
9576   SDValue Concat1Op1 = Op1.getOperand(1);
9577   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9578       Concat1Op1.getOpcode() != ISD::UNDEF)
9579     return SDValue();
9580   // Skip the transformation if any of the types are illegal.
9581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9582   EVT VT = N->getValueType(0);
9583   if (!TLI.isTypeLegal(VT) ||
9584       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9585       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9586     return SDValue();
9587 
9588   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9589                                   Op0.getOperand(0), Op1.getOperand(0));
9590   // Translate the shuffle mask.
9591   SmallVector<int, 16> NewMask;
9592   unsigned NumElts = VT.getVectorNumElements();
9593   unsigned HalfElts = NumElts/2;
9594   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9595   for (unsigned n = 0; n < NumElts; ++n) {
9596     int MaskElt = SVN->getMaskElt(n);
9597     int NewElt = -1;
9598     if (MaskElt < (int)HalfElts)
9599       NewElt = MaskElt;
9600     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9601       NewElt = HalfElts + MaskElt - NumElts;
9602     NewMask.push_back(NewElt);
9603   }
9604   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9605                               DAG.getUNDEF(VT), NewMask.data());
9606 }
9607 
9608 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9609 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9610 /// base address updates.
9611 /// For generic load/stores, the memory type is assumed to be a vector.
9612 /// The caller is assumed to have checked legality.
9613 static SDValue CombineBaseUpdate(SDNode *N,
9614                                  TargetLowering::DAGCombinerInfo &DCI) {
9615   SelectionDAG &DAG = DCI.DAG;
9616   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9617                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9618   const bool isStore = N->getOpcode() == ISD::STORE;
9619   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9620   SDValue Addr = N->getOperand(AddrOpIdx);
9621   MemSDNode *MemN = cast<MemSDNode>(N);
9622   SDLoc dl(N);
9623 
9624   // Search for a use of the address operand that is an increment.
9625   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9626          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9627     SDNode *User = *UI;
9628     if (User->getOpcode() != ISD::ADD ||
9629         UI.getUse().getResNo() != Addr.getResNo())
9630       continue;
9631 
9632     // Check that the add is independent of the load/store.  Otherwise, folding
9633     // it would create a cycle.
9634     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9635       continue;
9636 
9637     // Find the new opcode for the updating load/store.
9638     bool isLoadOp = true;
9639     bool isLaneOp = false;
9640     unsigned NewOpc = 0;
9641     unsigned NumVecs = 0;
9642     if (isIntrinsic) {
9643       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9644       switch (IntNo) {
9645       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9646       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9647         NumVecs = 1; break;
9648       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9649         NumVecs = 2; break;
9650       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9651         NumVecs = 3; break;
9652       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9653         NumVecs = 4; break;
9654       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9655         NumVecs = 2; isLaneOp = true; break;
9656       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9657         NumVecs = 3; isLaneOp = true; break;
9658       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9659         NumVecs = 4; isLaneOp = true; break;
9660       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9661         NumVecs = 1; isLoadOp = false; break;
9662       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9663         NumVecs = 2; isLoadOp = false; break;
9664       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9665         NumVecs = 3; isLoadOp = false; break;
9666       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9667         NumVecs = 4; isLoadOp = false; break;
9668       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9669         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9670       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9671         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9672       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9673         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9674       }
9675     } else {
9676       isLaneOp = true;
9677       switch (N->getOpcode()) {
9678       default: llvm_unreachable("unexpected opcode for Neon base update");
9679       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9680       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9681       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9682       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9683         NumVecs = 1; isLaneOp = false; break;
9684       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9685         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9686       }
9687     }
9688 
9689     // Find the size of memory referenced by the load/store.
9690     EVT VecTy;
9691     if (isLoadOp) {
9692       VecTy = N->getValueType(0);
9693     } else if (isIntrinsic) {
9694       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9695     } else {
9696       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9697       VecTy = N->getOperand(1).getValueType();
9698     }
9699 
9700     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9701     if (isLaneOp)
9702       NumBytes /= VecTy.getVectorNumElements();
9703 
9704     // If the increment is a constant, it must match the memory ref size.
9705     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9706     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9707       uint64_t IncVal = CInc->getZExtValue();
9708       if (IncVal != NumBytes)
9709         continue;
9710     } else if (NumBytes >= 3 * 16) {
9711       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9712       // separate instructions that make it harder to use a non-constant update.
9713       continue;
9714     }
9715 
9716     // OK, we found an ADD we can fold into the base update.
9717     // Now, create a _UPD node, taking care of not breaking alignment.
9718 
9719     EVT AlignedVecTy = VecTy;
9720     unsigned Alignment = MemN->getAlignment();
9721 
9722     // If this is a less-than-standard-aligned load/store, change the type to
9723     // match the standard alignment.
9724     // The alignment is overlooked when selecting _UPD variants; and it's
9725     // easier to introduce bitcasts here than fix that.
9726     // There are 3 ways to get to this base-update combine:
9727     // - intrinsics: they are assumed to be properly aligned (to the standard
9728     //   alignment of the memory type), so we don't need to do anything.
9729     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9730     //   intrinsics, so, likewise, there's nothing to do.
9731     // - generic load/store instructions: the alignment is specified as an
9732     //   explicit operand, rather than implicitly as the standard alignment
9733     //   of the memory type (like the intrisics).  We need to change the
9734     //   memory type to match the explicit alignment.  That way, we don't
9735     //   generate non-standard-aligned ARMISD::VLDx nodes.
9736     if (isa<LSBaseSDNode>(N)) {
9737       if (Alignment == 0)
9738         Alignment = 1;
9739       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9740         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9741         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9742         assert(!isLaneOp && "Unexpected generic load/store lane.");
9743         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9744         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9745       }
9746       // Don't set an explicit alignment on regular load/stores that we want
9747       // to transform to VLD/VST 1_UPD nodes.
9748       // This matches the behavior of regular load/stores, which only get an
9749       // explicit alignment if the MMO alignment is larger than the standard
9750       // alignment of the memory type.
9751       // Intrinsics, however, always get an explicit alignment, set to the
9752       // alignment of the MMO.
9753       Alignment = 1;
9754     }
9755 
9756     // Create the new updating load/store node.
9757     // First, create an SDVTList for the new updating node's results.
9758     EVT Tys[6];
9759     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9760     unsigned n;
9761     for (n = 0; n < NumResultVecs; ++n)
9762       Tys[n] = AlignedVecTy;
9763     Tys[n++] = MVT::i32;
9764     Tys[n] = MVT::Other;
9765     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9766 
9767     // Then, gather the new node's operands.
9768     SmallVector<SDValue, 8> Ops;
9769     Ops.push_back(N->getOperand(0)); // incoming chain
9770     Ops.push_back(N->getOperand(AddrOpIdx));
9771     Ops.push_back(Inc);
9772 
9773     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9774       // Try to match the intrinsic's signature
9775       Ops.push_back(StN->getValue());
9776     } else {
9777       // Loads (and of course intrinsics) match the intrinsics' signature,
9778       // so just add all but the alignment operand.
9779       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9780         Ops.push_back(N->getOperand(i));
9781     }
9782 
9783     // For all node types, the alignment operand is always the last one.
9784     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9785 
9786     // If this is a non-standard-aligned STORE, the penultimate operand is the
9787     // stored value.  Bitcast it to the aligned type.
9788     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9789       SDValue &StVal = Ops[Ops.size()-2];
9790       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9791     }
9792 
9793     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9794                                            Ops, AlignedVecTy,
9795                                            MemN->getMemOperand());
9796 
9797     // Update the uses.
9798     SmallVector<SDValue, 5> NewResults;
9799     for (unsigned i = 0; i < NumResultVecs; ++i)
9800       NewResults.push_back(SDValue(UpdN.getNode(), i));
9801 
9802     // If this is an non-standard-aligned LOAD, the first result is the loaded
9803     // value.  Bitcast it to the expected result type.
9804     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9805       SDValue &LdVal = NewResults[0];
9806       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9807     }
9808 
9809     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9810     DCI.CombineTo(N, NewResults);
9811     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9812 
9813     break;
9814   }
9815   return SDValue();
9816 }
9817 
9818 static SDValue PerformVLDCombine(SDNode *N,
9819                                  TargetLowering::DAGCombinerInfo &DCI) {
9820   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9821     return SDValue();
9822 
9823   return CombineBaseUpdate(N, DCI);
9824 }
9825 
9826 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9827 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9828 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9829 /// return true.
9830 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9831   SelectionDAG &DAG = DCI.DAG;
9832   EVT VT = N->getValueType(0);
9833   // vldN-dup instructions only support 64-bit vectors for N > 1.
9834   if (!VT.is64BitVector())
9835     return false;
9836 
9837   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9838   SDNode *VLD = N->getOperand(0).getNode();
9839   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9840     return false;
9841   unsigned NumVecs = 0;
9842   unsigned NewOpc = 0;
9843   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9844   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9845     NumVecs = 2;
9846     NewOpc = ARMISD::VLD2DUP;
9847   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9848     NumVecs = 3;
9849     NewOpc = ARMISD::VLD3DUP;
9850   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9851     NumVecs = 4;
9852     NewOpc = ARMISD::VLD4DUP;
9853   } else {
9854     return false;
9855   }
9856 
9857   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9858   // numbers match the load.
9859   unsigned VLDLaneNo =
9860     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9861   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9862        UI != UE; ++UI) {
9863     // Ignore uses of the chain result.
9864     if (UI.getUse().getResNo() == NumVecs)
9865       continue;
9866     SDNode *User = *UI;
9867     if (User->getOpcode() != ARMISD::VDUPLANE ||
9868         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9869       return false;
9870   }
9871 
9872   // Create the vldN-dup node.
9873   EVT Tys[5];
9874   unsigned n;
9875   for (n = 0; n < NumVecs; ++n)
9876     Tys[n] = VT;
9877   Tys[n] = MVT::Other;
9878   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9879   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9880   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9881   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9882                                            Ops, VLDMemInt->getMemoryVT(),
9883                                            VLDMemInt->getMemOperand());
9884 
9885   // Update the uses.
9886   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9887        UI != UE; ++UI) {
9888     unsigned ResNo = UI.getUse().getResNo();
9889     // Ignore uses of the chain result.
9890     if (ResNo == NumVecs)
9891       continue;
9892     SDNode *User = *UI;
9893     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9894   }
9895 
9896   // Now the vldN-lane intrinsic is dead except for its chain result.
9897   // Update uses of the chain.
9898   std::vector<SDValue> VLDDupResults;
9899   for (unsigned n = 0; n < NumVecs; ++n)
9900     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9901   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9902   DCI.CombineTo(VLD, VLDDupResults);
9903 
9904   return true;
9905 }
9906 
9907 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9908 /// ARMISD::VDUPLANE.
9909 static SDValue PerformVDUPLANECombine(SDNode *N,
9910                                       TargetLowering::DAGCombinerInfo &DCI) {
9911   SDValue Op = N->getOperand(0);
9912 
9913   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9914   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9915   if (CombineVLDDUP(N, DCI))
9916     return SDValue(N, 0);
9917 
9918   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9919   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9920   while (Op.getOpcode() == ISD::BITCAST)
9921     Op = Op.getOperand(0);
9922   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9923     return SDValue();
9924 
9925   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9926   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9927   // The canonical VMOV for a zero vector uses a 32-bit element size.
9928   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9929   unsigned EltBits;
9930   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9931     EltSize = 8;
9932   EVT VT = N->getValueType(0);
9933   if (EltSize > VT.getVectorElementType().getSizeInBits())
9934     return SDValue();
9935 
9936   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9937 }
9938 
9939 static SDValue PerformLOADCombine(SDNode *N,
9940                                   TargetLowering::DAGCombinerInfo &DCI) {
9941   EVT VT = N->getValueType(0);
9942 
9943   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9944   if (ISD::isNormalLoad(N) && VT.isVector() &&
9945       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9946     return CombineBaseUpdate(N, DCI);
9947 
9948   return SDValue();
9949 }
9950 
9951 /// PerformSTORECombine - Target-specific dag combine xforms for
9952 /// ISD::STORE.
9953 static SDValue PerformSTORECombine(SDNode *N,
9954                                    TargetLowering::DAGCombinerInfo &DCI) {
9955   StoreSDNode *St = cast<StoreSDNode>(N);
9956   if (St->isVolatile())
9957     return SDValue();
9958 
9959   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9960   // pack all of the elements in one place.  Next, store to memory in fewer
9961   // chunks.
9962   SDValue StVal = St->getValue();
9963   EVT VT = StVal.getValueType();
9964   if (St->isTruncatingStore() && VT.isVector()) {
9965     SelectionDAG &DAG = DCI.DAG;
9966     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9967     EVT StVT = St->getMemoryVT();
9968     unsigned NumElems = VT.getVectorNumElements();
9969     assert(StVT != VT && "Cannot truncate to the same type");
9970     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9971     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9972 
9973     // From, To sizes and ElemCount must be pow of two
9974     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9975 
9976     // We are going to use the original vector elt for storing.
9977     // Accumulated smaller vector elements must be a multiple of the store size.
9978     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9979 
9980     unsigned SizeRatio  = FromEltSz / ToEltSz;
9981     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9982 
9983     // Create a type on which we perform the shuffle.
9984     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9985                                      NumElems*SizeRatio);
9986     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9987 
9988     SDLoc DL(St);
9989     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9990     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9991     for (unsigned i = 0; i < NumElems; ++i)
9992       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9993                           ? (i + 1) * SizeRatio - 1
9994                           : i * SizeRatio;
9995 
9996     // Can't shuffle using an illegal type.
9997     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9998 
9999     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10000                                 DAG.getUNDEF(WideVec.getValueType()),
10001                                 ShuffleVec.data());
10002     // At this point all of the data is stored at the bottom of the
10003     // register. We now need to save it to mem.
10004 
10005     // Find the largest store unit
10006     MVT StoreType = MVT::i8;
10007     for (MVT Tp : MVT::integer_valuetypes()) {
10008       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10009         StoreType = Tp;
10010     }
10011     // Didn't find a legal store type.
10012     if (!TLI.isTypeLegal(StoreType))
10013       return SDValue();
10014 
10015     // Bitcast the original vector into a vector of store-size units
10016     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10017             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10018     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10019     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10020     SmallVector<SDValue, 8> Chains;
10021     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10022                                         TLI.getPointerTy(DAG.getDataLayout()));
10023     SDValue BasePtr = St->getBasePtr();
10024 
10025     // Perform one or more big stores into memory.
10026     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10027     for (unsigned I = 0; I < E; I++) {
10028       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10029                                    StoreType, ShuffWide,
10030                                    DAG.getIntPtrConstant(I, DL));
10031       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10032                                 St->getPointerInfo(), St->isVolatile(),
10033                                 St->isNonTemporal(), St->getAlignment());
10034       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10035                             Increment);
10036       Chains.push_back(Ch);
10037     }
10038     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10039   }
10040 
10041   if (!ISD::isNormalStore(St))
10042     return SDValue();
10043 
10044   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10045   // ARM stores of arguments in the same cache line.
10046   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10047       StVal.getNode()->hasOneUse()) {
10048     SelectionDAG  &DAG = DCI.DAG;
10049     bool isBigEndian = DAG.getDataLayout().isBigEndian();
10050     SDLoc DL(St);
10051     SDValue BasePtr = St->getBasePtr();
10052     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
10053                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
10054                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
10055                                   St->isNonTemporal(), St->getAlignment());
10056 
10057     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10058                                     DAG.getConstant(4, DL, MVT::i32));
10059     return DAG.getStore(NewST1.getValue(0), DL,
10060                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10061                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
10062                         St->isNonTemporal(),
10063                         std::min(4U, St->getAlignment() / 2));
10064   }
10065 
10066   if (StVal.getValueType() == MVT::i64 &&
10067       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10068 
10069     // Bitcast an i64 store extracted from a vector to f64.
10070     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10071     SelectionDAG &DAG = DCI.DAG;
10072     SDLoc dl(StVal);
10073     SDValue IntVec = StVal.getOperand(0);
10074     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10075                                    IntVec.getValueType().getVectorNumElements());
10076     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10077     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10078                                  Vec, StVal.getOperand(1));
10079     dl = SDLoc(N);
10080     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10081     // Make the DAGCombiner fold the bitcasts.
10082     DCI.AddToWorklist(Vec.getNode());
10083     DCI.AddToWorklist(ExtElt.getNode());
10084     DCI.AddToWorklist(V.getNode());
10085     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10086                         St->getPointerInfo(), St->isVolatile(),
10087                         St->isNonTemporal(), St->getAlignment(),
10088                         St->getAAInfo());
10089   }
10090 
10091   // If this is a legal vector store, try to combine it into a VST1_UPD.
10092   if (ISD::isNormalStore(N) && VT.isVector() &&
10093       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10094     return CombineBaseUpdate(N, DCI);
10095 
10096   return SDValue();
10097 }
10098 
10099 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10100 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10101 /// when the VMUL has a constant operand that is a power of 2.
10102 ///
10103 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10104 ///  vmul.f32        d16, d17, d16
10105 ///  vcvt.s32.f32    d16, d16
10106 /// becomes:
10107 ///  vcvt.s32.f32    d16, d16, #3
10108 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10109                                   const ARMSubtarget *Subtarget) {
10110   if (!Subtarget->hasNEON())
10111     return SDValue();
10112 
10113   SDValue Op = N->getOperand(0);
10114   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
10115     return SDValue();
10116 
10117   SDValue ConstVec = Op->getOperand(1);
10118   if (!isa<BuildVectorSDNode>(ConstVec))
10119     return SDValue();
10120 
10121   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10122   uint32_t FloatBits = FloatTy.getSizeInBits();
10123   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10124   uint32_t IntBits = IntTy.getSizeInBits();
10125   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10126   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10127     // These instructions only exist converting from f32 to i32. We can handle
10128     // smaller integers by generating an extra truncate, but larger ones would
10129     // be lossy. We also can't handle more then 4 lanes, since these intructions
10130     // only support v2i32/v4i32 types.
10131     return SDValue();
10132   }
10133 
10134   BitVector UndefElements;
10135   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10136   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10137   if (C == -1 || C == 0 || C > 32)
10138     return SDValue();
10139 
10140   SDLoc dl(N);
10141   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10142   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10143     Intrinsic::arm_neon_vcvtfp2fxu;
10144   SDValue FixConv = DAG.getNode(
10145       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10146       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10147       DAG.getConstant(C, dl, MVT::i32));
10148 
10149   if (IntBits < FloatBits)
10150     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10151 
10152   return FixConv;
10153 }
10154 
10155 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10156 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10157 /// when the VDIV has a constant operand that is a power of 2.
10158 ///
10159 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10160 ///  vcvt.f32.s32    d16, d16
10161 ///  vdiv.f32        d16, d17, d16
10162 /// becomes:
10163 ///  vcvt.f32.s32    d16, d16, #3
10164 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10165                                   const ARMSubtarget *Subtarget) {
10166   if (!Subtarget->hasNEON())
10167     return SDValue();
10168 
10169   SDValue Op = N->getOperand(0);
10170   unsigned OpOpcode = Op.getNode()->getOpcode();
10171   if (!N->getValueType(0).isVector() ||
10172       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10173     return SDValue();
10174 
10175   SDValue ConstVec = N->getOperand(1);
10176   if (!isa<BuildVectorSDNode>(ConstVec))
10177     return SDValue();
10178 
10179   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10180   uint32_t FloatBits = FloatTy.getSizeInBits();
10181   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10182   uint32_t IntBits = IntTy.getSizeInBits();
10183   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10184   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10185     // These instructions only exist converting from i32 to f32. We can handle
10186     // smaller integers by generating an extra extend, but larger ones would
10187     // be lossy. We also can't handle more then 4 lanes, since these intructions
10188     // only support v2i32/v4i32 types.
10189     return SDValue();
10190   }
10191 
10192   BitVector UndefElements;
10193   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10194   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10195   if (C == -1 || C == 0 || C > 32)
10196     return SDValue();
10197 
10198   SDLoc dl(N);
10199   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10200   SDValue ConvInput = Op.getOperand(0);
10201   if (IntBits < FloatBits)
10202     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10203                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10204                             ConvInput);
10205 
10206   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10207     Intrinsic::arm_neon_vcvtfxu2fp;
10208   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10209                      Op.getValueType(),
10210                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10211                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10212 }
10213 
10214 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10215 /// operand of a vector shift operation, where all the elements of the
10216 /// build_vector must have the same constant integer value.
10217 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10218   // Ignore bit_converts.
10219   while (Op.getOpcode() == ISD::BITCAST)
10220     Op = Op.getOperand(0);
10221   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10222   APInt SplatBits, SplatUndef;
10223   unsigned SplatBitSize;
10224   bool HasAnyUndefs;
10225   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10226                                       HasAnyUndefs, ElementBits) ||
10227       SplatBitSize > ElementBits)
10228     return false;
10229   Cnt = SplatBits.getSExtValue();
10230   return true;
10231 }
10232 
10233 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10234 /// operand of a vector shift left operation.  That value must be in the range:
10235 ///   0 <= Value < ElementBits for a left shift; or
10236 ///   0 <= Value <= ElementBits for a long left shift.
10237 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10238   assert(VT.isVector() && "vector shift count is not a vector type");
10239   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10240   if (! getVShiftImm(Op, ElementBits, Cnt))
10241     return false;
10242   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10243 }
10244 
10245 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10246 /// operand of a vector shift right operation.  For a shift opcode, the value
10247 /// is positive, but for an intrinsic the value count must be negative. The
10248 /// absolute value must be in the range:
10249 ///   1 <= |Value| <= ElementBits for a right shift; or
10250 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10251 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10252                          int64_t &Cnt) {
10253   assert(VT.isVector() && "vector shift count is not a vector type");
10254   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10255   if (! getVShiftImm(Op, ElementBits, Cnt))
10256     return false;
10257   if (!isIntrinsic)
10258     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10259   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10260     Cnt = -Cnt;
10261     return true;
10262   }
10263   return false;
10264 }
10265 
10266 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10267 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10268   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10269   switch (IntNo) {
10270   default:
10271     // Don't do anything for most intrinsics.
10272     break;
10273 
10274   // Vector shifts: check for immediate versions and lower them.
10275   // Note: This is done during DAG combining instead of DAG legalizing because
10276   // the build_vectors for 64-bit vector element shift counts are generally
10277   // not legal, and it is hard to see their values after they get legalized to
10278   // loads from a constant pool.
10279   case Intrinsic::arm_neon_vshifts:
10280   case Intrinsic::arm_neon_vshiftu:
10281   case Intrinsic::arm_neon_vrshifts:
10282   case Intrinsic::arm_neon_vrshiftu:
10283   case Intrinsic::arm_neon_vrshiftn:
10284   case Intrinsic::arm_neon_vqshifts:
10285   case Intrinsic::arm_neon_vqshiftu:
10286   case Intrinsic::arm_neon_vqshiftsu:
10287   case Intrinsic::arm_neon_vqshiftns:
10288   case Intrinsic::arm_neon_vqshiftnu:
10289   case Intrinsic::arm_neon_vqshiftnsu:
10290   case Intrinsic::arm_neon_vqrshiftns:
10291   case Intrinsic::arm_neon_vqrshiftnu:
10292   case Intrinsic::arm_neon_vqrshiftnsu: {
10293     EVT VT = N->getOperand(1).getValueType();
10294     int64_t Cnt;
10295     unsigned VShiftOpc = 0;
10296 
10297     switch (IntNo) {
10298     case Intrinsic::arm_neon_vshifts:
10299     case Intrinsic::arm_neon_vshiftu:
10300       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10301         VShiftOpc = ARMISD::VSHL;
10302         break;
10303       }
10304       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10305         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10306                      ARMISD::VSHRs : ARMISD::VSHRu);
10307         break;
10308       }
10309       return SDValue();
10310 
10311     case Intrinsic::arm_neon_vrshifts:
10312     case Intrinsic::arm_neon_vrshiftu:
10313       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10314         break;
10315       return SDValue();
10316 
10317     case Intrinsic::arm_neon_vqshifts:
10318     case Intrinsic::arm_neon_vqshiftu:
10319       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10320         break;
10321       return SDValue();
10322 
10323     case Intrinsic::arm_neon_vqshiftsu:
10324       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10325         break;
10326       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10327 
10328     case Intrinsic::arm_neon_vrshiftn:
10329     case Intrinsic::arm_neon_vqshiftns:
10330     case Intrinsic::arm_neon_vqshiftnu:
10331     case Intrinsic::arm_neon_vqshiftnsu:
10332     case Intrinsic::arm_neon_vqrshiftns:
10333     case Intrinsic::arm_neon_vqrshiftnu:
10334     case Intrinsic::arm_neon_vqrshiftnsu:
10335       // Narrowing shifts require an immediate right shift.
10336       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10337         break;
10338       llvm_unreachable("invalid shift count for narrowing vector shift "
10339                        "intrinsic");
10340 
10341     default:
10342       llvm_unreachable("unhandled vector shift");
10343     }
10344 
10345     switch (IntNo) {
10346     case Intrinsic::arm_neon_vshifts:
10347     case Intrinsic::arm_neon_vshiftu:
10348       // Opcode already set above.
10349       break;
10350     case Intrinsic::arm_neon_vrshifts:
10351       VShiftOpc = ARMISD::VRSHRs; break;
10352     case Intrinsic::arm_neon_vrshiftu:
10353       VShiftOpc = ARMISD::VRSHRu; break;
10354     case Intrinsic::arm_neon_vrshiftn:
10355       VShiftOpc = ARMISD::VRSHRN; break;
10356     case Intrinsic::arm_neon_vqshifts:
10357       VShiftOpc = ARMISD::VQSHLs; break;
10358     case Intrinsic::arm_neon_vqshiftu:
10359       VShiftOpc = ARMISD::VQSHLu; break;
10360     case Intrinsic::arm_neon_vqshiftsu:
10361       VShiftOpc = ARMISD::VQSHLsu; break;
10362     case Intrinsic::arm_neon_vqshiftns:
10363       VShiftOpc = ARMISD::VQSHRNs; break;
10364     case Intrinsic::arm_neon_vqshiftnu:
10365       VShiftOpc = ARMISD::VQSHRNu; break;
10366     case Intrinsic::arm_neon_vqshiftnsu:
10367       VShiftOpc = ARMISD::VQSHRNsu; break;
10368     case Intrinsic::arm_neon_vqrshiftns:
10369       VShiftOpc = ARMISD::VQRSHRNs; break;
10370     case Intrinsic::arm_neon_vqrshiftnu:
10371       VShiftOpc = ARMISD::VQRSHRNu; break;
10372     case Intrinsic::arm_neon_vqrshiftnsu:
10373       VShiftOpc = ARMISD::VQRSHRNsu; break;
10374     }
10375 
10376     SDLoc dl(N);
10377     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10378                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10379   }
10380 
10381   case Intrinsic::arm_neon_vshiftins: {
10382     EVT VT = N->getOperand(1).getValueType();
10383     int64_t Cnt;
10384     unsigned VShiftOpc = 0;
10385 
10386     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10387       VShiftOpc = ARMISD::VSLI;
10388     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10389       VShiftOpc = ARMISD::VSRI;
10390     else {
10391       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10392     }
10393 
10394     SDLoc dl(N);
10395     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10396                        N->getOperand(1), N->getOperand(2),
10397                        DAG.getConstant(Cnt, dl, MVT::i32));
10398   }
10399 
10400   case Intrinsic::arm_neon_vqrshifts:
10401   case Intrinsic::arm_neon_vqrshiftu:
10402     // No immediate versions of these to check for.
10403     break;
10404   }
10405 
10406   return SDValue();
10407 }
10408 
10409 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10410 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10411 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10412 /// vector element shift counts are generally not legal, and it is hard to see
10413 /// their values after they get legalized to loads from a constant pool.
10414 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10415                                    const ARMSubtarget *ST) {
10416   EVT VT = N->getValueType(0);
10417   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10418     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10419     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10420     SDValue N1 = N->getOperand(1);
10421     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10422       SDValue N0 = N->getOperand(0);
10423       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10424           DAG.MaskedValueIsZero(N0.getOperand(0),
10425                                 APInt::getHighBitsSet(32, 16)))
10426         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10427     }
10428   }
10429 
10430   // Nothing to be done for scalar shifts.
10431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10432   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10433     return SDValue();
10434 
10435   assert(ST->hasNEON() && "unexpected vector shift");
10436   int64_t Cnt;
10437 
10438   switch (N->getOpcode()) {
10439   default: llvm_unreachable("unexpected shift opcode");
10440 
10441   case ISD::SHL:
10442     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10443       SDLoc dl(N);
10444       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10445                          DAG.getConstant(Cnt, dl, MVT::i32));
10446     }
10447     break;
10448 
10449   case ISD::SRA:
10450   case ISD::SRL:
10451     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10452       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10453                             ARMISD::VSHRs : ARMISD::VSHRu);
10454       SDLoc dl(N);
10455       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10456                          DAG.getConstant(Cnt, dl, MVT::i32));
10457     }
10458   }
10459   return SDValue();
10460 }
10461 
10462 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10463 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10464 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10465                                     const ARMSubtarget *ST) {
10466   SDValue N0 = N->getOperand(0);
10467 
10468   // Check for sign- and zero-extensions of vector extract operations of 8-
10469   // and 16-bit vector elements.  NEON supports these directly.  They are
10470   // handled during DAG combining because type legalization will promote them
10471   // to 32-bit types and it is messy to recognize the operations after that.
10472   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10473     SDValue Vec = N0.getOperand(0);
10474     SDValue Lane = N0.getOperand(1);
10475     EVT VT = N->getValueType(0);
10476     EVT EltVT = N0.getValueType();
10477     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10478 
10479     if (VT == MVT::i32 &&
10480         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10481         TLI.isTypeLegal(Vec.getValueType()) &&
10482         isa<ConstantSDNode>(Lane)) {
10483 
10484       unsigned Opc = 0;
10485       switch (N->getOpcode()) {
10486       default: llvm_unreachable("unexpected opcode");
10487       case ISD::SIGN_EXTEND:
10488         Opc = ARMISD::VGETLANEs;
10489         break;
10490       case ISD::ZERO_EXTEND:
10491       case ISD::ANY_EXTEND:
10492         Opc = ARMISD::VGETLANEu;
10493         break;
10494       }
10495       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10496     }
10497   }
10498 
10499   return SDValue();
10500 }
10501 
10502 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10503                              APInt &KnownOne) {
10504   if (Op.getOpcode() == ARMISD::BFI) {
10505     // Conservatively, we can recurse down the first operand
10506     // and just mask out all affected bits.
10507     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10508 
10509     // The operand to BFI is already a mask suitable for removing the bits it
10510     // sets.
10511     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10512     APInt Mask = CI->getAPIntValue();
10513     KnownZero &= Mask;
10514     KnownOne &= Mask;
10515     return;
10516   }
10517   if (Op.getOpcode() == ARMISD::CMOV) {
10518     APInt KZ2(KnownZero.getBitWidth(), 0);
10519     APInt KO2(KnownOne.getBitWidth(), 0);
10520     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10521     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10522 
10523     KnownZero &= KZ2;
10524     KnownOne &= KO2;
10525     return;
10526   }
10527   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10528 }
10529 
10530 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10531   // If we have a CMOV, OR and AND combination such as:
10532   //   if (x & CN)
10533   //     y |= CM;
10534   //
10535   // And:
10536   //   * CN is a single bit;
10537   //   * All bits covered by CM are known zero in y
10538   //
10539   // Then we can convert this into a sequence of BFI instructions. This will
10540   // always be a win if CM is a single bit, will always be no worse than the
10541   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10542   // three bits (due to the extra IT instruction).
10543 
10544   SDValue Op0 = CMOV->getOperand(0);
10545   SDValue Op1 = CMOV->getOperand(1);
10546   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10547   auto CC = CCNode->getAPIntValue().getLimitedValue();
10548   SDValue CmpZ = CMOV->getOperand(4);
10549 
10550   // The compare must be against zero.
10551   if (!isNullConstant(CmpZ->getOperand(1)))
10552     return SDValue();
10553 
10554   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10555   SDValue And = CmpZ->getOperand(0);
10556   if (And->getOpcode() != ISD::AND)
10557     return SDValue();
10558   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10559   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10560     return SDValue();
10561   SDValue X = And->getOperand(0);
10562 
10563   if (CC == ARMCC::EQ) {
10564     // We're performing an "equal to zero" compare. Swap the operands so we
10565     // canonicalize on a "not equal to zero" compare.
10566     std::swap(Op0, Op1);
10567   } else {
10568     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10569   }
10570 
10571   if (Op1->getOpcode() != ISD::OR)
10572     return SDValue();
10573 
10574   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10575   if (!OrC)
10576     return SDValue();
10577   SDValue Y = Op1->getOperand(0);
10578 
10579   if (Op0 != Y)
10580     return SDValue();
10581 
10582   // Now, is it profitable to continue?
10583   APInt OrCI = OrC->getAPIntValue();
10584   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10585   if (OrCI.countPopulation() > Heuristic)
10586     return SDValue();
10587 
10588   // Lastly, can we determine that the bits defined by OrCI
10589   // are zero in Y?
10590   APInt KnownZero, KnownOne;
10591   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10592   if ((OrCI & KnownZero) != OrCI)
10593     return SDValue();
10594 
10595   // OK, we can do the combine.
10596   SDValue V = Y;
10597   SDLoc dl(X);
10598   EVT VT = X.getValueType();
10599   unsigned BitInX = AndC->getAPIntValue().logBase2();
10600 
10601   if (BitInX != 0) {
10602     // We must shift X first.
10603     X = DAG.getNode(ISD::SRL, dl, VT, X,
10604                     DAG.getConstant(BitInX, dl, VT));
10605   }
10606 
10607   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10608        BitInY < NumActiveBits; ++BitInY) {
10609     if (OrCI[BitInY] == 0)
10610       continue;
10611     APInt Mask(VT.getSizeInBits(), 0);
10612     Mask.setBit(BitInY);
10613     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10614                     // Confusingly, the operand is an *inverted* mask.
10615                     DAG.getConstant(~Mask, dl, VT));
10616   }
10617 
10618   return V;
10619 }
10620 
10621 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10622 SDValue
10623 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10624   SDValue Cmp = N->getOperand(4);
10625   if (Cmp.getOpcode() != ARMISD::CMPZ)
10626     // Only looking at EQ and NE cases.
10627     return SDValue();
10628 
10629   EVT VT = N->getValueType(0);
10630   SDLoc dl(N);
10631   SDValue LHS = Cmp.getOperand(0);
10632   SDValue RHS = Cmp.getOperand(1);
10633   SDValue FalseVal = N->getOperand(0);
10634   SDValue TrueVal = N->getOperand(1);
10635   SDValue ARMcc = N->getOperand(2);
10636   ARMCC::CondCodes CC =
10637     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10638 
10639   // BFI is only available on V6T2+.
10640   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10641     SDValue R = PerformCMOVToBFICombine(N, DAG);
10642     if (R)
10643       return R;
10644   }
10645 
10646   // Simplify
10647   //   mov     r1, r0
10648   //   cmp     r1, x
10649   //   mov     r0, y
10650   //   moveq   r0, x
10651   // to
10652   //   cmp     r0, x
10653   //   movne   r0, y
10654   //
10655   //   mov     r1, r0
10656   //   cmp     r1, x
10657   //   mov     r0, x
10658   //   movne   r0, y
10659   // to
10660   //   cmp     r0, x
10661   //   movne   r0, y
10662   /// FIXME: Turn this into a target neutral optimization?
10663   SDValue Res;
10664   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10665     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10666                       N->getOperand(3), Cmp);
10667   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10668     SDValue ARMcc;
10669     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10670     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10671                       N->getOperand(3), NewCmp);
10672   }
10673 
10674   if (Res.getNode()) {
10675     APInt KnownZero, KnownOne;
10676     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10677     // Capture demanded bits information that would be otherwise lost.
10678     if (KnownZero == 0xfffffffe)
10679       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10680                         DAG.getValueType(MVT::i1));
10681     else if (KnownZero == 0xffffff00)
10682       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10683                         DAG.getValueType(MVT::i8));
10684     else if (KnownZero == 0xffff0000)
10685       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10686                         DAG.getValueType(MVT::i16));
10687   }
10688 
10689   return Res;
10690 }
10691 
10692 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10693                                              DAGCombinerInfo &DCI) const {
10694   switch (N->getOpcode()) {
10695   default: break;
10696   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10697   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10698   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10699   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10700   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10701   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10702   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10703   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10704   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10705   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10706   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10707   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10708   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10709   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10710   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10711   case ISD::FP_TO_SINT:
10712   case ISD::FP_TO_UINT:
10713     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10714   case ISD::FDIV:
10715     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10716   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10717   case ISD::SHL:
10718   case ISD::SRA:
10719   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10720   case ISD::SIGN_EXTEND:
10721   case ISD::ZERO_EXTEND:
10722   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10723   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10724   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10725   case ARMISD::VLD2DUP:
10726   case ARMISD::VLD3DUP:
10727   case ARMISD::VLD4DUP:
10728     return PerformVLDCombine(N, DCI);
10729   case ARMISD::BUILD_VECTOR:
10730     return PerformARMBUILD_VECTORCombine(N, DCI);
10731   case ISD::INTRINSIC_VOID:
10732   case ISD::INTRINSIC_W_CHAIN:
10733     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10734     case Intrinsic::arm_neon_vld1:
10735     case Intrinsic::arm_neon_vld2:
10736     case Intrinsic::arm_neon_vld3:
10737     case Intrinsic::arm_neon_vld4:
10738     case Intrinsic::arm_neon_vld2lane:
10739     case Intrinsic::arm_neon_vld3lane:
10740     case Intrinsic::arm_neon_vld4lane:
10741     case Intrinsic::arm_neon_vst1:
10742     case Intrinsic::arm_neon_vst2:
10743     case Intrinsic::arm_neon_vst3:
10744     case Intrinsic::arm_neon_vst4:
10745     case Intrinsic::arm_neon_vst2lane:
10746     case Intrinsic::arm_neon_vst3lane:
10747     case Intrinsic::arm_neon_vst4lane:
10748       return PerformVLDCombine(N, DCI);
10749     default: break;
10750     }
10751     break;
10752   }
10753   return SDValue();
10754 }
10755 
10756 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10757                                                           EVT VT) const {
10758   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10759 }
10760 
10761 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10762                                                        unsigned,
10763                                                        unsigned,
10764                                                        bool *Fast) const {
10765   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10766   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10767 
10768   switch (VT.getSimpleVT().SimpleTy) {
10769   default:
10770     return false;
10771   case MVT::i8:
10772   case MVT::i16:
10773   case MVT::i32: {
10774     // Unaligned access can use (for example) LRDB, LRDH, LDR
10775     if (AllowsUnaligned) {
10776       if (Fast)
10777         *Fast = Subtarget->hasV7Ops();
10778       return true;
10779     }
10780     return false;
10781   }
10782   case MVT::f64:
10783   case MVT::v2f64: {
10784     // For any little-endian targets with neon, we can support unaligned ld/st
10785     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10786     // A big-endian target may also explicitly support unaligned accesses
10787     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10788       if (Fast)
10789         *Fast = true;
10790       return true;
10791     }
10792     return false;
10793   }
10794   }
10795 }
10796 
10797 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10798                        unsigned AlignCheck) {
10799   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10800           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10801 }
10802 
10803 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10804                                            unsigned DstAlign, unsigned SrcAlign,
10805                                            bool IsMemset, bool ZeroMemset,
10806                                            bool MemcpyStrSrc,
10807                                            MachineFunction &MF) const {
10808   const Function *F = MF.getFunction();
10809 
10810   // See if we can use NEON instructions for this...
10811   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10812       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10813     bool Fast;
10814     if (Size >= 16 &&
10815         (memOpAlign(SrcAlign, DstAlign, 16) ||
10816          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10817       return MVT::v2f64;
10818     } else if (Size >= 8 &&
10819                (memOpAlign(SrcAlign, DstAlign, 8) ||
10820                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10821                  Fast))) {
10822       return MVT::f64;
10823     }
10824   }
10825 
10826   // Lowering to i32/i16 if the size permits.
10827   if (Size >= 4)
10828     return MVT::i32;
10829   else if (Size >= 2)
10830     return MVT::i16;
10831 
10832   // Let the target-independent logic figure it out.
10833   return MVT::Other;
10834 }
10835 
10836 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10837   if (Val.getOpcode() != ISD::LOAD)
10838     return false;
10839 
10840   EVT VT1 = Val.getValueType();
10841   if (!VT1.isSimple() || !VT1.isInteger() ||
10842       !VT2.isSimple() || !VT2.isInteger())
10843     return false;
10844 
10845   switch (VT1.getSimpleVT().SimpleTy) {
10846   default: break;
10847   case MVT::i1:
10848   case MVT::i8:
10849   case MVT::i16:
10850     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10851     return true;
10852   }
10853 
10854   return false;
10855 }
10856 
10857 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10858   EVT VT = ExtVal.getValueType();
10859 
10860   if (!isTypeLegal(VT))
10861     return false;
10862 
10863   // Don't create a loadext if we can fold the extension into a wide/long
10864   // instruction.
10865   // If there's more than one user instruction, the loadext is desirable no
10866   // matter what.  There can be two uses by the same instruction.
10867   if (ExtVal->use_empty() ||
10868       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10869     return true;
10870 
10871   SDNode *U = *ExtVal->use_begin();
10872   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10873        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10874     return false;
10875 
10876   return true;
10877 }
10878 
10879 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10880   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10881     return false;
10882 
10883   if (!isTypeLegal(EVT::getEVT(Ty1)))
10884     return false;
10885 
10886   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10887 
10888   // Assuming the caller doesn't have a zeroext or signext return parameter,
10889   // truncation all the way down to i1 is valid.
10890   return true;
10891 }
10892 
10893 
10894 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10895   if (V < 0)
10896     return false;
10897 
10898   unsigned Scale = 1;
10899   switch (VT.getSimpleVT().SimpleTy) {
10900   default: return false;
10901   case MVT::i1:
10902   case MVT::i8:
10903     // Scale == 1;
10904     break;
10905   case MVT::i16:
10906     // Scale == 2;
10907     Scale = 2;
10908     break;
10909   case MVT::i32:
10910     // Scale == 4;
10911     Scale = 4;
10912     break;
10913   }
10914 
10915   if ((V & (Scale - 1)) != 0)
10916     return false;
10917   V /= Scale;
10918   return V == (V & ((1LL << 5) - 1));
10919 }
10920 
10921 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10922                                       const ARMSubtarget *Subtarget) {
10923   bool isNeg = false;
10924   if (V < 0) {
10925     isNeg = true;
10926     V = - V;
10927   }
10928 
10929   switch (VT.getSimpleVT().SimpleTy) {
10930   default: return false;
10931   case MVT::i1:
10932   case MVT::i8:
10933   case MVT::i16:
10934   case MVT::i32:
10935     // + imm12 or - imm8
10936     if (isNeg)
10937       return V == (V & ((1LL << 8) - 1));
10938     return V == (V & ((1LL << 12) - 1));
10939   case MVT::f32:
10940   case MVT::f64:
10941     // Same as ARM mode. FIXME: NEON?
10942     if (!Subtarget->hasVFP2())
10943       return false;
10944     if ((V & 3) != 0)
10945       return false;
10946     V >>= 2;
10947     return V == (V & ((1LL << 8) - 1));
10948   }
10949 }
10950 
10951 /// isLegalAddressImmediate - Return true if the integer value can be used
10952 /// as the offset of the target addressing mode for load / store of the
10953 /// given type.
10954 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10955                                     const ARMSubtarget *Subtarget) {
10956   if (V == 0)
10957     return true;
10958 
10959   if (!VT.isSimple())
10960     return false;
10961 
10962   if (Subtarget->isThumb1Only())
10963     return isLegalT1AddressImmediate(V, VT);
10964   else if (Subtarget->isThumb2())
10965     return isLegalT2AddressImmediate(V, VT, Subtarget);
10966 
10967   // ARM mode.
10968   if (V < 0)
10969     V = - V;
10970   switch (VT.getSimpleVT().SimpleTy) {
10971   default: return false;
10972   case MVT::i1:
10973   case MVT::i8:
10974   case MVT::i32:
10975     // +- imm12
10976     return V == (V & ((1LL << 12) - 1));
10977   case MVT::i16:
10978     // +- imm8
10979     return V == (V & ((1LL << 8) - 1));
10980   case MVT::f32:
10981   case MVT::f64:
10982     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10983       return false;
10984     if ((V & 3) != 0)
10985       return false;
10986     V >>= 2;
10987     return V == (V & ((1LL << 8) - 1));
10988   }
10989 }
10990 
10991 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10992                                                       EVT VT) const {
10993   int Scale = AM.Scale;
10994   if (Scale < 0)
10995     return false;
10996 
10997   switch (VT.getSimpleVT().SimpleTy) {
10998   default: return false;
10999   case MVT::i1:
11000   case MVT::i8:
11001   case MVT::i16:
11002   case MVT::i32:
11003     if (Scale == 1)
11004       return true;
11005     // r + r << imm
11006     Scale = Scale & ~1;
11007     return Scale == 2 || Scale == 4 || Scale == 8;
11008   case MVT::i64:
11009     // r + r
11010     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11011       return true;
11012     return false;
11013   case MVT::isVoid:
11014     // Note, we allow "void" uses (basically, uses that aren't loads or
11015     // stores), because arm allows folding a scale into many arithmetic
11016     // operations.  This should be made more precise and revisited later.
11017 
11018     // Allow r << imm, but the imm has to be a multiple of two.
11019     if (Scale & 1) return false;
11020     return isPowerOf2_32(Scale);
11021   }
11022 }
11023 
11024 /// isLegalAddressingMode - Return true if the addressing mode represented
11025 /// by AM is legal for this target, for a load/store of the specified type.
11026 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11027                                               const AddrMode &AM, Type *Ty,
11028                                               unsigned AS) const {
11029   EVT VT = getValueType(DL, Ty, true);
11030   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
11031     return false;
11032 
11033   // Can never fold addr of global into load/store.
11034   if (AM.BaseGV)
11035     return false;
11036 
11037   switch (AM.Scale) {
11038   case 0:  // no scale reg, must be "r+i" or "r", or "i".
11039     break;
11040   case 1:
11041     if (Subtarget->isThumb1Only())
11042       return false;
11043     // FALL THROUGH.
11044   default:
11045     // ARM doesn't support any R+R*scale+imm addr modes.
11046     if (AM.BaseOffs)
11047       return false;
11048 
11049     if (!VT.isSimple())
11050       return false;
11051 
11052     if (Subtarget->isThumb2())
11053       return isLegalT2ScaledAddressingMode(AM, VT);
11054 
11055     int Scale = AM.Scale;
11056     switch (VT.getSimpleVT().SimpleTy) {
11057     default: return false;
11058     case MVT::i1:
11059     case MVT::i8:
11060     case MVT::i32:
11061       if (Scale < 0) Scale = -Scale;
11062       if (Scale == 1)
11063         return true;
11064       // r + r << imm
11065       return isPowerOf2_32(Scale & ~1);
11066     case MVT::i16:
11067     case MVT::i64:
11068       // r + r
11069       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11070         return true;
11071       return false;
11072 
11073     case MVT::isVoid:
11074       // Note, we allow "void" uses (basically, uses that aren't loads or
11075       // stores), because arm allows folding a scale into many arithmetic
11076       // operations.  This should be made more precise and revisited later.
11077 
11078       // Allow r << imm, but the imm has to be a multiple of two.
11079       if (Scale & 1) return false;
11080       return isPowerOf2_32(Scale);
11081     }
11082   }
11083   return true;
11084 }
11085 
11086 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11087 /// icmp immediate, that is the target has icmp instructions which can compare
11088 /// a register against the immediate without having to materialize the
11089 /// immediate into a register.
11090 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11091   // Thumb2 and ARM modes can use cmn for negative immediates.
11092   if (!Subtarget->isThumb())
11093     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11094   if (Subtarget->isThumb2())
11095     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11096   // Thumb1 doesn't have cmn, and only 8-bit immediates.
11097   return Imm >= 0 && Imm <= 255;
11098 }
11099 
11100 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11101 /// *or sub* immediate, that is the target has add or sub instructions which can
11102 /// add a register with the immediate without having to materialize the
11103 /// immediate into a register.
11104 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11105   // Same encoding for add/sub, just flip the sign.
11106   int64_t AbsImm = std::abs(Imm);
11107   if (!Subtarget->isThumb())
11108     return ARM_AM::getSOImmVal(AbsImm) != -1;
11109   if (Subtarget->isThumb2())
11110     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11111   // Thumb1 only has 8-bit unsigned immediate.
11112   return AbsImm >= 0 && AbsImm <= 255;
11113 }
11114 
11115 static bool getARMIndexedAddressParts(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   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11123     // AddressingMode 3
11124     Base = Ptr->getOperand(0);
11125     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11126       int RHSC = (int)RHS->getZExtValue();
11127       if (RHSC < 0 && RHSC > -256) {
11128         assert(Ptr->getOpcode() == ISD::ADD);
11129         isInc = false;
11130         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11131         return true;
11132       }
11133     }
11134     isInc = (Ptr->getOpcode() == ISD::ADD);
11135     Offset = Ptr->getOperand(1);
11136     return true;
11137   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11138     // AddressingMode 2
11139     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11140       int RHSC = (int)RHS->getZExtValue();
11141       if (RHSC < 0 && RHSC > -0x1000) {
11142         assert(Ptr->getOpcode() == ISD::ADD);
11143         isInc = false;
11144         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11145         Base = Ptr->getOperand(0);
11146         return true;
11147       }
11148     }
11149 
11150     if (Ptr->getOpcode() == ISD::ADD) {
11151       isInc = true;
11152       ARM_AM::ShiftOpc ShOpcVal=
11153         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11154       if (ShOpcVal != ARM_AM::no_shift) {
11155         Base = Ptr->getOperand(1);
11156         Offset = Ptr->getOperand(0);
11157       } else {
11158         Base = Ptr->getOperand(0);
11159         Offset = Ptr->getOperand(1);
11160       }
11161       return true;
11162     }
11163 
11164     isInc = (Ptr->getOpcode() == ISD::ADD);
11165     Base = Ptr->getOperand(0);
11166     Offset = Ptr->getOperand(1);
11167     return true;
11168   }
11169 
11170   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11171   return false;
11172 }
11173 
11174 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11175                                      bool isSEXTLoad, SDValue &Base,
11176                                      SDValue &Offset, bool &isInc,
11177                                      SelectionDAG &DAG) {
11178   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11179     return false;
11180 
11181   Base = Ptr->getOperand(0);
11182   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11183     int RHSC = (int)RHS->getZExtValue();
11184     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11185       assert(Ptr->getOpcode() == ISD::ADD);
11186       isInc = false;
11187       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11188       return true;
11189     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11190       isInc = Ptr->getOpcode() == ISD::ADD;
11191       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11192       return true;
11193     }
11194   }
11195 
11196   return false;
11197 }
11198 
11199 /// getPreIndexedAddressParts - returns true by value, base pointer and
11200 /// offset pointer and addressing mode by reference if the node's address
11201 /// can be legally represented as pre-indexed load / store address.
11202 bool
11203 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11204                                              SDValue &Offset,
11205                                              ISD::MemIndexedMode &AM,
11206                                              SelectionDAG &DAG) const {
11207   if (Subtarget->isThumb1Only())
11208     return false;
11209 
11210   EVT VT;
11211   SDValue Ptr;
11212   bool isSEXTLoad = false;
11213   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11214     Ptr = LD->getBasePtr();
11215     VT  = LD->getMemoryVT();
11216     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11217   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11218     Ptr = ST->getBasePtr();
11219     VT  = ST->getMemoryVT();
11220   } else
11221     return false;
11222 
11223   bool isInc;
11224   bool isLegal = false;
11225   if (Subtarget->isThumb2())
11226     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11227                                        Offset, isInc, DAG);
11228   else
11229     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11230                                         Offset, isInc, DAG);
11231   if (!isLegal)
11232     return false;
11233 
11234   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11235   return true;
11236 }
11237 
11238 /// getPostIndexedAddressParts - returns true by value, base pointer and
11239 /// offset pointer and addressing mode by reference if this node can be
11240 /// combined with a load / store to form a post-indexed load / store.
11241 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11242                                                    SDValue &Base,
11243                                                    SDValue &Offset,
11244                                                    ISD::MemIndexedMode &AM,
11245                                                    SelectionDAG &DAG) const {
11246   if (Subtarget->isThumb1Only())
11247     return false;
11248 
11249   EVT VT;
11250   SDValue Ptr;
11251   bool isSEXTLoad = false;
11252   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11253     VT  = LD->getMemoryVT();
11254     Ptr = LD->getBasePtr();
11255     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11256   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11257     VT  = ST->getMemoryVT();
11258     Ptr = ST->getBasePtr();
11259   } else
11260     return false;
11261 
11262   bool isInc;
11263   bool isLegal = false;
11264   if (Subtarget->isThumb2())
11265     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11266                                        isInc, DAG);
11267   else
11268     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11269                                         isInc, DAG);
11270   if (!isLegal)
11271     return false;
11272 
11273   if (Ptr != Base) {
11274     // Swap base ptr and offset to catch more post-index load / store when
11275     // it's legal. In Thumb2 mode, offset must be an immediate.
11276     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11277         !Subtarget->isThumb2())
11278       std::swap(Base, Offset);
11279 
11280     // Post-indexed load / store update the base pointer.
11281     if (Ptr != Base)
11282       return false;
11283   }
11284 
11285   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11286   return true;
11287 }
11288 
11289 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11290                                                       APInt &KnownZero,
11291                                                       APInt &KnownOne,
11292                                                       const SelectionDAG &DAG,
11293                                                       unsigned Depth) const {
11294   unsigned BitWidth = KnownOne.getBitWidth();
11295   KnownZero = KnownOne = APInt(BitWidth, 0);
11296   switch (Op.getOpcode()) {
11297   default: break;
11298   case ARMISD::ADDC:
11299   case ARMISD::ADDE:
11300   case ARMISD::SUBC:
11301   case ARMISD::SUBE:
11302     // These nodes' second result is a boolean
11303     if (Op.getResNo() == 0)
11304       break;
11305     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11306     break;
11307   case ARMISD::CMOV: {
11308     // Bits are known zero/one if known on the LHS and RHS.
11309     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11310     if (KnownZero == 0 && KnownOne == 0) return;
11311 
11312     APInt KnownZeroRHS, KnownOneRHS;
11313     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11314     KnownZero &= KnownZeroRHS;
11315     KnownOne  &= KnownOneRHS;
11316     return;
11317   }
11318   case ISD::INTRINSIC_W_CHAIN: {
11319     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11320     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11321     switch (IntID) {
11322     default: return;
11323     case Intrinsic::arm_ldaex:
11324     case Intrinsic::arm_ldrex: {
11325       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11326       unsigned MemBits = VT.getScalarType().getSizeInBits();
11327       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11328       return;
11329     }
11330     }
11331   }
11332   }
11333 }
11334 
11335 //===----------------------------------------------------------------------===//
11336 //                           ARM Inline Assembly Support
11337 //===----------------------------------------------------------------------===//
11338 
11339 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11340   // Looking for "rev" which is V6+.
11341   if (!Subtarget->hasV6Ops())
11342     return false;
11343 
11344   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11345   std::string AsmStr = IA->getAsmString();
11346   SmallVector<StringRef, 4> AsmPieces;
11347   SplitString(AsmStr, AsmPieces, ";\n");
11348 
11349   switch (AsmPieces.size()) {
11350   default: return false;
11351   case 1:
11352     AsmStr = AsmPieces[0];
11353     AsmPieces.clear();
11354     SplitString(AsmStr, AsmPieces, " \t,");
11355 
11356     // rev $0, $1
11357     if (AsmPieces.size() == 3 &&
11358         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11359         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11360       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11361       if (Ty && Ty->getBitWidth() == 32)
11362         return IntrinsicLowering::LowerToByteSwap(CI);
11363     }
11364     break;
11365   }
11366 
11367   return false;
11368 }
11369 
11370 /// getConstraintType - Given a constraint letter, return the type of
11371 /// constraint it is for this target.
11372 ARMTargetLowering::ConstraintType
11373 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11374   if (Constraint.size() == 1) {
11375     switch (Constraint[0]) {
11376     default:  break;
11377     case 'l': return C_RegisterClass;
11378     case 'w': return C_RegisterClass;
11379     case 'h': return C_RegisterClass;
11380     case 'x': return C_RegisterClass;
11381     case 't': return C_RegisterClass;
11382     case 'j': return C_Other; // Constant for movw.
11383       // An address with a single base register. Due to the way we
11384       // currently handle addresses it is the same as an 'r' memory constraint.
11385     case 'Q': return C_Memory;
11386     }
11387   } else if (Constraint.size() == 2) {
11388     switch (Constraint[0]) {
11389     default: break;
11390     // All 'U+' constraints are addresses.
11391     case 'U': return C_Memory;
11392     }
11393   }
11394   return TargetLowering::getConstraintType(Constraint);
11395 }
11396 
11397 /// Examine constraint type and operand type and determine a weight value.
11398 /// This object must already have been set up with the operand type
11399 /// and the current alternative constraint selected.
11400 TargetLowering::ConstraintWeight
11401 ARMTargetLowering::getSingleConstraintMatchWeight(
11402     AsmOperandInfo &info, const char *constraint) const {
11403   ConstraintWeight weight = CW_Invalid;
11404   Value *CallOperandVal = info.CallOperandVal;
11405     // If we don't have a value, we can't do a match,
11406     // but allow it at the lowest weight.
11407   if (!CallOperandVal)
11408     return CW_Default;
11409   Type *type = CallOperandVal->getType();
11410   // Look at the constraint type.
11411   switch (*constraint) {
11412   default:
11413     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11414     break;
11415   case 'l':
11416     if (type->isIntegerTy()) {
11417       if (Subtarget->isThumb())
11418         weight = CW_SpecificReg;
11419       else
11420         weight = CW_Register;
11421     }
11422     break;
11423   case 'w':
11424     if (type->isFloatingPointTy())
11425       weight = CW_Register;
11426     break;
11427   }
11428   return weight;
11429 }
11430 
11431 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11432 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11433     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11434   if (Constraint.size() == 1) {
11435     // GCC ARM Constraint Letters
11436     switch (Constraint[0]) {
11437     case 'l': // Low regs or general regs.
11438       if (Subtarget->isThumb())
11439         return RCPair(0U, &ARM::tGPRRegClass);
11440       return RCPair(0U, &ARM::GPRRegClass);
11441     case 'h': // High regs or no regs.
11442       if (Subtarget->isThumb())
11443         return RCPair(0U, &ARM::hGPRRegClass);
11444       break;
11445     case 'r':
11446       if (Subtarget->isThumb1Only())
11447         return RCPair(0U, &ARM::tGPRRegClass);
11448       return RCPair(0U, &ARM::GPRRegClass);
11449     case 'w':
11450       if (VT == MVT::Other)
11451         break;
11452       if (VT == MVT::f32)
11453         return RCPair(0U, &ARM::SPRRegClass);
11454       if (VT.getSizeInBits() == 64)
11455         return RCPair(0U, &ARM::DPRRegClass);
11456       if (VT.getSizeInBits() == 128)
11457         return RCPair(0U, &ARM::QPRRegClass);
11458       break;
11459     case 'x':
11460       if (VT == MVT::Other)
11461         break;
11462       if (VT == MVT::f32)
11463         return RCPair(0U, &ARM::SPR_8RegClass);
11464       if (VT.getSizeInBits() == 64)
11465         return RCPair(0U, &ARM::DPR_8RegClass);
11466       if (VT.getSizeInBits() == 128)
11467         return RCPair(0U, &ARM::QPR_8RegClass);
11468       break;
11469     case 't':
11470       if (VT == MVT::f32)
11471         return RCPair(0U, &ARM::SPRRegClass);
11472       break;
11473     }
11474   }
11475   if (StringRef("{cc}").equals_lower(Constraint))
11476     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11477 
11478   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11479 }
11480 
11481 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11482 /// vector.  If it is invalid, don't add anything to Ops.
11483 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11484                                                      std::string &Constraint,
11485                                                      std::vector<SDValue>&Ops,
11486                                                      SelectionDAG &DAG) const {
11487   SDValue Result;
11488 
11489   // Currently only support length 1 constraints.
11490   if (Constraint.length() != 1) return;
11491 
11492   char ConstraintLetter = Constraint[0];
11493   switch (ConstraintLetter) {
11494   default: break;
11495   case 'j':
11496   case 'I': case 'J': case 'K': case 'L':
11497   case 'M': case 'N': case 'O':
11498     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11499     if (!C)
11500       return;
11501 
11502     int64_t CVal64 = C->getSExtValue();
11503     int CVal = (int) CVal64;
11504     // None of these constraints allow values larger than 32 bits.  Check
11505     // that the value fits in an int.
11506     if (CVal != CVal64)
11507       return;
11508 
11509     switch (ConstraintLetter) {
11510       case 'j':
11511         // Constant suitable for movw, must be between 0 and
11512         // 65535.
11513         if (Subtarget->hasV6T2Ops())
11514           if (CVal >= 0 && CVal <= 65535)
11515             break;
11516         return;
11517       case 'I':
11518         if (Subtarget->isThumb1Only()) {
11519           // This must be a constant between 0 and 255, for ADD
11520           // immediates.
11521           if (CVal >= 0 && CVal <= 255)
11522             break;
11523         } else if (Subtarget->isThumb2()) {
11524           // A constant that can be used as an immediate value in a
11525           // data-processing instruction.
11526           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11527             break;
11528         } else {
11529           // A constant that can be used as an immediate value in a
11530           // data-processing instruction.
11531           if (ARM_AM::getSOImmVal(CVal) != -1)
11532             break;
11533         }
11534         return;
11535 
11536       case 'J':
11537         if (Subtarget->isThumb1Only()) {
11538           // This must be a constant between -255 and -1, for negated ADD
11539           // immediates. This can be used in GCC with an "n" modifier that
11540           // prints the negated value, for use with SUB instructions. It is
11541           // not useful otherwise but is implemented for compatibility.
11542           if (CVal >= -255 && CVal <= -1)
11543             break;
11544         } else {
11545           // This must be a constant between -4095 and 4095. It is not clear
11546           // what this constraint is intended for. Implemented for
11547           // compatibility with GCC.
11548           if (CVal >= -4095 && CVal <= 4095)
11549             break;
11550         }
11551         return;
11552 
11553       case 'K':
11554         if (Subtarget->isThumb1Only()) {
11555           // A 32-bit value where only one byte has a nonzero value. Exclude
11556           // zero to match GCC. This constraint is used by GCC internally for
11557           // constants that can be loaded with a move/shift combination.
11558           // It is not useful otherwise but is implemented for compatibility.
11559           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11560             break;
11561         } else if (Subtarget->isThumb2()) {
11562           // A constant whose bitwise inverse can be used as an immediate
11563           // value in a data-processing instruction. This can be used in GCC
11564           // with a "B" modifier that prints the inverted value, for use with
11565           // BIC and MVN instructions. It is not useful otherwise but is
11566           // implemented for compatibility.
11567           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11568             break;
11569         } else {
11570           // A constant whose bitwise inverse can be used as an immediate
11571           // value in a data-processing instruction. This can be used in GCC
11572           // with a "B" modifier that prints the inverted value, for use with
11573           // BIC and MVN instructions. It is not useful otherwise but is
11574           // implemented for compatibility.
11575           if (ARM_AM::getSOImmVal(~CVal) != -1)
11576             break;
11577         }
11578         return;
11579 
11580       case 'L':
11581         if (Subtarget->isThumb1Only()) {
11582           // This must be a constant between -7 and 7,
11583           // for 3-operand ADD/SUB immediate instructions.
11584           if (CVal >= -7 && CVal < 7)
11585             break;
11586         } else if (Subtarget->isThumb2()) {
11587           // A constant whose negation can be used as an immediate value in a
11588           // data-processing instruction. This can be used in GCC with an "n"
11589           // modifier that prints the negated value, for use with SUB
11590           // instructions. It is not useful otherwise but is implemented for
11591           // compatibility.
11592           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11593             break;
11594         } else {
11595           // A constant whose negation can be used as an immediate value in a
11596           // data-processing instruction. This can be used in GCC with an "n"
11597           // modifier that prints the negated value, for use with SUB
11598           // instructions. It is not useful otherwise but is implemented for
11599           // compatibility.
11600           if (ARM_AM::getSOImmVal(-CVal) != -1)
11601             break;
11602         }
11603         return;
11604 
11605       case 'M':
11606         if (Subtarget->isThumb1Only()) {
11607           // This must be a multiple of 4 between 0 and 1020, for
11608           // ADD sp + immediate.
11609           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11610             break;
11611         } else {
11612           // A power of two or a constant between 0 and 32.  This is used in
11613           // GCC for the shift amount on shifted register operands, but it is
11614           // useful in general for any shift amounts.
11615           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11616             break;
11617         }
11618         return;
11619 
11620       case 'N':
11621         if (Subtarget->isThumb()) {  // FIXME thumb2
11622           // This must be a constant between 0 and 31, for shift amounts.
11623           if (CVal >= 0 && CVal <= 31)
11624             break;
11625         }
11626         return;
11627 
11628       case 'O':
11629         if (Subtarget->isThumb()) {  // FIXME thumb2
11630           // This must be a multiple of 4 between -508 and 508, for
11631           // ADD/SUB sp = sp + immediate.
11632           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11633             break;
11634         }
11635         return;
11636     }
11637     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11638     break;
11639   }
11640 
11641   if (Result.getNode()) {
11642     Ops.push_back(Result);
11643     return;
11644   }
11645   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11646 }
11647 
11648 static RTLIB::Libcall getDivRemLibcall(
11649     const SDNode *N, MVT::SimpleValueType SVT) {
11650   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11651           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11652          "Unhandled Opcode in getDivRemLibcall");
11653   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11654                   N->getOpcode() == ISD::SREM;
11655   RTLIB::Libcall LC;
11656   switch (SVT) {
11657   default: llvm_unreachable("Unexpected request for libcall!");
11658   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11659   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11660   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11661   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11662   }
11663   return LC;
11664 }
11665 
11666 static TargetLowering::ArgListTy getDivRemArgList(
11667     const SDNode *N, LLVMContext *Context) {
11668   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11669           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11670          "Unhandled Opcode in getDivRemArgList");
11671   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11672                   N->getOpcode() == ISD::SREM;
11673   TargetLowering::ArgListTy Args;
11674   TargetLowering::ArgListEntry Entry;
11675   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11676     EVT ArgVT = N->getOperand(i).getValueType();
11677     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11678     Entry.Node = N->getOperand(i);
11679     Entry.Ty = ArgTy;
11680     Entry.isSExt = isSigned;
11681     Entry.isZExt = !isSigned;
11682     Args.push_back(Entry);
11683   }
11684   return Args;
11685 }
11686 
11687 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11688   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
11689           Subtarget->isTargetGNUAEABI()) &&
11690          "Register-based DivRem lowering only");
11691   unsigned Opcode = Op->getOpcode();
11692   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11693          "Invalid opcode for Div/Rem lowering");
11694   bool isSigned = (Opcode == ISD::SDIVREM);
11695   EVT VT = Op->getValueType(0);
11696   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11697 
11698   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11699                                        VT.getSimpleVT().SimpleTy);
11700   SDValue InChain = DAG.getEntryNode();
11701 
11702   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11703                                                     DAG.getContext());
11704 
11705   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11706                                          getPointerTy(DAG.getDataLayout()));
11707 
11708   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11709 
11710   SDLoc dl(Op);
11711   TargetLowering::CallLoweringInfo CLI(DAG);
11712   CLI.setDebugLoc(dl).setChain(InChain)
11713     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11714     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11715 
11716   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11717   return CallInfo.first;
11718 }
11719 
11720 // Lowers REM using divmod helpers
11721 // see RTABI section 4.2/4.3
11722 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11723   // Build return types (div and rem)
11724   std::vector<Type*> RetTyParams;
11725   Type *RetTyElement;
11726 
11727   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11728   default: llvm_unreachable("Unexpected request for libcall!");
11729   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11730   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11731   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11732   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11733   }
11734 
11735   RetTyParams.push_back(RetTyElement);
11736   RetTyParams.push_back(RetTyElement);
11737   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11738   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11739 
11740   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11741                                                              SimpleTy);
11742   SDValue InChain = DAG.getEntryNode();
11743   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11744   bool isSigned = N->getOpcode() == ISD::SREM;
11745   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11746                                          getPointerTy(DAG.getDataLayout()));
11747 
11748   // Lower call
11749   CallLoweringInfo CLI(DAG);
11750   CLI.setChain(InChain)
11751      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11752      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11753   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11754 
11755   // Return second (rem) result operand (first contains div)
11756   SDNode *ResNode = CallResult.first.getNode();
11757   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11758   return ResNode->getOperand(1);
11759 }
11760 
11761 SDValue
11762 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11763   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11764   SDLoc DL(Op);
11765 
11766   // Get the inputs.
11767   SDValue Chain = Op.getOperand(0);
11768   SDValue Size  = Op.getOperand(1);
11769 
11770   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11771                               DAG.getConstant(2, DL, MVT::i32));
11772 
11773   SDValue Flag;
11774   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11775   Flag = Chain.getValue(1);
11776 
11777   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11778   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11779 
11780   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11781   Chain = NewSP.getValue(1);
11782 
11783   SDValue Ops[2] = { NewSP, Chain };
11784   return DAG.getMergeValues(Ops, DL);
11785 }
11786 
11787 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11788   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11789          "Unexpected type for custom-lowering FP_EXTEND");
11790 
11791   RTLIB::Libcall LC;
11792   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11793 
11794   SDValue SrcVal = Op.getOperand(0);
11795   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11796                      SDLoc(Op)).first;
11797 }
11798 
11799 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11800   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11801          Subtarget->isFPOnlySP() &&
11802          "Unexpected type for custom-lowering FP_ROUND");
11803 
11804   RTLIB::Libcall LC;
11805   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11806 
11807   SDValue SrcVal = Op.getOperand(0);
11808   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11809                      SDLoc(Op)).first;
11810 }
11811 
11812 bool
11813 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11814   // The ARM target isn't yet aware of offsets.
11815   return false;
11816 }
11817 
11818 bool ARM::isBitFieldInvertedMask(unsigned v) {
11819   if (v == 0xffffffff)
11820     return false;
11821 
11822   // there can be 1's on either or both "outsides", all the "inside"
11823   // bits must be 0's
11824   return isShiftedMask_32(~v);
11825 }
11826 
11827 /// isFPImmLegal - Returns true if the target can instruction select the
11828 /// specified FP immediate natively. If false, the legalizer will
11829 /// materialize the FP immediate as a load from a constant pool.
11830 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11831   if (!Subtarget->hasVFP3())
11832     return false;
11833   if (VT == MVT::f32)
11834     return ARM_AM::getFP32Imm(Imm) != -1;
11835   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11836     return ARM_AM::getFP64Imm(Imm) != -1;
11837   return false;
11838 }
11839 
11840 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11841 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11842 /// specified in the intrinsic calls.
11843 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11844                                            const CallInst &I,
11845                                            unsigned Intrinsic) const {
11846   switch (Intrinsic) {
11847   case Intrinsic::arm_neon_vld1:
11848   case Intrinsic::arm_neon_vld2:
11849   case Intrinsic::arm_neon_vld3:
11850   case Intrinsic::arm_neon_vld4:
11851   case Intrinsic::arm_neon_vld2lane:
11852   case Intrinsic::arm_neon_vld3lane:
11853   case Intrinsic::arm_neon_vld4lane: {
11854     Info.opc = ISD::INTRINSIC_W_CHAIN;
11855     // Conservatively set memVT to the entire set of vectors loaded.
11856     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11857     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11858     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11859     Info.ptrVal = I.getArgOperand(0);
11860     Info.offset = 0;
11861     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11862     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11863     Info.vol = false; // volatile loads with NEON intrinsics not supported
11864     Info.readMem = true;
11865     Info.writeMem = false;
11866     return true;
11867   }
11868   case Intrinsic::arm_neon_vst1:
11869   case Intrinsic::arm_neon_vst2:
11870   case Intrinsic::arm_neon_vst3:
11871   case Intrinsic::arm_neon_vst4:
11872   case Intrinsic::arm_neon_vst2lane:
11873   case Intrinsic::arm_neon_vst3lane:
11874   case Intrinsic::arm_neon_vst4lane: {
11875     Info.opc = ISD::INTRINSIC_VOID;
11876     // Conservatively set memVT to the entire set of vectors stored.
11877     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11878     unsigned NumElts = 0;
11879     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11880       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11881       if (!ArgTy->isVectorTy())
11882         break;
11883       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11884     }
11885     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11886     Info.ptrVal = I.getArgOperand(0);
11887     Info.offset = 0;
11888     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11889     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11890     Info.vol = false; // volatile stores with NEON intrinsics not supported
11891     Info.readMem = false;
11892     Info.writeMem = true;
11893     return true;
11894   }
11895   case Intrinsic::arm_ldaex:
11896   case Intrinsic::arm_ldrex: {
11897     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11898     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11899     Info.opc = ISD::INTRINSIC_W_CHAIN;
11900     Info.memVT = MVT::getVT(PtrTy->getElementType());
11901     Info.ptrVal = I.getArgOperand(0);
11902     Info.offset = 0;
11903     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11904     Info.vol = true;
11905     Info.readMem = true;
11906     Info.writeMem = false;
11907     return true;
11908   }
11909   case Intrinsic::arm_stlex:
11910   case Intrinsic::arm_strex: {
11911     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11912     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11913     Info.opc = ISD::INTRINSIC_W_CHAIN;
11914     Info.memVT = MVT::getVT(PtrTy->getElementType());
11915     Info.ptrVal = I.getArgOperand(1);
11916     Info.offset = 0;
11917     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11918     Info.vol = true;
11919     Info.readMem = false;
11920     Info.writeMem = true;
11921     return true;
11922   }
11923   case Intrinsic::arm_stlexd:
11924   case Intrinsic::arm_strexd: {
11925     Info.opc = ISD::INTRINSIC_W_CHAIN;
11926     Info.memVT = MVT::i64;
11927     Info.ptrVal = I.getArgOperand(2);
11928     Info.offset = 0;
11929     Info.align = 8;
11930     Info.vol = true;
11931     Info.readMem = false;
11932     Info.writeMem = true;
11933     return true;
11934   }
11935   case Intrinsic::arm_ldaexd:
11936   case Intrinsic::arm_ldrexd: {
11937     Info.opc = ISD::INTRINSIC_W_CHAIN;
11938     Info.memVT = MVT::i64;
11939     Info.ptrVal = I.getArgOperand(0);
11940     Info.offset = 0;
11941     Info.align = 8;
11942     Info.vol = true;
11943     Info.readMem = true;
11944     Info.writeMem = false;
11945     return true;
11946   }
11947   default:
11948     break;
11949   }
11950 
11951   return false;
11952 }
11953 
11954 /// \brief Returns true if it is beneficial to convert a load of a constant
11955 /// to just the constant itself.
11956 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11957                                                           Type *Ty) const {
11958   assert(Ty->isIntegerTy());
11959 
11960   unsigned Bits = Ty->getPrimitiveSizeInBits();
11961   if (Bits == 0 || Bits > 32)
11962     return false;
11963   return true;
11964 }
11965 
11966 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11967                                         ARM_MB::MemBOpt Domain) const {
11968   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11969 
11970   // First, if the target has no DMB, see what fallback we can use.
11971   if (!Subtarget->hasDataBarrier()) {
11972     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11973     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11974     // here.
11975     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11976       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11977       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11978                         Builder.getInt32(0), Builder.getInt32(7),
11979                         Builder.getInt32(10), Builder.getInt32(5)};
11980       return Builder.CreateCall(MCR, args);
11981     } else {
11982       // Instead of using barriers, atomic accesses on these subtargets use
11983       // libcalls.
11984       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11985     }
11986   } else {
11987     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11988     // Only a full system barrier exists in the M-class architectures.
11989     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11990     Constant *CDomain = Builder.getInt32(Domain);
11991     return Builder.CreateCall(DMB, CDomain);
11992   }
11993 }
11994 
11995 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11996 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11997                                          AtomicOrdering Ord, bool IsStore,
11998                                          bool IsLoad) const {
11999   if (!getInsertFencesForAtomic())
12000     return nullptr;
12001 
12002   switch (Ord) {
12003   case NotAtomic:
12004   case Unordered:
12005     llvm_unreachable("Invalid fence: unordered/non-atomic");
12006   case Monotonic:
12007   case Acquire:
12008     return nullptr; // Nothing to do
12009   case SequentiallyConsistent:
12010     if (!IsStore)
12011       return nullptr; // Nothing to do
12012     /*FALLTHROUGH*/
12013   case Release:
12014   case AcquireRelease:
12015     if (Subtarget->isSwift())
12016       return makeDMB(Builder, ARM_MB::ISHST);
12017     // FIXME: add a comment with a link to documentation justifying this.
12018     else
12019       return makeDMB(Builder, ARM_MB::ISH);
12020   }
12021   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
12022 }
12023 
12024 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
12025                                           AtomicOrdering Ord, bool IsStore,
12026                                           bool IsLoad) const {
12027   if (!getInsertFencesForAtomic())
12028     return nullptr;
12029 
12030   switch (Ord) {
12031   case NotAtomic:
12032   case Unordered:
12033     llvm_unreachable("Invalid fence: unordered/not-atomic");
12034   case Monotonic:
12035   case Release:
12036     return nullptr; // Nothing to do
12037   case Acquire:
12038   case AcquireRelease:
12039   case SequentiallyConsistent:
12040     return makeDMB(Builder, ARM_MB::ISH);
12041   }
12042   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
12043 }
12044 
12045 // Loads and stores less than 64-bits are already atomic; ones above that
12046 // are doomed anyway, so defer to the default libcall and blame the OS when
12047 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12048 // anything for those.
12049 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12050   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12051   return (Size == 64) && !Subtarget->isMClass();
12052 }
12053 
12054 // Loads and stores less than 64-bits are already atomic; ones above that
12055 // are doomed anyway, so defer to the default libcall and blame the OS when
12056 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12057 // anything for those.
12058 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12059 // guarantee, see DDI0406C ARM architecture reference manual,
12060 // sections A8.8.72-74 LDRD)
12061 TargetLowering::AtomicExpansionKind
12062 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12063   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12064   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12065                                                   : AtomicExpansionKind::None;
12066 }
12067 
12068 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12069 // and up to 64 bits on the non-M profiles
12070 TargetLowering::AtomicExpansionKind
12071 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12072   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12073   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12074              ? AtomicExpansionKind::LLSC
12075              : AtomicExpansionKind::None;
12076 }
12077 
12078 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12079     AtomicCmpXchgInst *AI) const {
12080   return true;
12081 }
12082 
12083 // This has so far only been implemented for MachO.
12084 bool ARMTargetLowering::useLoadStackGuardNode() const {
12085   return Subtarget->isTargetMachO();
12086 }
12087 
12088 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12089                                                   unsigned &Cost) const {
12090   // If we do not have NEON, vector types are not natively supported.
12091   if (!Subtarget->hasNEON())
12092     return false;
12093 
12094   // Floating point values and vector values map to the same register file.
12095   // Therefore, although we could do a store extract of a vector type, this is
12096   // better to leave at float as we have more freedom in the addressing mode for
12097   // those.
12098   if (VectorTy->isFPOrFPVectorTy())
12099     return false;
12100 
12101   // If the index is unknown at compile time, this is very expensive to lower
12102   // and it is not possible to combine the store with the extract.
12103   if (!isa<ConstantInt>(Idx))
12104     return false;
12105 
12106   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12107   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12108   // We can do a store + vector extract on any vector that fits perfectly in a D
12109   // or Q register.
12110   if (BitWidth == 64 || BitWidth == 128) {
12111     Cost = 0;
12112     return true;
12113   }
12114   return false;
12115 }
12116 
12117 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12118   return Subtarget->hasV6T2Ops();
12119 }
12120 
12121 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12122   return Subtarget->hasV6T2Ops();
12123 }
12124 
12125 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12126                                          AtomicOrdering Ord) const {
12127   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12128   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12129   bool IsAcquire = isAtLeastAcquire(Ord);
12130 
12131   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12132   // intrinsic must return {i32, i32} and we have to recombine them into a
12133   // single i64 here.
12134   if (ValTy->getPrimitiveSizeInBits() == 64) {
12135     Intrinsic::ID Int =
12136         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12137     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12138 
12139     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12140     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12141 
12142     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12143     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12144     if (!Subtarget->isLittle())
12145       std::swap (Lo, Hi);
12146     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12147     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12148     return Builder.CreateOr(
12149         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12150   }
12151 
12152   Type *Tys[] = { Addr->getType() };
12153   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12154   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12155 
12156   return Builder.CreateTruncOrBitCast(
12157       Builder.CreateCall(Ldrex, Addr),
12158       cast<PointerType>(Addr->getType())->getElementType());
12159 }
12160 
12161 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12162     IRBuilder<> &Builder) const {
12163   if (!Subtarget->hasV7Ops())
12164     return;
12165   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12166   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12167 }
12168 
12169 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12170                                                Value *Addr,
12171                                                AtomicOrdering Ord) const {
12172   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12173   bool IsRelease = isAtLeastRelease(Ord);
12174 
12175   // Since the intrinsics must have legal type, the i64 intrinsics take two
12176   // parameters: "i32, i32". We must marshal Val into the appropriate form
12177   // before the call.
12178   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12179     Intrinsic::ID Int =
12180         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12181     Function *Strex = Intrinsic::getDeclaration(M, Int);
12182     Type *Int32Ty = Type::getInt32Ty(M->getContext());
12183 
12184     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12185     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12186     if (!Subtarget->isLittle())
12187       std::swap (Lo, Hi);
12188     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12189     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12190   }
12191 
12192   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12193   Type *Tys[] = { Addr->getType() };
12194   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12195 
12196   return Builder.CreateCall(
12197       Strex, {Builder.CreateZExtOrBitCast(
12198                   Val, Strex->getFunctionType()->getParamType(0)),
12199               Addr});
12200 }
12201 
12202 /// \brief Lower an interleaved load into a vldN intrinsic.
12203 ///
12204 /// E.g. Lower an interleaved load (Factor = 2):
12205 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12206 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12207 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12208 ///
12209 ///      Into:
12210 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12211 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12212 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12213 bool ARMTargetLowering::lowerInterleavedLoad(
12214     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12215     ArrayRef<unsigned> Indices, unsigned Factor) const {
12216   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12217          "Invalid interleave factor");
12218   assert(!Shuffles.empty() && "Empty shufflevector input");
12219   assert(Shuffles.size() == Indices.size() &&
12220          "Unmatched number of shufflevectors and indices");
12221 
12222   VectorType *VecTy = Shuffles[0]->getType();
12223   Type *EltTy = VecTy->getVectorElementType();
12224 
12225   const DataLayout &DL = LI->getModule()->getDataLayout();
12226   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12227   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12228 
12229   // Skip if we do not have NEON and skip illegal vector types and vector types
12230   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12231   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12232     return false;
12233 
12234   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12235   // load integer vectors first and then convert to pointer vectors.
12236   if (EltTy->isPointerTy())
12237     VecTy =
12238         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12239 
12240   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12241                                             Intrinsic::arm_neon_vld3,
12242                                             Intrinsic::arm_neon_vld4};
12243 
12244   IRBuilder<> Builder(LI);
12245   SmallVector<Value *, 2> Ops;
12246 
12247   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12248   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12249   Ops.push_back(Builder.getInt32(LI->getAlignment()));
12250 
12251   Type *Tys[] = { VecTy, Int8Ptr };
12252   Function *VldnFunc =
12253       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12254   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12255 
12256   // Replace uses of each shufflevector with the corresponding vector loaded
12257   // by ldN.
12258   for (unsigned i = 0; i < Shuffles.size(); i++) {
12259     ShuffleVectorInst *SV = Shuffles[i];
12260     unsigned Index = Indices[i];
12261 
12262     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12263 
12264     // Convert the integer vector to pointer vector if the element is pointer.
12265     if (EltTy->isPointerTy())
12266       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12267 
12268     SV->replaceAllUsesWith(SubVec);
12269   }
12270 
12271   return true;
12272 }
12273 
12274 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12275 ///
12276 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12277 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12278                                    unsigned NumElts) {
12279   SmallVector<Constant *, 16> Mask;
12280   for (unsigned i = 0; i < NumElts; i++)
12281     Mask.push_back(Builder.getInt32(Start + i));
12282 
12283   return ConstantVector::get(Mask);
12284 }
12285 
12286 /// \brief Lower an interleaved store into a vstN intrinsic.
12287 ///
12288 /// E.g. Lower an interleaved store (Factor = 3):
12289 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12290 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12291 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12292 ///
12293 ///      Into:
12294 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12295 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12296 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12297 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12298 ///
12299 /// Note that the new shufflevectors will be removed and we'll only generate one
12300 /// vst3 instruction in CodeGen.
12301 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12302                                               ShuffleVectorInst *SVI,
12303                                               unsigned Factor) const {
12304   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12305          "Invalid interleave factor");
12306 
12307   VectorType *VecTy = SVI->getType();
12308   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12309          "Invalid interleaved store");
12310 
12311   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12312   Type *EltTy = VecTy->getVectorElementType();
12313   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12314 
12315   const DataLayout &DL = SI->getModule()->getDataLayout();
12316   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12317   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12318 
12319   // Skip if we do not have NEON and skip illegal vector types and vector types
12320   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12321   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12322       EltIs64Bits)
12323     return false;
12324 
12325   Value *Op0 = SVI->getOperand(0);
12326   Value *Op1 = SVI->getOperand(1);
12327   IRBuilder<> Builder(SI);
12328 
12329   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12330   // vectors to integer vectors.
12331   if (EltTy->isPointerTy()) {
12332     Type *IntTy = DL.getIntPtrType(EltTy);
12333 
12334     // Convert to the corresponding integer vector.
12335     Type *IntVecTy =
12336         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12337     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12338     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12339 
12340     SubVecTy = VectorType::get(IntTy, NumSubElts);
12341   }
12342 
12343   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12344                                              Intrinsic::arm_neon_vst3,
12345                                              Intrinsic::arm_neon_vst4};
12346   SmallVector<Value *, 6> Ops;
12347 
12348   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12349   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12350 
12351   Type *Tys[] = { Int8Ptr, SubVecTy };
12352   Function *VstNFunc = Intrinsic::getDeclaration(
12353       SI->getModule(), StoreInts[Factor - 2], Tys);
12354 
12355   // Split the shufflevector operands into sub vectors for the new vstN call.
12356   for (unsigned i = 0; i < Factor; i++)
12357     Ops.push_back(Builder.CreateShuffleVector(
12358         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12359 
12360   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12361   Builder.CreateCall(VstNFunc, Ops);
12362   return true;
12363 }
12364 
12365 enum HABaseType {
12366   HA_UNKNOWN = 0,
12367   HA_FLOAT,
12368   HA_DOUBLE,
12369   HA_VECT64,
12370   HA_VECT128
12371 };
12372 
12373 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12374                                    uint64_t &Members) {
12375   if (auto *ST = dyn_cast<StructType>(Ty)) {
12376     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12377       uint64_t SubMembers = 0;
12378       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12379         return false;
12380       Members += SubMembers;
12381     }
12382   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12383     uint64_t SubMembers = 0;
12384     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12385       return false;
12386     Members += SubMembers * AT->getNumElements();
12387   } else if (Ty->isFloatTy()) {
12388     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12389       return false;
12390     Members = 1;
12391     Base = HA_FLOAT;
12392   } else if (Ty->isDoubleTy()) {
12393     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12394       return false;
12395     Members = 1;
12396     Base = HA_DOUBLE;
12397   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12398     Members = 1;
12399     switch (Base) {
12400     case HA_FLOAT:
12401     case HA_DOUBLE:
12402       return false;
12403     case HA_VECT64:
12404       return VT->getBitWidth() == 64;
12405     case HA_VECT128:
12406       return VT->getBitWidth() == 128;
12407     case HA_UNKNOWN:
12408       switch (VT->getBitWidth()) {
12409       case 64:
12410         Base = HA_VECT64;
12411         return true;
12412       case 128:
12413         Base = HA_VECT128;
12414         return true;
12415       default:
12416         return false;
12417       }
12418     }
12419   }
12420 
12421   return (Members > 0 && Members <= 4);
12422 }
12423 
12424 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12425 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12426 /// passing according to AAPCS rules.
12427 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12428     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12429   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12430       CallingConv::ARM_AAPCS_VFP)
12431     return false;
12432 
12433   HABaseType Base = HA_UNKNOWN;
12434   uint64_t Members = 0;
12435   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12436   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12437 
12438   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12439   return IsHA || IsIntArray;
12440 }
12441 
12442 unsigned ARMTargetLowering::getExceptionPointerRegister(
12443     const Constant *PersonalityFn) const {
12444   // Platforms which do not use SjLj EH may return values in these registers
12445   // via the personality function.
12446   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12447 }
12448 
12449 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12450     const Constant *PersonalityFn) const {
12451   // Platforms which do not use SjLj EH may return values in these registers
12452   // via the personality function.
12453   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12454 }
12455 
12456 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12457   // Update IsSplitCSR in ARMFunctionInfo.
12458   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
12459   AFI->setIsSplitCSR(true);
12460 }
12461 
12462 void ARMTargetLowering::insertCopiesSplitCSR(
12463     MachineBasicBlock *Entry,
12464     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12465   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
12466   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12467   if (!IStart)
12468     return;
12469 
12470   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12471   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12472   MachineBasicBlock::iterator MBBI = Entry->begin();
12473   for (const MCPhysReg *I = IStart; *I; ++I) {
12474     const TargetRegisterClass *RC = nullptr;
12475     if (ARM::GPRRegClass.contains(*I))
12476       RC = &ARM::GPRRegClass;
12477     else if (ARM::DPRRegClass.contains(*I))
12478       RC = &ARM::DPRRegClass;
12479     else
12480       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12481 
12482     unsigned NewVR = MRI->createVirtualRegister(RC);
12483     // Create copy from CSR to a virtual register.
12484     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12485     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12486     // nounwind. If we want to generalize this later, we may need to emit
12487     // CFI pseudo-instructions.
12488     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12489                Attribute::NoUnwind) &&
12490            "Function should be nounwind in insertCopiesSplitCSR!");
12491     Entry->addLiveIn(*I);
12492     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12493         .addReg(*I);
12494 
12495     // Insert the copy-back instructions right before the terminator.
12496     for (auto *Exit : Exits)
12497       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12498               TII->get(TargetOpcode::COPY), *I)
12499           .addReg(NewVR);
12500   }
12501 }
12502