3a4f788c84844682611d9278ce33105bff8b9631
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <utility>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "arm-isel"
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 cl::opt<bool>
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61   cl::desc("Generate calls via indirect call instructions"),
62   cl::init(false));
63
64 static cl::opt<bool>
65 ARMInterworking("arm-interworking", cl::Hidden,
66   cl::desc("Enable / disable ARM interworking (for debugging only)"),
67   cl::init(true));
68
69 namespace {
70   class ARMCCState : public CCState {
71   public:
72     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74                ParmContext PC)
75         : CCState(CC, isVarArg, MF, locs, C) {
76       assert(((PC == Call) || (PC == Prologue)) &&
77              "ARMCCState users must specify whether their context is call"
78              "or prologue generation.");
79       CallOrPrologue = PC;
80     }
81   };
82 }
83
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86   ARM::R0, ARM::R1, ARM::R2, ARM::R3
87 };
88
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90                                        MVT PromotedBitwiseVT) {
91   if (VT != PromotedLdStVT) {
92     setOperationAction(ISD::LOAD, VT, Promote);
93     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94
95     setOperationAction(ISD::STORE, VT, Promote);
96     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
97   }
98
99   MVT ElemTy = VT.getVectorElementType();
100   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101     setOperationAction(ISD::SETCC, VT, Custom);
102   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104   if (ElemTy == MVT::i32) {
105     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109   } else {
110     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114   }
115   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
116   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
117   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
118   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119   setOperationAction(ISD::SELECT,            VT, Expand);
120   setOperationAction(ISD::SELECT_CC,         VT, Expand);
121   setOperationAction(ISD::VSELECT,           VT, Expand);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT, Custom);
125     setOperationAction(ISD::SRA, VT, Custom);
126     setOperationAction(ISD::SRL, VT, Custom);
127   }
128
129   // Promote all bit-wise operations.
130   if (VT.isInteger() && VT != PromotedBitwiseVT) {
131     setOperationAction(ISD::AND, VT, Promote);
132     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133     setOperationAction(ISD::OR,  VT, Promote);
134     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
135     setOperationAction(ISD::XOR, VT, Promote);
136     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
137   }
138
139   // Neon does not support vector divide/remainder operations.
140   setOperationAction(ISD::SDIV, VT, Expand);
141   setOperationAction(ISD::UDIV, VT, Expand);
142   setOperationAction(ISD::FDIV, VT, Expand);
143   setOperationAction(ISD::SREM, VT, Expand);
144   setOperationAction(ISD::UREM, VT, Expand);
145   setOperationAction(ISD::FREM, VT, Expand);
146 }
147
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149   addRegisterClass(VT, &ARM::DPRRegClass);
150   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
151 }
152
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPairRegClass);
155   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
156 }
157
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159   if (TT.isOSBinFormatMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TT.isOSWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
170   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
171
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   if (Subtarget->isTargetMachO()) {
175     // Uses VFP for Thumb libfuncs if available.
176     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178       // Single-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183
184       // Double-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189
190       // Single-precision comparisons.
191       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
198       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
199
200       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
207       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
208
209       // Double-precision comparisons.
210       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
217       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
218
219       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
226       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
227
228       // Floating-point to integer conversions.
229       // i64 conversions are done via library routines even when generating VFP
230       // instructions, so use the same ones.
231       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235
236       // Conversions between floating types.
237       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
239
240       // Integer to floating-point conversions.
241       // i64 conversions are done via library routines even when generating VFP
242       // instructions, so use the same ones.
243       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244       // e.g., __floatunsidf vs. __floatunssidfvfp.
245       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
249     }
250   }
251
252   // These libcalls are not available in 32-bit.
253   setLibcallName(RTLIB::SHL_I128, nullptr);
254   setLibcallName(RTLIB::SRL_I128, nullptr);
255   setLibcallName(RTLIB::SRA_I128, nullptr);
256
257   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258       !Subtarget->isTargetWindows()) {
259     static const struct {
260       const RTLIB::Libcall Op;
261       const char * const Name;
262       const CallingConv::ID CC;
263       const ISD::CondCode Cond;
264     } LibraryCalls[] = {
265       // Double-precision floating-point arithmetic helper functions
266       // RTABI chapter 4.1.2, Table 2
267       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271
272       // Double-precision floating-point comparison helper functions
273       // RTABI chapter 4.1.2, Table 3
274       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
282
283       // Single-precision floating-point arithmetic helper functions
284       // RTABI chapter 4.1.2, Table 4
285       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289
290       // Single-precision floating-point comparison helper functions
291       // RTABI chapter 4.1.2, Table 5
292       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
300
301       // Floating-point to integer conversions.
302       // RTABI chapter 4.1.2, Table 6
303       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Conversions between floating types.
313       // RTABI chapter 4.1.2, Table 7
314       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317
318       // Integer to floating-point conversions.
319       // RTABI chapter 4.1.2, Table 8
320       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328
329       // Long long helper functions
330       // RTABI chapter 4.2, Table 9
331       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335
336       // Integer division functions
337       // RTABI chapter 4.3.1
338       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346
347       // Memory operations
348       // RTABI chapter 4.3.4
349       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352     };
353
354     for (const auto &LC : LibraryCalls) {
355       setLibcallName(LC.Op, LC.Name);
356       setLibcallCallingConv(LC.Op, LC.CC);
357       if (LC.Cond != ISD::SETCC_INVALID)
358         setCmpLibcallCC(LC.Op, LC.Cond);
359     }
360   }
361
362   if (Subtarget->isTargetWindows()) {
363     static const struct {
364       const RTLIB::Libcall Op;
365       const char * const Name;
366       const CallingConv::ID CC;
367     } LibraryCalls[] = {
368       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
376     };
377
378     for (const auto &LC : LibraryCalls) {
379       setLibcallName(LC.Op, LC.Name);
380       setLibcallCallingConv(LC.Op, LC.CC);
381     }
382   }
383
384   // Use divmod compiler-rt calls for iOS 5.0 and later.
385   if (Subtarget->getTargetTriple().isiOS() &&
386       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
389   }
390
391   if (Subtarget->isThumb1Only())
392     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
393   else
394     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
395   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
396       !Subtarget->isThumb1Only()) {
397     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
398     if (!Subtarget->isFPOnlySP())
399       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
400   }
401
402   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
403        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
404     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
405          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
406       setTruncStoreAction((MVT::SimpleValueType)VT,
407                           (MVT::SimpleValueType)InnerVT, Expand);
408     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
409     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
411
412     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
413     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
415     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
416
417     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
418   }
419
420   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
421   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
422
423   if (Subtarget->hasNEON()) {
424     addDRTypeForNEON(MVT::v2f32);
425     addDRTypeForNEON(MVT::v8i8);
426     addDRTypeForNEON(MVT::v4i16);
427     addDRTypeForNEON(MVT::v2i32);
428     addDRTypeForNEON(MVT::v1i64);
429
430     addQRTypeForNEON(MVT::v4f32);
431     addQRTypeForNEON(MVT::v2f64);
432     addQRTypeForNEON(MVT::v16i8);
433     addQRTypeForNEON(MVT::v8i16);
434     addQRTypeForNEON(MVT::v4i32);
435     addQRTypeForNEON(MVT::v2i64);
436
437     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
438     // neither Neon nor VFP support any arithmetic operations on it.
439     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
440     // supported for v4f32.
441     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
442     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
443     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
444     // FIXME: Code duplication: FDIV and FREM are expanded always, see
445     // ARMTargetLowering::addTypeForNEON method for details.
446     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
447     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
448     // FIXME: Create unittest.
449     // In another words, find a way when "copysign" appears in DAG with vector
450     // operands.
451     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
452     // FIXME: Code duplication: SETCC has custom operation action, see
453     // ARMTargetLowering::addTypeForNEON method for details.
454     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
455     // FIXME: Create unittest for FNEG and for FABS.
456     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
457     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
458     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
459     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
460     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
461     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
462     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
463     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
465     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
466     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
467     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
469     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
470     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
471     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
474     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
475
476     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
477     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
478     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
479     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
480     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
481     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
483     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
484     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
485     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
486     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
487     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
488     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
489     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
491
492     // Mark v2f32 intrinsics.
493     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
494     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
495     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
496     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
497     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
498     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
500     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
501     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
502     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
503     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
504     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
505     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
506     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
508
509     // Neon does not support some operations on v1i64 and v2i64 types.
510     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
511     // Custom handling for some quad-vector types to detect VMULL.
512     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
513     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
515     // Custom handling for some vector types to avoid expensive expansions
516     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
517     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
518     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
519     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
520     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
521     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
522     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
523     // a destination type that is wider than the source, and nor does
524     // it have a FP_TO_[SU]INT instruction with a narrower destination than
525     // source.
526     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
527     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
528     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
529     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
530
531     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
532     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
533
534     // NEON does not have single instruction CTPOP for vectors with element
535     // types wider than 8-bits.  However, custom lowering can leverage the
536     // v8i8/v16i8 vcnt instruction.
537     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
538     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
540     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
541
542     // NEON only has FMA instructions as of VFP4.
543     if (!Subtarget->hasVFP4()) {
544       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
545       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
546     }
547
548     setTargetDAGCombine(ISD::INTRINSIC_VOID);
549     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
550     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
551     setTargetDAGCombine(ISD::SHL);
552     setTargetDAGCombine(ISD::SRL);
553     setTargetDAGCombine(ISD::SRA);
554     setTargetDAGCombine(ISD::SIGN_EXTEND);
555     setTargetDAGCombine(ISD::ZERO_EXTEND);
556     setTargetDAGCombine(ISD::ANY_EXTEND);
557     setTargetDAGCombine(ISD::SELECT_CC);
558     setTargetDAGCombine(ISD::BUILD_VECTOR);
559     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
560     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
561     setTargetDAGCombine(ISD::STORE);
562     setTargetDAGCombine(ISD::FP_TO_SINT);
563     setTargetDAGCombine(ISD::FP_TO_UINT);
564     setTargetDAGCombine(ISD::FDIV);
565
566     // It is legal to extload from v4i8 to v4i16 or v4i32.
567     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
568                   MVT::v4i16, MVT::v2i16,
569                   MVT::v2i32};
570     for (unsigned i = 0; i < 6; ++i) {
571       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
572       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
574     }
575   }
576
577   // ARM and Thumb2 support UMLAL/SMLAL.
578   if (!Subtarget->isThumb1Only())
579     setTargetDAGCombine(ISD::ADDC);
580
581
582   computeRegisterProperties();
583
584   // ARM does not have floating-point extending loads.
585   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
586   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
587
588   // ... or truncating stores
589   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
590   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
591   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
592
593   // ARM does not have i1 sign extending load.
594   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
595
596   // ARM supports all 4 flavors of integer indexed load / store.
597   if (!Subtarget->isThumb1Only()) {
598     for (unsigned im = (unsigned)ISD::PRE_INC;
599          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
600       setIndexedLoadAction(im,  MVT::i1,  Legal);
601       setIndexedLoadAction(im,  MVT::i8,  Legal);
602       setIndexedLoadAction(im,  MVT::i16, Legal);
603       setIndexedLoadAction(im,  MVT::i32, Legal);
604       setIndexedStoreAction(im, MVT::i1,  Legal);
605       setIndexedStoreAction(im, MVT::i8,  Legal);
606       setIndexedStoreAction(im, MVT::i16, Legal);
607       setIndexedStoreAction(im, MVT::i32, Legal);
608     }
609   }
610
611   setOperationAction(ISD::SADDO, MVT::i32, Custom);
612   setOperationAction(ISD::UADDO, MVT::i32, Custom);
613   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
614   setOperationAction(ISD::USUBO, MVT::i32, Custom);
615
616   // i64 operation support.
617   setOperationAction(ISD::MUL,     MVT::i64, Expand);
618   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
619   if (Subtarget->isThumb1Only()) {
620     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
621     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
622   }
623   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
624       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
625     setOperationAction(ISD::MULHS, MVT::i32, Expand);
626
627   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
628   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
629   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
630   setOperationAction(ISD::SRL,       MVT::i64, Custom);
631   setOperationAction(ISD::SRA,       MVT::i64, Custom);
632
633   if (!Subtarget->isThumb1Only()) {
634     // FIXME: We should do this for Thumb1 as well.
635     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
636     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
637     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
638     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
639   }
640
641   // ARM does not have ROTL.
642   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
643   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
644   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
645   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
646     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
647
648   // These just redirect to CTTZ and CTLZ on ARM.
649   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
650   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
651
652   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
653
654   // Only ARMv6 has BSWAP.
655   if (!Subtarget->hasV6Ops())
656     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
657
658   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
659       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
660     // These are expanded into libcalls if the cpu doesn't have HW divider.
661     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
662     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
663   }
664
665   // FIXME: Also set divmod for SREM on EABI
666   setOperationAction(ISD::SREM,  MVT::i32, Expand);
667   setOperationAction(ISD::UREM,  MVT::i32, Expand);
668   // Register based DivRem for AEABI (RTABI 4.2)
669   if (Subtarget->isTargetAEABI()) {
670     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
671     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
672     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
673     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
674     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
675     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
676     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
677     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
678
679     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
680     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
682     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
683     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
684     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
685     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
686     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
687
688     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
689     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
690   } else {
691     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
692     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
693   }
694
695   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
696   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
697   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
698   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
699   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
700
701   setOperationAction(ISD::TRAP, MVT::Other, Legal);
702
703   // Use the default implementation.
704   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
705   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
706   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
707   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
708   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
709   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
710
711   if (!Subtarget->isTargetMachO()) {
712     // Non-MachO platforms may return values in these registers via the
713     // personality function.
714     setExceptionPointerRegister(ARM::R0);
715     setExceptionSelectorRegister(ARM::R1);
716   }
717
718   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
719     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
720   else
721     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
722
723   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
724   // the default expansion.
725   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
726     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
727     // to ldrex/strex loops already.
728     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
729
730     // On v8, we have particularly efficient implementations of atomic fences
731     // if they can be combined with nearby atomic loads and stores.
732     if (!Subtarget->hasV8Ops()) {
733       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
734       setInsertFencesForAtomic(true);
735     }
736   } else {
737     // If there's anything we can use as a barrier, go through custom lowering
738     // for ATOMIC_FENCE.
739     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
740                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
741
742     // Set them all for expansion, which will force libcalls.
743     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
744     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
746     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
747     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
748     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
749     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
750     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
751     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
752     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
755     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
756     // Unordered/Monotonic case.
757     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
758     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
759   }
760
761   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
762
763   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
764   if (!Subtarget->hasV6Ops()) {
765     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
766     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
767   }
768   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
769
770   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
771       !Subtarget->isThumb1Only()) {
772     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
773     // iff target supports vfp2.
774     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
775     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
776   }
777
778   // We want to custom lower some of our intrinsics.
779   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
780   if (Subtarget->isTargetDarwin()) {
781     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
782     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
783     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
784   }
785
786   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
787   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
788   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
789   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
790   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
791   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
792   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
793   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
794   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
795
796   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
797   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
798   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
799   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
800   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
801
802   // We don't support sin/cos/fmod/copysign/pow
803   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
804   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
805   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
806   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
807   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
808   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
809   setOperationAction(ISD::FREM,      MVT::f64, Expand);
810   setOperationAction(ISD::FREM,      MVT::f32, Expand);
811   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
812       !Subtarget->isThumb1Only()) {
813     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
814     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
815   }
816   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
817   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
818
819   if (!Subtarget->hasVFP4()) {
820     setOperationAction(ISD::FMA, MVT::f64, Expand);
821     setOperationAction(ISD::FMA, MVT::f32, Expand);
822   }
823
824   // Various VFP goodness
825   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
826     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
827     if (Subtarget->hasVFP2()) {
828       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
829       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
830       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
831       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
832     }
833
834     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
835     if (!Subtarget->hasV8Ops()) {
836       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
837       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
838     }
839
840     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
841     if (!Subtarget->hasFP16()) {
842       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
843       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
844     }
845   }
846
847   // Combine sin / cos into one node or libcall if possible.
848   if (Subtarget->hasSinCos()) {
849     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
850     setLibcallName(RTLIB::SINCOS_F64, "sincos");
851     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
852       // For iOS, we don't want to the normal expansion of a libcall to
853       // sincos. We want to issue a libcall to __sincos_stret.
854       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
855       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
856     }
857   }
858
859   // We have target-specific dag combine patterns for the following nodes:
860   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
861   setTargetDAGCombine(ISD::ADD);
862   setTargetDAGCombine(ISD::SUB);
863   setTargetDAGCombine(ISD::MUL);
864   setTargetDAGCombine(ISD::AND);
865   setTargetDAGCombine(ISD::OR);
866   setTargetDAGCombine(ISD::XOR);
867
868   if (Subtarget->hasV6Ops())
869     setTargetDAGCombine(ISD::SRL);
870
871   setStackPointerRegisterToSaveRestore(ARM::SP);
872
873   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
874       !Subtarget->hasVFP2())
875     setSchedulingPreference(Sched::RegPressure);
876   else
877     setSchedulingPreference(Sched::Hybrid);
878
879   //// temporary - rewrite interface to use type
880   MaxStoresPerMemset = 8;
881   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
882   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
883   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
884   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
885   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
886
887   // On ARM arguments smaller than 4 bytes are extended, so all arguments
888   // are at least 4 bytes aligned.
889   setMinStackArgumentAlignment(4);
890
891   // Prefer likely predicted branches to selects on out-of-order cores.
892   PredictableSelectIsExpensive = Subtarget->isLikeA9();
893
894   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
895 }
896
897 // FIXME: It might make sense to define the representative register class as the
898 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
899 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
900 // SPR's representative would be DPR_VFP2. This should work well if register
901 // pressure tracking were modified such that a register use would increment the
902 // pressure of the register class's representative and all of it's super
903 // classes' representatives transitively. We have not implemented this because
904 // of the difficulty prior to coalescing of modeling operand register classes
905 // due to the common occurrence of cross class copies and subregister insertions
906 // and extractions.
907 std::pair<const TargetRegisterClass*, uint8_t>
908 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
909   const TargetRegisterClass *RRC = nullptr;
910   uint8_t Cost = 1;
911   switch (VT.SimpleTy) {
912   default:
913     return TargetLowering::findRepresentativeClass(VT);
914   // Use DPR as representative register class for all floating point
915   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
916   // the cost is 1 for both f32 and f64.
917   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
918   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
919     RRC = &ARM::DPRRegClass;
920     // When NEON is used for SP, only half of the register file is available
921     // because operations that define both SP and DP results will be constrained
922     // to the VFP2 class (D0-D15). We currently model this constraint prior to
923     // coalescing by double-counting the SP regs. See the FIXME above.
924     if (Subtarget->useNEONForSinglePrecisionFP())
925       Cost = 2;
926     break;
927   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
928   case MVT::v4f32: case MVT::v2f64:
929     RRC = &ARM::DPRRegClass;
930     Cost = 2;
931     break;
932   case MVT::v4i64:
933     RRC = &ARM::DPRRegClass;
934     Cost = 4;
935     break;
936   case MVT::v8i64:
937     RRC = &ARM::DPRRegClass;
938     Cost = 8;
939     break;
940   }
941   return std::make_pair(RRC, Cost);
942 }
943
944 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
945   switch (Opcode) {
946   default: return nullptr;
947   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
948   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
949   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
950   case ARMISD::CALL:          return "ARMISD::CALL";
951   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
952   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
953   case ARMISD::tCALL:         return "ARMISD::tCALL";
954   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
955   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
956   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
957   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
958   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
959   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
960   case ARMISD::CMP:           return "ARMISD::CMP";
961   case ARMISD::CMN:           return "ARMISD::CMN";
962   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
963   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
964   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
965   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
966   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
967
968   case ARMISD::CMOV:          return "ARMISD::CMOV";
969
970   case ARMISD::RBIT:          return "ARMISD::RBIT";
971
972   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
973   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
974   case ARMISD::SITOF:         return "ARMISD::SITOF";
975   case ARMISD::UITOF:         return "ARMISD::UITOF";
976
977   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
978   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
979   case ARMISD::RRX:           return "ARMISD::RRX";
980
981   case ARMISD::ADDC:          return "ARMISD::ADDC";
982   case ARMISD::ADDE:          return "ARMISD::ADDE";
983   case ARMISD::SUBC:          return "ARMISD::SUBC";
984   case ARMISD::SUBE:          return "ARMISD::SUBE";
985
986   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
987   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
988
989   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
990   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
991
992   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
993
994   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
995
996   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
997
998   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
999
1000   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1001
1002   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1003
1004   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1005   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1006   case ARMISD::VCGE:          return "ARMISD::VCGE";
1007   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1008   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1009   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1010   case ARMISD::VCGT:          return "ARMISD::VCGT";
1011   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1012   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1013   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1014   case ARMISD::VTST:          return "ARMISD::VTST";
1015
1016   case ARMISD::VSHL:          return "ARMISD::VSHL";
1017   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1018   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1019   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1020   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1021   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1022   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1023   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1024   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1025   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1026   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1027   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1028   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1029   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1030   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1031   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1032   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1033   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1034   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1035   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1036   case ARMISD::VDUP:          return "ARMISD::VDUP";
1037   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1038   case ARMISD::VEXT:          return "ARMISD::VEXT";
1039   case ARMISD::VREV64:        return "ARMISD::VREV64";
1040   case ARMISD::VREV32:        return "ARMISD::VREV32";
1041   case ARMISD::VREV16:        return "ARMISD::VREV16";
1042   case ARMISD::VZIP:          return "ARMISD::VZIP";
1043   case ARMISD::VUZP:          return "ARMISD::VUZP";
1044   case ARMISD::VTRN:          return "ARMISD::VTRN";
1045   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1046   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1047   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1048   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1049   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1050   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1051   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1052   case ARMISD::FMAX:          return "ARMISD::FMAX";
1053   case ARMISD::FMIN:          return "ARMISD::FMIN";
1054   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1055   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1056   case ARMISD::BFI:           return "ARMISD::BFI";
1057   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1058   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1059   case ARMISD::VBSL:          return "ARMISD::VBSL";
1060   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1061   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1062   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1063   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1064   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1065   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1066   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1067   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1068   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1069   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1070   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1071   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1072   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1073   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1074   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1075   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1076   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1077   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1078   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1079   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1080   }
1081 }
1082
1083 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1084   if (!VT.isVector()) return getPointerTy();
1085   return VT.changeVectorElementTypeToInteger();
1086 }
1087
1088 /// getRegClassFor - Return the register class that should be used for the
1089 /// specified value type.
1090 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1091   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1092   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1093   // load / store 4 to 8 consecutive D registers.
1094   if (Subtarget->hasNEON()) {
1095     if (VT == MVT::v4i64)
1096       return &ARM::QQPRRegClass;
1097     if (VT == MVT::v8i64)
1098       return &ARM::QQQQPRRegClass;
1099   }
1100   return TargetLowering::getRegClassFor(VT);
1101 }
1102
1103 // Create a fast isel object.
1104 FastISel *
1105 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1106                                   const TargetLibraryInfo *libInfo) const {
1107   return ARM::createFastISel(funcInfo, libInfo);
1108 }
1109
1110 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1111 /// be used for loads / stores from the global.
1112 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1113   return (Subtarget->isThumb1Only() ? 127 : 4095);
1114 }
1115
1116 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1117   unsigned NumVals = N->getNumValues();
1118   if (!NumVals)
1119     return Sched::RegPressure;
1120
1121   for (unsigned i = 0; i != NumVals; ++i) {
1122     EVT VT = N->getValueType(i);
1123     if (VT == MVT::Glue || VT == MVT::Other)
1124       continue;
1125     if (VT.isFloatingPoint() || VT.isVector())
1126       return Sched::ILP;
1127   }
1128
1129   if (!N->isMachineOpcode())
1130     return Sched::RegPressure;
1131
1132   // Load are scheduled for latency even if there instruction itinerary
1133   // is not available.
1134   const TargetInstrInfo *TII =
1135       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1136   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1137
1138   if (MCID.getNumDefs() == 0)
1139     return Sched::RegPressure;
1140   if (!Itins->isEmpty() &&
1141       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1142     return Sched::ILP;
1143
1144   return Sched::RegPressure;
1145 }
1146
1147 //===----------------------------------------------------------------------===//
1148 // Lowering Code
1149 //===----------------------------------------------------------------------===//
1150
1151 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1152 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1153   switch (CC) {
1154   default: llvm_unreachable("Unknown condition code!");
1155   case ISD::SETNE:  return ARMCC::NE;
1156   case ISD::SETEQ:  return ARMCC::EQ;
1157   case ISD::SETGT:  return ARMCC::GT;
1158   case ISD::SETGE:  return ARMCC::GE;
1159   case ISD::SETLT:  return ARMCC::LT;
1160   case ISD::SETLE:  return ARMCC::LE;
1161   case ISD::SETUGT: return ARMCC::HI;
1162   case ISD::SETUGE: return ARMCC::HS;
1163   case ISD::SETULT: return ARMCC::LO;
1164   case ISD::SETULE: return ARMCC::LS;
1165   }
1166 }
1167
1168 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1169 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1170                         ARMCC::CondCodes &CondCode2) {
1171   CondCode2 = ARMCC::AL;
1172   switch (CC) {
1173   default: llvm_unreachable("Unknown FP condition!");
1174   case ISD::SETEQ:
1175   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1176   case ISD::SETGT:
1177   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1178   case ISD::SETGE:
1179   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1180   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1181   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1182   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1183   case ISD::SETO:   CondCode = ARMCC::VC; break;
1184   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1185   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1186   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1187   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1188   case ISD::SETLT:
1189   case ISD::SETULT: CondCode = ARMCC::LT; break;
1190   case ISD::SETLE:
1191   case ISD::SETULE: CondCode = ARMCC::LE; break;
1192   case ISD::SETNE:
1193   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1194   }
1195 }
1196
1197 //===----------------------------------------------------------------------===//
1198 //                      Calling Convention Implementation
1199 //===----------------------------------------------------------------------===//
1200
1201 #include "ARMGenCallingConv.inc"
1202
1203 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1204 /// account presence of floating point hardware and calling convention
1205 /// limitations, such as support for variadic functions.
1206 CallingConv::ID
1207 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1208                                            bool isVarArg) const {
1209   switch (CC) {
1210   default:
1211     llvm_unreachable("Unsupported calling convention");
1212   case CallingConv::ARM_AAPCS:
1213   case CallingConv::ARM_APCS:
1214   case CallingConv::GHC:
1215     return CC;
1216   case CallingConv::ARM_AAPCS_VFP:
1217     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1218   case CallingConv::C:
1219     if (!Subtarget->isAAPCS_ABI())
1220       return CallingConv::ARM_APCS;
1221     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1222              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1223              !isVarArg)
1224       return CallingConv::ARM_AAPCS_VFP;
1225     else
1226       return CallingConv::ARM_AAPCS;
1227   case CallingConv::Fast:
1228     if (!Subtarget->isAAPCS_ABI()) {
1229       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1230         return CallingConv::Fast;
1231       return CallingConv::ARM_APCS;
1232     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1233       return CallingConv::ARM_AAPCS_VFP;
1234     else
1235       return CallingConv::ARM_AAPCS;
1236   }
1237 }
1238
1239 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1240 /// CallingConvention.
1241 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1242                                                  bool Return,
1243                                                  bool isVarArg) const {
1244   switch (getEffectiveCallingConv(CC, isVarArg)) {
1245   default:
1246     llvm_unreachable("Unsupported calling convention");
1247   case CallingConv::ARM_APCS:
1248     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1249   case CallingConv::ARM_AAPCS:
1250     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1251   case CallingConv::ARM_AAPCS_VFP:
1252     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1253   case CallingConv::Fast:
1254     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1255   case CallingConv::GHC:
1256     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1257   }
1258 }
1259
1260 /// LowerCallResult - Lower the result values of a call into the
1261 /// appropriate copies out of appropriate physical registers.
1262 SDValue
1263 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1264                                    CallingConv::ID CallConv, bool isVarArg,
1265                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1266                                    SDLoc dl, SelectionDAG &DAG,
1267                                    SmallVectorImpl<SDValue> &InVals,
1268                                    bool isThisReturn, SDValue ThisVal) const {
1269
1270   // Assign locations to each value returned by this call.
1271   SmallVector<CCValAssign, 16> RVLocs;
1272   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1273                     *DAG.getContext(), Call);
1274   CCInfo.AnalyzeCallResult(Ins,
1275                            CCAssignFnForNode(CallConv, /* Return*/ true,
1276                                              isVarArg));
1277
1278   // Copy all of the result registers out of their specified physreg.
1279   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1280     CCValAssign VA = RVLocs[i];
1281
1282     // Pass 'this' value directly from the argument to return value, to avoid
1283     // reg unit interference
1284     if (i == 0 && isThisReturn) {
1285       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1286              "unexpected return calling convention register assignment");
1287       InVals.push_back(ThisVal);
1288       continue;
1289     }
1290
1291     SDValue Val;
1292     if (VA.needsCustom()) {
1293       // Handle f64 or half of a v2f64.
1294       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1295                                       InFlag);
1296       Chain = Lo.getValue(1);
1297       InFlag = Lo.getValue(2);
1298       VA = RVLocs[++i]; // skip ahead to next loc
1299       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1300                                       InFlag);
1301       Chain = Hi.getValue(1);
1302       InFlag = Hi.getValue(2);
1303       if (!Subtarget->isLittle())
1304         std::swap (Lo, Hi);
1305       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1306
1307       if (VA.getLocVT() == MVT::v2f64) {
1308         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1309         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1310                           DAG.getConstant(0, MVT::i32));
1311
1312         VA = RVLocs[++i]; // skip ahead to next loc
1313         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1314         Chain = Lo.getValue(1);
1315         InFlag = Lo.getValue(2);
1316         VA = RVLocs[++i]; // skip ahead to next loc
1317         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1318         Chain = Hi.getValue(1);
1319         InFlag = Hi.getValue(2);
1320         if (!Subtarget->isLittle())
1321           std::swap (Lo, Hi);
1322         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1323         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1324                           DAG.getConstant(1, MVT::i32));
1325       }
1326     } else {
1327       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1328                                InFlag);
1329       Chain = Val.getValue(1);
1330       InFlag = Val.getValue(2);
1331     }
1332
1333     switch (VA.getLocInfo()) {
1334     default: llvm_unreachable("Unknown loc info!");
1335     case CCValAssign::Full: break;
1336     case CCValAssign::BCvt:
1337       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1338       break;
1339     }
1340
1341     InVals.push_back(Val);
1342   }
1343
1344   return Chain;
1345 }
1346
1347 /// LowerMemOpCallTo - Store the argument to the stack.
1348 SDValue
1349 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1350                                     SDValue StackPtr, SDValue Arg,
1351                                     SDLoc dl, SelectionDAG &DAG,
1352                                     const CCValAssign &VA,
1353                                     ISD::ArgFlagsTy Flags) const {
1354   unsigned LocMemOffset = VA.getLocMemOffset();
1355   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1356   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1357   return DAG.getStore(Chain, dl, Arg, PtrOff,
1358                       MachinePointerInfo::getStack(LocMemOffset),
1359                       false, false, 0);
1360 }
1361
1362 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1363                                          SDValue Chain, SDValue &Arg,
1364                                          RegsToPassVector &RegsToPass,
1365                                          CCValAssign &VA, CCValAssign &NextVA,
1366                                          SDValue &StackPtr,
1367                                          SmallVectorImpl<SDValue> &MemOpChains,
1368                                          ISD::ArgFlagsTy Flags) const {
1369
1370   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1371                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1372   unsigned id = Subtarget->isLittle() ? 0 : 1;
1373   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1374
1375   if (NextVA.isRegLoc())
1376     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1377   else {
1378     assert(NextVA.isMemLoc());
1379     if (!StackPtr.getNode())
1380       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1381
1382     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1383                                            dl, DAG, NextVA,
1384                                            Flags));
1385   }
1386 }
1387
1388 /// LowerCall - Lowering a call into a callseq_start <-
1389 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1390 /// nodes.
1391 SDValue
1392 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1393                              SmallVectorImpl<SDValue> &InVals) const {
1394   SelectionDAG &DAG                     = CLI.DAG;
1395   SDLoc &dl                          = CLI.DL;
1396   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1397   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1398   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1399   SDValue Chain                         = CLI.Chain;
1400   SDValue Callee                        = CLI.Callee;
1401   bool &isTailCall                      = CLI.IsTailCall;
1402   CallingConv::ID CallConv              = CLI.CallConv;
1403   bool doesNotRet                       = CLI.DoesNotReturn;
1404   bool isVarArg                         = CLI.IsVarArg;
1405
1406   MachineFunction &MF = DAG.getMachineFunction();
1407   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1408   bool isThisReturn   = false;
1409   bool isSibCall      = false;
1410
1411   // Disable tail calls if they're not supported.
1412   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1413     isTailCall = false;
1414
1415   if (isTailCall) {
1416     // Check if it's really possible to do a tail call.
1417     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1418                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1419                                                    Outs, OutVals, Ins, DAG);
1420     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1421       report_fatal_error("failed to perform tail call elimination on a call "
1422                          "site marked musttail");
1423     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1424     // detected sibcalls.
1425     if (isTailCall) {
1426       ++NumTailCalls;
1427       isSibCall = true;
1428     }
1429   }
1430
1431   // Analyze operands of the call, assigning locations to each operand.
1432   SmallVector<CCValAssign, 16> ArgLocs;
1433   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1434                     *DAG.getContext(), Call);
1435   CCInfo.AnalyzeCallOperands(Outs,
1436                              CCAssignFnForNode(CallConv, /* Return*/ false,
1437                                                isVarArg));
1438
1439   // Get a count of how many bytes are to be pushed on the stack.
1440   unsigned NumBytes = CCInfo.getNextStackOffset();
1441
1442   // For tail calls, memory operands are available in our caller's stack.
1443   if (isSibCall)
1444     NumBytes = 0;
1445
1446   // Adjust the stack pointer for the new arguments...
1447   // These operations are automatically eliminated by the prolog/epilog pass
1448   if (!isSibCall)
1449     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1450                                  dl);
1451
1452   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1453
1454   RegsToPassVector RegsToPass;
1455   SmallVector<SDValue, 8> MemOpChains;
1456
1457   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1458   // of tail call optimization, arguments are handled later.
1459   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1460        i != e;
1461        ++i, ++realArgIdx) {
1462     CCValAssign &VA = ArgLocs[i];
1463     SDValue Arg = OutVals[realArgIdx];
1464     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1465     bool isByVal = Flags.isByVal();
1466
1467     // Promote the value if needed.
1468     switch (VA.getLocInfo()) {
1469     default: llvm_unreachable("Unknown loc info!");
1470     case CCValAssign::Full: break;
1471     case CCValAssign::SExt:
1472       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1473       break;
1474     case CCValAssign::ZExt:
1475       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1476       break;
1477     case CCValAssign::AExt:
1478       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1479       break;
1480     case CCValAssign::BCvt:
1481       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1482       break;
1483     }
1484
1485     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1486     if (VA.needsCustom()) {
1487       if (VA.getLocVT() == MVT::v2f64) {
1488         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1489                                   DAG.getConstant(0, MVT::i32));
1490         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1491                                   DAG.getConstant(1, MVT::i32));
1492
1493         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1494                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1495
1496         VA = ArgLocs[++i]; // skip ahead to next loc
1497         if (VA.isRegLoc()) {
1498           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1499                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1500         } else {
1501           assert(VA.isMemLoc());
1502
1503           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1504                                                  dl, DAG, VA, Flags));
1505         }
1506       } else {
1507         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1508                          StackPtr, MemOpChains, Flags);
1509       }
1510     } else if (VA.isRegLoc()) {
1511       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1512         assert(VA.getLocVT() == MVT::i32 &&
1513                "unexpected calling convention register assignment");
1514         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1515                "unexpected use of 'returned'");
1516         isThisReturn = true;
1517       }
1518       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1519     } else if (isByVal) {
1520       assert(VA.isMemLoc());
1521       unsigned offset = 0;
1522
1523       // True if this byval aggregate will be split between registers
1524       // and memory.
1525       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1526       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1527
1528       if (CurByValIdx < ByValArgsCount) {
1529
1530         unsigned RegBegin, RegEnd;
1531         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1532
1533         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1534         unsigned int i, j;
1535         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1536           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1537           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1538           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1539                                      MachinePointerInfo(),
1540                                      false, false, false,
1541                                      DAG.InferPtrAlignment(AddArg));
1542           MemOpChains.push_back(Load.getValue(1));
1543           RegsToPass.push_back(std::make_pair(j, Load));
1544         }
1545
1546         // If parameter size outsides register area, "offset" value
1547         // helps us to calculate stack slot for remained part properly.
1548         offset = RegEnd - RegBegin;
1549
1550         CCInfo.nextInRegsParam();
1551       }
1552
1553       if (Flags.getByValSize() > 4*offset) {
1554         unsigned LocMemOffset = VA.getLocMemOffset();
1555         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1556         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1557                                   StkPtrOff);
1558         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1559         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1560         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1561                                            MVT::i32);
1562         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1563
1564         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1565         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1566         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1567                                           Ops));
1568       }
1569     } else if (!isSibCall) {
1570       assert(VA.isMemLoc());
1571
1572       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1573                                              dl, DAG, VA, Flags));
1574     }
1575   }
1576
1577   if (!MemOpChains.empty())
1578     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1579
1580   // Build a sequence of copy-to-reg nodes chained together with token chain
1581   // and flag operands which copy the outgoing args into the appropriate regs.
1582   SDValue InFlag;
1583   // Tail call byval lowering might overwrite argument registers so in case of
1584   // tail call optimization the copies to registers are lowered later.
1585   if (!isTailCall)
1586     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1587       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1588                                RegsToPass[i].second, InFlag);
1589       InFlag = Chain.getValue(1);
1590     }
1591
1592   // For tail calls lower the arguments to the 'real' stack slot.
1593   if (isTailCall) {
1594     // Force all the incoming stack arguments to be loaded from the stack
1595     // before any new outgoing arguments are stored to the stack, because the
1596     // outgoing stack slots may alias the incoming argument stack slots, and
1597     // the alias isn't otherwise explicit. This is slightly more conservative
1598     // than necessary, because it means that each store effectively depends
1599     // on every argument instead of just those arguments it would clobber.
1600
1601     // Do not flag preceding copytoreg stuff together with the following stuff.
1602     InFlag = SDValue();
1603     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1604       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1605                                RegsToPass[i].second, InFlag);
1606       InFlag = Chain.getValue(1);
1607     }
1608     InFlag = SDValue();
1609   }
1610
1611   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1612   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1613   // node so that legalize doesn't hack it.
1614   bool isDirect = false;
1615   bool isARMFunc = false;
1616   bool isLocalARMFunc = false;
1617   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1618
1619   if (EnableARMLongCalls) {
1620     assert((Subtarget->isTargetWindows() ||
1621             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1622            "long-calls with non-static relocation model!");
1623     // Handle a global address or an external symbol. If it's not one of
1624     // those, the target's already in a register, so we don't need to do
1625     // anything extra.
1626     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1627       const GlobalValue *GV = G->getGlobal();
1628       // Create a constant pool entry for the callee address
1629       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1630       ARMConstantPoolValue *CPV =
1631         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1632
1633       // Get the address of the callee into a register
1634       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1635       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1636       Callee = DAG.getLoad(getPointerTy(), dl,
1637                            DAG.getEntryNode(), CPAddr,
1638                            MachinePointerInfo::getConstantPool(),
1639                            false, false, false, 0);
1640     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1641       const char *Sym = S->getSymbol();
1642
1643       // Create a constant pool entry for the callee address
1644       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1645       ARMConstantPoolValue *CPV =
1646         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1647                                       ARMPCLabelIndex, 0);
1648       // Get the address of the callee into a register
1649       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1650       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1651       Callee = DAG.getLoad(getPointerTy(), dl,
1652                            DAG.getEntryNode(), CPAddr,
1653                            MachinePointerInfo::getConstantPool(),
1654                            false, false, false, 0);
1655     }
1656   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1657     const GlobalValue *GV = G->getGlobal();
1658     isDirect = true;
1659     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1660     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1661                    getTargetMachine().getRelocationModel() != Reloc::Static;
1662     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1663     // ARM call to a local ARM function is predicable.
1664     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1665     // tBX takes a register source operand.
1666     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1667       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1668       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1669                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1670                                                       0, ARMII::MO_NONLAZY));
1671       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1672                            MachinePointerInfo::getGOT(), false, false, true, 0);
1673     } else if (Subtarget->isTargetCOFF()) {
1674       assert(Subtarget->isTargetWindows() &&
1675              "Windows is the only supported COFF target");
1676       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1677                                  ? ARMII::MO_DLLIMPORT
1678                                  : ARMII::MO_NO_FLAG;
1679       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1680                                           TargetFlags);
1681       if (GV->hasDLLImportStorageClass())
1682         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1683                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1684                                          Callee), MachinePointerInfo::getGOT(),
1685                              false, false, false, 0);
1686     } else {
1687       // On ELF targets for PIC code, direct calls should go through the PLT
1688       unsigned OpFlags = 0;
1689       if (Subtarget->isTargetELF() &&
1690           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1691         OpFlags = ARMII::MO_PLT;
1692       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1693     }
1694   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1695     isDirect = true;
1696     bool isStub = Subtarget->isTargetMachO() &&
1697                   getTargetMachine().getRelocationModel() != Reloc::Static;
1698     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1699     // tBX takes a register source operand.
1700     const char *Sym = S->getSymbol();
1701     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1702       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1703       ARMConstantPoolValue *CPV =
1704         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1705                                       ARMPCLabelIndex, 4);
1706       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1707       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1708       Callee = DAG.getLoad(getPointerTy(), dl,
1709                            DAG.getEntryNode(), CPAddr,
1710                            MachinePointerInfo::getConstantPool(),
1711                            false, false, false, 0);
1712       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1713       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1714                            getPointerTy(), Callee, PICLabel);
1715     } else {
1716       unsigned OpFlags = 0;
1717       // On ELF targets for PIC code, direct calls should go through the PLT
1718       if (Subtarget->isTargetELF() &&
1719                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1720         OpFlags = ARMII::MO_PLT;
1721       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1722     }
1723   }
1724
1725   // FIXME: handle tail calls differently.
1726   unsigned CallOpc;
1727   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1728       AttributeSet::FunctionIndex, Attribute::MinSize);
1729   if (Subtarget->isThumb()) {
1730     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1731       CallOpc = ARMISD::CALL_NOLINK;
1732     else
1733       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1734   } else {
1735     if (!isDirect && !Subtarget->hasV5TOps())
1736       CallOpc = ARMISD::CALL_NOLINK;
1737     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1738                // Emit regular call when code size is the priority
1739                !HasMinSizeAttr)
1740       // "mov lr, pc; b _foo" to avoid confusing the RSP
1741       CallOpc = ARMISD::CALL_NOLINK;
1742     else
1743       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1744   }
1745
1746   std::vector<SDValue> Ops;
1747   Ops.push_back(Chain);
1748   Ops.push_back(Callee);
1749
1750   // Add argument registers to the end of the list so that they are known live
1751   // into the call.
1752   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1753     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1754                                   RegsToPass[i].second.getValueType()));
1755
1756   // Add a register mask operand representing the call-preserved registers.
1757   if (!isTailCall) {
1758     const uint32_t *Mask;
1759     const TargetRegisterInfo *TRI =
1760         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1761     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1762     if (isThisReturn) {
1763       // For 'this' returns, use the R0-preserving mask if applicable
1764       Mask = ARI->getThisReturnPreservedMask(CallConv);
1765       if (!Mask) {
1766         // Set isThisReturn to false if the calling convention is not one that
1767         // allows 'returned' to be modeled in this way, so LowerCallResult does
1768         // not try to pass 'this' straight through
1769         isThisReturn = false;
1770         Mask = ARI->getCallPreservedMask(CallConv);
1771       }
1772     } else
1773       Mask = ARI->getCallPreservedMask(CallConv);
1774
1775     assert(Mask && "Missing call preserved mask for calling convention");
1776     Ops.push_back(DAG.getRegisterMask(Mask));
1777   }
1778
1779   if (InFlag.getNode())
1780     Ops.push_back(InFlag);
1781
1782   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1783   if (isTailCall)
1784     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1785
1786   // Returns a chain and a flag for retval copy to use.
1787   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1788   InFlag = Chain.getValue(1);
1789
1790   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1791                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1792   if (!Ins.empty())
1793     InFlag = Chain.getValue(1);
1794
1795   // Handle result values, copying them out of physregs into vregs that we
1796   // return.
1797   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1798                          InVals, isThisReturn,
1799                          isThisReturn ? OutVals[0] : SDValue());
1800 }
1801
1802 /// HandleByVal - Every parameter *after* a byval parameter is passed
1803 /// on the stack.  Remember the next parameter register to allocate,
1804 /// and then confiscate the rest of the parameter registers to insure
1805 /// this.
1806 void
1807 ARMTargetLowering::HandleByVal(
1808     CCState *State, unsigned &size, unsigned Align) const {
1809   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1810   assert((State->getCallOrPrologue() == Prologue ||
1811           State->getCallOrPrologue() == Call) &&
1812          "unhandled ParmContext");
1813
1814   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1815     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1816       unsigned AlignInRegs = Align / 4;
1817       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1818       for (unsigned i = 0; i < Waste; ++i)
1819         reg = State->AllocateReg(GPRArgRegs, 4);
1820     }
1821     if (reg != 0) {
1822       unsigned excess = 4 * (ARM::R4 - reg);
1823
1824       // Special case when NSAA != SP and parameter size greater than size of
1825       // all remained GPR regs. In that case we can't split parameter, we must
1826       // send it to stack. We also must set NCRN to R4, so waste all
1827       // remained registers.
1828       const unsigned NSAAOffset = State->getNextStackOffset();
1829       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1830         while (State->AllocateReg(GPRArgRegs, 4))
1831           ;
1832         return;
1833       }
1834
1835       // First register for byval parameter is the first register that wasn't
1836       // allocated before this method call, so it would be "reg".
1837       // If parameter is small enough to be saved in range [reg, r4), then
1838       // the end (first after last) register would be reg + param-size-in-regs,
1839       // else parameter would be splitted between registers and stack,
1840       // end register would be r4 in this case.
1841       unsigned ByValRegBegin = reg;
1842       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1843       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1844       // Note, first register is allocated in the beginning of function already,
1845       // allocate remained amount of registers we need.
1846       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1847         State->AllocateReg(GPRArgRegs, 4);
1848       // A byval parameter that is split between registers and memory needs its
1849       // size truncated here.
1850       // In the case where the entire structure fits in registers, we set the
1851       // size in memory to zero.
1852       if (size < excess)
1853         size = 0;
1854       else
1855         size -= excess;
1856     }
1857   }
1858 }
1859
1860 /// MatchingStackOffset - Return true if the given stack call argument is
1861 /// already available in the same position (relatively) of the caller's
1862 /// incoming argument stack.
1863 static
1864 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1865                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1866                          const TargetInstrInfo *TII) {
1867   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1868   int FI = INT_MAX;
1869   if (Arg.getOpcode() == ISD::CopyFromReg) {
1870     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1871     if (!TargetRegisterInfo::isVirtualRegister(VR))
1872       return false;
1873     MachineInstr *Def = MRI->getVRegDef(VR);
1874     if (!Def)
1875       return false;
1876     if (!Flags.isByVal()) {
1877       if (!TII->isLoadFromStackSlot(Def, FI))
1878         return false;
1879     } else {
1880       return false;
1881     }
1882   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1883     if (Flags.isByVal())
1884       // ByVal argument is passed in as a pointer but it's now being
1885       // dereferenced. e.g.
1886       // define @foo(%struct.X* %A) {
1887       //   tail call @bar(%struct.X* byval %A)
1888       // }
1889       return false;
1890     SDValue Ptr = Ld->getBasePtr();
1891     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1892     if (!FINode)
1893       return false;
1894     FI = FINode->getIndex();
1895   } else
1896     return false;
1897
1898   assert(FI != INT_MAX);
1899   if (!MFI->isFixedObjectIndex(FI))
1900     return false;
1901   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1902 }
1903
1904 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1905 /// for tail call optimization. Targets which want to do tail call
1906 /// optimization should implement this function.
1907 bool
1908 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1909                                                      CallingConv::ID CalleeCC,
1910                                                      bool isVarArg,
1911                                                      bool isCalleeStructRet,
1912                                                      bool isCallerStructRet,
1913                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1914                                     const SmallVectorImpl<SDValue> &OutVals,
1915                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1916                                                      SelectionDAG& DAG) const {
1917   const Function *CallerF = DAG.getMachineFunction().getFunction();
1918   CallingConv::ID CallerCC = CallerF->getCallingConv();
1919   bool CCMatch = CallerCC == CalleeCC;
1920
1921   // Look for obvious safe cases to perform tail call optimization that do not
1922   // require ABI changes. This is what gcc calls sibcall.
1923
1924   // Do not sibcall optimize vararg calls unless the call site is not passing
1925   // any arguments.
1926   if (isVarArg && !Outs.empty())
1927     return false;
1928
1929   // Exception-handling functions need a special set of instructions to indicate
1930   // a return to the hardware. Tail-calling another function would probably
1931   // break this.
1932   if (CallerF->hasFnAttribute("interrupt"))
1933     return false;
1934
1935   // Also avoid sibcall optimization if either caller or callee uses struct
1936   // return semantics.
1937   if (isCalleeStructRet || isCallerStructRet)
1938     return false;
1939
1940   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1941   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1942   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1943   // support in the assembler and linker to be used. This would need to be
1944   // fixed to fully support tail calls in Thumb1.
1945   //
1946   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1947   // LR.  This means if we need to reload LR, it takes an extra instructions,
1948   // which outweighs the value of the tail call; but here we don't know yet
1949   // whether LR is going to be used.  Probably the right approach is to
1950   // generate the tail call here and turn it back into CALL/RET in
1951   // emitEpilogue if LR is used.
1952
1953   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1954   // but we need to make sure there are enough registers; the only valid
1955   // registers are the 4 used for parameters.  We don't currently do this
1956   // case.
1957   if (Subtarget->isThumb1Only())
1958     return false;
1959
1960   // If the calling conventions do not match, then we'd better make sure the
1961   // results are returned in the same way as what the caller expects.
1962   if (!CCMatch) {
1963     SmallVector<CCValAssign, 16> RVLocs1;
1964     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
1965                        *DAG.getContext(), Call);
1966     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1967
1968     SmallVector<CCValAssign, 16> RVLocs2;
1969     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
1970                        *DAG.getContext(), Call);
1971     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1972
1973     if (RVLocs1.size() != RVLocs2.size())
1974       return false;
1975     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1976       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1977         return false;
1978       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1979         return false;
1980       if (RVLocs1[i].isRegLoc()) {
1981         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1982           return false;
1983       } else {
1984         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1985           return false;
1986       }
1987     }
1988   }
1989
1990   // If Caller's vararg or byval argument has been split between registers and
1991   // stack, do not perform tail call, since part of the argument is in caller's
1992   // local frame.
1993   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1994                                       getInfo<ARMFunctionInfo>();
1995   if (AFI_Caller->getArgRegsSaveSize())
1996     return false;
1997
1998   // If the callee takes no arguments then go on to check the results of the
1999   // call.
2000   if (!Outs.empty()) {
2001     // Check if stack adjustment is needed. For now, do not do this if any
2002     // argument is passed on the stack.
2003     SmallVector<CCValAssign, 16> ArgLocs;
2004     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2005                       *DAG.getContext(), Call);
2006     CCInfo.AnalyzeCallOperands(Outs,
2007                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2008     if (CCInfo.getNextStackOffset()) {
2009       MachineFunction &MF = DAG.getMachineFunction();
2010
2011       // Check if the arguments are already laid out in the right way as
2012       // the caller's fixed stack objects.
2013       MachineFrameInfo *MFI = MF.getFrameInfo();
2014       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2015       const TargetInstrInfo *TII =
2016           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2017       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2018            i != e;
2019            ++i, ++realArgIdx) {
2020         CCValAssign &VA = ArgLocs[i];
2021         EVT RegVT = VA.getLocVT();
2022         SDValue Arg = OutVals[realArgIdx];
2023         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2024         if (VA.getLocInfo() == CCValAssign::Indirect)
2025           return false;
2026         if (VA.needsCustom()) {
2027           // f64 and vector types are split into multiple registers or
2028           // register/stack-slot combinations.  The types will not match
2029           // the registers; give up on memory f64 refs until we figure
2030           // out what to do about this.
2031           if (!VA.isRegLoc())
2032             return false;
2033           if (!ArgLocs[++i].isRegLoc())
2034             return false;
2035           if (RegVT == MVT::v2f64) {
2036             if (!ArgLocs[++i].isRegLoc())
2037               return false;
2038             if (!ArgLocs[++i].isRegLoc())
2039               return false;
2040           }
2041         } else if (!VA.isRegLoc()) {
2042           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2043                                    MFI, MRI, TII))
2044             return false;
2045         }
2046       }
2047     }
2048   }
2049
2050   return true;
2051 }
2052
2053 bool
2054 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2055                                   MachineFunction &MF, bool isVarArg,
2056                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2057                                   LLVMContext &Context) const {
2058   SmallVector<CCValAssign, 16> RVLocs;
2059   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2060   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2061                                                     isVarArg));
2062 }
2063
2064 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2065                                     SDLoc DL, SelectionDAG &DAG) {
2066   const MachineFunction &MF = DAG.getMachineFunction();
2067   const Function *F = MF.getFunction();
2068
2069   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2070
2071   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2072   // version of the "preferred return address". These offsets affect the return
2073   // instruction if this is a return from PL1 without hypervisor extensions.
2074   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2075   //    SWI:     0      "subs pc, lr, #0"
2076   //    ABORT:   +4     "subs pc, lr, #4"
2077   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2078   // UNDEF varies depending on where the exception came from ARM or Thumb
2079   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2080
2081   int64_t LROffset;
2082   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2083       IntKind == "ABORT")
2084     LROffset = 4;
2085   else if (IntKind == "SWI" || IntKind == "UNDEF")
2086     LROffset = 0;
2087   else
2088     report_fatal_error("Unsupported interrupt attribute. If present, value "
2089                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2090
2091   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2092
2093   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2094 }
2095
2096 SDValue
2097 ARMTargetLowering::LowerReturn(SDValue Chain,
2098                                CallingConv::ID CallConv, bool isVarArg,
2099                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2100                                const SmallVectorImpl<SDValue> &OutVals,
2101                                SDLoc dl, SelectionDAG &DAG) const {
2102
2103   // CCValAssign - represent the assignment of the return value to a location.
2104   SmallVector<CCValAssign, 16> RVLocs;
2105
2106   // CCState - Info about the registers and stack slots.
2107   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2108                     *DAG.getContext(), Call);
2109
2110   // Analyze outgoing return values.
2111   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2112                                                isVarArg));
2113
2114   SDValue Flag;
2115   SmallVector<SDValue, 4> RetOps;
2116   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2117   bool isLittleEndian = Subtarget->isLittle();
2118
2119   MachineFunction &MF = DAG.getMachineFunction();
2120   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2121   AFI->setReturnRegsCount(RVLocs.size());
2122
2123   // Copy the result values into the output registers.
2124   for (unsigned i = 0, realRVLocIdx = 0;
2125        i != RVLocs.size();
2126        ++i, ++realRVLocIdx) {
2127     CCValAssign &VA = RVLocs[i];
2128     assert(VA.isRegLoc() && "Can only return in registers!");
2129
2130     SDValue Arg = OutVals[realRVLocIdx];
2131
2132     switch (VA.getLocInfo()) {
2133     default: llvm_unreachable("Unknown loc info!");
2134     case CCValAssign::Full: break;
2135     case CCValAssign::BCvt:
2136       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2137       break;
2138     }
2139
2140     if (VA.needsCustom()) {
2141       if (VA.getLocVT() == MVT::v2f64) {
2142         // Extract the first half and return it in two registers.
2143         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2144                                    DAG.getConstant(0, MVT::i32));
2145         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2146                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2147
2148         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2149                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2150                                  Flag);
2151         Flag = Chain.getValue(1);
2152         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2153         VA = RVLocs[++i]; // skip ahead to next loc
2154         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2155                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2156                                  Flag);
2157         Flag = Chain.getValue(1);
2158         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2159         VA = RVLocs[++i]; // skip ahead to next loc
2160
2161         // Extract the 2nd half and fall through to handle it as an f64 value.
2162         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2163                           DAG.getConstant(1, MVT::i32));
2164       }
2165       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2166       // available.
2167       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2168                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2169       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2170                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2171                                Flag);
2172       Flag = Chain.getValue(1);
2173       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2174       VA = RVLocs[++i]; // skip ahead to next loc
2175       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2176                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2177                                Flag);
2178     } else
2179       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2180
2181     // Guarantee that all emitted copies are
2182     // stuck together, avoiding something bad.
2183     Flag = Chain.getValue(1);
2184     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2185   }
2186
2187   // Update chain and glue.
2188   RetOps[0] = Chain;
2189   if (Flag.getNode())
2190     RetOps.push_back(Flag);
2191
2192   // CPUs which aren't M-class use a special sequence to return from
2193   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2194   // though we use "subs pc, lr, #N").
2195   //
2196   // M-class CPUs actually use a normal return sequence with a special
2197   // (hardware-provided) value in LR, so the normal code path works.
2198   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2199       !Subtarget->isMClass()) {
2200     if (Subtarget->isThumb1Only())
2201       report_fatal_error("interrupt attribute is not supported in Thumb1");
2202     return LowerInterruptReturn(RetOps, dl, DAG);
2203   }
2204
2205   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2206 }
2207
2208 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2209   if (N->getNumValues() != 1)
2210     return false;
2211   if (!N->hasNUsesOfValue(1, 0))
2212     return false;
2213
2214   SDValue TCChain = Chain;
2215   SDNode *Copy = *N->use_begin();
2216   if (Copy->getOpcode() == ISD::CopyToReg) {
2217     // If the copy has a glue operand, we conservatively assume it isn't safe to
2218     // perform a tail call.
2219     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2220       return false;
2221     TCChain = Copy->getOperand(0);
2222   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2223     SDNode *VMov = Copy;
2224     // f64 returned in a pair of GPRs.
2225     SmallPtrSet<SDNode*, 2> Copies;
2226     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2227          UI != UE; ++UI) {
2228       if (UI->getOpcode() != ISD::CopyToReg)
2229         return false;
2230       Copies.insert(*UI);
2231     }
2232     if (Copies.size() > 2)
2233       return false;
2234
2235     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2236          UI != UE; ++UI) {
2237       SDValue UseChain = UI->getOperand(0);
2238       if (Copies.count(UseChain.getNode()))
2239         // Second CopyToReg
2240         Copy = *UI;
2241       else
2242         // First CopyToReg
2243         TCChain = UseChain;
2244     }
2245   } else if (Copy->getOpcode() == ISD::BITCAST) {
2246     // f32 returned in a single GPR.
2247     if (!Copy->hasOneUse())
2248       return false;
2249     Copy = *Copy->use_begin();
2250     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2251       return false;
2252     TCChain = Copy->getOperand(0);
2253   } else {
2254     return false;
2255   }
2256
2257   bool HasRet = false;
2258   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2259        UI != UE; ++UI) {
2260     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2261         UI->getOpcode() != ARMISD::INTRET_FLAG)
2262       return false;
2263     HasRet = true;
2264   }
2265
2266   if (!HasRet)
2267     return false;
2268
2269   Chain = TCChain;
2270   return true;
2271 }
2272
2273 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2274   if (!Subtarget->supportsTailCall())
2275     return false;
2276
2277   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2278     return false;
2279
2280   return !Subtarget->isThumb1Only();
2281 }
2282
2283 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2284 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2285 // one of the above mentioned nodes. It has to be wrapped because otherwise
2286 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2287 // be used to form addressing mode. These wrapped nodes will be selected
2288 // into MOVi.
2289 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2290   EVT PtrVT = Op.getValueType();
2291   // FIXME there is no actual debug info here
2292   SDLoc dl(Op);
2293   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2294   SDValue Res;
2295   if (CP->isMachineConstantPoolEntry())
2296     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2297                                     CP->getAlignment());
2298   else
2299     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2300                                     CP->getAlignment());
2301   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2302 }
2303
2304 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2305   return MachineJumpTableInfo::EK_Inline;
2306 }
2307
2308 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2309                                              SelectionDAG &DAG) const {
2310   MachineFunction &MF = DAG.getMachineFunction();
2311   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2312   unsigned ARMPCLabelIndex = 0;
2313   SDLoc DL(Op);
2314   EVT PtrVT = getPointerTy();
2315   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2316   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2317   SDValue CPAddr;
2318   if (RelocM == Reloc::Static) {
2319     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2320   } else {
2321     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2322     ARMPCLabelIndex = AFI->createPICLabelUId();
2323     ARMConstantPoolValue *CPV =
2324       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2325                                       ARMCP::CPBlockAddress, PCAdj);
2326     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2327   }
2328   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2329   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2330                                MachinePointerInfo::getConstantPool(),
2331                                false, false, false, 0);
2332   if (RelocM == Reloc::Static)
2333     return Result;
2334   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2335   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2336 }
2337
2338 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2339 SDValue
2340 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2341                                                  SelectionDAG &DAG) const {
2342   SDLoc dl(GA);
2343   EVT PtrVT = getPointerTy();
2344   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2345   MachineFunction &MF = DAG.getMachineFunction();
2346   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2347   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2348   ARMConstantPoolValue *CPV =
2349     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2350                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2351   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2352   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2353   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2354                          MachinePointerInfo::getConstantPool(),
2355                          false, false, false, 0);
2356   SDValue Chain = Argument.getValue(1);
2357
2358   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2359   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2360
2361   // call __tls_get_addr.
2362   ArgListTy Args;
2363   ArgListEntry Entry;
2364   Entry.Node = Argument;
2365   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2366   Args.push_back(Entry);
2367
2368   // FIXME: is there useful debug info available here?
2369   TargetLowering::CallLoweringInfo CLI(DAG);
2370   CLI.setDebugLoc(dl).setChain(Chain)
2371     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2372                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2373                0);
2374
2375   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2376   return CallResult.first;
2377 }
2378
2379 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2380 // "local exec" model.
2381 SDValue
2382 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2383                                         SelectionDAG &DAG,
2384                                         TLSModel::Model model) const {
2385   const GlobalValue *GV = GA->getGlobal();
2386   SDLoc dl(GA);
2387   SDValue Offset;
2388   SDValue Chain = DAG.getEntryNode();
2389   EVT PtrVT = getPointerTy();
2390   // Get the Thread Pointer
2391   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2392
2393   if (model == TLSModel::InitialExec) {
2394     MachineFunction &MF = DAG.getMachineFunction();
2395     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2396     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2397     // Initial exec model.
2398     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2399     ARMConstantPoolValue *CPV =
2400       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2401                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2402                                       true);
2403     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2404     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2405     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2406                          MachinePointerInfo::getConstantPool(),
2407                          false, false, false, 0);
2408     Chain = Offset.getValue(1);
2409
2410     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2411     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2412
2413     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2414                          MachinePointerInfo::getConstantPool(),
2415                          false, false, false, 0);
2416   } else {
2417     // local exec model
2418     assert(model == TLSModel::LocalExec);
2419     ARMConstantPoolValue *CPV =
2420       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2421     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2422     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2423     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2424                          MachinePointerInfo::getConstantPool(),
2425                          false, false, false, 0);
2426   }
2427
2428   // The address of the thread local variable is the add of the thread
2429   // pointer with the offset of the variable.
2430   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2431 }
2432
2433 SDValue
2434 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2435   // TODO: implement the "local dynamic" model
2436   assert(Subtarget->isTargetELF() &&
2437          "TLS not implemented for non-ELF targets");
2438   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2439
2440   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2441
2442   switch (model) {
2443     case TLSModel::GeneralDynamic:
2444     case TLSModel::LocalDynamic:
2445       return LowerToTLSGeneralDynamicModel(GA, DAG);
2446     case TLSModel::InitialExec:
2447     case TLSModel::LocalExec:
2448       return LowerToTLSExecModels(GA, DAG, model);
2449   }
2450   llvm_unreachable("bogus TLS model");
2451 }
2452
2453 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2454                                                  SelectionDAG &DAG) const {
2455   EVT PtrVT = getPointerTy();
2456   SDLoc dl(Op);
2457   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2458   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2459     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2460     ARMConstantPoolValue *CPV =
2461       ARMConstantPoolConstant::Create(GV,
2462                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2463     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2464     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2465     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2466                                  CPAddr,
2467                                  MachinePointerInfo::getConstantPool(),
2468                                  false, false, false, 0);
2469     SDValue Chain = Result.getValue(1);
2470     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2471     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2472     if (!UseGOTOFF)
2473       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2474                            MachinePointerInfo::getGOT(),
2475                            false, false, false, 0);
2476     return Result;
2477   }
2478
2479   // If we have T2 ops, we can materialize the address directly via movt/movw
2480   // pair. This is always cheaper.
2481   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2482     ++NumMovwMovt;
2483     // FIXME: Once remat is capable of dealing with instructions with register
2484     // operands, expand this into two nodes.
2485     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2486                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2487   } else {
2488     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2489     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2490     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2491                        MachinePointerInfo::getConstantPool(),
2492                        false, false, false, 0);
2493   }
2494 }
2495
2496 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2497                                                     SelectionDAG &DAG) const {
2498   EVT PtrVT = getPointerTy();
2499   SDLoc dl(Op);
2500   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2501   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2502
2503   if (Subtarget->useMovt(DAG.getMachineFunction()))
2504     ++NumMovwMovt;
2505
2506   // FIXME: Once remat is capable of dealing with instructions with register
2507   // operands, expand this into multiple nodes
2508   unsigned Wrapper =
2509       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2510
2511   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2512   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2513
2514   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2515     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2516                          MachinePointerInfo::getGOT(), false, false, false, 0);
2517   return Result;
2518 }
2519
2520 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2521                                                      SelectionDAG &DAG) const {
2522   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2523   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2524          "Windows on ARM expects to use movw/movt");
2525
2526   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2527   const ARMII::TOF TargetFlags =
2528     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2529   EVT PtrVT = getPointerTy();
2530   SDValue Result;
2531   SDLoc DL(Op);
2532
2533   ++NumMovwMovt;
2534
2535   // FIXME: Once remat is capable of dealing with instructions with register
2536   // operands, expand this into two nodes.
2537   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2538                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2539                                                   TargetFlags));
2540   if (GV->hasDLLImportStorageClass())
2541     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2542                          MachinePointerInfo::getGOT(), false, false, false, 0);
2543   return Result;
2544 }
2545
2546 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2547                                                     SelectionDAG &DAG) const {
2548   assert(Subtarget->isTargetELF() &&
2549          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2550   MachineFunction &MF = DAG.getMachineFunction();
2551   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2552   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2553   EVT PtrVT = getPointerTy();
2554   SDLoc dl(Op);
2555   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2556   ARMConstantPoolValue *CPV =
2557     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2558                                   ARMPCLabelIndex, PCAdj);
2559   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2560   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2561   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2562                                MachinePointerInfo::getConstantPool(),
2563                                false, false, false, 0);
2564   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2565   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2566 }
2567
2568 SDValue
2569 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2570   SDLoc dl(Op);
2571   SDValue Val = DAG.getConstant(0, MVT::i32);
2572   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2573                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2574                      Op.getOperand(1), Val);
2575 }
2576
2577 SDValue
2578 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2579   SDLoc dl(Op);
2580   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2581                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2582 }
2583
2584 SDValue
2585 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2586                                           const ARMSubtarget *Subtarget) const {
2587   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2588   SDLoc dl(Op);
2589   switch (IntNo) {
2590   default: return SDValue();    // Don't custom lower most intrinsics.
2591   case Intrinsic::arm_rbit: {
2592     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2593            "RBIT intrinsic must have i32 type!");
2594     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2595   }
2596   case Intrinsic::arm_thread_pointer: {
2597     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2598     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2599   }
2600   case Intrinsic::eh_sjlj_lsda: {
2601     MachineFunction &MF = DAG.getMachineFunction();
2602     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2603     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2604     EVT PtrVT = getPointerTy();
2605     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2606     SDValue CPAddr;
2607     unsigned PCAdj = (RelocM != Reloc::PIC_)
2608       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2609     ARMConstantPoolValue *CPV =
2610       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2611                                       ARMCP::CPLSDA, PCAdj);
2612     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2613     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2614     SDValue Result =
2615       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2616                   MachinePointerInfo::getConstantPool(),
2617                   false, false, false, 0);
2618
2619     if (RelocM == Reloc::PIC_) {
2620       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2621       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2622     }
2623     return Result;
2624   }
2625   case Intrinsic::arm_neon_vmulls:
2626   case Intrinsic::arm_neon_vmullu: {
2627     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2628       ? ARMISD::VMULLs : ARMISD::VMULLu;
2629     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2630                        Op.getOperand(1), Op.getOperand(2));
2631   }
2632   }
2633 }
2634
2635 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2636                                  const ARMSubtarget *Subtarget) {
2637   // FIXME: handle "fence singlethread" more efficiently.
2638   SDLoc dl(Op);
2639   if (!Subtarget->hasDataBarrier()) {
2640     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2641     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2642     // here.
2643     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2644            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2645     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2646                        DAG.getConstant(0, MVT::i32));
2647   }
2648
2649   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2650   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2651   unsigned Domain = ARM_MB::ISH;
2652   if (Subtarget->isMClass()) {
2653     // Only a full system barrier exists in the M-class architectures.
2654     Domain = ARM_MB::SY;
2655   } else if (Subtarget->isSwift() && Ord == Release) {
2656     // Swift happens to implement ISHST barriers in a way that's compatible with
2657     // Release semantics but weaker than ISH so we'd be fools not to use
2658     // it. Beware: other processors probably don't!
2659     Domain = ARM_MB::ISHST;
2660   }
2661
2662   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2663                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2664                      DAG.getConstant(Domain, MVT::i32));
2665 }
2666
2667 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2668                              const ARMSubtarget *Subtarget) {
2669   // ARM pre v5TE and Thumb1 does not have preload instructions.
2670   if (!(Subtarget->isThumb2() ||
2671         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2672     // Just preserve the chain.
2673     return Op.getOperand(0);
2674
2675   SDLoc dl(Op);
2676   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2677   if (!isRead &&
2678       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2679     // ARMv7 with MP extension has PLDW.
2680     return Op.getOperand(0);
2681
2682   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2683   if (Subtarget->isThumb()) {
2684     // Invert the bits.
2685     isRead = ~isRead & 1;
2686     isData = ~isData & 1;
2687   }
2688
2689   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2690                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2691                      DAG.getConstant(isData, MVT::i32));
2692 }
2693
2694 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2695   MachineFunction &MF = DAG.getMachineFunction();
2696   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2697
2698   // vastart just stores the address of the VarArgsFrameIndex slot into the
2699   // memory location argument.
2700   SDLoc dl(Op);
2701   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2702   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2703   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2704   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2705                       MachinePointerInfo(SV), false, false, 0);
2706 }
2707
2708 SDValue
2709 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2710                                         SDValue &Root, SelectionDAG &DAG,
2711                                         SDLoc dl) const {
2712   MachineFunction &MF = DAG.getMachineFunction();
2713   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2714
2715   const TargetRegisterClass *RC;
2716   if (AFI->isThumb1OnlyFunction())
2717     RC = &ARM::tGPRRegClass;
2718   else
2719     RC = &ARM::GPRRegClass;
2720
2721   // Transform the arguments stored in physical registers into virtual ones.
2722   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2723   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2724
2725   SDValue ArgValue2;
2726   if (NextVA.isMemLoc()) {
2727     MachineFrameInfo *MFI = MF.getFrameInfo();
2728     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2729
2730     // Create load node to retrieve arguments from the stack.
2731     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2732     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2733                             MachinePointerInfo::getFixedStack(FI),
2734                             false, false, false, 0);
2735   } else {
2736     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2737     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2738   }
2739   if (!Subtarget->isLittle())
2740     std::swap (ArgValue, ArgValue2);
2741   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2742 }
2743
2744 void
2745 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2746                                   unsigned InRegsParamRecordIdx,
2747                                   unsigned ArgSize,
2748                                   unsigned &ArgRegsSize,
2749                                   unsigned &ArgRegsSaveSize)
2750   const {
2751   unsigned NumGPRs;
2752   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2753     unsigned RBegin, REnd;
2754     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2755     NumGPRs = REnd - RBegin;
2756   } else {
2757     unsigned int firstUnalloced;
2758     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2759                                                 sizeof(GPRArgRegs) /
2760                                                 sizeof(GPRArgRegs[0]));
2761     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2762   }
2763
2764   unsigned Align = MF.getTarget()
2765                        .getSubtargetImpl()
2766                        ->getFrameLowering()
2767                        ->getStackAlignment();
2768   ArgRegsSize = NumGPRs * 4;
2769
2770   // If parameter is split between stack and GPRs...
2771   if (NumGPRs && Align > 4 &&
2772       (ArgRegsSize < ArgSize ||
2773         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2774     // Add padding for part of param recovered from GPRs.  For example,
2775     // if Align == 8, its last byte must be at address K*8 - 1.
2776     // We need to do it, since remained (stack) part of parameter has
2777     // stack alignment, and we need to "attach" "GPRs head" without gaps
2778     // to it:
2779     // Stack:
2780     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2781     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2782     //
2783     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2784     unsigned Padding =
2785         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2786     ArgRegsSaveSize = ArgRegsSize + Padding;
2787   } else
2788     // We don't need to extend regs save size for byval parameters if they
2789     // are passed via GPRs only.
2790     ArgRegsSaveSize = ArgRegsSize;
2791 }
2792
2793 // The remaining GPRs hold either the beginning of variable-argument
2794 // data, or the beginning of an aggregate passed by value (usually
2795 // byval).  Either way, we allocate stack slots adjacent to the data
2796 // provided by our caller, and store the unallocated registers there.
2797 // If this is a variadic function, the va_list pointer will begin with
2798 // these values; otherwise, this reassembles a (byval) structure that
2799 // was split between registers and memory.
2800 // Return: The frame index registers were stored into.
2801 int
2802 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2803                                   SDLoc dl, SDValue &Chain,
2804                                   const Value *OrigArg,
2805                                   unsigned InRegsParamRecordIdx,
2806                                   unsigned OffsetFromOrigArg,
2807                                   unsigned ArgOffset,
2808                                   unsigned ArgSize,
2809                                   bool ForceMutable,
2810                                   unsigned ByValStoreOffset,
2811                                   unsigned TotalArgRegsSaveSize) const {
2812
2813   // Currently, two use-cases possible:
2814   // Case #1. Non-var-args function, and we meet first byval parameter.
2815   //          Setup first unallocated register as first byval register;
2816   //          eat all remained registers
2817   //          (these two actions are performed by HandleByVal method).
2818   //          Then, here, we initialize stack frame with
2819   //          "store-reg" instructions.
2820   // Case #2. Var-args function, that doesn't contain byval parameters.
2821   //          The same: eat all remained unallocated registers,
2822   //          initialize stack frame.
2823
2824   MachineFunction &MF = DAG.getMachineFunction();
2825   MachineFrameInfo *MFI = MF.getFrameInfo();
2826   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2827   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2828   unsigned RBegin, REnd;
2829   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2830     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2831     firstRegToSaveIndex = RBegin - ARM::R0;
2832     lastRegToSaveIndex = REnd - ARM::R0;
2833   } else {
2834     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2835       (GPRArgRegs, array_lengthof(GPRArgRegs));
2836     lastRegToSaveIndex = 4;
2837   }
2838
2839   unsigned ArgRegsSize, ArgRegsSaveSize;
2840   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2841                  ArgRegsSize, ArgRegsSaveSize);
2842
2843   // Store any by-val regs to their spots on the stack so that they may be
2844   // loaded by deferencing the result of formal parameter pointer or va_next.
2845   // Note: once stack area for byval/varargs registers
2846   // was initialized, it can't be initialized again.
2847   if (ArgRegsSaveSize) {
2848     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2849
2850     if (Padding) {
2851       assert(AFI->getStoredByValParamsPadding() == 0 &&
2852              "The only parameter may be padded.");
2853       AFI->setStoredByValParamsPadding(Padding);
2854     }
2855
2856     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2857                                             Padding +
2858                                               ByValStoreOffset -
2859                                               (int64_t)TotalArgRegsSaveSize,
2860                                             false);
2861     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2862     if (Padding) {
2863        MFI->CreateFixedObject(Padding,
2864                               ArgOffset + ByValStoreOffset -
2865                                 (int64_t)ArgRegsSaveSize,
2866                               false);
2867     }
2868
2869     SmallVector<SDValue, 4> MemOps;
2870     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2871          ++firstRegToSaveIndex, ++i) {
2872       const TargetRegisterClass *RC;
2873       if (AFI->isThumb1OnlyFunction())
2874         RC = &ARM::tGPRRegClass;
2875       else
2876         RC = &ARM::GPRRegClass;
2877
2878       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2879       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2880       SDValue Store =
2881         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2882                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2883                      false, false, 0);
2884       MemOps.push_back(Store);
2885       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2886                         DAG.getConstant(4, getPointerTy()));
2887     }
2888
2889     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2890
2891     if (!MemOps.empty())
2892       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2893     return FrameIndex;
2894   } else {
2895     if (ArgSize == 0) {
2896       // We cannot allocate a zero-byte object for the first variadic argument,
2897       // so just make up a size.
2898       ArgSize = 4;
2899     }
2900     // This will point to the next argument passed via stack.
2901     return MFI->CreateFixedObject(
2902       ArgSize, ArgOffset, !ForceMutable);
2903   }
2904 }
2905
2906 // Setup stack frame, the va_list pointer will start from.
2907 void
2908 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2909                                         SDLoc dl, SDValue &Chain,
2910                                         unsigned ArgOffset,
2911                                         unsigned TotalArgRegsSaveSize,
2912                                         bool ForceMutable) const {
2913   MachineFunction &MF = DAG.getMachineFunction();
2914   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2915
2916   // Try to store any remaining integer argument regs
2917   // to their spots on the stack so that they may be loaded by deferencing
2918   // the result of va_next.
2919   // If there is no regs to be stored, just point address after last
2920   // argument passed via stack.
2921   int FrameIndex =
2922     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2923                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2924                    0, TotalArgRegsSaveSize);
2925
2926   AFI->setVarArgsFrameIndex(FrameIndex);
2927 }
2928
2929 SDValue
2930 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2931                                         CallingConv::ID CallConv, bool isVarArg,
2932                                         const SmallVectorImpl<ISD::InputArg>
2933                                           &Ins,
2934                                         SDLoc dl, SelectionDAG &DAG,
2935                                         SmallVectorImpl<SDValue> &InVals)
2936                                           const {
2937   MachineFunction &MF = DAG.getMachineFunction();
2938   MachineFrameInfo *MFI = MF.getFrameInfo();
2939
2940   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2941
2942   // Assign locations to all of the incoming arguments.
2943   SmallVector<CCValAssign, 16> ArgLocs;
2944   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2945                     *DAG.getContext(), Prologue);
2946   CCInfo.AnalyzeFormalArguments(Ins,
2947                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2948                                                   isVarArg));
2949
2950   SmallVector<SDValue, 16> ArgValues;
2951   int lastInsIndex = -1;
2952   SDValue ArgValue;
2953   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2954   unsigned CurArgIdx = 0;
2955
2956   // Initially ArgRegsSaveSize is zero.
2957   // Then we increase this value each time we meet byval parameter.
2958   // We also increase this value in case of varargs function.
2959   AFI->setArgRegsSaveSize(0);
2960
2961   unsigned ByValStoreOffset = 0;
2962   unsigned TotalArgRegsSaveSize = 0;
2963   unsigned ArgRegsSaveSizeMaxAlign = 4;
2964
2965   // Calculate the amount of stack space that we need to allocate to store
2966   // byval and variadic arguments that are passed in registers.
2967   // We need to know this before we allocate the first byval or variadic
2968   // argument, as they will be allocated a stack slot below the CFA (Canonical
2969   // Frame Address, the stack pointer at entry to the function).
2970   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2971     CCValAssign &VA = ArgLocs[i];
2972     if (VA.isMemLoc()) {
2973       int index = VA.getValNo();
2974       if (index != lastInsIndex) {
2975         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2976         if (Flags.isByVal()) {
2977           unsigned ExtraArgRegsSize;
2978           unsigned ExtraArgRegsSaveSize;
2979           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2980                          Flags.getByValSize(),
2981                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2982
2983           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2984           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2985               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2986           CCInfo.nextInRegsParam();
2987         }
2988         lastInsIndex = index;
2989       }
2990     }
2991   }
2992   CCInfo.rewindByValRegsInfo();
2993   lastInsIndex = -1;
2994   if (isVarArg) {
2995     unsigned ExtraArgRegsSize;
2996     unsigned ExtraArgRegsSaveSize;
2997     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2998                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2999     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3000   }
3001   // If the arg regs save area contains N-byte aligned values, the
3002   // bottom of it must be at least N-byte aligned.
3003   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3004   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3005
3006   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3007     CCValAssign &VA = ArgLocs[i];
3008     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3009     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3010     // Arguments stored in registers.
3011     if (VA.isRegLoc()) {
3012       EVT RegVT = VA.getLocVT();
3013
3014       if (VA.needsCustom()) {
3015         // f64 and vector types are split up into multiple registers or
3016         // combinations of registers and stack slots.
3017         if (VA.getLocVT() == MVT::v2f64) {
3018           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3019                                                    Chain, DAG, dl);
3020           VA = ArgLocs[++i]; // skip ahead to next loc
3021           SDValue ArgValue2;
3022           if (VA.isMemLoc()) {
3023             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3024             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3025             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3026                                     MachinePointerInfo::getFixedStack(FI),
3027                                     false, false, false, 0);
3028           } else {
3029             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3030                                              Chain, DAG, dl);
3031           }
3032           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3033           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3034                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3035           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3036                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3037         } else
3038           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3039
3040       } else {
3041         const TargetRegisterClass *RC;
3042
3043         if (RegVT == MVT::f32)
3044           RC = &ARM::SPRRegClass;
3045         else if (RegVT == MVT::f64)
3046           RC = &ARM::DPRRegClass;
3047         else if (RegVT == MVT::v2f64)
3048           RC = &ARM::QPRRegClass;
3049         else if (RegVT == MVT::i32)
3050           RC = AFI->isThumb1OnlyFunction() ?
3051             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3052             (const TargetRegisterClass*)&ARM::GPRRegClass;
3053         else
3054           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3055
3056         // Transform the arguments in physical registers into virtual ones.
3057         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3058         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3059       }
3060
3061       // If this is an 8 or 16-bit value, it is really passed promoted
3062       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3063       // truncate to the right size.
3064       switch (VA.getLocInfo()) {
3065       default: llvm_unreachable("Unknown loc info!");
3066       case CCValAssign::Full: break;
3067       case CCValAssign::BCvt:
3068         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3069         break;
3070       case CCValAssign::SExt:
3071         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3072                                DAG.getValueType(VA.getValVT()));
3073         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3074         break;
3075       case CCValAssign::ZExt:
3076         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3077                                DAG.getValueType(VA.getValVT()));
3078         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3079         break;
3080       }
3081
3082       InVals.push_back(ArgValue);
3083
3084     } else { // VA.isRegLoc()
3085
3086       // sanity check
3087       assert(VA.isMemLoc());
3088       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3089
3090       int index = ArgLocs[i].getValNo();
3091
3092       // Some Ins[] entries become multiple ArgLoc[] entries.
3093       // Process them only once.
3094       if (index != lastInsIndex)
3095         {
3096           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3097           // FIXME: For now, all byval parameter objects are marked mutable.
3098           // This can be changed with more analysis.
3099           // In case of tail call optimization mark all arguments mutable.
3100           // Since they could be overwritten by lowering of arguments in case of
3101           // a tail call.
3102           if (Flags.isByVal()) {
3103             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3104
3105             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3106             int FrameIndex = StoreByValRegs(
3107                 CCInfo, DAG, dl, Chain, CurOrigArg,
3108                 CurByValIndex,
3109                 Ins[VA.getValNo()].PartOffset,
3110                 VA.getLocMemOffset(),
3111                 Flags.getByValSize(),
3112                 true /*force mutable frames*/,
3113                 ByValStoreOffset,
3114                 TotalArgRegsSaveSize);
3115             ByValStoreOffset += Flags.getByValSize();
3116             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3117             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3118             CCInfo.nextInRegsParam();
3119           } else {
3120             unsigned FIOffset = VA.getLocMemOffset();
3121             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3122                                             FIOffset, true);
3123
3124             // Create load nodes to retrieve arguments from the stack.
3125             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3126             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3127                                          MachinePointerInfo::getFixedStack(FI),
3128                                          false, false, false, 0));
3129           }
3130           lastInsIndex = index;
3131         }
3132     }
3133   }
3134
3135   // varargs
3136   if (isVarArg)
3137     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3138                          CCInfo.getNextStackOffset(),
3139                          TotalArgRegsSaveSize);
3140
3141   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3142
3143   return Chain;
3144 }
3145
3146 /// isFloatingPointZero - Return true if this is +0.0.
3147 static bool isFloatingPointZero(SDValue Op) {
3148   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3149     return CFP->getValueAPF().isPosZero();
3150   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3151     // Maybe this has already been legalized into the constant pool?
3152     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3153       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3154       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3155         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3156           return CFP->getValueAPF().isPosZero();
3157     }
3158   }
3159   return false;
3160 }
3161
3162 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3163 /// the given operands.
3164 SDValue
3165 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3166                              SDValue &ARMcc, SelectionDAG &DAG,
3167                              SDLoc dl) const {
3168   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3169     unsigned C = RHSC->getZExtValue();
3170     if (!isLegalICmpImmediate(C)) {
3171       // Constant does not fit, try adjusting it by one?
3172       switch (CC) {
3173       default: break;
3174       case ISD::SETLT:
3175       case ISD::SETGE:
3176         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3177           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3178           RHS = DAG.getConstant(C-1, MVT::i32);
3179         }
3180         break;
3181       case ISD::SETULT:
3182       case ISD::SETUGE:
3183         if (C != 0 && isLegalICmpImmediate(C-1)) {
3184           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3185           RHS = DAG.getConstant(C-1, MVT::i32);
3186         }
3187         break;
3188       case ISD::SETLE:
3189       case ISD::SETGT:
3190         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3191           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3192           RHS = DAG.getConstant(C+1, MVT::i32);
3193         }
3194         break;
3195       case ISD::SETULE:
3196       case ISD::SETUGT:
3197         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3198           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3199           RHS = DAG.getConstant(C+1, MVT::i32);
3200         }
3201         break;
3202       }
3203     }
3204   }
3205
3206   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3207   ARMISD::NodeType CompareType;
3208   switch (CondCode) {
3209   default:
3210     CompareType = ARMISD::CMP;
3211     break;
3212   case ARMCC::EQ:
3213   case ARMCC::NE:
3214     // Uses only Z Flag
3215     CompareType = ARMISD::CMPZ;
3216     break;
3217   }
3218   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3219   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3220 }
3221
3222 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3223 SDValue
3224 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3225                              SDLoc dl) const {
3226   SDValue Cmp;
3227   if (!isFloatingPointZero(RHS))
3228     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3229   else
3230     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3231   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3232 }
3233
3234 /// duplicateCmp - Glue values can have only one use, so this function
3235 /// duplicates a comparison node.
3236 SDValue
3237 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3238   unsigned Opc = Cmp.getOpcode();
3239   SDLoc DL(Cmp);
3240   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3241     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3242
3243   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3244   Cmp = Cmp.getOperand(0);
3245   Opc = Cmp.getOpcode();
3246   if (Opc == ARMISD::CMPFP)
3247     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3248   else {
3249     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3250     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3251   }
3252   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3253 }
3254
3255 std::pair<SDValue, SDValue>
3256 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3257                                  SDValue &ARMcc) const {
3258   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3259
3260   SDValue Value, OverflowCmp;
3261   SDValue LHS = Op.getOperand(0);
3262   SDValue RHS = Op.getOperand(1);
3263
3264
3265   // FIXME: We are currently always generating CMPs because we don't support
3266   // generating CMN through the backend. This is not as good as the natural
3267   // CMP case because it causes a register dependency and cannot be folded
3268   // later.
3269
3270   switch (Op.getOpcode()) {
3271   default:
3272     llvm_unreachable("Unknown overflow instruction!");
3273   case ISD::SADDO:
3274     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3275     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3276     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3277     break;
3278   case ISD::UADDO:
3279     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3280     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3281     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3282     break;
3283   case ISD::SSUBO:
3284     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3285     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3286     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3287     break;
3288   case ISD::USUBO:
3289     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3290     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3291     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3292     break;
3293   } // switch (...)
3294
3295   return std::make_pair(Value, OverflowCmp);
3296 }
3297
3298
3299 SDValue
3300 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3301   // Let legalize expand this if it isn't a legal type yet.
3302   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3303     return SDValue();
3304
3305   SDValue Value, OverflowCmp;
3306   SDValue ARMcc;
3307   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3308   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3309   // We use 0 and 1 as false and true values.
3310   SDValue TVal = DAG.getConstant(1, MVT::i32);
3311   SDValue FVal = DAG.getConstant(0, MVT::i32);
3312   EVT VT = Op.getValueType();
3313
3314   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3315                                  ARMcc, CCR, OverflowCmp);
3316
3317   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3318   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3319 }
3320
3321
3322 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3323   SDValue Cond = Op.getOperand(0);
3324   SDValue SelectTrue = Op.getOperand(1);
3325   SDValue SelectFalse = Op.getOperand(2);
3326   SDLoc dl(Op);
3327   unsigned Opc = Cond.getOpcode();
3328
3329   if (Cond.getResNo() == 1 &&
3330       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3331        Opc == ISD::USUBO)) {
3332     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3333       return SDValue();
3334
3335     SDValue Value, OverflowCmp;
3336     SDValue ARMcc;
3337     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3338     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3339     EVT VT = Op.getValueType();
3340
3341     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3342                        ARMcc, CCR, OverflowCmp);
3343
3344   }
3345
3346   // Convert:
3347   //
3348   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3349   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3350   //
3351   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3352     const ConstantSDNode *CMOVTrue =
3353       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3354     const ConstantSDNode *CMOVFalse =
3355       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3356
3357     if (CMOVTrue && CMOVFalse) {
3358       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3359       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3360
3361       SDValue True;
3362       SDValue False;
3363       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3364         True = SelectTrue;
3365         False = SelectFalse;
3366       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3367         True = SelectFalse;
3368         False = SelectTrue;
3369       }
3370
3371       if (True.getNode() && False.getNode()) {
3372         EVT VT = Op.getValueType();
3373         SDValue ARMcc = Cond.getOperand(2);
3374         SDValue CCR = Cond.getOperand(3);
3375         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3376         assert(True.getValueType() == VT);
3377         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3378       }
3379     }
3380   }
3381
3382   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3383   // undefined bits before doing a full-word comparison with zero.
3384   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3385                      DAG.getConstant(1, Cond.getValueType()));
3386
3387   return DAG.getSelectCC(dl, Cond,
3388                          DAG.getConstant(0, Cond.getValueType()),
3389                          SelectTrue, SelectFalse, ISD::SETNE);
3390 }
3391
3392 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3393   if (CC == ISD::SETNE)
3394     return ISD::SETEQ;
3395   return ISD::getSetCCInverse(CC, true);
3396 }
3397
3398 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3399                                  bool &swpCmpOps, bool &swpVselOps) {
3400   // Start by selecting the GE condition code for opcodes that return true for
3401   // 'equality'
3402   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3403       CC == ISD::SETULE)
3404     CondCode = ARMCC::GE;
3405
3406   // and GT for opcodes that return false for 'equality'.
3407   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3408            CC == ISD::SETULT)
3409     CondCode = ARMCC::GT;
3410
3411   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3412   // to swap the compare operands.
3413   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3414       CC == ISD::SETULT)
3415     swpCmpOps = true;
3416
3417   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3418   // If we have an unordered opcode, we need to swap the operands to the VSEL
3419   // instruction (effectively negating the condition).
3420   //
3421   // This also has the effect of swapping which one of 'less' or 'greater'
3422   // returns true, so we also swap the compare operands. It also switches
3423   // whether we return true for 'equality', so we compensate by picking the
3424   // opposite condition code to our original choice.
3425   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3426       CC == ISD::SETUGT) {
3427     swpCmpOps = !swpCmpOps;
3428     swpVselOps = !swpVselOps;
3429     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3430   }
3431
3432   // 'ordered' is 'anything but unordered', so use the VS condition code and
3433   // swap the VSEL operands.
3434   if (CC == ISD::SETO) {
3435     CondCode = ARMCC::VS;
3436     swpVselOps = true;
3437   }
3438
3439   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3440   // code and swap the VSEL operands.
3441   if (CC == ISD::SETUNE) {
3442     CondCode = ARMCC::EQ;
3443     swpVselOps = true;
3444   }
3445 }
3446
3447 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3448   EVT VT = Op.getValueType();
3449   SDValue LHS = Op.getOperand(0);
3450   SDValue RHS = Op.getOperand(1);
3451   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3452   SDValue TrueVal = Op.getOperand(2);
3453   SDValue FalseVal = Op.getOperand(3);
3454   SDLoc dl(Op);
3455
3456   if (LHS.getValueType() == MVT::i32) {
3457     // Try to generate VSEL on ARMv8.
3458     // The VSEL instruction can't use all the usual ARM condition
3459     // codes: it only has two bits to select the condition code, so it's
3460     // constrained to use only GE, GT, VS and EQ.
3461     //
3462     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3463     // swap the operands of the previous compare instruction (effectively
3464     // inverting the compare condition, swapping 'less' and 'greater') and
3465     // sometimes need to swap the operands to the VSEL (which inverts the
3466     // condition in the sense of firing whenever the previous condition didn't)
3467     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3468                                       TrueVal.getValueType() == MVT::f64)) {
3469       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3470       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3471           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3472         CC = getInverseCCForVSEL(CC);
3473         std::swap(TrueVal, FalseVal);
3474       }
3475     }
3476
3477     SDValue ARMcc;
3478     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3479     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3480     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3481                        Cmp);
3482   }
3483
3484   ARMCC::CondCodes CondCode, CondCode2;
3485   FPCCToARMCC(CC, CondCode, CondCode2);
3486
3487   // Try to generate VSEL on ARMv8.
3488   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3489                                     TrueVal.getValueType() == MVT::f64)) {
3490     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3491     // same operands, as follows:
3492     //   c = fcmp [ogt, olt, ugt, ult] a, b
3493     //   select c, a, b
3494     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3495     // handled differently than the original code sequence.
3496     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3497         RHS == FalseVal) {
3498       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3499         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3500       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3501         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3502     }
3503
3504     bool swpCmpOps = false;
3505     bool swpVselOps = false;
3506     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3507
3508     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3509         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3510       if (swpCmpOps)
3511         std::swap(LHS, RHS);
3512       if (swpVselOps)
3513         std::swap(TrueVal, FalseVal);
3514     }
3515   }
3516
3517   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3518   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3519   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3520   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3521                                ARMcc, CCR, Cmp);
3522   if (CondCode2 != ARMCC::AL) {
3523     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3524     // FIXME: Needs another CMP because flag can have but one use.
3525     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3526     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3527                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3528   }
3529   return Result;
3530 }
3531
3532 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3533 /// to morph to an integer compare sequence.
3534 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3535                            const ARMSubtarget *Subtarget) {
3536   SDNode *N = Op.getNode();
3537   if (!N->hasOneUse())
3538     // Otherwise it requires moving the value from fp to integer registers.
3539     return false;
3540   if (!N->getNumValues())
3541     return false;
3542   EVT VT = Op.getValueType();
3543   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3544     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3545     // vmrs are very slow, e.g. cortex-a8.
3546     return false;
3547
3548   if (isFloatingPointZero(Op)) {
3549     SeenZero = true;
3550     return true;
3551   }
3552   return ISD::isNormalLoad(N);
3553 }
3554
3555 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3556   if (isFloatingPointZero(Op))
3557     return DAG.getConstant(0, MVT::i32);
3558
3559   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3560     return DAG.getLoad(MVT::i32, SDLoc(Op),
3561                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3562                        Ld->isVolatile(), Ld->isNonTemporal(),
3563                        Ld->isInvariant(), Ld->getAlignment());
3564
3565   llvm_unreachable("Unknown VFP cmp argument!");
3566 }
3567
3568 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3569                            SDValue &RetVal1, SDValue &RetVal2) {
3570   if (isFloatingPointZero(Op)) {
3571     RetVal1 = DAG.getConstant(0, MVT::i32);
3572     RetVal2 = DAG.getConstant(0, MVT::i32);
3573     return;
3574   }
3575
3576   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3577     SDValue Ptr = Ld->getBasePtr();
3578     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3579                           Ld->getChain(), Ptr,
3580                           Ld->getPointerInfo(),
3581                           Ld->isVolatile(), Ld->isNonTemporal(),
3582                           Ld->isInvariant(), Ld->getAlignment());
3583
3584     EVT PtrType = Ptr.getValueType();
3585     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3586     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3587                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3588     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3589                           Ld->getChain(), NewPtr,
3590                           Ld->getPointerInfo().getWithOffset(4),
3591                           Ld->isVolatile(), Ld->isNonTemporal(),
3592                           Ld->isInvariant(), NewAlign);
3593     return;
3594   }
3595
3596   llvm_unreachable("Unknown VFP cmp argument!");
3597 }
3598
3599 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3600 /// f32 and even f64 comparisons to integer ones.
3601 SDValue
3602 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3603   SDValue Chain = Op.getOperand(0);
3604   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3605   SDValue LHS = Op.getOperand(2);
3606   SDValue RHS = Op.getOperand(3);
3607   SDValue Dest = Op.getOperand(4);
3608   SDLoc dl(Op);
3609
3610   bool LHSSeenZero = false;
3611   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3612   bool RHSSeenZero = false;
3613   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3614   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3615     // If unsafe fp math optimization is enabled and there are no other uses of
3616     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3617     // to an integer comparison.
3618     if (CC == ISD::SETOEQ)
3619       CC = ISD::SETEQ;
3620     else if (CC == ISD::SETUNE)
3621       CC = ISD::SETNE;
3622
3623     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3624     SDValue ARMcc;
3625     if (LHS.getValueType() == MVT::f32) {
3626       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3627                         bitcastf32Toi32(LHS, DAG), Mask);
3628       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3629                         bitcastf32Toi32(RHS, DAG), Mask);
3630       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3631       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3632       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3633                          Chain, Dest, ARMcc, CCR, Cmp);
3634     }
3635
3636     SDValue LHS1, LHS2;
3637     SDValue RHS1, RHS2;
3638     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3639     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3640     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3641     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3642     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3643     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3644     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3645     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3646     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3647   }
3648
3649   return SDValue();
3650 }
3651
3652 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3653   SDValue Chain = Op.getOperand(0);
3654   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3655   SDValue LHS = Op.getOperand(2);
3656   SDValue RHS = Op.getOperand(3);
3657   SDValue Dest = Op.getOperand(4);
3658   SDLoc dl(Op);
3659
3660   if (LHS.getValueType() == MVT::i32) {
3661     SDValue ARMcc;
3662     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3663     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3664     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3665                        Chain, Dest, ARMcc, CCR, Cmp);
3666   }
3667
3668   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3669
3670   if (getTargetMachine().Options.UnsafeFPMath &&
3671       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3672        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3673     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3674     if (Result.getNode())
3675       return Result;
3676   }
3677
3678   ARMCC::CondCodes CondCode, CondCode2;
3679   FPCCToARMCC(CC, CondCode, CondCode2);
3680
3681   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3682   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3683   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3684   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3685   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3686   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3687   if (CondCode2 != ARMCC::AL) {
3688     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3689     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3690     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3691   }
3692   return Res;
3693 }
3694
3695 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3696   SDValue Chain = Op.getOperand(0);
3697   SDValue Table = Op.getOperand(1);
3698   SDValue Index = Op.getOperand(2);
3699   SDLoc dl(Op);
3700
3701   EVT PTy = getPointerTy();
3702   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3703   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3704   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3705   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3706   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3707   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3708   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3709   if (Subtarget->isThumb2()) {
3710     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3711     // which does another jump to the destination. This also makes it easier
3712     // to translate it to TBB / TBH later.
3713     // FIXME: This might not work if the function is extremely large.
3714     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3715                        Addr, Op.getOperand(2), JTI, UId);
3716   }
3717   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3718     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3719                        MachinePointerInfo::getJumpTable(),
3720                        false, false, false, 0);
3721     Chain = Addr.getValue(1);
3722     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3723     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3724   } else {
3725     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3726                        MachinePointerInfo::getJumpTable(),
3727                        false, false, false, 0);
3728     Chain = Addr.getValue(1);
3729     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3730   }
3731 }
3732
3733 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3734   EVT VT = Op.getValueType();
3735   SDLoc dl(Op);
3736
3737   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3738     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3739       return Op;
3740     return DAG.UnrollVectorOp(Op.getNode());
3741   }
3742
3743   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3744          "Invalid type for custom lowering!");
3745   if (VT != MVT::v4i16)
3746     return DAG.UnrollVectorOp(Op.getNode());
3747
3748   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3749   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3750 }
3751
3752 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3753   EVT VT = Op.getValueType();
3754   if (VT.isVector())
3755     return LowerVectorFP_TO_INT(Op, DAG);
3756
3757   SDLoc dl(Op);
3758   unsigned Opc;
3759
3760   switch (Op.getOpcode()) {
3761   default: llvm_unreachable("Invalid opcode!");
3762   case ISD::FP_TO_SINT:
3763     Opc = ARMISD::FTOSI;
3764     break;
3765   case ISD::FP_TO_UINT:
3766     Opc = ARMISD::FTOUI;
3767     break;
3768   }
3769   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3770   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3771 }
3772
3773 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3774   EVT VT = Op.getValueType();
3775   SDLoc dl(Op);
3776
3777   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3778     if (VT.getVectorElementType() == MVT::f32)
3779       return Op;
3780     return DAG.UnrollVectorOp(Op.getNode());
3781   }
3782
3783   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3784          "Invalid type for custom lowering!");
3785   if (VT != MVT::v4f32)
3786     return DAG.UnrollVectorOp(Op.getNode());
3787
3788   unsigned CastOpc;
3789   unsigned Opc;
3790   switch (Op.getOpcode()) {
3791   default: llvm_unreachable("Invalid opcode!");
3792   case ISD::SINT_TO_FP:
3793     CastOpc = ISD::SIGN_EXTEND;
3794     Opc = ISD::SINT_TO_FP;
3795     break;
3796   case ISD::UINT_TO_FP:
3797     CastOpc = ISD::ZERO_EXTEND;
3798     Opc = ISD::UINT_TO_FP;
3799     break;
3800   }
3801
3802   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3803   return DAG.getNode(Opc, dl, VT, Op);
3804 }
3805
3806 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3807   EVT VT = Op.getValueType();
3808   if (VT.isVector())
3809     return LowerVectorINT_TO_FP(Op, DAG);
3810
3811   SDLoc dl(Op);
3812   unsigned Opc;
3813
3814   switch (Op.getOpcode()) {
3815   default: llvm_unreachable("Invalid opcode!");
3816   case ISD::SINT_TO_FP:
3817     Opc = ARMISD::SITOF;
3818     break;
3819   case ISD::UINT_TO_FP:
3820     Opc = ARMISD::UITOF;
3821     break;
3822   }
3823
3824   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3825   return DAG.getNode(Opc, dl, VT, Op);
3826 }
3827
3828 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3829   // Implement fcopysign with a fabs and a conditional fneg.
3830   SDValue Tmp0 = Op.getOperand(0);
3831   SDValue Tmp1 = Op.getOperand(1);
3832   SDLoc dl(Op);
3833   EVT VT = Op.getValueType();
3834   EVT SrcVT = Tmp1.getValueType();
3835   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3836     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3837   bool UseNEON = !InGPR && Subtarget->hasNEON();
3838
3839   if (UseNEON) {
3840     // Use VBSL to copy the sign bit.
3841     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3842     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3843                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3844     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3845     if (VT == MVT::f64)
3846       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3847                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3848                          DAG.getConstant(32, MVT::i32));
3849     else /*if (VT == MVT::f32)*/
3850       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3851     if (SrcVT == MVT::f32) {
3852       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3853       if (VT == MVT::f64)
3854         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3855                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3856                            DAG.getConstant(32, MVT::i32));
3857     } else if (VT == MVT::f32)
3858       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3859                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3860                          DAG.getConstant(32, MVT::i32));
3861     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3862     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3863
3864     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3865                                             MVT::i32);
3866     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3867     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3868                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3869
3870     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3871                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3872                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3873     if (VT == MVT::f32) {
3874       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3875       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3876                         DAG.getConstant(0, MVT::i32));
3877     } else {
3878       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3879     }
3880
3881     return Res;
3882   }
3883
3884   // Bitcast operand 1 to i32.
3885   if (SrcVT == MVT::f64)
3886     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3887                        Tmp1).getValue(1);
3888   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3889
3890   // Or in the signbit with integer operations.
3891   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3892   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3893   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3894   if (VT == MVT::f32) {
3895     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3896                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3897     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3898                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3899   }
3900
3901   // f64: Or the high part with signbit and then combine two parts.
3902   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3903                      Tmp0);
3904   SDValue Lo = Tmp0.getValue(0);
3905   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3906   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3907   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3908 }
3909
3910 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3911   MachineFunction &MF = DAG.getMachineFunction();
3912   MachineFrameInfo *MFI = MF.getFrameInfo();
3913   MFI->setReturnAddressIsTaken(true);
3914
3915   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3916     return SDValue();
3917
3918   EVT VT = Op.getValueType();
3919   SDLoc dl(Op);
3920   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3921   if (Depth) {
3922     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3923     SDValue Offset = DAG.getConstant(4, MVT::i32);
3924     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3925                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3926                        MachinePointerInfo(), false, false, false, 0);
3927   }
3928
3929   // Return LR, which contains the return address. Mark it an implicit live-in.
3930   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3931   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3932 }
3933
3934 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3935   const ARMBaseRegisterInfo &ARI =
3936     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3937   MachineFunction &MF = DAG.getMachineFunction();
3938   MachineFrameInfo *MFI = MF.getFrameInfo();
3939   MFI->setFrameAddressIsTaken(true);
3940
3941   EVT VT = Op.getValueType();
3942   SDLoc dl(Op);  // FIXME probably not meaningful
3943   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3944   unsigned FrameReg = ARI.getFrameRegister(MF);
3945   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3946   while (Depth--)
3947     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3948                             MachinePointerInfo(),
3949                             false, false, false, 0);
3950   return FrameAddr;
3951 }
3952
3953 // FIXME? Maybe this could be a TableGen attribute on some registers and
3954 // this table could be generated automatically from RegInfo.
3955 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3956                                               EVT VT) const {
3957   unsigned Reg = StringSwitch<unsigned>(RegName)
3958                        .Case("sp", ARM::SP)
3959                        .Default(0);
3960   if (Reg)
3961     return Reg;
3962   report_fatal_error("Invalid register name global variable");
3963 }
3964
3965 /// ExpandBITCAST - If the target supports VFP, this function is called to
3966 /// expand a bit convert where either the source or destination type is i64 to
3967 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3968 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3969 /// vectors), since the legalizer won't know what to do with that.
3970 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3972   SDLoc dl(N);
3973   SDValue Op = N->getOperand(0);
3974
3975   // This function is only supposed to be called for i64 types, either as the
3976   // source or destination of the bit convert.
3977   EVT SrcVT = Op.getValueType();
3978   EVT DstVT = N->getValueType(0);
3979   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3980          "ExpandBITCAST called for non-i64 type");
3981
3982   // Turn i64->f64 into VMOVDRR.
3983   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3984     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3985                              DAG.getConstant(0, MVT::i32));
3986     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3987                              DAG.getConstant(1, MVT::i32));
3988     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3989                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3990   }
3991
3992   // Turn f64->i64 into VMOVRRD.
3993   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3994     SDValue Cvt;
3995     if (TLI.isBigEndian() && SrcVT.isVector() &&
3996         SrcVT.getVectorNumElements() > 1)
3997       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3998                         DAG.getVTList(MVT::i32, MVT::i32),
3999                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4000     else
4001       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4002                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4003     // Merge the pieces into a single i64 value.
4004     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4005   }
4006
4007   return SDValue();
4008 }
4009
4010 /// getZeroVector - Returns a vector of specified type with all zero elements.
4011 /// Zero vectors are used to represent vector negation and in those cases
4012 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4013 /// not support i64 elements, so sometimes the zero vectors will need to be
4014 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4015 /// zero vector.
4016 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4017   assert(VT.isVector() && "Expected a vector type");
4018   // The canonical modified immediate encoding of a zero vector is....0!
4019   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4020   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4021   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4022   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4023 }
4024
4025 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4026 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4027 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4028                                                 SelectionDAG &DAG) const {
4029   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4030   EVT VT = Op.getValueType();
4031   unsigned VTBits = VT.getSizeInBits();
4032   SDLoc dl(Op);
4033   SDValue ShOpLo = Op.getOperand(0);
4034   SDValue ShOpHi = Op.getOperand(1);
4035   SDValue ShAmt  = Op.getOperand(2);
4036   SDValue ARMcc;
4037   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4038
4039   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4040
4041   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4042                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4043   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4044   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4045                                    DAG.getConstant(VTBits, MVT::i32));
4046   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4047   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4048   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4049
4050   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4051   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4052                           ARMcc, DAG, dl);
4053   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4054   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4055                            CCR, Cmp);
4056
4057   SDValue Ops[2] = { Lo, Hi };
4058   return DAG.getMergeValues(Ops, dl);
4059 }
4060
4061 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4062 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4063 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4064                                                SelectionDAG &DAG) const {
4065   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4066   EVT VT = Op.getValueType();
4067   unsigned VTBits = VT.getSizeInBits();
4068   SDLoc dl(Op);
4069   SDValue ShOpLo = Op.getOperand(0);
4070   SDValue ShOpHi = Op.getOperand(1);
4071   SDValue ShAmt  = Op.getOperand(2);
4072   SDValue ARMcc;
4073
4074   assert(Op.getOpcode() == ISD::SHL_PARTS);
4075   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4076                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4077   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4078   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4079                                    DAG.getConstant(VTBits, MVT::i32));
4080   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4081   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4082
4083   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4084   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4085   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4086                           ARMcc, DAG, dl);
4087   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4088   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4089                            CCR, Cmp);
4090
4091   SDValue Ops[2] = { Lo, Hi };
4092   return DAG.getMergeValues(Ops, dl);
4093 }
4094
4095 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4096                                             SelectionDAG &DAG) const {
4097   // The rounding mode is in bits 23:22 of the FPSCR.
4098   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4099   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4100   // so that the shift + and get folded into a bitfield extract.
4101   SDLoc dl(Op);
4102   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4103                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4104                                               MVT::i32));
4105   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4106                                   DAG.getConstant(1U << 22, MVT::i32));
4107   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4108                               DAG.getConstant(22, MVT::i32));
4109   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4110                      DAG.getConstant(3, MVT::i32));
4111 }
4112
4113 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4114                          const ARMSubtarget *ST) {
4115   EVT VT = N->getValueType(0);
4116   SDLoc dl(N);
4117
4118   if (!ST->hasV6T2Ops())
4119     return SDValue();
4120
4121   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4122   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4123 }
4124
4125 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4126 /// for each 16-bit element from operand, repeated.  The basic idea is to
4127 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4128 ///
4129 /// Trace for v4i16:
4130 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4131 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4132 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4133 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4134 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4135 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4136 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4137 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4138 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4139   EVT VT = N->getValueType(0);
4140   SDLoc DL(N);
4141
4142   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4143   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4144   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4145   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4146   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4147   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4148 }
4149
4150 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4151 /// bit-count for each 16-bit element from the operand.  We need slightly
4152 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4153 /// 64/128-bit registers.
4154 ///
4155 /// Trace for v4i16:
4156 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4157 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4158 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4159 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4160 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4161   EVT VT = N->getValueType(0);
4162   SDLoc DL(N);
4163
4164   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4165   if (VT.is64BitVector()) {
4166     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4167     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4168                        DAG.getIntPtrConstant(0));
4169   } else {
4170     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4171                                     BitCounts, DAG.getIntPtrConstant(0));
4172     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4173   }
4174 }
4175
4176 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4177 /// bit-count for each 32-bit element from the operand.  The idea here is
4178 /// to split the vector into 16-bit elements, leverage the 16-bit count
4179 /// routine, and then combine the results.
4180 ///
4181 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4182 /// input    = [v0    v1    ] (vi: 32-bit elements)
4183 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4184 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4185 /// vrev: N0 = [k1 k0 k3 k2 ]
4186 ///            [k0 k1 k2 k3 ]
4187 ///       N1 =+[k1 k0 k3 k2 ]
4188 ///            [k0 k2 k1 k3 ]
4189 ///       N2 =+[k1 k3 k0 k2 ]
4190 ///            [k0    k2    k1    k3    ]
4191 /// Extended =+[k1    k3    k0    k2    ]
4192 ///            [k0    k2    ]
4193 /// Extracted=+[k1    k3    ]
4194 ///
4195 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4196   EVT VT = N->getValueType(0);
4197   SDLoc DL(N);
4198
4199   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4200
4201   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4202   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4203   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4204   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4205   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4206
4207   if (VT.is64BitVector()) {
4208     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4209     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4210                        DAG.getIntPtrConstant(0));
4211   } else {
4212     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4213                                     DAG.getIntPtrConstant(0));
4214     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4215   }
4216 }
4217
4218 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4219                           const ARMSubtarget *ST) {
4220   EVT VT = N->getValueType(0);
4221
4222   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4223   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4224           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4225          "Unexpected type for custom ctpop lowering");
4226
4227   if (VT.getVectorElementType() == MVT::i32)
4228     return lowerCTPOP32BitElements(N, DAG);
4229   else
4230     return lowerCTPOP16BitElements(N, DAG);
4231 }
4232
4233 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4234                           const ARMSubtarget *ST) {
4235   EVT VT = N->getValueType(0);
4236   SDLoc dl(N);
4237
4238   if (!VT.isVector())
4239     return SDValue();
4240
4241   // Lower vector shifts on NEON to use VSHL.
4242   assert(ST->hasNEON() && "unexpected vector shift");
4243
4244   // Left shifts translate directly to the vshiftu intrinsic.
4245   if (N->getOpcode() == ISD::SHL)
4246     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4247                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4248                        N->getOperand(0), N->getOperand(1));
4249
4250   assert((N->getOpcode() == ISD::SRA ||
4251           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4252
4253   // NEON uses the same intrinsics for both left and right shifts.  For
4254   // right shifts, the shift amounts are negative, so negate the vector of
4255   // shift amounts.
4256   EVT ShiftVT = N->getOperand(1).getValueType();
4257   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4258                                      getZeroVector(ShiftVT, DAG, dl),
4259                                      N->getOperand(1));
4260   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4261                              Intrinsic::arm_neon_vshifts :
4262                              Intrinsic::arm_neon_vshiftu);
4263   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4264                      DAG.getConstant(vshiftInt, MVT::i32),
4265                      N->getOperand(0), NegatedCount);
4266 }
4267
4268 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4269                                 const ARMSubtarget *ST) {
4270   EVT VT = N->getValueType(0);
4271   SDLoc dl(N);
4272
4273   // We can get here for a node like i32 = ISD::SHL i32, i64
4274   if (VT != MVT::i64)
4275     return SDValue();
4276
4277   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4278          "Unknown shift to lower!");
4279
4280   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4281   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4282       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4283     return SDValue();
4284
4285   // If we are in thumb mode, we don't have RRX.
4286   if (ST->isThumb1Only()) return SDValue();
4287
4288   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4289   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4290                            DAG.getConstant(0, MVT::i32));
4291   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4292                            DAG.getConstant(1, MVT::i32));
4293
4294   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4295   // captures the result into a carry flag.
4296   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4297   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4298
4299   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4300   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4301
4302   // Merge the pieces into a single i64 value.
4303  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4304 }
4305
4306 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4307   SDValue TmpOp0, TmpOp1;
4308   bool Invert = false;
4309   bool Swap = false;
4310   unsigned Opc = 0;
4311
4312   SDValue Op0 = Op.getOperand(0);
4313   SDValue Op1 = Op.getOperand(1);
4314   SDValue CC = Op.getOperand(2);
4315   EVT VT = Op.getValueType();
4316   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4317   SDLoc dl(Op);
4318
4319   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4320     switch (SetCCOpcode) {
4321     default: llvm_unreachable("Illegal FP comparison");
4322     case ISD::SETUNE:
4323     case ISD::SETNE:  Invert = true; // Fallthrough
4324     case ISD::SETOEQ:
4325     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4326     case ISD::SETOLT:
4327     case ISD::SETLT: Swap = true; // Fallthrough
4328     case ISD::SETOGT:
4329     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4330     case ISD::SETOLE:
4331     case ISD::SETLE:  Swap = true; // Fallthrough
4332     case ISD::SETOGE:
4333     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4334     case ISD::SETUGE: Swap = true; // Fallthrough
4335     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4336     case ISD::SETUGT: Swap = true; // Fallthrough
4337     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4338     case ISD::SETUEQ: Invert = true; // Fallthrough
4339     case ISD::SETONE:
4340       // Expand this to (OLT | OGT).
4341       TmpOp0 = Op0;
4342       TmpOp1 = Op1;
4343       Opc = ISD::OR;
4344       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4345       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4346       break;
4347     case ISD::SETUO: Invert = true; // Fallthrough
4348     case ISD::SETO:
4349       // Expand this to (OLT | OGE).
4350       TmpOp0 = Op0;
4351       TmpOp1 = Op1;
4352       Opc = ISD::OR;
4353       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4354       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4355       break;
4356     }
4357   } else {
4358     // Integer comparisons.
4359     switch (SetCCOpcode) {
4360     default: llvm_unreachable("Illegal integer comparison");
4361     case ISD::SETNE:  Invert = true;
4362     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4363     case ISD::SETLT:  Swap = true;
4364     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4365     case ISD::SETLE:  Swap = true;
4366     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4367     case ISD::SETULT: Swap = true;
4368     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4369     case ISD::SETULE: Swap = true;
4370     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4371     }
4372
4373     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4374     if (Opc == ARMISD::VCEQ) {
4375
4376       SDValue AndOp;
4377       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4378         AndOp = Op0;
4379       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4380         AndOp = Op1;
4381
4382       // Ignore bitconvert.
4383       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4384         AndOp = AndOp.getOperand(0);
4385
4386       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4387         Opc = ARMISD::VTST;
4388         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4389         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4390         Invert = !Invert;
4391       }
4392     }
4393   }
4394
4395   if (Swap)
4396     std::swap(Op0, Op1);
4397
4398   // If one of the operands is a constant vector zero, attempt to fold the
4399   // comparison to a specialized compare-against-zero form.
4400   SDValue SingleOp;
4401   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4402     SingleOp = Op0;
4403   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4404     if (Opc == ARMISD::VCGE)
4405       Opc = ARMISD::VCLEZ;
4406     else if (Opc == ARMISD::VCGT)
4407       Opc = ARMISD::VCLTZ;
4408     SingleOp = Op1;
4409   }
4410
4411   SDValue Result;
4412   if (SingleOp.getNode()) {
4413     switch (Opc) {
4414     case ARMISD::VCEQ:
4415       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4416     case ARMISD::VCGE:
4417       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4418     case ARMISD::VCLEZ:
4419       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4420     case ARMISD::VCGT:
4421       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4422     case ARMISD::VCLTZ:
4423       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4424     default:
4425       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4426     }
4427   } else {
4428      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4429   }
4430
4431   if (Invert)
4432     Result = DAG.getNOT(dl, Result, VT);
4433
4434   return Result;
4435 }
4436
4437 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4438 /// valid vector constant for a NEON instruction with a "modified immediate"
4439 /// operand (e.g., VMOV).  If so, return the encoded value.
4440 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4441                                  unsigned SplatBitSize, SelectionDAG &DAG,
4442                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4443   unsigned OpCmode, Imm;
4444
4445   // SplatBitSize is set to the smallest size that splats the vector, so a
4446   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4447   // immediate instructions others than VMOV do not support the 8-bit encoding
4448   // of a zero vector, and the default encoding of zero is supposed to be the
4449   // 32-bit version.
4450   if (SplatBits == 0)
4451     SplatBitSize = 32;
4452
4453   switch (SplatBitSize) {
4454   case 8:
4455     if (type != VMOVModImm)
4456       return SDValue();
4457     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4458     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4459     OpCmode = 0xe;
4460     Imm = SplatBits;
4461     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4462     break;
4463
4464   case 16:
4465     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4466     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4467     if ((SplatBits & ~0xff) == 0) {
4468       // Value = 0x00nn: Op=x, Cmode=100x.
4469       OpCmode = 0x8;
4470       Imm = SplatBits;
4471       break;
4472     }
4473     if ((SplatBits & ~0xff00) == 0) {
4474       // Value = 0xnn00: Op=x, Cmode=101x.
4475       OpCmode = 0xa;
4476       Imm = SplatBits >> 8;
4477       break;
4478     }
4479     return SDValue();
4480
4481   case 32:
4482     // NEON's 32-bit VMOV supports splat values where:
4483     // * only one byte is nonzero, or
4484     // * the least significant byte is 0xff and the second byte is nonzero, or
4485     // * the least significant 2 bytes are 0xff and the third is nonzero.
4486     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4487     if ((SplatBits & ~0xff) == 0) {
4488       // Value = 0x000000nn: Op=x, Cmode=000x.
4489       OpCmode = 0;
4490       Imm = SplatBits;
4491       break;
4492     }
4493     if ((SplatBits & ~0xff00) == 0) {
4494       // Value = 0x0000nn00: Op=x, Cmode=001x.
4495       OpCmode = 0x2;
4496       Imm = SplatBits >> 8;
4497       break;
4498     }
4499     if ((SplatBits & ~0xff0000) == 0) {
4500       // Value = 0x00nn0000: Op=x, Cmode=010x.
4501       OpCmode = 0x4;
4502       Imm = SplatBits >> 16;
4503       break;
4504     }
4505     if ((SplatBits & ~0xff000000) == 0) {
4506       // Value = 0xnn000000: Op=x, Cmode=011x.
4507       OpCmode = 0x6;
4508       Imm = SplatBits >> 24;
4509       break;
4510     }
4511
4512     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4513     if (type == OtherModImm) return SDValue();
4514
4515     if ((SplatBits & ~0xffff) == 0 &&
4516         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4517       // Value = 0x0000nnff: Op=x, Cmode=1100.
4518       OpCmode = 0xc;
4519       Imm = SplatBits >> 8;
4520       break;
4521     }
4522
4523     if ((SplatBits & ~0xffffff) == 0 &&
4524         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4525       // Value = 0x00nnffff: Op=x, Cmode=1101.
4526       OpCmode = 0xd;
4527       Imm = SplatBits >> 16;
4528       break;
4529     }
4530
4531     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4532     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4533     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4534     // and fall through here to test for a valid 64-bit splat.  But, then the
4535     // caller would also need to check and handle the change in size.
4536     return SDValue();
4537
4538   case 64: {
4539     if (type != VMOVModImm)
4540       return SDValue();
4541     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4542     uint64_t BitMask = 0xff;
4543     uint64_t Val = 0;
4544     unsigned ImmMask = 1;
4545     Imm = 0;
4546     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4547       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4548         Val |= BitMask;
4549         Imm |= ImmMask;
4550       } else if ((SplatBits & BitMask) != 0) {
4551         return SDValue();
4552       }
4553       BitMask <<= 8;
4554       ImmMask <<= 1;
4555     }
4556
4557     if (DAG.getTargetLoweringInfo().isBigEndian())
4558       // swap higher and lower 32 bit word
4559       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4560
4561     // Op=1, Cmode=1110.
4562     OpCmode = 0x1e;
4563     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4564     break;
4565   }
4566
4567   default:
4568     llvm_unreachable("unexpected size for isNEONModifiedImm");
4569   }
4570
4571   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4572   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4573 }
4574
4575 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4576                                            const ARMSubtarget *ST) const {
4577   if (!ST->hasVFP3())
4578     return SDValue();
4579
4580   bool IsDouble = Op.getValueType() == MVT::f64;
4581   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4582
4583   // Try splatting with a VMOV.f32...
4584   APFloat FPVal = CFP->getValueAPF();
4585   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4586
4587   if (ImmVal != -1) {
4588     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4589       // We have code in place to select a valid ConstantFP already, no need to
4590       // do any mangling.
4591       return Op;
4592     }
4593
4594     // It's a float and we are trying to use NEON operations where
4595     // possible. Lower it to a splat followed by an extract.
4596     SDLoc DL(Op);
4597     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4598     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4599                                       NewVal);
4600     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4601                        DAG.getConstant(0, MVT::i32));
4602   }
4603
4604   // The rest of our options are NEON only, make sure that's allowed before
4605   // proceeding..
4606   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4607     return SDValue();
4608
4609   EVT VMovVT;
4610   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4611
4612   // It wouldn't really be worth bothering for doubles except for one very
4613   // important value, which does happen to match: 0.0. So make sure we don't do
4614   // anything stupid.
4615   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4616     return SDValue();
4617
4618   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4619   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4620                                      false, VMOVModImm);
4621   if (NewVal != SDValue()) {
4622     SDLoc DL(Op);
4623     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4624                                       NewVal);
4625     if (IsDouble)
4626       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4627
4628     // It's a float: cast and extract a vector element.
4629     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4630                                        VecConstant);
4631     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4632                        DAG.getConstant(0, MVT::i32));
4633   }
4634
4635   // Finally, try a VMVN.i32
4636   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4637                              false, VMVNModImm);
4638   if (NewVal != SDValue()) {
4639     SDLoc DL(Op);
4640     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4641
4642     if (IsDouble)
4643       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4644
4645     // It's a float: cast and extract a vector element.
4646     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4647                                        VecConstant);
4648     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4649                        DAG.getConstant(0, MVT::i32));
4650   }
4651
4652   return SDValue();
4653 }
4654
4655 // check if an VEXT instruction can handle the shuffle mask when the
4656 // vector sources of the shuffle are the same.
4657 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4658   unsigned NumElts = VT.getVectorNumElements();
4659
4660   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4661   if (M[0] < 0)
4662     return false;
4663
4664   Imm = M[0];
4665
4666   // If this is a VEXT shuffle, the immediate value is the index of the first
4667   // element.  The other shuffle indices must be the successive elements after
4668   // the first one.
4669   unsigned ExpectedElt = Imm;
4670   for (unsigned i = 1; i < NumElts; ++i) {
4671     // Increment the expected index.  If it wraps around, just follow it
4672     // back to index zero and keep going.
4673     ++ExpectedElt;
4674     if (ExpectedElt == NumElts)
4675       ExpectedElt = 0;
4676
4677     if (M[i] < 0) continue; // ignore UNDEF indices
4678     if (ExpectedElt != static_cast<unsigned>(M[i]))
4679       return false;
4680   }
4681
4682   return true;
4683 }
4684
4685
4686 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4687                        bool &ReverseVEXT, unsigned &Imm) {
4688   unsigned NumElts = VT.getVectorNumElements();
4689   ReverseVEXT = false;
4690
4691   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4692   if (M[0] < 0)
4693     return false;
4694
4695   Imm = M[0];
4696
4697   // If this is a VEXT shuffle, the immediate value is the index of the first
4698   // element.  The other shuffle indices must be the successive elements after
4699   // the first one.
4700   unsigned ExpectedElt = Imm;
4701   for (unsigned i = 1; i < NumElts; ++i) {
4702     // Increment the expected index.  If it wraps around, it may still be
4703     // a VEXT but the source vectors must be swapped.
4704     ExpectedElt += 1;
4705     if (ExpectedElt == NumElts * 2) {
4706       ExpectedElt = 0;
4707       ReverseVEXT = true;
4708     }
4709
4710     if (M[i] < 0) continue; // ignore UNDEF indices
4711     if (ExpectedElt != static_cast<unsigned>(M[i]))
4712       return false;
4713   }
4714
4715   // Adjust the index value if the source operands will be swapped.
4716   if (ReverseVEXT)
4717     Imm -= NumElts;
4718
4719   return true;
4720 }
4721
4722 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4723 /// instruction with the specified blocksize.  (The order of the elements
4724 /// within each block of the vector is reversed.)
4725 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4726   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4727          "Only possible block sizes for VREV are: 16, 32, 64");
4728
4729   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4730   if (EltSz == 64)
4731     return false;
4732
4733   unsigned NumElts = VT.getVectorNumElements();
4734   unsigned BlockElts = M[0] + 1;
4735   // If the first shuffle index is UNDEF, be optimistic.
4736   if (M[0] < 0)
4737     BlockElts = BlockSize / EltSz;
4738
4739   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4740     return false;
4741
4742   for (unsigned i = 0; i < NumElts; ++i) {
4743     if (M[i] < 0) continue; // ignore UNDEF indices
4744     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4745       return false;
4746   }
4747
4748   return true;
4749 }
4750
4751 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4752   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4753   // range, then 0 is placed into the resulting vector. So pretty much any mask
4754   // of 8 elements can work here.
4755   return VT == MVT::v8i8 && M.size() == 8;
4756 }
4757
4758 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4759   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4760   if (EltSz == 64)
4761     return false;
4762
4763   unsigned NumElts = VT.getVectorNumElements();
4764   WhichResult = (M[0] == 0 ? 0 : 1);
4765   for (unsigned i = 0; i < NumElts; i += 2) {
4766     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4767         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4768       return false;
4769   }
4770   return true;
4771 }
4772
4773 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4774 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4775 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4776 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4777   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4778   if (EltSz == 64)
4779     return false;
4780
4781   unsigned NumElts = VT.getVectorNumElements();
4782   WhichResult = (M[0] == 0 ? 0 : 1);
4783   for (unsigned i = 0; i < NumElts; i += 2) {
4784     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4785         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4786       return false;
4787   }
4788   return true;
4789 }
4790
4791 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4792   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4793   if (EltSz == 64)
4794     return false;
4795
4796   unsigned NumElts = VT.getVectorNumElements();
4797   WhichResult = (M[0] == 0 ? 0 : 1);
4798   for (unsigned i = 0; i != NumElts; ++i) {
4799     if (M[i] < 0) continue; // ignore UNDEF indices
4800     if ((unsigned) M[i] != 2 * i + WhichResult)
4801       return false;
4802   }
4803
4804   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4805   if (VT.is64BitVector() && EltSz == 32)
4806     return false;
4807
4808   return true;
4809 }
4810
4811 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4812 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4813 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4814 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4815   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4816   if (EltSz == 64)
4817     return false;
4818
4819   unsigned Half = VT.getVectorNumElements() / 2;
4820   WhichResult = (M[0] == 0 ? 0 : 1);
4821   for (unsigned j = 0; j != 2; ++j) {
4822     unsigned Idx = WhichResult;
4823     for (unsigned i = 0; i != Half; ++i) {
4824       int MIdx = M[i + j * Half];
4825       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4826         return false;
4827       Idx += 2;
4828     }
4829   }
4830
4831   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4832   if (VT.is64BitVector() && EltSz == 32)
4833     return false;
4834
4835   return true;
4836 }
4837
4838 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4839   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4840   if (EltSz == 64)
4841     return false;
4842
4843   unsigned NumElts = VT.getVectorNumElements();
4844   WhichResult = (M[0] == 0 ? 0 : 1);
4845   unsigned Idx = WhichResult * NumElts / 2;
4846   for (unsigned i = 0; i != NumElts; i += 2) {
4847     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4848         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4849       return false;
4850     Idx += 1;
4851   }
4852
4853   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4854   if (VT.is64BitVector() && EltSz == 32)
4855     return false;
4856
4857   return true;
4858 }
4859
4860 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4861 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4862 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4863 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4864   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4865   if (EltSz == 64)
4866     return false;
4867
4868   unsigned NumElts = VT.getVectorNumElements();
4869   WhichResult = (M[0] == 0 ? 0 : 1);
4870   unsigned Idx = WhichResult * NumElts / 2;
4871   for (unsigned i = 0; i != NumElts; i += 2) {
4872     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4873         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4874       return false;
4875     Idx += 1;
4876   }
4877
4878   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4879   if (VT.is64BitVector() && EltSz == 32)
4880     return false;
4881
4882   return true;
4883 }
4884
4885 /// \return true if this is a reverse operation on an vector.
4886 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4887   unsigned NumElts = VT.getVectorNumElements();
4888   // Make sure the mask has the right size.
4889   if (NumElts != M.size())
4890       return false;
4891
4892   // Look for <15, ..., 3, -1, 1, 0>.
4893   for (unsigned i = 0; i != NumElts; ++i)
4894     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4895       return false;
4896
4897   return true;
4898 }
4899
4900 // If N is an integer constant that can be moved into a register in one
4901 // instruction, return an SDValue of such a constant (will become a MOV
4902 // instruction).  Otherwise return null.
4903 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4904                                      const ARMSubtarget *ST, SDLoc dl) {
4905   uint64_t Val;
4906   if (!isa<ConstantSDNode>(N))
4907     return SDValue();
4908   Val = cast<ConstantSDNode>(N)->getZExtValue();
4909
4910   if (ST->isThumb1Only()) {
4911     if (Val <= 255 || ~Val <= 255)
4912       return DAG.getConstant(Val, MVT::i32);
4913   } else {
4914     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4915       return DAG.getConstant(Val, MVT::i32);
4916   }
4917   return SDValue();
4918 }
4919
4920 // If this is a case we can't handle, return null and let the default
4921 // expansion code take care of it.
4922 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4923                                              const ARMSubtarget *ST) const {
4924   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4925   SDLoc dl(Op);
4926   EVT VT = Op.getValueType();
4927
4928   APInt SplatBits, SplatUndef;
4929   unsigned SplatBitSize;
4930   bool HasAnyUndefs;
4931   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4932     if (SplatBitSize <= 64) {
4933       // Check if an immediate VMOV works.
4934       EVT VmovVT;
4935       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4936                                       SplatUndef.getZExtValue(), SplatBitSize,
4937                                       DAG, VmovVT, VT.is128BitVector(),
4938                                       VMOVModImm);
4939       if (Val.getNode()) {
4940         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4941         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4942       }
4943
4944       // Try an immediate VMVN.
4945       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4946       Val = isNEONModifiedImm(NegatedImm,
4947                                       SplatUndef.getZExtValue(), SplatBitSize,
4948                                       DAG, VmovVT, VT.is128BitVector(),
4949                                       VMVNModImm);
4950       if (Val.getNode()) {
4951         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4952         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4953       }
4954
4955       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4956       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4957         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4958         if (ImmVal != -1) {
4959           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4960           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4961         }
4962       }
4963     }
4964   }
4965
4966   // Scan through the operands to see if only one value is used.
4967   //
4968   // As an optimisation, even if more than one value is used it may be more
4969   // profitable to splat with one value then change some lanes.
4970   //
4971   // Heuristically we decide to do this if the vector has a "dominant" value,
4972   // defined as splatted to more than half of the lanes.
4973   unsigned NumElts = VT.getVectorNumElements();
4974   bool isOnlyLowElement = true;
4975   bool usesOnlyOneValue = true;
4976   bool hasDominantValue = false;
4977   bool isConstant = true;
4978
4979   // Map of the number of times a particular SDValue appears in the
4980   // element list.
4981   DenseMap<SDValue, unsigned> ValueCounts;
4982   SDValue Value;
4983   for (unsigned i = 0; i < NumElts; ++i) {
4984     SDValue V = Op.getOperand(i);
4985     if (V.getOpcode() == ISD::UNDEF)
4986       continue;
4987     if (i > 0)
4988       isOnlyLowElement = false;
4989     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4990       isConstant = false;
4991
4992     ValueCounts.insert(std::make_pair(V, 0));
4993     unsigned &Count = ValueCounts[V];
4994
4995     // Is this value dominant? (takes up more than half of the lanes)
4996     if (++Count > (NumElts / 2)) {
4997       hasDominantValue = true;
4998       Value = V;
4999     }
5000   }
5001   if (ValueCounts.size() != 1)
5002     usesOnlyOneValue = false;
5003   if (!Value.getNode() && ValueCounts.size() > 0)
5004     Value = ValueCounts.begin()->first;
5005
5006   if (ValueCounts.size() == 0)
5007     return DAG.getUNDEF(VT);
5008
5009   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5010   // Keep going if we are hitting this case.
5011   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5012     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5013
5014   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5015
5016   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5017   // i32 and try again.
5018   if (hasDominantValue && EltSize <= 32) {
5019     if (!isConstant) {
5020       SDValue N;
5021
5022       // If we are VDUPing a value that comes directly from a vector, that will
5023       // cause an unnecessary move to and from a GPR, where instead we could
5024       // just use VDUPLANE. We can only do this if the lane being extracted
5025       // is at a constant index, as the VDUP from lane instructions only have
5026       // constant-index forms.
5027       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5028           isa<ConstantSDNode>(Value->getOperand(1))) {
5029         // We need to create a new undef vector to use for the VDUPLANE if the
5030         // size of the vector from which we get the value is different than the
5031         // size of the vector that we need to create. We will insert the element
5032         // such that the register coalescer will remove unnecessary copies.
5033         if (VT != Value->getOperand(0).getValueType()) {
5034           ConstantSDNode *constIndex;
5035           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5036           assert(constIndex && "The index is not a constant!");
5037           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5038                              VT.getVectorNumElements();
5039           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5040                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5041                         Value, DAG.getConstant(index, MVT::i32)),
5042                            DAG.getConstant(index, MVT::i32));
5043         } else
5044           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5045                         Value->getOperand(0), Value->getOperand(1));
5046       } else
5047         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5048
5049       if (!usesOnlyOneValue) {
5050         // The dominant value was splatted as 'N', but we now have to insert
5051         // all differing elements.
5052         for (unsigned I = 0; I < NumElts; ++I) {
5053           if (Op.getOperand(I) == Value)
5054             continue;
5055           SmallVector<SDValue, 3> Ops;
5056           Ops.push_back(N);
5057           Ops.push_back(Op.getOperand(I));
5058           Ops.push_back(DAG.getConstant(I, MVT::i32));
5059           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5060         }
5061       }
5062       return N;
5063     }
5064     if (VT.getVectorElementType().isFloatingPoint()) {
5065       SmallVector<SDValue, 8> Ops;
5066       for (unsigned i = 0; i < NumElts; ++i)
5067         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5068                                   Op.getOperand(i)));
5069       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5070       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5071       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5072       if (Val.getNode())
5073         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5074     }
5075     if (usesOnlyOneValue) {
5076       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5077       if (isConstant && Val.getNode())
5078         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5079     }
5080   }
5081
5082   // If all elements are constants and the case above didn't get hit, fall back
5083   // to the default expansion, which will generate a load from the constant
5084   // pool.
5085   if (isConstant)
5086     return SDValue();
5087
5088   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5089   if (NumElts >= 4) {
5090     SDValue shuffle = ReconstructShuffle(Op, DAG);
5091     if (shuffle != SDValue())
5092       return shuffle;
5093   }
5094
5095   // Vectors with 32- or 64-bit elements can be built by directly assigning
5096   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5097   // will be legalized.
5098   if (EltSize >= 32) {
5099     // Do the expansion with floating-point types, since that is what the VFP
5100     // registers are defined to use, and since i64 is not legal.
5101     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5102     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5103     SmallVector<SDValue, 8> Ops;
5104     for (unsigned i = 0; i < NumElts; ++i)
5105       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5106     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5107     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5108   }
5109
5110   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5111   // know the default expansion would otherwise fall back on something even
5112   // worse. For a vector with one or two non-undef values, that's
5113   // scalar_to_vector for the elements followed by a shuffle (provided the
5114   // shuffle is valid for the target) and materialization element by element
5115   // on the stack followed by a load for everything else.
5116   if (!isConstant && !usesOnlyOneValue) {
5117     SDValue Vec = DAG.getUNDEF(VT);
5118     for (unsigned i = 0 ; i < NumElts; ++i) {
5119       SDValue V = Op.getOperand(i);
5120       if (V.getOpcode() == ISD::UNDEF)
5121         continue;
5122       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5123       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5124     }
5125     return Vec;
5126   }
5127
5128   return SDValue();
5129 }
5130
5131 // Gather data to see if the operation can be modelled as a
5132 // shuffle in combination with VEXTs.
5133 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5134                                               SelectionDAG &DAG) const {
5135   SDLoc dl(Op);
5136   EVT VT = Op.getValueType();
5137   unsigned NumElts = VT.getVectorNumElements();
5138
5139   SmallVector<SDValue, 2> SourceVecs;
5140   SmallVector<unsigned, 2> MinElts;
5141   SmallVector<unsigned, 2> MaxElts;
5142
5143   for (unsigned i = 0; i < NumElts; ++i) {
5144     SDValue V = Op.getOperand(i);
5145     if (V.getOpcode() == ISD::UNDEF)
5146       continue;
5147     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5148       // A shuffle can only come from building a vector from various
5149       // elements of other vectors.
5150       return SDValue();
5151     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5152                VT.getVectorElementType()) {
5153       // This code doesn't know how to handle shuffles where the vector
5154       // element types do not match (this happens because type legalization
5155       // promotes the return type of EXTRACT_VECTOR_ELT).
5156       // FIXME: It might be appropriate to extend this code to handle
5157       // mismatched types.
5158       return SDValue();
5159     }
5160
5161     // Record this extraction against the appropriate vector if possible...
5162     SDValue SourceVec = V.getOperand(0);
5163     // If the element number isn't a constant, we can't effectively
5164     // analyze what's going on.
5165     if (!isa<ConstantSDNode>(V.getOperand(1)))
5166       return SDValue();
5167     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5168     bool FoundSource = false;
5169     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5170       if (SourceVecs[j] == SourceVec) {
5171         if (MinElts[j] > EltNo)
5172           MinElts[j] = EltNo;
5173         if (MaxElts[j] < EltNo)
5174           MaxElts[j] = EltNo;
5175         FoundSource = true;
5176         break;
5177       }
5178     }
5179
5180     // Or record a new source if not...
5181     if (!FoundSource) {
5182       SourceVecs.push_back(SourceVec);
5183       MinElts.push_back(EltNo);
5184       MaxElts.push_back(EltNo);
5185     }
5186   }
5187
5188   // Currently only do something sane when at most two source vectors
5189   // involved.
5190   if (SourceVecs.size() > 2)
5191     return SDValue();
5192
5193   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5194   int VEXTOffsets[2] = {0, 0};
5195
5196   // This loop extracts the usage patterns of the source vectors
5197   // and prepares appropriate SDValues for a shuffle if possible.
5198   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5199     if (SourceVecs[i].getValueType() == VT) {
5200       // No VEXT necessary
5201       ShuffleSrcs[i] = SourceVecs[i];
5202       VEXTOffsets[i] = 0;
5203       continue;
5204     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5205       // It probably isn't worth padding out a smaller vector just to
5206       // break it down again in a shuffle.
5207       return SDValue();
5208     }
5209
5210     // Since only 64-bit and 128-bit vectors are legal on ARM and
5211     // we've eliminated the other cases...
5212     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5213            "unexpected vector sizes in ReconstructShuffle");
5214
5215     if (MaxElts[i] - MinElts[i] >= NumElts) {
5216       // Span too large for a VEXT to cope
5217       return SDValue();
5218     }
5219
5220     if (MinElts[i] >= NumElts) {
5221       // The extraction can just take the second half
5222       VEXTOffsets[i] = NumElts;
5223       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5224                                    SourceVecs[i],
5225                                    DAG.getIntPtrConstant(NumElts));
5226     } else if (MaxElts[i] < NumElts) {
5227       // The extraction can just take the first half
5228       VEXTOffsets[i] = 0;
5229       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5230                                    SourceVecs[i],
5231                                    DAG.getIntPtrConstant(0));
5232     } else {
5233       // An actual VEXT is needed
5234       VEXTOffsets[i] = MinElts[i];
5235       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5236                                      SourceVecs[i],
5237                                      DAG.getIntPtrConstant(0));
5238       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5239                                      SourceVecs[i],
5240                                      DAG.getIntPtrConstant(NumElts));
5241       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5242                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5243     }
5244   }
5245
5246   SmallVector<int, 8> Mask;
5247
5248   for (unsigned i = 0; i < NumElts; ++i) {
5249     SDValue Entry = Op.getOperand(i);
5250     if (Entry.getOpcode() == ISD::UNDEF) {
5251       Mask.push_back(-1);
5252       continue;
5253     }
5254
5255     SDValue ExtractVec = Entry.getOperand(0);
5256     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5257                                           .getOperand(1))->getSExtValue();
5258     if (ExtractVec == SourceVecs[0]) {
5259       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5260     } else {
5261       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5262     }
5263   }
5264
5265   // Final check before we try to produce nonsense...
5266   if (isShuffleMaskLegal(Mask, VT))
5267     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5268                                 &Mask[0]);
5269
5270   return SDValue();
5271 }
5272
5273 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5274 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5275 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5276 /// are assumed to be legal.
5277 bool
5278 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5279                                       EVT VT) const {
5280   if (VT.getVectorNumElements() == 4 &&
5281       (VT.is128BitVector() || VT.is64BitVector())) {
5282     unsigned PFIndexes[4];
5283     for (unsigned i = 0; i != 4; ++i) {
5284       if (M[i] < 0)
5285         PFIndexes[i] = 8;
5286       else
5287         PFIndexes[i] = M[i];
5288     }
5289
5290     // Compute the index in the perfect shuffle table.
5291     unsigned PFTableIndex =
5292       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5293     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5294     unsigned Cost = (PFEntry >> 30);
5295
5296     if (Cost <= 4)
5297       return true;
5298   }
5299
5300   bool ReverseVEXT;
5301   unsigned Imm, WhichResult;
5302
5303   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5304   return (EltSize >= 32 ||
5305           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5306           isVREVMask(M, VT, 64) ||
5307           isVREVMask(M, VT, 32) ||
5308           isVREVMask(M, VT, 16) ||
5309           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5310           isVTBLMask(M, VT) ||
5311           isVTRNMask(M, VT, WhichResult) ||
5312           isVUZPMask(M, VT, WhichResult) ||
5313           isVZIPMask(M, VT, WhichResult) ||
5314           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5315           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5316           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5317           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5318 }
5319
5320 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5321 /// the specified operations to build the shuffle.
5322 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5323                                       SDValue RHS, SelectionDAG &DAG,
5324                                       SDLoc dl) {
5325   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5326   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5327   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5328
5329   enum {
5330     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5331     OP_VREV,
5332     OP_VDUP0,
5333     OP_VDUP1,
5334     OP_VDUP2,
5335     OP_VDUP3,
5336     OP_VEXT1,
5337     OP_VEXT2,
5338     OP_VEXT3,
5339     OP_VUZPL, // VUZP, left result
5340     OP_VUZPR, // VUZP, right result
5341     OP_VZIPL, // VZIP, left result
5342     OP_VZIPR, // VZIP, right result
5343     OP_VTRNL, // VTRN, left result
5344     OP_VTRNR  // VTRN, right result
5345   };
5346
5347   if (OpNum == OP_COPY) {
5348     if (LHSID == (1*9+2)*9+3) return LHS;
5349     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5350     return RHS;
5351   }
5352
5353   SDValue OpLHS, OpRHS;
5354   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5355   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5356   EVT VT = OpLHS.getValueType();
5357
5358   switch (OpNum) {
5359   default: llvm_unreachable("Unknown shuffle opcode!");
5360   case OP_VREV:
5361     // VREV divides the vector in half and swaps within the half.
5362     if (VT.getVectorElementType() == MVT::i32 ||
5363         VT.getVectorElementType() == MVT::f32)
5364       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5365     // vrev <4 x i16> -> VREV32
5366     if (VT.getVectorElementType() == MVT::i16)
5367       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5368     // vrev <4 x i8> -> VREV16
5369     assert(VT.getVectorElementType() == MVT::i8);
5370     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5371   case OP_VDUP0:
5372   case OP_VDUP1:
5373   case OP_VDUP2:
5374   case OP_VDUP3:
5375     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5376                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5377   case OP_VEXT1:
5378   case OP_VEXT2:
5379   case OP_VEXT3:
5380     return DAG.getNode(ARMISD::VEXT, dl, VT,
5381                        OpLHS, OpRHS,
5382                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5383   case OP_VUZPL:
5384   case OP_VUZPR:
5385     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5386                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5387   case OP_VZIPL:
5388   case OP_VZIPR:
5389     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5390                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5391   case OP_VTRNL:
5392   case OP_VTRNR:
5393     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5394                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5395   }
5396 }
5397
5398 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5399                                        ArrayRef<int> ShuffleMask,
5400                                        SelectionDAG &DAG) {
5401   // Check to see if we can use the VTBL instruction.
5402   SDValue V1 = Op.getOperand(0);
5403   SDValue V2 = Op.getOperand(1);
5404   SDLoc DL(Op);
5405
5406   SmallVector<SDValue, 8> VTBLMask;
5407   for (ArrayRef<int>::iterator
5408          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5409     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5410
5411   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5412     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5413                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5414
5415   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5416                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5417 }
5418
5419 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5420                                                       SelectionDAG &DAG) {
5421   SDLoc DL(Op);
5422   SDValue OpLHS = Op.getOperand(0);
5423   EVT VT = OpLHS.getValueType();
5424
5425   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5426          "Expect an v8i16/v16i8 type");
5427   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5428   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5429   // extract the first 8 bytes into the top double word and the last 8 bytes
5430   // into the bottom double word. The v8i16 case is similar.
5431   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5432   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5433                      DAG.getConstant(ExtractNum, MVT::i32));
5434 }
5435
5436 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5437   SDValue V1 = Op.getOperand(0);
5438   SDValue V2 = Op.getOperand(1);
5439   SDLoc dl(Op);
5440   EVT VT = Op.getValueType();
5441   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5442
5443   // Convert shuffles that are directly supported on NEON to target-specific
5444   // DAG nodes, instead of keeping them as shuffles and matching them again
5445   // during code selection.  This is more efficient and avoids the possibility
5446   // of inconsistencies between legalization and selection.
5447   // FIXME: floating-point vectors should be canonicalized to integer vectors
5448   // of the same time so that they get CSEd properly.
5449   ArrayRef<int> ShuffleMask = SVN->getMask();
5450
5451   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5452   if (EltSize <= 32) {
5453     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5454       int Lane = SVN->getSplatIndex();
5455       // If this is undef splat, generate it via "just" vdup, if possible.
5456       if (Lane == -1) Lane = 0;
5457
5458       // Test if V1 is a SCALAR_TO_VECTOR.
5459       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5460         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5461       }
5462       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5463       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5464       // reaches it).
5465       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5466           !isa<ConstantSDNode>(V1.getOperand(0))) {
5467         bool IsScalarToVector = true;
5468         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5469           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5470             IsScalarToVector = false;
5471             break;
5472           }
5473         if (IsScalarToVector)
5474           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5475       }
5476       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5477                          DAG.getConstant(Lane, MVT::i32));
5478     }
5479
5480     bool ReverseVEXT;
5481     unsigned Imm;
5482     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5483       if (ReverseVEXT)
5484         std::swap(V1, V2);
5485       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5486                          DAG.getConstant(Imm, MVT::i32));
5487     }
5488
5489     if (isVREVMask(ShuffleMask, VT, 64))
5490       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5491     if (isVREVMask(ShuffleMask, VT, 32))
5492       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5493     if (isVREVMask(ShuffleMask, VT, 16))
5494       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5495
5496     if (V2->getOpcode() == ISD::UNDEF &&
5497         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5498       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5499                          DAG.getConstant(Imm, MVT::i32));
5500     }
5501
5502     // Check for Neon shuffles that modify both input vectors in place.
5503     // If both results are used, i.e., if there are two shuffles with the same
5504     // source operands and with masks corresponding to both results of one of
5505     // these operations, DAG memoization will ensure that a single node is
5506     // used for both shuffles.
5507     unsigned WhichResult;
5508     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5509       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5510                          V1, V2).getValue(WhichResult);
5511     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5512       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5513                          V1, V2).getValue(WhichResult);
5514     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5515       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5516                          V1, V2).getValue(WhichResult);
5517
5518     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5519       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5520                          V1, V1).getValue(WhichResult);
5521     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5522       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5523                          V1, V1).getValue(WhichResult);
5524     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5525       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5526                          V1, V1).getValue(WhichResult);
5527   }
5528
5529   // If the shuffle is not directly supported and it has 4 elements, use
5530   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5531   unsigned NumElts = VT.getVectorNumElements();
5532   if (NumElts == 4) {
5533     unsigned PFIndexes[4];
5534     for (unsigned i = 0; i != 4; ++i) {
5535       if (ShuffleMask[i] < 0)
5536         PFIndexes[i] = 8;
5537       else
5538         PFIndexes[i] = ShuffleMask[i];
5539     }
5540
5541     // Compute the index in the perfect shuffle table.
5542     unsigned PFTableIndex =
5543       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5544     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5545     unsigned Cost = (PFEntry >> 30);
5546
5547     if (Cost <= 4)
5548       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5549   }
5550
5551   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5552   if (EltSize >= 32) {
5553     // Do the expansion with floating-point types, since that is what the VFP
5554     // registers are defined to use, and since i64 is not legal.
5555     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5556     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5557     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5558     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5559     SmallVector<SDValue, 8> Ops;
5560     for (unsigned i = 0; i < NumElts; ++i) {
5561       if (ShuffleMask[i] < 0)
5562         Ops.push_back(DAG.getUNDEF(EltVT));
5563       else
5564         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5565                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5566                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5567                                                   MVT::i32)));
5568     }
5569     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5570     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5571   }
5572
5573   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5574     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5575
5576   if (VT == MVT::v8i8) {
5577     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5578     if (NewOp.getNode())
5579       return NewOp;
5580   }
5581
5582   return SDValue();
5583 }
5584
5585 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5586   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5587   SDValue Lane = Op.getOperand(2);
5588   if (!isa<ConstantSDNode>(Lane))
5589     return SDValue();
5590
5591   return Op;
5592 }
5593
5594 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5595   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5596   SDValue Lane = Op.getOperand(1);
5597   if (!isa<ConstantSDNode>(Lane))
5598     return SDValue();
5599
5600   SDValue Vec = Op.getOperand(0);
5601   if (Op.getValueType() == MVT::i32 &&
5602       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5603     SDLoc dl(Op);
5604     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5605   }
5606
5607   return Op;
5608 }
5609
5610 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5611   // The only time a CONCAT_VECTORS operation can have legal types is when
5612   // two 64-bit vectors are concatenated to a 128-bit vector.
5613   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5614          "unexpected CONCAT_VECTORS");
5615   SDLoc dl(Op);
5616   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5617   SDValue Op0 = Op.getOperand(0);
5618   SDValue Op1 = Op.getOperand(1);
5619   if (Op0.getOpcode() != ISD::UNDEF)
5620     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5621                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5622                       DAG.getIntPtrConstant(0));
5623   if (Op1.getOpcode() != ISD::UNDEF)
5624     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5625                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5626                       DAG.getIntPtrConstant(1));
5627   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5628 }
5629
5630 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5631 /// element has been zero/sign-extended, depending on the isSigned parameter,
5632 /// from an integer type half its size.
5633 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5634                                    bool isSigned) {
5635   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5636   EVT VT = N->getValueType(0);
5637   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5638     SDNode *BVN = N->getOperand(0).getNode();
5639     if (BVN->getValueType(0) != MVT::v4i32 ||
5640         BVN->getOpcode() != ISD::BUILD_VECTOR)
5641       return false;
5642     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5643     unsigned HiElt = 1 - LoElt;
5644     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5645     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5646     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5647     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5648     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5649       return false;
5650     if (isSigned) {
5651       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5652           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5653         return true;
5654     } else {
5655       if (Hi0->isNullValue() && Hi1->isNullValue())
5656         return true;
5657     }
5658     return false;
5659   }
5660
5661   if (N->getOpcode() != ISD::BUILD_VECTOR)
5662     return false;
5663
5664   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5665     SDNode *Elt = N->getOperand(i).getNode();
5666     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5667       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5668       unsigned HalfSize = EltSize / 2;
5669       if (isSigned) {
5670         if (!isIntN(HalfSize, C->getSExtValue()))
5671           return false;
5672       } else {
5673         if (!isUIntN(HalfSize, C->getZExtValue()))
5674           return false;
5675       }
5676       continue;
5677     }
5678     return false;
5679   }
5680
5681   return true;
5682 }
5683
5684 /// isSignExtended - Check if a node is a vector value that is sign-extended
5685 /// or a constant BUILD_VECTOR with sign-extended elements.
5686 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5687   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5688     return true;
5689   if (isExtendedBUILD_VECTOR(N, DAG, true))
5690     return true;
5691   return false;
5692 }
5693
5694 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5695 /// or a constant BUILD_VECTOR with zero-extended elements.
5696 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5697   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5698     return true;
5699   if (isExtendedBUILD_VECTOR(N, DAG, false))
5700     return true;
5701   return false;
5702 }
5703
5704 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5705   if (OrigVT.getSizeInBits() >= 64)
5706     return OrigVT;
5707
5708   assert(OrigVT.isSimple() && "Expecting a simple value type");
5709
5710   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5711   switch (OrigSimpleTy) {
5712   default: llvm_unreachable("Unexpected Vector Type");
5713   case MVT::v2i8:
5714   case MVT::v2i16:
5715      return MVT::v2i32;
5716   case MVT::v4i8:
5717     return  MVT::v4i16;
5718   }
5719 }
5720
5721 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5722 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5723 /// We insert the required extension here to get the vector to fill a D register.
5724 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5725                                             const EVT &OrigTy,
5726                                             const EVT &ExtTy,
5727                                             unsigned ExtOpcode) {
5728   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5729   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5730   // 64-bits we need to insert a new extension so that it will be 64-bits.
5731   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5732   if (OrigTy.getSizeInBits() >= 64)
5733     return N;
5734
5735   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5736   EVT NewVT = getExtensionTo64Bits(OrigTy);
5737
5738   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5739 }
5740
5741 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5742 /// does not do any sign/zero extension. If the original vector is less
5743 /// than 64 bits, an appropriate extension will be added after the load to
5744 /// reach a total size of 64 bits. We have to add the extension separately
5745 /// because ARM does not have a sign/zero extending load for vectors.
5746 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5747   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5748
5749   // The load already has the right type.
5750   if (ExtendedTy == LD->getMemoryVT())
5751     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5752                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5753                 LD->isNonTemporal(), LD->isInvariant(),
5754                 LD->getAlignment());
5755
5756   // We need to create a zextload/sextload. We cannot just create a load
5757   // followed by a zext/zext node because LowerMUL is also run during normal
5758   // operation legalization where we can't create illegal types.
5759   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5760                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5761                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5762                         LD->isNonTemporal(), LD->getAlignment());
5763 }
5764
5765 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5766 /// extending load, or BUILD_VECTOR with extended elements, return the
5767 /// unextended value. The unextended vector should be 64 bits so that it can
5768 /// be used as an operand to a VMULL instruction. If the original vector size
5769 /// before extension is less than 64 bits we add a an extension to resize
5770 /// the vector to 64 bits.
5771 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5772   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5773     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5774                                         N->getOperand(0)->getValueType(0),
5775                                         N->getValueType(0),
5776                                         N->getOpcode());
5777
5778   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5779     return SkipLoadExtensionForVMULL(LD, DAG);
5780
5781   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5782   // have been legalized as a BITCAST from v4i32.
5783   if (N->getOpcode() == ISD::BITCAST) {
5784     SDNode *BVN = N->getOperand(0).getNode();
5785     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5786            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5787     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5788     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5789                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5790   }
5791   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5792   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5793   EVT VT = N->getValueType(0);
5794   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5795   unsigned NumElts = VT.getVectorNumElements();
5796   MVT TruncVT = MVT::getIntegerVT(EltSize);
5797   SmallVector<SDValue, 8> Ops;
5798   for (unsigned i = 0; i != NumElts; ++i) {
5799     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5800     const APInt &CInt = C->getAPIntValue();
5801     // Element types smaller than 32 bits are not legal, so use i32 elements.
5802     // The values are implicitly truncated so sext vs. zext doesn't matter.
5803     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5804   }
5805   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5806                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5807 }
5808
5809 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5810   unsigned Opcode = N->getOpcode();
5811   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5812     SDNode *N0 = N->getOperand(0).getNode();
5813     SDNode *N1 = N->getOperand(1).getNode();
5814     return N0->hasOneUse() && N1->hasOneUse() &&
5815       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5816   }
5817   return false;
5818 }
5819
5820 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5821   unsigned Opcode = N->getOpcode();
5822   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5823     SDNode *N0 = N->getOperand(0).getNode();
5824     SDNode *N1 = N->getOperand(1).getNode();
5825     return N0->hasOneUse() && N1->hasOneUse() &&
5826       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5827   }
5828   return false;
5829 }
5830
5831 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5832   // Multiplications are only custom-lowered for 128-bit vectors so that
5833   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5834   EVT VT = Op.getValueType();
5835   assert(VT.is128BitVector() && VT.isInteger() &&
5836          "unexpected type for custom-lowering ISD::MUL");
5837   SDNode *N0 = Op.getOperand(0).getNode();
5838   SDNode *N1 = Op.getOperand(1).getNode();
5839   unsigned NewOpc = 0;
5840   bool isMLA = false;
5841   bool isN0SExt = isSignExtended(N0, DAG);
5842   bool isN1SExt = isSignExtended(N1, DAG);
5843   if (isN0SExt && isN1SExt)
5844     NewOpc = ARMISD::VMULLs;
5845   else {
5846     bool isN0ZExt = isZeroExtended(N0, DAG);
5847     bool isN1ZExt = isZeroExtended(N1, DAG);
5848     if (isN0ZExt && isN1ZExt)
5849       NewOpc = ARMISD::VMULLu;
5850     else if (isN1SExt || isN1ZExt) {
5851       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5852       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5853       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5854         NewOpc = ARMISD::VMULLs;
5855         isMLA = true;
5856       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5857         NewOpc = ARMISD::VMULLu;
5858         isMLA = true;
5859       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5860         std::swap(N0, N1);
5861         NewOpc = ARMISD::VMULLu;
5862         isMLA = true;
5863       }
5864     }
5865
5866     if (!NewOpc) {
5867       if (VT == MVT::v2i64)
5868         // Fall through to expand this.  It is not legal.
5869         return SDValue();
5870       else
5871         // Other vector multiplications are legal.
5872         return Op;
5873     }
5874   }
5875
5876   // Legalize to a VMULL instruction.
5877   SDLoc DL(Op);
5878   SDValue Op0;
5879   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5880   if (!isMLA) {
5881     Op0 = SkipExtensionForVMULL(N0, DAG);
5882     assert(Op0.getValueType().is64BitVector() &&
5883            Op1.getValueType().is64BitVector() &&
5884            "unexpected types for extended operands to VMULL");
5885     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5886   }
5887
5888   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5889   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5890   //   vmull q0, d4, d6
5891   //   vmlal q0, d5, d6
5892   // is faster than
5893   //   vaddl q0, d4, d5
5894   //   vmovl q1, d6
5895   //   vmul  q0, q0, q1
5896   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5897   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5898   EVT Op1VT = Op1.getValueType();
5899   return DAG.getNode(N0->getOpcode(), DL, VT,
5900                      DAG.getNode(NewOpc, DL, VT,
5901                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5902                      DAG.getNode(NewOpc, DL, VT,
5903                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5904 }
5905
5906 static SDValue
5907 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5908   // Convert to float
5909   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5910   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5911   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5912   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5913   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5914   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5915   // Get reciprocal estimate.
5916   // float4 recip = vrecpeq_f32(yf);
5917   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5918                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5919   // Because char has a smaller range than uchar, we can actually get away
5920   // without any newton steps.  This requires that we use a weird bias
5921   // of 0xb000, however (again, this has been exhaustively tested).
5922   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5923   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5924   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5925   Y = DAG.getConstant(0xb000, MVT::i32);
5926   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5927   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5928   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5929   // Convert back to short.
5930   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5931   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5932   return X;
5933 }
5934
5935 static SDValue
5936 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5937   SDValue N2;
5938   // Convert to float.
5939   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5940   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5941   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5942   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5943   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5944   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5945
5946   // Use reciprocal estimate and one refinement step.
5947   // float4 recip = vrecpeq_f32(yf);
5948   // recip *= vrecpsq_f32(yf, recip);
5949   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5950                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5951   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5952                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5953                    N1, N2);
5954   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5955   // Because short has a smaller range than ushort, we can actually get away
5956   // with only a single newton step.  This requires that we use a weird bias
5957   // of 89, however (again, this has been exhaustively tested).
5958   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5959   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5960   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5961   N1 = DAG.getConstant(0x89, MVT::i32);
5962   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5963   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5964   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5965   // Convert back to integer and return.
5966   // return vmovn_s32(vcvt_s32_f32(result));
5967   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5968   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5969   return N0;
5970 }
5971
5972 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5973   EVT VT = Op.getValueType();
5974   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5975          "unexpected type for custom-lowering ISD::SDIV");
5976
5977   SDLoc dl(Op);
5978   SDValue N0 = Op.getOperand(0);
5979   SDValue N1 = Op.getOperand(1);
5980   SDValue N2, N3;
5981
5982   if (VT == MVT::v8i8) {
5983     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5984     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5985
5986     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5987                      DAG.getIntPtrConstant(4));
5988     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5989                      DAG.getIntPtrConstant(4));
5990     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5991                      DAG.getIntPtrConstant(0));
5992     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5993                      DAG.getIntPtrConstant(0));
5994
5995     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5996     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5997
5998     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5999     N0 = LowerCONCAT_VECTORS(N0, DAG);
6000
6001     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6002     return N0;
6003   }
6004   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6005 }
6006
6007 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6008   EVT VT = Op.getValueType();
6009   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6010          "unexpected type for custom-lowering ISD::UDIV");
6011
6012   SDLoc dl(Op);
6013   SDValue N0 = Op.getOperand(0);
6014   SDValue N1 = Op.getOperand(1);
6015   SDValue N2, N3;
6016
6017   if (VT == MVT::v8i8) {
6018     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6019     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6020
6021     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6022                      DAG.getIntPtrConstant(4));
6023     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6024                      DAG.getIntPtrConstant(4));
6025     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6026                      DAG.getIntPtrConstant(0));
6027     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6028                      DAG.getIntPtrConstant(0));
6029
6030     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6031     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6032
6033     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6034     N0 = LowerCONCAT_VECTORS(N0, DAG);
6035
6036     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6037                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6038                      N0);
6039     return N0;
6040   }
6041
6042   // v4i16 sdiv ... Convert to float.
6043   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6044   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6045   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6046   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6047   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6048   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6049
6050   // Use reciprocal estimate and two refinement steps.
6051   // float4 recip = vrecpeq_f32(yf);
6052   // recip *= vrecpsq_f32(yf, recip);
6053   // recip *= vrecpsq_f32(yf, recip);
6054   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6055                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6056   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6057                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6058                    BN1, N2);
6059   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6060   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6061                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6062                    BN1, N2);
6063   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6064   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6065   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6066   // and that it will never cause us to return an answer too large).
6067   // float4 result = as_float4(as_int4(xf*recip) + 2);
6068   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6069   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6070   N1 = DAG.getConstant(2, MVT::i32);
6071   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6072   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6073   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6074   // Convert back to integer and return.
6075   // return vmovn_u32(vcvt_s32_f32(result));
6076   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6077   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6078   return N0;
6079 }
6080
6081 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6082   EVT VT = Op.getNode()->getValueType(0);
6083   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6084
6085   unsigned Opc;
6086   bool ExtraOp = false;
6087   switch (Op.getOpcode()) {
6088   default: llvm_unreachable("Invalid code");
6089   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6090   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6091   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6092   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6093   }
6094
6095   if (!ExtraOp)
6096     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6097                        Op.getOperand(1));
6098   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6099                      Op.getOperand(1), Op.getOperand(2));
6100 }
6101
6102 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6103   assert(Subtarget->isTargetDarwin());
6104
6105   // For iOS, we want to call an alternative entry point: __sincos_stret,
6106   // return values are passed via sret.
6107   SDLoc dl(Op);
6108   SDValue Arg = Op.getOperand(0);
6109   EVT ArgVT = Arg.getValueType();
6110   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6111
6112   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6114
6115   // Pair of floats / doubles used to pass the result.
6116   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6117
6118   // Create stack object for sret.
6119   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6120   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6121   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6122   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6123
6124   ArgListTy Args;
6125   ArgListEntry Entry;
6126
6127   Entry.Node = SRet;
6128   Entry.Ty = RetTy->getPointerTo();
6129   Entry.isSExt = false;
6130   Entry.isZExt = false;
6131   Entry.isSRet = true;
6132   Args.push_back(Entry);
6133
6134   Entry.Node = Arg;
6135   Entry.Ty = ArgTy;
6136   Entry.isSExt = false;
6137   Entry.isZExt = false;
6138   Args.push_back(Entry);
6139
6140   const char *LibcallName  = (ArgVT == MVT::f64)
6141   ? "__sincos_stret" : "__sincosf_stret";
6142   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6143
6144   TargetLowering::CallLoweringInfo CLI(DAG);
6145   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6146     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6147                std::move(Args), 0)
6148     .setDiscardResult();
6149
6150   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6151
6152   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6153                                 MachinePointerInfo(), false, false, false, 0);
6154
6155   // Address of cos field.
6156   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6157                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6158   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6159                                 MachinePointerInfo(), false, false, false, 0);
6160
6161   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6162   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6163                      LoadSin.getValue(0), LoadCos.getValue(0));
6164 }
6165
6166 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6167   // Monotonic load/store is legal for all targets
6168   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6169     return Op;
6170
6171   // Acquire/Release load/store is not legal for targets without a
6172   // dmb or equivalent available.
6173   return SDValue();
6174 }
6175
6176 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6177                                     SmallVectorImpl<SDValue> &Results,
6178                                     SelectionDAG &DAG,
6179                                     const ARMSubtarget *Subtarget) {
6180   SDLoc DL(N);
6181   SDValue Cycles32, OutChain;
6182
6183   if (Subtarget->hasPerfMon()) {
6184     // Under Power Management extensions, the cycle-count is:
6185     //    mrc p15, #0, <Rt>, c9, c13, #0
6186     SDValue Ops[] = { N->getOperand(0), // Chain
6187                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6188                       DAG.getConstant(15, MVT::i32),
6189                       DAG.getConstant(0, MVT::i32),
6190                       DAG.getConstant(9, MVT::i32),
6191                       DAG.getConstant(13, MVT::i32),
6192                       DAG.getConstant(0, MVT::i32)
6193     };
6194
6195     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6196                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6197     OutChain = Cycles32.getValue(1);
6198   } else {
6199     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6200     // there are older ARM CPUs that have implementation-specific ways of
6201     // obtaining this information (FIXME!).
6202     Cycles32 = DAG.getConstant(0, MVT::i32);
6203     OutChain = DAG.getEntryNode();
6204   }
6205
6206
6207   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6208                                  Cycles32, DAG.getConstant(0, MVT::i32));
6209   Results.push_back(Cycles64);
6210   Results.push_back(OutChain);
6211 }
6212
6213 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6214   switch (Op.getOpcode()) {
6215   default: llvm_unreachable("Don't know how to custom lower this!");
6216   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6217   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6218   case ISD::GlobalAddress:
6219     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6220     default: llvm_unreachable("unknown object format");
6221     case Triple::COFF:
6222       return LowerGlobalAddressWindows(Op, DAG);
6223     case Triple::ELF:
6224       return LowerGlobalAddressELF(Op, DAG);
6225     case Triple::MachO:
6226       return LowerGlobalAddressDarwin(Op, DAG);
6227     }
6228   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6229   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6230   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6231   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6232   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6233   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6234   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6235   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6236   case ISD::SINT_TO_FP:
6237   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6238   case ISD::FP_TO_SINT:
6239   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6240   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6241   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6242   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6243   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6244   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6245   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6246   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6247                                                                Subtarget);
6248   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6249   case ISD::SHL:
6250   case ISD::SRL:
6251   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6252   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6253   case ISD::SRL_PARTS:
6254   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6255   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6256   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6257   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6258   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6259   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6260   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6261   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6262   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6263   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6264   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6265   case ISD::MUL:           return LowerMUL(Op, DAG);
6266   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6267   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6268   case ISD::ADDC:
6269   case ISD::ADDE:
6270   case ISD::SUBC:
6271   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6272   case ISD::SADDO:
6273   case ISD::UADDO:
6274   case ISD::SSUBO:
6275   case ISD::USUBO:
6276     return LowerXALUO(Op, DAG);
6277   case ISD::ATOMIC_LOAD:
6278   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6279   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6280   case ISD::SDIVREM:
6281   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6282   case ISD::DYNAMIC_STACKALLOC:
6283     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6284       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6285     llvm_unreachable("Don't know how to custom lower this!");
6286   }
6287 }
6288
6289 /// ReplaceNodeResults - Replace the results of node with an illegal result
6290 /// type with new values built out of custom code.
6291 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6292                                            SmallVectorImpl<SDValue>&Results,
6293                                            SelectionDAG &DAG) const {
6294   SDValue Res;
6295   switch (N->getOpcode()) {
6296   default:
6297     llvm_unreachable("Don't know how to custom expand this!");
6298   case ISD::BITCAST:
6299     Res = ExpandBITCAST(N, DAG);
6300     break;
6301   case ISD::SRL:
6302   case ISD::SRA:
6303     Res = Expand64BitShift(N, DAG, Subtarget);
6304     break;
6305   case ISD::READCYCLECOUNTER:
6306     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6307     return;
6308   }
6309   if (Res.getNode())
6310     Results.push_back(Res);
6311 }
6312
6313 //===----------------------------------------------------------------------===//
6314 //                           ARM Scheduler Hooks
6315 //===----------------------------------------------------------------------===//
6316
6317 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6318 /// registers the function context.
6319 void ARMTargetLowering::
6320 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6321                        MachineBasicBlock *DispatchBB, int FI) const {
6322   const TargetInstrInfo *TII =
6323       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6324   DebugLoc dl = MI->getDebugLoc();
6325   MachineFunction *MF = MBB->getParent();
6326   MachineRegisterInfo *MRI = &MF->getRegInfo();
6327   MachineConstantPool *MCP = MF->getConstantPool();
6328   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6329   const Function *F = MF->getFunction();
6330
6331   bool isThumb = Subtarget->isThumb();
6332   bool isThumb2 = Subtarget->isThumb2();
6333
6334   unsigned PCLabelId = AFI->createPICLabelUId();
6335   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6336   ARMConstantPoolValue *CPV =
6337     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6338   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6339
6340   const TargetRegisterClass *TRC = isThumb ?
6341     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6342     (const TargetRegisterClass*)&ARM::GPRRegClass;
6343
6344   // Grab constant pool and fixed stack memory operands.
6345   MachineMemOperand *CPMMO =
6346     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6347                              MachineMemOperand::MOLoad, 4, 4);
6348
6349   MachineMemOperand *FIMMOSt =
6350     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6351                              MachineMemOperand::MOStore, 4, 4);
6352
6353   // Load the address of the dispatch MBB into the jump buffer.
6354   if (isThumb2) {
6355     // Incoming value: jbuf
6356     //   ldr.n  r5, LCPI1_1
6357     //   orr    r5, r5, #1
6358     //   add    r5, pc
6359     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6360     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6361     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6362                    .addConstantPoolIndex(CPI)
6363                    .addMemOperand(CPMMO));
6364     // Set the low bit because of thumb mode.
6365     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6366     AddDefaultCC(
6367       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6368                      .addReg(NewVReg1, RegState::Kill)
6369                      .addImm(0x01)));
6370     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6371     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6372       .addReg(NewVReg2, RegState::Kill)
6373       .addImm(PCLabelId);
6374     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6375                    .addReg(NewVReg3, RegState::Kill)
6376                    .addFrameIndex(FI)
6377                    .addImm(36)  // &jbuf[1] :: pc
6378                    .addMemOperand(FIMMOSt));
6379   } else if (isThumb) {
6380     // Incoming value: jbuf
6381     //   ldr.n  r1, LCPI1_4
6382     //   add    r1, pc
6383     //   mov    r2, #1
6384     //   orrs   r1, r2
6385     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6386     //   str    r1, [r2]
6387     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6388     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6389                    .addConstantPoolIndex(CPI)
6390                    .addMemOperand(CPMMO));
6391     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6392     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6393       .addReg(NewVReg1, RegState::Kill)
6394       .addImm(PCLabelId);
6395     // Set the low bit because of thumb mode.
6396     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6397     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6398                    .addReg(ARM::CPSR, RegState::Define)
6399                    .addImm(1));
6400     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6401     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6402                    .addReg(ARM::CPSR, RegState::Define)
6403                    .addReg(NewVReg2, RegState::Kill)
6404                    .addReg(NewVReg3, RegState::Kill));
6405     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6406     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6407                    .addFrameIndex(FI)
6408                    .addImm(36)); // &jbuf[1] :: pc
6409     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6410                    .addReg(NewVReg4, RegState::Kill)
6411                    .addReg(NewVReg5, RegState::Kill)
6412                    .addImm(0)
6413                    .addMemOperand(FIMMOSt));
6414   } else {
6415     // Incoming value: jbuf
6416     //   ldr  r1, LCPI1_1
6417     //   add  r1, pc, r1
6418     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6419     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6420     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6421                    .addConstantPoolIndex(CPI)
6422                    .addImm(0)
6423                    .addMemOperand(CPMMO));
6424     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6425     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6426                    .addReg(NewVReg1, RegState::Kill)
6427                    .addImm(PCLabelId));
6428     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6429                    .addReg(NewVReg2, RegState::Kill)
6430                    .addFrameIndex(FI)
6431                    .addImm(36)  // &jbuf[1] :: pc
6432                    .addMemOperand(FIMMOSt));
6433   }
6434 }
6435
6436 MachineBasicBlock *ARMTargetLowering::
6437 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6438   const TargetInstrInfo *TII =
6439       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6440   DebugLoc dl = MI->getDebugLoc();
6441   MachineFunction *MF = MBB->getParent();
6442   MachineRegisterInfo *MRI = &MF->getRegInfo();
6443   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6444   MachineFrameInfo *MFI = MF->getFrameInfo();
6445   int FI = MFI->getFunctionContextIndex();
6446
6447   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6448     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6449     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6450
6451   // Get a mapping of the call site numbers to all of the landing pads they're
6452   // associated with.
6453   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6454   unsigned MaxCSNum = 0;
6455   MachineModuleInfo &MMI = MF->getMMI();
6456   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6457        ++BB) {
6458     if (!BB->isLandingPad()) continue;
6459
6460     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6461     // pad.
6462     for (MachineBasicBlock::iterator
6463            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6464       if (!II->isEHLabel()) continue;
6465
6466       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6467       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6468
6469       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6470       for (SmallVectorImpl<unsigned>::iterator
6471              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6472            CSI != CSE; ++CSI) {
6473         CallSiteNumToLPad[*CSI].push_back(BB);
6474         MaxCSNum = std::max(MaxCSNum, *CSI);
6475       }
6476       break;
6477     }
6478   }
6479
6480   // Get an ordered list of the machine basic blocks for the jump table.
6481   std::vector<MachineBasicBlock*> LPadList;
6482   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6483   LPadList.reserve(CallSiteNumToLPad.size());
6484   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6485     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6486     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6487            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6488       LPadList.push_back(*II);
6489       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6490     }
6491   }
6492
6493   assert(!LPadList.empty() &&
6494          "No landing pad destinations for the dispatch jump table!");
6495
6496   // Create the jump table and associated information.
6497   MachineJumpTableInfo *JTI =
6498     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6499   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6500   unsigned UId = AFI->createJumpTableUId();
6501   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6502
6503   // Create the MBBs for the dispatch code.
6504
6505   // Shove the dispatch's address into the return slot in the function context.
6506   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6507   DispatchBB->setIsLandingPad();
6508
6509   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6510   unsigned trap_opcode;
6511   if (Subtarget->isThumb())
6512     trap_opcode = ARM::tTRAP;
6513   else
6514     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6515
6516   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6517   DispatchBB->addSuccessor(TrapBB);
6518
6519   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6520   DispatchBB->addSuccessor(DispContBB);
6521
6522   // Insert and MBBs.
6523   MF->insert(MF->end(), DispatchBB);
6524   MF->insert(MF->end(), DispContBB);
6525   MF->insert(MF->end(), TrapBB);
6526
6527   // Insert code into the entry block that creates and registers the function
6528   // context.
6529   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6530
6531   MachineMemOperand *FIMMOLd =
6532     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6533                              MachineMemOperand::MOLoad |
6534                              MachineMemOperand::MOVolatile, 4, 4);
6535
6536   MachineInstrBuilder MIB;
6537   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6538
6539   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6540   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6541
6542   // Add a register mask with no preserved registers.  This results in all
6543   // registers being marked as clobbered.
6544   MIB.addRegMask(RI.getNoPreservedMask());
6545
6546   unsigned NumLPads = LPadList.size();
6547   if (Subtarget->isThumb2()) {
6548     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6549     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6550                    .addFrameIndex(FI)
6551                    .addImm(4)
6552                    .addMemOperand(FIMMOLd));
6553
6554     if (NumLPads < 256) {
6555       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6556                      .addReg(NewVReg1)
6557                      .addImm(LPadList.size()));
6558     } else {
6559       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6560       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6561                      .addImm(NumLPads & 0xFFFF));
6562
6563       unsigned VReg2 = VReg1;
6564       if ((NumLPads & 0xFFFF0000) != 0) {
6565         VReg2 = MRI->createVirtualRegister(TRC);
6566         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6567                        .addReg(VReg1)
6568                        .addImm(NumLPads >> 16));
6569       }
6570
6571       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6572                      .addReg(NewVReg1)
6573                      .addReg(VReg2));
6574     }
6575
6576     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6577       .addMBB(TrapBB)
6578       .addImm(ARMCC::HI)
6579       .addReg(ARM::CPSR);
6580
6581     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6582     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6583                    .addJumpTableIndex(MJTI)
6584                    .addImm(UId));
6585
6586     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6587     AddDefaultCC(
6588       AddDefaultPred(
6589         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6590         .addReg(NewVReg3, RegState::Kill)
6591         .addReg(NewVReg1)
6592         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6593
6594     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6595       .addReg(NewVReg4, RegState::Kill)
6596       .addReg(NewVReg1)
6597       .addJumpTableIndex(MJTI)
6598       .addImm(UId);
6599   } else if (Subtarget->isThumb()) {
6600     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6601     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6602                    .addFrameIndex(FI)
6603                    .addImm(1)
6604                    .addMemOperand(FIMMOLd));
6605
6606     if (NumLPads < 256) {
6607       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6608                      .addReg(NewVReg1)
6609                      .addImm(NumLPads));
6610     } else {
6611       MachineConstantPool *ConstantPool = MF->getConstantPool();
6612       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6613       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6614
6615       // MachineConstantPool wants an explicit alignment.
6616       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6617       if (Align == 0)
6618         Align = getDataLayout()->getTypeAllocSize(C->getType());
6619       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6620
6621       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6622       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6623                      .addReg(VReg1, RegState::Define)
6624                      .addConstantPoolIndex(Idx));
6625       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6626                      .addReg(NewVReg1)
6627                      .addReg(VReg1));
6628     }
6629
6630     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6631       .addMBB(TrapBB)
6632       .addImm(ARMCC::HI)
6633       .addReg(ARM::CPSR);
6634
6635     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6636     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6637                    .addReg(ARM::CPSR, RegState::Define)
6638                    .addReg(NewVReg1)
6639                    .addImm(2));
6640
6641     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6642     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6643                    .addJumpTableIndex(MJTI)
6644                    .addImm(UId));
6645
6646     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6647     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6648                    .addReg(ARM::CPSR, RegState::Define)
6649                    .addReg(NewVReg2, RegState::Kill)
6650                    .addReg(NewVReg3));
6651
6652     MachineMemOperand *JTMMOLd =
6653       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6654                                MachineMemOperand::MOLoad, 4, 4);
6655
6656     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6657     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6658                    .addReg(NewVReg4, RegState::Kill)
6659                    .addImm(0)
6660                    .addMemOperand(JTMMOLd));
6661
6662     unsigned NewVReg6 = NewVReg5;
6663     if (RelocM == Reloc::PIC_) {
6664       NewVReg6 = MRI->createVirtualRegister(TRC);
6665       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6666                      .addReg(ARM::CPSR, RegState::Define)
6667                      .addReg(NewVReg5, RegState::Kill)
6668                      .addReg(NewVReg3));
6669     }
6670
6671     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6672       .addReg(NewVReg6, RegState::Kill)
6673       .addJumpTableIndex(MJTI)
6674       .addImm(UId);
6675   } else {
6676     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6677     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6678                    .addFrameIndex(FI)
6679                    .addImm(4)
6680                    .addMemOperand(FIMMOLd));
6681
6682     if (NumLPads < 256) {
6683       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6684                      .addReg(NewVReg1)
6685                      .addImm(NumLPads));
6686     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6687       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6688       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6689                      .addImm(NumLPads & 0xFFFF));
6690
6691       unsigned VReg2 = VReg1;
6692       if ((NumLPads & 0xFFFF0000) != 0) {
6693         VReg2 = MRI->createVirtualRegister(TRC);
6694         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6695                        .addReg(VReg1)
6696                        .addImm(NumLPads >> 16));
6697       }
6698
6699       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6700                      .addReg(NewVReg1)
6701                      .addReg(VReg2));
6702     } else {
6703       MachineConstantPool *ConstantPool = MF->getConstantPool();
6704       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6705       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6706
6707       // MachineConstantPool wants an explicit alignment.
6708       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6709       if (Align == 0)
6710         Align = getDataLayout()->getTypeAllocSize(C->getType());
6711       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6712
6713       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6714       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6715                      .addReg(VReg1, RegState::Define)
6716                      .addConstantPoolIndex(Idx)
6717                      .addImm(0));
6718       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6719                      .addReg(NewVReg1)
6720                      .addReg(VReg1, RegState::Kill));
6721     }
6722
6723     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6724       .addMBB(TrapBB)
6725       .addImm(ARMCC::HI)
6726       .addReg(ARM::CPSR);
6727
6728     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6729     AddDefaultCC(
6730       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6731                      .addReg(NewVReg1)
6732                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6733     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6734     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6735                    .addJumpTableIndex(MJTI)
6736                    .addImm(UId));
6737
6738     MachineMemOperand *JTMMOLd =
6739       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6740                                MachineMemOperand::MOLoad, 4, 4);
6741     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6742     AddDefaultPred(
6743       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6744       .addReg(NewVReg3, RegState::Kill)
6745       .addReg(NewVReg4)
6746       .addImm(0)
6747       .addMemOperand(JTMMOLd));
6748
6749     if (RelocM == Reloc::PIC_) {
6750       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6751         .addReg(NewVReg5, RegState::Kill)
6752         .addReg(NewVReg4)
6753         .addJumpTableIndex(MJTI)
6754         .addImm(UId);
6755     } else {
6756       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6757         .addReg(NewVReg5, RegState::Kill)
6758         .addJumpTableIndex(MJTI)
6759         .addImm(UId);
6760     }
6761   }
6762
6763   // Add the jump table entries as successors to the MBB.
6764   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6765   for (std::vector<MachineBasicBlock*>::iterator
6766          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6767     MachineBasicBlock *CurMBB = *I;
6768     if (SeenMBBs.insert(CurMBB))
6769       DispContBB->addSuccessor(CurMBB);
6770   }
6771
6772   // N.B. the order the invoke BBs are processed in doesn't matter here.
6773   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6774   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6775   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6776          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6777     MachineBasicBlock *BB = *I;
6778
6779     // Remove the landing pad successor from the invoke block and replace it
6780     // with the new dispatch block.
6781     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6782                                                   BB->succ_end());
6783     while (!Successors.empty()) {
6784       MachineBasicBlock *SMBB = Successors.pop_back_val();
6785       if (SMBB->isLandingPad()) {
6786         BB->removeSuccessor(SMBB);
6787         MBBLPads.push_back(SMBB);
6788       }
6789     }
6790
6791     BB->addSuccessor(DispatchBB);
6792
6793     // Find the invoke call and mark all of the callee-saved registers as
6794     // 'implicit defined' so that they're spilled. This prevents code from
6795     // moving instructions to before the EH block, where they will never be
6796     // executed.
6797     for (MachineBasicBlock::reverse_iterator
6798            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6799       if (!II->isCall()) continue;
6800
6801       DenseMap<unsigned, bool> DefRegs;
6802       for (MachineInstr::mop_iterator
6803              OI = II->operands_begin(), OE = II->operands_end();
6804            OI != OE; ++OI) {
6805         if (!OI->isReg()) continue;
6806         DefRegs[OI->getReg()] = true;
6807       }
6808
6809       MachineInstrBuilder MIB(*MF, &*II);
6810
6811       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6812         unsigned Reg = SavedRegs[i];
6813         if (Subtarget->isThumb2() &&
6814             !ARM::tGPRRegClass.contains(Reg) &&
6815             !ARM::hGPRRegClass.contains(Reg))
6816           continue;
6817         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6818           continue;
6819         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6820           continue;
6821         if (!DefRegs[Reg])
6822           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6823       }
6824
6825       break;
6826     }
6827   }
6828
6829   // Mark all former landing pads as non-landing pads. The dispatch is the only
6830   // landing pad now.
6831   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6832          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6833     (*I)->setIsLandingPad(false);
6834
6835   // The instruction is gone now.
6836   MI->eraseFromParent();
6837
6838   return MBB;
6839 }
6840
6841 static
6842 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6843   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6844        E = MBB->succ_end(); I != E; ++I)
6845     if (*I != Succ)
6846       return *I;
6847   llvm_unreachable("Expecting a BB with two successors!");
6848 }
6849
6850 /// Return the load opcode for a given load size. If load size >= 8,
6851 /// neon opcode will be returned.
6852 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6853   if (LdSize >= 8)
6854     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6855                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6856   if (IsThumb1)
6857     return LdSize == 4 ? ARM::tLDRi
6858                        : LdSize == 2 ? ARM::tLDRHi
6859                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6860   if (IsThumb2)
6861     return LdSize == 4 ? ARM::t2LDR_POST
6862                        : LdSize == 2 ? ARM::t2LDRH_POST
6863                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6864   return LdSize == 4 ? ARM::LDR_POST_IMM
6865                      : LdSize == 2 ? ARM::LDRH_POST
6866                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6867 }
6868
6869 /// Return the store opcode for a given store size. If store size >= 8,
6870 /// neon opcode will be returned.
6871 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6872   if (StSize >= 8)
6873     return StSize == 16 ? ARM::VST1q32wb_fixed
6874                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6875   if (IsThumb1)
6876     return StSize == 4 ? ARM::tSTRi
6877                        : StSize == 2 ? ARM::tSTRHi
6878                                      : StSize == 1 ? ARM::tSTRBi : 0;
6879   if (IsThumb2)
6880     return StSize == 4 ? ARM::t2STR_POST
6881                        : StSize == 2 ? ARM::t2STRH_POST
6882                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6883   return StSize == 4 ? ARM::STR_POST_IMM
6884                      : StSize == 2 ? ARM::STRH_POST
6885                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6886 }
6887
6888 /// Emit a post-increment load operation with given size. The instructions
6889 /// will be added to BB at Pos.
6890 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6891                        const TargetInstrInfo *TII, DebugLoc dl,
6892                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6893                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6894   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6895   assert(LdOpc != 0 && "Should have a load opcode");
6896   if (LdSize >= 8) {
6897     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6898                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6899                        .addImm(0));
6900   } else if (IsThumb1) {
6901     // load + update AddrIn
6902     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6903                        .addReg(AddrIn).addImm(0));
6904     MachineInstrBuilder MIB =
6905         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6906     MIB = AddDefaultT1CC(MIB);
6907     MIB.addReg(AddrIn).addImm(LdSize);
6908     AddDefaultPred(MIB);
6909   } else if (IsThumb2) {
6910     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6911                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6912                        .addImm(LdSize));
6913   } else { // arm
6914     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6915                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6916                        .addReg(0).addImm(LdSize));
6917   }
6918 }
6919
6920 /// Emit a post-increment store operation with given size. The instructions
6921 /// will be added to BB at Pos.
6922 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6923                        const TargetInstrInfo *TII, DebugLoc dl,
6924                        unsigned StSize, unsigned Data, unsigned AddrIn,
6925                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6926   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6927   assert(StOpc != 0 && "Should have a store opcode");
6928   if (StSize >= 8) {
6929     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6930                        .addReg(AddrIn).addImm(0).addReg(Data));
6931   } else if (IsThumb1) {
6932     // store + update AddrIn
6933     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6934                        .addReg(AddrIn).addImm(0));
6935     MachineInstrBuilder MIB =
6936         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6937     MIB = AddDefaultT1CC(MIB);
6938     MIB.addReg(AddrIn).addImm(StSize);
6939     AddDefaultPred(MIB);
6940   } else if (IsThumb2) {
6941     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6942                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6943   } else { // arm
6944     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6945                        .addReg(Data).addReg(AddrIn).addReg(0)
6946                        .addImm(StSize));
6947   }
6948 }
6949
6950 MachineBasicBlock *
6951 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6952                                    MachineBasicBlock *BB) const {
6953   // This pseudo instruction has 3 operands: dst, src, size
6954   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6955   // Otherwise, we will generate unrolled scalar copies.
6956   const TargetInstrInfo *TII =
6957       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6958   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6959   MachineFunction::iterator It = BB;
6960   ++It;
6961
6962   unsigned dest = MI->getOperand(0).getReg();
6963   unsigned src = MI->getOperand(1).getReg();
6964   unsigned SizeVal = MI->getOperand(2).getImm();
6965   unsigned Align = MI->getOperand(3).getImm();
6966   DebugLoc dl = MI->getDebugLoc();
6967
6968   MachineFunction *MF = BB->getParent();
6969   MachineRegisterInfo &MRI = MF->getRegInfo();
6970   unsigned UnitSize = 0;
6971   const TargetRegisterClass *TRC = nullptr;
6972   const TargetRegisterClass *VecTRC = nullptr;
6973
6974   bool IsThumb1 = Subtarget->isThumb1Only();
6975   bool IsThumb2 = Subtarget->isThumb2();
6976
6977   if (Align & 1) {
6978     UnitSize = 1;
6979   } else if (Align & 2) {
6980     UnitSize = 2;
6981   } else {
6982     // Check whether we can use NEON instructions.
6983     if (!MF->getFunction()->getAttributes().
6984           hasAttribute(AttributeSet::FunctionIndex,
6985                        Attribute::NoImplicitFloat) &&
6986         Subtarget->hasNEON()) {
6987       if ((Align % 16 == 0) && SizeVal >= 16)
6988         UnitSize = 16;
6989       else if ((Align % 8 == 0) && SizeVal >= 8)
6990         UnitSize = 8;
6991     }
6992     // Can't use NEON instructions.
6993     if (UnitSize == 0)
6994       UnitSize = 4;
6995   }
6996
6997   // Select the correct opcode and register class for unit size load/store
6998   bool IsNeon = UnitSize >= 8;
6999   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7000                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7001   if (IsNeon)
7002     VecTRC = UnitSize == 16
7003                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7004                  : UnitSize == 8
7005                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7006                        : nullptr;
7007
7008   unsigned BytesLeft = SizeVal % UnitSize;
7009   unsigned LoopSize = SizeVal - BytesLeft;
7010
7011   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7012     // Use LDR and STR to copy.
7013     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7014     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7015     unsigned srcIn = src;
7016     unsigned destIn = dest;
7017     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7018       unsigned srcOut = MRI.createVirtualRegister(TRC);
7019       unsigned destOut = MRI.createVirtualRegister(TRC);
7020       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7021       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7022                  IsThumb1, IsThumb2);
7023       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7024                  IsThumb1, IsThumb2);
7025       srcIn = srcOut;
7026       destIn = destOut;
7027     }
7028
7029     // Handle the leftover bytes with LDRB and STRB.
7030     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7031     // [destOut] = STRB_POST(scratch, destIn, 1)
7032     for (unsigned i = 0; i < BytesLeft; i++) {
7033       unsigned srcOut = MRI.createVirtualRegister(TRC);
7034       unsigned destOut = MRI.createVirtualRegister(TRC);
7035       unsigned scratch = MRI.createVirtualRegister(TRC);
7036       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7037                  IsThumb1, IsThumb2);
7038       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7039                  IsThumb1, IsThumb2);
7040       srcIn = srcOut;
7041       destIn = destOut;
7042     }
7043     MI->eraseFromParent();   // The instruction is gone now.
7044     return BB;
7045   }
7046
7047   // Expand the pseudo op to a loop.
7048   // thisMBB:
7049   //   ...
7050   //   movw varEnd, # --> with thumb2
7051   //   movt varEnd, #
7052   //   ldrcp varEnd, idx --> without thumb2
7053   //   fallthrough --> loopMBB
7054   // loopMBB:
7055   //   PHI varPhi, varEnd, varLoop
7056   //   PHI srcPhi, src, srcLoop
7057   //   PHI destPhi, dst, destLoop
7058   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7059   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7060   //   subs varLoop, varPhi, #UnitSize
7061   //   bne loopMBB
7062   //   fallthrough --> exitMBB
7063   // exitMBB:
7064   //   epilogue to handle left-over bytes
7065   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7066   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7067   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7068   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7069   MF->insert(It, loopMBB);
7070   MF->insert(It, exitMBB);
7071
7072   // Transfer the remainder of BB and its successor edges to exitMBB.
7073   exitMBB->splice(exitMBB->begin(), BB,
7074                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7075   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7076
7077   // Load an immediate to varEnd.
7078   unsigned varEnd = MRI.createVirtualRegister(TRC);
7079   if (IsThumb2) {
7080     unsigned Vtmp = varEnd;
7081     if ((LoopSize & 0xFFFF0000) != 0)
7082       Vtmp = MRI.createVirtualRegister(TRC);
7083     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7084                        .addImm(LoopSize & 0xFFFF));
7085
7086     if ((LoopSize & 0xFFFF0000) != 0)
7087       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7088                          .addReg(Vtmp).addImm(LoopSize >> 16));
7089   } else {
7090     MachineConstantPool *ConstantPool = MF->getConstantPool();
7091     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7092     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7093
7094     // MachineConstantPool wants an explicit alignment.
7095     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7096     if (Align == 0)
7097       Align = getDataLayout()->getTypeAllocSize(C->getType());
7098     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7099
7100     if (IsThumb1)
7101       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7102           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7103     else
7104       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7105           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7106   }
7107   BB->addSuccessor(loopMBB);
7108
7109   // Generate the loop body:
7110   //   varPhi = PHI(varLoop, varEnd)
7111   //   srcPhi = PHI(srcLoop, src)
7112   //   destPhi = PHI(destLoop, dst)
7113   MachineBasicBlock *entryBB = BB;
7114   BB = loopMBB;
7115   unsigned varLoop = MRI.createVirtualRegister(TRC);
7116   unsigned varPhi = MRI.createVirtualRegister(TRC);
7117   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7118   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7119   unsigned destLoop = MRI.createVirtualRegister(TRC);
7120   unsigned destPhi = MRI.createVirtualRegister(TRC);
7121
7122   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7123     .addReg(varLoop).addMBB(loopMBB)
7124     .addReg(varEnd).addMBB(entryBB);
7125   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7126     .addReg(srcLoop).addMBB(loopMBB)
7127     .addReg(src).addMBB(entryBB);
7128   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7129     .addReg(destLoop).addMBB(loopMBB)
7130     .addReg(dest).addMBB(entryBB);
7131
7132   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7133   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7134   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7135   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7136              IsThumb1, IsThumb2);
7137   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7138              IsThumb1, IsThumb2);
7139
7140   // Decrement loop variable by UnitSize.
7141   if (IsThumb1) {
7142     MachineInstrBuilder MIB =
7143         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7144     MIB = AddDefaultT1CC(MIB);
7145     MIB.addReg(varPhi).addImm(UnitSize);
7146     AddDefaultPred(MIB);
7147   } else {
7148     MachineInstrBuilder MIB =
7149         BuildMI(*BB, BB->end(), dl,
7150                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7151     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7152     MIB->getOperand(5).setReg(ARM::CPSR);
7153     MIB->getOperand(5).setIsDef(true);
7154   }
7155   BuildMI(*BB, BB->end(), dl,
7156           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7157       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7158
7159   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7160   BB->addSuccessor(loopMBB);
7161   BB->addSuccessor(exitMBB);
7162
7163   // Add epilogue to handle BytesLeft.
7164   BB = exitMBB;
7165   MachineInstr *StartOfExit = exitMBB->begin();
7166
7167   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7168   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7169   unsigned srcIn = srcLoop;
7170   unsigned destIn = destLoop;
7171   for (unsigned i = 0; i < BytesLeft; i++) {
7172     unsigned srcOut = MRI.createVirtualRegister(TRC);
7173     unsigned destOut = MRI.createVirtualRegister(TRC);
7174     unsigned scratch = MRI.createVirtualRegister(TRC);
7175     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7176                IsThumb1, IsThumb2);
7177     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7178                IsThumb1, IsThumb2);
7179     srcIn = srcOut;
7180     destIn = destOut;
7181   }
7182
7183   MI->eraseFromParent();   // The instruction is gone now.
7184   return BB;
7185 }
7186
7187 MachineBasicBlock *
7188 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7189                                        MachineBasicBlock *MBB) const {
7190   const TargetMachine &TM = getTargetMachine();
7191   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7192   DebugLoc DL = MI->getDebugLoc();
7193
7194   assert(Subtarget->isTargetWindows() &&
7195          "__chkstk is only supported on Windows");
7196   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7197
7198   // __chkstk takes the number of words to allocate on the stack in R4, and
7199   // returns the stack adjustment in number of bytes in R4.  This will not
7200   // clober any other registers (other than the obvious lr).
7201   //
7202   // Although, technically, IP should be considered a register which may be
7203   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7204   // thumb-2 environment, so there is no interworking required.  As a result, we
7205   // do not expect a veneer to be emitted by the linker, clobbering IP.
7206   //
7207   // Each module receives its own copy of __chkstk, so no import thunk is
7208   // required, again, ensuring that IP is not clobbered.
7209   //
7210   // Finally, although some linkers may theoretically provide a trampoline for
7211   // out of range calls (which is quite common due to a 32M range limitation of
7212   // branches for Thumb), we can generate the long-call version via
7213   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7214   // IP.
7215
7216   switch (TM.getCodeModel()) {
7217   case CodeModel::Small:
7218   case CodeModel::Medium:
7219   case CodeModel::Default:
7220   case CodeModel::Kernel:
7221     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7222       .addImm((unsigned)ARMCC::AL).addReg(0)
7223       .addExternalSymbol("__chkstk")
7224       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7225       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7226       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7227     break;
7228   case CodeModel::Large:
7229   case CodeModel::JITDefault: {
7230     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7231     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7232
7233     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7234       .addExternalSymbol("__chkstk");
7235     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7236       .addImm((unsigned)ARMCC::AL).addReg(0)
7237       .addReg(Reg, RegState::Kill)
7238       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7239       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7240       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7241     break;
7242   }
7243   }
7244
7245   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7246                                       ARM::SP)
7247                               .addReg(ARM::SP).addReg(ARM::R4)));
7248
7249   MI->eraseFromParent();
7250   return MBB;
7251 }
7252
7253 MachineBasicBlock *
7254 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7255                                                MachineBasicBlock *BB) const {
7256   const TargetInstrInfo *TII =
7257       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7258   DebugLoc dl = MI->getDebugLoc();
7259   bool isThumb2 = Subtarget->isThumb2();
7260   switch (MI->getOpcode()) {
7261   default: {
7262     MI->dump();
7263     llvm_unreachable("Unexpected instr type to insert");
7264   }
7265   // The Thumb2 pre-indexed stores have the same MI operands, they just
7266   // define them differently in the .td files from the isel patterns, so
7267   // they need pseudos.
7268   case ARM::t2STR_preidx:
7269     MI->setDesc(TII->get(ARM::t2STR_PRE));
7270     return BB;
7271   case ARM::t2STRB_preidx:
7272     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7273     return BB;
7274   case ARM::t2STRH_preidx:
7275     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7276     return BB;
7277
7278   case ARM::STRi_preidx:
7279   case ARM::STRBi_preidx: {
7280     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7281       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7282     // Decode the offset.
7283     unsigned Offset = MI->getOperand(4).getImm();
7284     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7285     Offset = ARM_AM::getAM2Offset(Offset);
7286     if (isSub)
7287       Offset = -Offset;
7288
7289     MachineMemOperand *MMO = *MI->memoperands_begin();
7290     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7291       .addOperand(MI->getOperand(0))  // Rn_wb
7292       .addOperand(MI->getOperand(1))  // Rt
7293       .addOperand(MI->getOperand(2))  // Rn
7294       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7295       .addOperand(MI->getOperand(5))  // pred
7296       .addOperand(MI->getOperand(6))
7297       .addMemOperand(MMO);
7298     MI->eraseFromParent();
7299     return BB;
7300   }
7301   case ARM::STRr_preidx:
7302   case ARM::STRBr_preidx:
7303   case ARM::STRH_preidx: {
7304     unsigned NewOpc;
7305     switch (MI->getOpcode()) {
7306     default: llvm_unreachable("unexpected opcode!");
7307     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7308     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7309     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7310     }
7311     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7312     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7313       MIB.addOperand(MI->getOperand(i));
7314     MI->eraseFromParent();
7315     return BB;
7316   }
7317
7318   case ARM::tMOVCCr_pseudo: {
7319     // To "insert" a SELECT_CC instruction, we actually have to insert the
7320     // diamond control-flow pattern.  The incoming instruction knows the
7321     // destination vreg to set, the condition code register to branch on, the
7322     // true/false values to select between, and a branch opcode to use.
7323     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7324     MachineFunction::iterator It = BB;
7325     ++It;
7326
7327     //  thisMBB:
7328     //  ...
7329     //   TrueVal = ...
7330     //   cmpTY ccX, r1, r2
7331     //   bCC copy1MBB
7332     //   fallthrough --> copy0MBB
7333     MachineBasicBlock *thisMBB  = BB;
7334     MachineFunction *F = BB->getParent();
7335     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7336     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7337     F->insert(It, copy0MBB);
7338     F->insert(It, sinkMBB);
7339
7340     // Transfer the remainder of BB and its successor edges to sinkMBB.
7341     sinkMBB->splice(sinkMBB->begin(), BB,
7342                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7343     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7344
7345     BB->addSuccessor(copy0MBB);
7346     BB->addSuccessor(sinkMBB);
7347
7348     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7349       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7350
7351     //  copy0MBB:
7352     //   %FalseValue = ...
7353     //   # fallthrough to sinkMBB
7354     BB = copy0MBB;
7355
7356     // Update machine-CFG edges
7357     BB->addSuccessor(sinkMBB);
7358
7359     //  sinkMBB:
7360     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7361     //  ...
7362     BB = sinkMBB;
7363     BuildMI(*BB, BB->begin(), dl,
7364             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7365       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7366       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7367
7368     MI->eraseFromParent();   // The pseudo instruction is gone now.
7369     return BB;
7370   }
7371
7372   case ARM::BCCi64:
7373   case ARM::BCCZi64: {
7374     // If there is an unconditional branch to the other successor, remove it.
7375     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7376
7377     // Compare both parts that make up the double comparison separately for
7378     // equality.
7379     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7380
7381     unsigned LHS1 = MI->getOperand(1).getReg();
7382     unsigned LHS2 = MI->getOperand(2).getReg();
7383     if (RHSisZero) {
7384       AddDefaultPred(BuildMI(BB, dl,
7385                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7386                      .addReg(LHS1).addImm(0));
7387       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7388         .addReg(LHS2).addImm(0)
7389         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7390     } else {
7391       unsigned RHS1 = MI->getOperand(3).getReg();
7392       unsigned RHS2 = MI->getOperand(4).getReg();
7393       AddDefaultPred(BuildMI(BB, dl,
7394                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7395                      .addReg(LHS1).addReg(RHS1));
7396       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7397         .addReg(LHS2).addReg(RHS2)
7398         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7399     }
7400
7401     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7402     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7403     if (MI->getOperand(0).getImm() == ARMCC::NE)
7404       std::swap(destMBB, exitMBB);
7405
7406     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7407       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7408     if (isThumb2)
7409       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7410     else
7411       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7412
7413     MI->eraseFromParent();   // The pseudo instruction is gone now.
7414     return BB;
7415   }
7416
7417   case ARM::Int_eh_sjlj_setjmp:
7418   case ARM::Int_eh_sjlj_setjmp_nofp:
7419   case ARM::tInt_eh_sjlj_setjmp:
7420   case ARM::t2Int_eh_sjlj_setjmp:
7421   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7422     EmitSjLjDispatchBlock(MI, BB);
7423     return BB;
7424
7425   case ARM::ABS:
7426   case ARM::t2ABS: {
7427     // To insert an ABS instruction, we have to insert the
7428     // diamond control-flow pattern.  The incoming instruction knows the
7429     // source vreg to test against 0, the destination vreg to set,
7430     // the condition code register to branch on, the
7431     // true/false values to select between, and a branch opcode to use.
7432     // It transforms
7433     //     V1 = ABS V0
7434     // into
7435     //     V2 = MOVS V0
7436     //     BCC                      (branch to SinkBB if V0 >= 0)
7437     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7438     //     SinkBB: V1 = PHI(V2, V3)
7439     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7440     MachineFunction::iterator BBI = BB;
7441     ++BBI;
7442     MachineFunction *Fn = BB->getParent();
7443     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7444     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7445     Fn->insert(BBI, RSBBB);
7446     Fn->insert(BBI, SinkBB);
7447
7448     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7449     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7450     bool isThumb2 = Subtarget->isThumb2();
7451     MachineRegisterInfo &MRI = Fn->getRegInfo();
7452     // In Thumb mode S must not be specified if source register is the SP or
7453     // PC and if destination register is the SP, so restrict register class
7454     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7455       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7456       (const TargetRegisterClass*)&ARM::GPRRegClass);
7457
7458     // Transfer the remainder of BB and its successor edges to sinkMBB.
7459     SinkBB->splice(SinkBB->begin(), BB,
7460                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7461     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7462
7463     BB->addSuccessor(RSBBB);
7464     BB->addSuccessor(SinkBB);
7465
7466     // fall through to SinkMBB
7467     RSBBB->addSuccessor(SinkBB);
7468
7469     // insert a cmp at the end of BB
7470     AddDefaultPred(BuildMI(BB, dl,
7471                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7472                    .addReg(ABSSrcReg).addImm(0));
7473
7474     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7475     BuildMI(BB, dl,
7476       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7477       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7478
7479     // insert rsbri in RSBBB
7480     // Note: BCC and rsbri will be converted into predicated rsbmi
7481     // by if-conversion pass
7482     BuildMI(*RSBBB, RSBBB->begin(), dl,
7483       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7484       .addReg(ABSSrcReg, RegState::Kill)
7485       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7486
7487     // insert PHI in SinkBB,
7488     // reuse ABSDstReg to not change uses of ABS instruction
7489     BuildMI(*SinkBB, SinkBB->begin(), dl,
7490       TII->get(ARM::PHI), ABSDstReg)
7491       .addReg(NewRsbDstReg).addMBB(RSBBB)
7492       .addReg(ABSSrcReg).addMBB(BB);
7493
7494     // remove ABS instruction
7495     MI->eraseFromParent();
7496
7497     // return last added BB
7498     return SinkBB;
7499   }
7500   case ARM::COPY_STRUCT_BYVAL_I32:
7501     ++NumLoopByVals;
7502     return EmitStructByval(MI, BB);
7503   case ARM::WIN__CHKSTK:
7504     return EmitLowered__chkstk(MI, BB);
7505   }
7506 }
7507
7508 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7509                                                       SDNode *Node) const {
7510   if (!MI->hasPostISelHook()) {
7511     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7512            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7513     return;
7514   }
7515
7516   const MCInstrDesc *MCID = &MI->getDesc();
7517   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7518   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7519   // operand is still set to noreg. If needed, set the optional operand's
7520   // register to CPSR, and remove the redundant implicit def.
7521   //
7522   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7523
7524   // Rename pseudo opcodes.
7525   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7526   if (NewOpc) {
7527     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7528         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7529     MCID = &TII->get(NewOpc);
7530
7531     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7532            "converted opcode should be the same except for cc_out");
7533
7534     MI->setDesc(*MCID);
7535
7536     // Add the optional cc_out operand
7537     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7538   }
7539   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7540
7541   // Any ARM instruction that sets the 's' bit should specify an optional
7542   // "cc_out" operand in the last operand position.
7543   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7544     assert(!NewOpc && "Optional cc_out operand required");
7545     return;
7546   }
7547   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7548   // since we already have an optional CPSR def.
7549   bool definesCPSR = false;
7550   bool deadCPSR = false;
7551   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7552        i != e; ++i) {
7553     const MachineOperand &MO = MI->getOperand(i);
7554     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7555       definesCPSR = true;
7556       if (MO.isDead())
7557         deadCPSR = true;
7558       MI->RemoveOperand(i);
7559       break;
7560     }
7561   }
7562   if (!definesCPSR) {
7563     assert(!NewOpc && "Optional cc_out operand required");
7564     return;
7565   }
7566   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7567   if (deadCPSR) {
7568     assert(!MI->getOperand(ccOutIdx).getReg() &&
7569            "expect uninitialized optional cc_out operand");
7570     return;
7571   }
7572
7573   // If this instruction was defined with an optional CPSR def and its dag node
7574   // had a live implicit CPSR def, then activate the optional CPSR def.
7575   MachineOperand &MO = MI->getOperand(ccOutIdx);
7576   MO.setReg(ARM::CPSR);
7577   MO.setIsDef(true);
7578 }
7579
7580 //===----------------------------------------------------------------------===//
7581 //                           ARM Optimization Hooks
7582 //===----------------------------------------------------------------------===//
7583
7584 // Helper function that checks if N is a null or all ones constant.
7585 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7586   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7587   if (!C)
7588     return false;
7589   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7590 }
7591
7592 // Return true if N is conditionally 0 or all ones.
7593 // Detects these expressions where cc is an i1 value:
7594 //
7595 //   (select cc 0, y)   [AllOnes=0]
7596 //   (select cc y, 0)   [AllOnes=0]
7597 //   (zext cc)          [AllOnes=0]
7598 //   (sext cc)          [AllOnes=0/1]
7599 //   (select cc -1, y)  [AllOnes=1]
7600 //   (select cc y, -1)  [AllOnes=1]
7601 //
7602 // Invert is set when N is the null/all ones constant when CC is false.
7603 // OtherOp is set to the alternative value of N.
7604 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7605                                        SDValue &CC, bool &Invert,
7606                                        SDValue &OtherOp,
7607                                        SelectionDAG &DAG) {
7608   switch (N->getOpcode()) {
7609   default: return false;
7610   case ISD::SELECT: {
7611     CC = N->getOperand(0);
7612     SDValue N1 = N->getOperand(1);
7613     SDValue N2 = N->getOperand(2);
7614     if (isZeroOrAllOnes(N1, AllOnes)) {
7615       Invert = false;
7616       OtherOp = N2;
7617       return true;
7618     }
7619     if (isZeroOrAllOnes(N2, AllOnes)) {
7620       Invert = true;
7621       OtherOp = N1;
7622       return true;
7623     }
7624     return false;
7625   }
7626   case ISD::ZERO_EXTEND:
7627     // (zext cc) can never be the all ones value.
7628     if (AllOnes)
7629       return false;
7630     // Fall through.
7631   case ISD::SIGN_EXTEND: {
7632     EVT VT = N->getValueType(0);
7633     CC = N->getOperand(0);
7634     if (CC.getValueType() != MVT::i1)
7635       return false;
7636     Invert = !AllOnes;
7637     if (AllOnes)
7638       // When looking for an AllOnes constant, N is an sext, and the 'other'
7639       // value is 0.
7640       OtherOp = DAG.getConstant(0, VT);
7641     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7642       // When looking for a 0 constant, N can be zext or sext.
7643       OtherOp = DAG.getConstant(1, VT);
7644     else
7645       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7646     return true;
7647   }
7648   }
7649 }
7650
7651 // Combine a constant select operand into its use:
7652 //
7653 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7654 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7655 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7656 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7657 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7658 //
7659 // The transform is rejected if the select doesn't have a constant operand that
7660 // is null, or all ones when AllOnes is set.
7661 //
7662 // Also recognize sext/zext from i1:
7663 //
7664 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7665 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7666 //
7667 // These transformations eventually create predicated instructions.
7668 //
7669 // @param N       The node to transform.
7670 // @param Slct    The N operand that is a select.
7671 // @param OtherOp The other N operand (x above).
7672 // @param DCI     Context.
7673 // @param AllOnes Require the select constant to be all ones instead of null.
7674 // @returns The new node, or SDValue() on failure.
7675 static
7676 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7677                             TargetLowering::DAGCombinerInfo &DCI,
7678                             bool AllOnes = false) {
7679   SelectionDAG &DAG = DCI.DAG;
7680   EVT VT = N->getValueType(0);
7681   SDValue NonConstantVal;
7682   SDValue CCOp;
7683   bool SwapSelectOps;
7684   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7685                                   NonConstantVal, DAG))
7686     return SDValue();
7687
7688   // Slct is now know to be the desired identity constant when CC is true.
7689   SDValue TrueVal = OtherOp;
7690   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7691                                  OtherOp, NonConstantVal);
7692   // Unless SwapSelectOps says CC should be false.
7693   if (SwapSelectOps)
7694     std::swap(TrueVal, FalseVal);
7695
7696   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7697                      CCOp, TrueVal, FalseVal);
7698 }
7699
7700 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7701 static
7702 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7703                                        TargetLowering::DAGCombinerInfo &DCI) {
7704   SDValue N0 = N->getOperand(0);
7705   SDValue N1 = N->getOperand(1);
7706   if (N0.getNode()->hasOneUse()) {
7707     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7708     if (Result.getNode())
7709       return Result;
7710   }
7711   if (N1.getNode()->hasOneUse()) {
7712     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7713     if (Result.getNode())
7714       return Result;
7715   }
7716   return SDValue();
7717 }
7718
7719 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7720 // (only after legalization).
7721 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7722                                  TargetLowering::DAGCombinerInfo &DCI,
7723                                  const ARMSubtarget *Subtarget) {
7724
7725   // Only perform optimization if after legalize, and if NEON is available. We
7726   // also expected both operands to be BUILD_VECTORs.
7727   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7728       || N0.getOpcode() != ISD::BUILD_VECTOR
7729       || N1.getOpcode() != ISD::BUILD_VECTOR)
7730     return SDValue();
7731
7732   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7733   EVT VT = N->getValueType(0);
7734   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7735     return SDValue();
7736
7737   // Check that the vector operands are of the right form.
7738   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7739   // operands, where N is the size of the formed vector.
7740   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7741   // index such that we have a pair wise add pattern.
7742
7743   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7744   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7745     return SDValue();
7746   SDValue Vec = N0->getOperand(0)->getOperand(0);
7747   SDNode *V = Vec.getNode();
7748   unsigned nextIndex = 0;
7749
7750   // For each operands to the ADD which are BUILD_VECTORs,
7751   // check to see if each of their operands are an EXTRACT_VECTOR with
7752   // the same vector and appropriate index.
7753   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7754     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7755         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7756
7757       SDValue ExtVec0 = N0->getOperand(i);
7758       SDValue ExtVec1 = N1->getOperand(i);
7759
7760       // First operand is the vector, verify its the same.
7761       if (V != ExtVec0->getOperand(0).getNode() ||
7762           V != ExtVec1->getOperand(0).getNode())
7763         return SDValue();
7764
7765       // Second is the constant, verify its correct.
7766       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7767       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7768
7769       // For the constant, we want to see all the even or all the odd.
7770       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7771           || C1->getZExtValue() != nextIndex+1)
7772         return SDValue();
7773
7774       // Increment index.
7775       nextIndex+=2;
7776     } else
7777       return SDValue();
7778   }
7779
7780   // Create VPADDL node.
7781   SelectionDAG &DAG = DCI.DAG;
7782   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7783
7784   // Build operand list.
7785   SmallVector<SDValue, 8> Ops;
7786   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7787                                 TLI.getPointerTy()));
7788
7789   // Input is the vector.
7790   Ops.push_back(Vec);
7791
7792   // Get widened type and narrowed type.
7793   MVT widenType;
7794   unsigned numElem = VT.getVectorNumElements();
7795   
7796   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7797   switch (inputLaneType.getSimpleVT().SimpleTy) {
7798     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7799     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7800     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7801     default:
7802       llvm_unreachable("Invalid vector element type for padd optimization.");
7803   }
7804
7805   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7806   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7807   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7808 }
7809
7810 static SDValue findMUL_LOHI(SDValue V) {
7811   if (V->getOpcode() == ISD::UMUL_LOHI ||
7812       V->getOpcode() == ISD::SMUL_LOHI)
7813     return V;
7814   return SDValue();
7815 }
7816
7817 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7818                                      TargetLowering::DAGCombinerInfo &DCI,
7819                                      const ARMSubtarget *Subtarget) {
7820
7821   if (Subtarget->isThumb1Only()) return SDValue();
7822
7823   // Only perform the checks after legalize when the pattern is available.
7824   if (DCI.isBeforeLegalize()) return SDValue();
7825
7826   // Look for multiply add opportunities.
7827   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7828   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7829   // a glue link from the first add to the second add.
7830   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7831   // a S/UMLAL instruction.
7832   //          loAdd   UMUL_LOHI
7833   //            \    / :lo    \ :hi
7834   //             \  /          \          [no multiline comment]
7835   //              ADDC         |  hiAdd
7836   //                 \ :glue  /  /
7837   //                  \      /  /
7838   //                    ADDE
7839   //
7840   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7841   SDValue AddcOp0 = AddcNode->getOperand(0);
7842   SDValue AddcOp1 = AddcNode->getOperand(1);
7843
7844   // Check if the two operands are from the same mul_lohi node.
7845   if (AddcOp0.getNode() == AddcOp1.getNode())
7846     return SDValue();
7847
7848   assert(AddcNode->getNumValues() == 2 &&
7849          AddcNode->getValueType(0) == MVT::i32 &&
7850          "Expect ADDC with two result values. First: i32");
7851
7852   // Check that we have a glued ADDC node.
7853   if (AddcNode->getValueType(1) != MVT::Glue)
7854     return SDValue();
7855
7856   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7857   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7858       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7859       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7860       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7861     return SDValue();
7862
7863   // Look for the glued ADDE.
7864   SDNode* AddeNode = AddcNode->getGluedUser();
7865   if (!AddeNode)
7866     return SDValue();
7867
7868   // Make sure it is really an ADDE.
7869   if (AddeNode->getOpcode() != ISD::ADDE)
7870     return SDValue();
7871
7872   assert(AddeNode->getNumOperands() == 3 &&
7873          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7874          "ADDE node has the wrong inputs");
7875
7876   // Check for the triangle shape.
7877   SDValue AddeOp0 = AddeNode->getOperand(0);
7878   SDValue AddeOp1 = AddeNode->getOperand(1);
7879
7880   // Make sure that the ADDE operands are not coming from the same node.
7881   if (AddeOp0.getNode() == AddeOp1.getNode())
7882     return SDValue();
7883
7884   // Find the MUL_LOHI node walking up ADDE's operands.
7885   bool IsLeftOperandMUL = false;
7886   SDValue MULOp = findMUL_LOHI(AddeOp0);
7887   if (MULOp == SDValue())
7888    MULOp = findMUL_LOHI(AddeOp1);
7889   else
7890     IsLeftOperandMUL = true;
7891   if (MULOp == SDValue())
7892      return SDValue();
7893
7894   // Figure out the right opcode.
7895   unsigned Opc = MULOp->getOpcode();
7896   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7897
7898   // Figure out the high and low input values to the MLAL node.
7899   SDValue* HiMul = &MULOp;
7900   SDValue* HiAdd = nullptr;
7901   SDValue* LoMul = nullptr;
7902   SDValue* LowAdd = nullptr;
7903
7904   if (IsLeftOperandMUL)
7905     HiAdd = &AddeOp1;
7906   else
7907     HiAdd = &AddeOp0;
7908
7909
7910   if (AddcOp0->getOpcode() == Opc) {
7911     LoMul = &AddcOp0;
7912     LowAdd = &AddcOp1;
7913   }
7914   if (AddcOp1->getOpcode() == Opc) {
7915     LoMul = &AddcOp1;
7916     LowAdd = &AddcOp0;
7917   }
7918
7919   if (!LoMul)
7920     return SDValue();
7921
7922   if (LoMul->getNode() != HiMul->getNode())
7923     return SDValue();
7924
7925   // Create the merged node.
7926   SelectionDAG &DAG = DCI.DAG;
7927
7928   // Build operand list.
7929   SmallVector<SDValue, 8> Ops;
7930   Ops.push_back(LoMul->getOperand(0));
7931   Ops.push_back(LoMul->getOperand(1));
7932   Ops.push_back(*LowAdd);
7933   Ops.push_back(*HiAdd);
7934
7935   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7936                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7937
7938   // Replace the ADDs' nodes uses by the MLA node's values.
7939   SDValue HiMLALResult(MLALNode.getNode(), 1);
7940   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7941
7942   SDValue LoMLALResult(MLALNode.getNode(), 0);
7943   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7944
7945   // Return original node to notify the driver to stop replacing.
7946   SDValue resNode(AddcNode, 0);
7947   return resNode;
7948 }
7949
7950 /// PerformADDCCombine - Target-specific dag combine transform from
7951 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7952 static SDValue PerformADDCCombine(SDNode *N,
7953                                  TargetLowering::DAGCombinerInfo &DCI,
7954                                  const ARMSubtarget *Subtarget) {
7955
7956   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7957
7958 }
7959
7960 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7961 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7962 /// called with the default operands, and if that fails, with commuted
7963 /// operands.
7964 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7965                                           TargetLowering::DAGCombinerInfo &DCI,
7966                                           const ARMSubtarget *Subtarget){
7967
7968   // Attempt to create vpaddl for this add.
7969   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7970   if (Result.getNode())
7971     return Result;
7972
7973   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7974   if (N0.getNode()->hasOneUse()) {
7975     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7976     if (Result.getNode()) return Result;
7977   }
7978   return SDValue();
7979 }
7980
7981 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7982 ///
7983 static SDValue PerformADDCombine(SDNode *N,
7984                                  TargetLowering::DAGCombinerInfo &DCI,
7985                                  const ARMSubtarget *Subtarget) {
7986   SDValue N0 = N->getOperand(0);
7987   SDValue N1 = N->getOperand(1);
7988
7989   // First try with the default operand order.
7990   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7991   if (Result.getNode())
7992     return Result;
7993
7994   // If that didn't work, try again with the operands commuted.
7995   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7996 }
7997
7998 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7999 ///
8000 static SDValue PerformSUBCombine(SDNode *N,
8001                                  TargetLowering::DAGCombinerInfo &DCI) {
8002   SDValue N0 = N->getOperand(0);
8003   SDValue N1 = N->getOperand(1);
8004
8005   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8006   if (N1.getNode()->hasOneUse()) {
8007     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8008     if (Result.getNode()) return Result;
8009   }
8010
8011   return SDValue();
8012 }
8013
8014 /// PerformVMULCombine
8015 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8016 /// special multiplier accumulator forwarding.
8017 ///   vmul d3, d0, d2
8018 ///   vmla d3, d1, d2
8019 /// is faster than
8020 ///   vadd d3, d0, d1
8021 ///   vmul d3, d3, d2
8022 //  However, for (A + B) * (A + B),
8023 //    vadd d2, d0, d1
8024 //    vmul d3, d0, d2
8025 //    vmla d3, d1, d2
8026 //  is slower than
8027 //    vadd d2, d0, d1
8028 //    vmul d3, d2, d2
8029 static SDValue PerformVMULCombine(SDNode *N,
8030                                   TargetLowering::DAGCombinerInfo &DCI,
8031                                   const ARMSubtarget *Subtarget) {
8032   if (!Subtarget->hasVMLxForwarding())
8033     return SDValue();
8034
8035   SelectionDAG &DAG = DCI.DAG;
8036   SDValue N0 = N->getOperand(0);
8037   SDValue N1 = N->getOperand(1);
8038   unsigned Opcode = N0.getOpcode();
8039   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8040       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8041     Opcode = N1.getOpcode();
8042     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8043         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8044       return SDValue();
8045     std::swap(N0, N1);
8046   }
8047
8048   if (N0 == N1)
8049     return SDValue();
8050
8051   EVT VT = N->getValueType(0);
8052   SDLoc DL(N);
8053   SDValue N00 = N0->getOperand(0);
8054   SDValue N01 = N0->getOperand(1);
8055   return DAG.getNode(Opcode, DL, VT,
8056                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8057                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8058 }
8059
8060 static SDValue PerformMULCombine(SDNode *N,
8061                                  TargetLowering::DAGCombinerInfo &DCI,
8062                                  const ARMSubtarget *Subtarget) {
8063   SelectionDAG &DAG = DCI.DAG;
8064
8065   if (Subtarget->isThumb1Only())
8066     return SDValue();
8067
8068   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8069     return SDValue();
8070
8071   EVT VT = N->getValueType(0);
8072   if (VT.is64BitVector() || VT.is128BitVector())
8073     return PerformVMULCombine(N, DCI, Subtarget);
8074   if (VT != MVT::i32)
8075     return SDValue();
8076
8077   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8078   if (!C)
8079     return SDValue();
8080
8081   int64_t MulAmt = C->getSExtValue();
8082   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8083
8084   ShiftAmt = ShiftAmt & (32 - 1);
8085   SDValue V = N->getOperand(0);
8086   SDLoc DL(N);
8087
8088   SDValue Res;
8089   MulAmt >>= ShiftAmt;
8090
8091   if (MulAmt >= 0) {
8092     if (isPowerOf2_32(MulAmt - 1)) {
8093       // (mul x, 2^N + 1) => (add (shl x, N), x)
8094       Res = DAG.getNode(ISD::ADD, DL, VT,
8095                         V,
8096                         DAG.getNode(ISD::SHL, DL, VT,
8097                                     V,
8098                                     DAG.getConstant(Log2_32(MulAmt - 1),
8099                                                     MVT::i32)));
8100     } else if (isPowerOf2_32(MulAmt + 1)) {
8101       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8102       Res = DAG.getNode(ISD::SUB, DL, VT,
8103                         DAG.getNode(ISD::SHL, DL, VT,
8104                                     V,
8105                                     DAG.getConstant(Log2_32(MulAmt + 1),
8106                                                     MVT::i32)),
8107                         V);
8108     } else
8109       return SDValue();
8110   } else {
8111     uint64_t MulAmtAbs = -MulAmt;
8112     if (isPowerOf2_32(MulAmtAbs + 1)) {
8113       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8114       Res = DAG.getNode(ISD::SUB, DL, VT,
8115                         V,
8116                         DAG.getNode(ISD::SHL, DL, VT,
8117                                     V,
8118                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8119                                                     MVT::i32)));
8120     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8121       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8122       Res = DAG.getNode(ISD::ADD, DL, VT,
8123                         V,
8124                         DAG.getNode(ISD::SHL, DL, VT,
8125                                     V,
8126                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8127                                                     MVT::i32)));
8128       Res = DAG.getNode(ISD::SUB, DL, VT,
8129                         DAG.getConstant(0, MVT::i32),Res);
8130
8131     } else
8132       return SDValue();
8133   }
8134
8135   if (ShiftAmt != 0)
8136     Res = DAG.getNode(ISD::SHL, DL, VT,
8137                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8138
8139   // Do not add new nodes to DAG combiner worklist.
8140   DCI.CombineTo(N, Res, false);
8141   return SDValue();
8142 }
8143
8144 static SDValue PerformANDCombine(SDNode *N,
8145                                  TargetLowering::DAGCombinerInfo &DCI,
8146                                  const ARMSubtarget *Subtarget) {
8147
8148   // Attempt to use immediate-form VBIC
8149   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8150   SDLoc dl(N);
8151   EVT VT = N->getValueType(0);
8152   SelectionDAG &DAG = DCI.DAG;
8153
8154   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8155     return SDValue();
8156
8157   APInt SplatBits, SplatUndef;
8158   unsigned SplatBitSize;
8159   bool HasAnyUndefs;
8160   if (BVN &&
8161       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8162     if (SplatBitSize <= 64) {
8163       EVT VbicVT;
8164       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8165                                       SplatUndef.getZExtValue(), SplatBitSize,
8166                                       DAG, VbicVT, VT.is128BitVector(),
8167                                       OtherModImm);
8168       if (Val.getNode()) {
8169         SDValue Input =
8170           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8171         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8172         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8173       }
8174     }
8175   }
8176
8177   if (!Subtarget->isThumb1Only()) {
8178     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8179     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8180     if (Result.getNode())
8181       return Result;
8182   }
8183
8184   return SDValue();
8185 }
8186
8187 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8188 static SDValue PerformORCombine(SDNode *N,
8189                                 TargetLowering::DAGCombinerInfo &DCI,
8190                                 const ARMSubtarget *Subtarget) {
8191   // Attempt to use immediate-form VORR
8192   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8193   SDLoc dl(N);
8194   EVT VT = N->getValueType(0);
8195   SelectionDAG &DAG = DCI.DAG;
8196
8197   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8198     return SDValue();
8199
8200   APInt SplatBits, SplatUndef;
8201   unsigned SplatBitSize;
8202   bool HasAnyUndefs;
8203   if (BVN && Subtarget->hasNEON() &&
8204       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8205     if (SplatBitSize <= 64) {
8206       EVT VorrVT;
8207       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8208                                       SplatUndef.getZExtValue(), SplatBitSize,
8209                                       DAG, VorrVT, VT.is128BitVector(),
8210                                       OtherModImm);
8211       if (Val.getNode()) {
8212         SDValue Input =
8213           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8214         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8215         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8216       }
8217     }
8218   }
8219
8220   if (!Subtarget->isThumb1Only()) {
8221     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8222     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8223     if (Result.getNode())
8224       return Result;
8225   }
8226
8227   // The code below optimizes (or (and X, Y), Z).
8228   // The AND operand needs to have a single user to make these optimizations
8229   // profitable.
8230   SDValue N0 = N->getOperand(0);
8231   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8232     return SDValue();
8233   SDValue N1 = N->getOperand(1);
8234
8235   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8236   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8237       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8238     APInt SplatUndef;
8239     unsigned SplatBitSize;
8240     bool HasAnyUndefs;
8241
8242     APInt SplatBits0, SplatBits1;
8243     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8244     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8245     // Ensure that the second operand of both ands are constants
8246     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8247                                       HasAnyUndefs) && !HasAnyUndefs) {
8248         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8249                                           HasAnyUndefs) && !HasAnyUndefs) {
8250             // Ensure that the bit width of the constants are the same and that
8251             // the splat arguments are logical inverses as per the pattern we
8252             // are trying to simplify.
8253             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8254                 SplatBits0 == ~SplatBits1) {
8255                 // Canonicalize the vector type to make instruction selection
8256                 // simpler.
8257                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8258                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8259                                              N0->getOperand(1),
8260                                              N0->getOperand(0),
8261                                              N1->getOperand(0));
8262                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8263             }
8264         }
8265     }
8266   }
8267
8268   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8269   // reasonable.
8270
8271   // BFI is only available on V6T2+
8272   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8273     return SDValue();
8274
8275   SDLoc DL(N);
8276   // 1) or (and A, mask), val => ARMbfi A, val, mask
8277   //      iff (val & mask) == val
8278   //
8279   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8280   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8281   //          && mask == ~mask2
8282   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8283   //          && ~mask == mask2
8284   //  (i.e., copy a bitfield value into another bitfield of the same width)
8285
8286   if (VT != MVT::i32)
8287     return SDValue();
8288
8289   SDValue N00 = N0.getOperand(0);
8290
8291   // The value and the mask need to be constants so we can verify this is
8292   // actually a bitfield set. If the mask is 0xffff, we can do better
8293   // via a movt instruction, so don't use BFI in that case.
8294   SDValue MaskOp = N0.getOperand(1);
8295   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8296   if (!MaskC)
8297     return SDValue();
8298   unsigned Mask = MaskC->getZExtValue();
8299   if (Mask == 0xffff)
8300     return SDValue();
8301   SDValue Res;
8302   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8303   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8304   if (N1C) {
8305     unsigned Val = N1C->getZExtValue();
8306     if ((Val & ~Mask) != Val)
8307       return SDValue();
8308
8309     if (ARM::isBitFieldInvertedMask(Mask)) {
8310       Val >>= countTrailingZeros(~Mask);
8311
8312       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8313                         DAG.getConstant(Val, MVT::i32),
8314                         DAG.getConstant(Mask, MVT::i32));
8315
8316       // Do not add new nodes to DAG combiner worklist.
8317       DCI.CombineTo(N, Res, false);
8318       return SDValue();
8319     }
8320   } else if (N1.getOpcode() == ISD::AND) {
8321     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8322     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8323     if (!N11C)
8324       return SDValue();
8325     unsigned Mask2 = N11C->getZExtValue();
8326
8327     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8328     // as is to match.
8329     if (ARM::isBitFieldInvertedMask(Mask) &&
8330         (Mask == ~Mask2)) {
8331       // The pack halfword instruction works better for masks that fit it,
8332       // so use that when it's available.
8333       if (Subtarget->hasT2ExtractPack() &&
8334           (Mask == 0xffff || Mask == 0xffff0000))
8335         return SDValue();
8336       // 2a
8337       unsigned amt = countTrailingZeros(Mask2);
8338       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8339                         DAG.getConstant(amt, MVT::i32));
8340       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8341                         DAG.getConstant(Mask, MVT::i32));
8342       // Do not add new nodes to DAG combiner worklist.
8343       DCI.CombineTo(N, Res, false);
8344       return SDValue();
8345     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8346                (~Mask == Mask2)) {
8347       // The pack halfword instruction works better for masks that fit it,
8348       // so use that when it's available.
8349       if (Subtarget->hasT2ExtractPack() &&
8350           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8351         return SDValue();
8352       // 2b
8353       unsigned lsb = countTrailingZeros(Mask);
8354       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8355                         DAG.getConstant(lsb, MVT::i32));
8356       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8357                         DAG.getConstant(Mask2, MVT::i32));
8358       // Do not add new nodes to DAG combiner worklist.
8359       DCI.CombineTo(N, Res, false);
8360       return SDValue();
8361     }
8362   }
8363
8364   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8365       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8366       ARM::isBitFieldInvertedMask(~Mask)) {
8367     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8368     // where lsb(mask) == #shamt and masked bits of B are known zero.
8369     SDValue ShAmt = N00.getOperand(1);
8370     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8371     unsigned LSB = countTrailingZeros(Mask);
8372     if (ShAmtC != LSB)
8373       return SDValue();
8374
8375     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8376                       DAG.getConstant(~Mask, MVT::i32));
8377
8378     // Do not add new nodes to DAG combiner worklist.
8379     DCI.CombineTo(N, Res, false);
8380   }
8381
8382   return SDValue();
8383 }
8384
8385 static SDValue PerformXORCombine(SDNode *N,
8386                                  TargetLowering::DAGCombinerInfo &DCI,
8387                                  const ARMSubtarget *Subtarget) {
8388   EVT VT = N->getValueType(0);
8389   SelectionDAG &DAG = DCI.DAG;
8390
8391   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8392     return SDValue();
8393
8394   if (!Subtarget->isThumb1Only()) {
8395     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8396     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8397     if (Result.getNode())
8398       return Result;
8399   }
8400
8401   return SDValue();
8402 }
8403
8404 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8405 /// the bits being cleared by the AND are not demanded by the BFI.
8406 static SDValue PerformBFICombine(SDNode *N,
8407                                  TargetLowering::DAGCombinerInfo &DCI) {
8408   SDValue N1 = N->getOperand(1);
8409   if (N1.getOpcode() == ISD::AND) {
8410     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8411     if (!N11C)
8412       return SDValue();
8413     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8414     unsigned LSB = countTrailingZeros(~InvMask);
8415     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8416     unsigned Mask = (1 << Width)-1;
8417     unsigned Mask2 = N11C->getZExtValue();
8418     if ((Mask & (~Mask2)) == 0)
8419       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8420                              N->getOperand(0), N1.getOperand(0),
8421                              N->getOperand(2));
8422   }
8423   return SDValue();
8424 }
8425
8426 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8427 /// ARMISD::VMOVRRD.
8428 static SDValue PerformVMOVRRDCombine(SDNode *N,
8429                                      TargetLowering::DAGCombinerInfo &DCI) {
8430   // vmovrrd(vmovdrr x, y) -> x,y
8431   SDValue InDouble = N->getOperand(0);
8432   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8433     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8434
8435   // vmovrrd(load f64) -> (load i32), (load i32)
8436   SDNode *InNode = InDouble.getNode();
8437   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8438       InNode->getValueType(0) == MVT::f64 &&
8439       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8440       !cast<LoadSDNode>(InNode)->isVolatile()) {
8441     // TODO: Should this be done for non-FrameIndex operands?
8442     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8443
8444     SelectionDAG &DAG = DCI.DAG;
8445     SDLoc DL(LD);
8446     SDValue BasePtr = LD->getBasePtr();
8447     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8448                                  LD->getPointerInfo(), LD->isVolatile(),
8449                                  LD->isNonTemporal(), LD->isInvariant(),
8450                                  LD->getAlignment());
8451
8452     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8453                                     DAG.getConstant(4, MVT::i32));
8454     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8455                                  LD->getPointerInfo(), LD->isVolatile(),
8456                                  LD->isNonTemporal(), LD->isInvariant(),
8457                                  std::min(4U, LD->getAlignment() / 2));
8458
8459     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8460     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8461       std::swap (NewLD1, NewLD2);
8462     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8463     return Result;
8464   }
8465
8466   return SDValue();
8467 }
8468
8469 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8470 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8471 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8472   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8473   SDValue Op0 = N->getOperand(0);
8474   SDValue Op1 = N->getOperand(1);
8475   if (Op0.getOpcode() == ISD::BITCAST)
8476     Op0 = Op0.getOperand(0);
8477   if (Op1.getOpcode() == ISD::BITCAST)
8478     Op1 = Op1.getOperand(0);
8479   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8480       Op0.getNode() == Op1.getNode() &&
8481       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8482     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8483                        N->getValueType(0), Op0.getOperand(0));
8484   return SDValue();
8485 }
8486
8487 /// PerformSTORECombine - Target-specific dag combine xforms for
8488 /// ISD::STORE.
8489 static SDValue PerformSTORECombine(SDNode *N,
8490                                    TargetLowering::DAGCombinerInfo &DCI) {
8491   StoreSDNode *St = cast<StoreSDNode>(N);
8492   if (St->isVolatile())
8493     return SDValue();
8494
8495   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8496   // pack all of the elements in one place.  Next, store to memory in fewer
8497   // chunks.
8498   SDValue StVal = St->getValue();
8499   EVT VT = StVal.getValueType();
8500   if (St->isTruncatingStore() && VT.isVector()) {
8501     SelectionDAG &DAG = DCI.DAG;
8502     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8503     EVT StVT = St->getMemoryVT();
8504     unsigned NumElems = VT.getVectorNumElements();
8505     assert(StVT != VT && "Cannot truncate to the same type");
8506     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8507     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8508
8509     // From, To sizes and ElemCount must be pow of two
8510     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8511
8512     // We are going to use the original vector elt for storing.
8513     // Accumulated smaller vector elements must be a multiple of the store size.
8514     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8515
8516     unsigned SizeRatio  = FromEltSz / ToEltSz;
8517     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8518
8519     // Create a type on which we perform the shuffle.
8520     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8521                                      NumElems*SizeRatio);
8522     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8523
8524     SDLoc DL(St);
8525     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8526     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8527     for (unsigned i = 0; i < NumElems; ++i)
8528       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8529
8530     // Can't shuffle using an illegal type.
8531     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8532
8533     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8534                                 DAG.getUNDEF(WideVec.getValueType()),
8535                                 ShuffleVec.data());
8536     // At this point all of the data is stored at the bottom of the
8537     // register. We now need to save it to mem.
8538
8539     // Find the largest store unit
8540     MVT StoreType = MVT::i8;
8541     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8542          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8543       MVT Tp = (MVT::SimpleValueType)tp;
8544       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8545         StoreType = Tp;
8546     }
8547     // Didn't find a legal store type.
8548     if (!TLI.isTypeLegal(StoreType))
8549       return SDValue();
8550
8551     // Bitcast the original vector into a vector of store-size units
8552     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8553             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8554     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8555     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8556     SmallVector<SDValue, 8> Chains;
8557     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8558                                         TLI.getPointerTy());
8559     SDValue BasePtr = St->getBasePtr();
8560
8561     // Perform one or more big stores into memory.
8562     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8563     for (unsigned I = 0; I < E; I++) {
8564       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8565                                    StoreType, ShuffWide,
8566                                    DAG.getIntPtrConstant(I));
8567       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8568                                 St->getPointerInfo(), St->isVolatile(),
8569                                 St->isNonTemporal(), St->getAlignment());
8570       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8571                             Increment);
8572       Chains.push_back(Ch);
8573     }
8574     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8575   }
8576
8577   if (!ISD::isNormalStore(St))
8578     return SDValue();
8579
8580   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8581   // ARM stores of arguments in the same cache line.
8582   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8583       StVal.getNode()->hasOneUse()) {
8584     SelectionDAG  &DAG = DCI.DAG;
8585     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8586     SDLoc DL(St);
8587     SDValue BasePtr = St->getBasePtr();
8588     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8589                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8590                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8591                                   St->isNonTemporal(), St->getAlignment());
8592
8593     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8594                                     DAG.getConstant(4, MVT::i32));
8595     return DAG.getStore(NewST1.getValue(0), DL,
8596                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8597                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8598                         St->isNonTemporal(),
8599                         std::min(4U, St->getAlignment() / 2));
8600   }
8601
8602   if (StVal.getValueType() != MVT::i64 ||
8603       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8604     return SDValue();
8605
8606   // Bitcast an i64 store extracted from a vector to f64.
8607   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8608   SelectionDAG &DAG = DCI.DAG;
8609   SDLoc dl(StVal);
8610   SDValue IntVec = StVal.getOperand(0);
8611   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8612                                  IntVec.getValueType().getVectorNumElements());
8613   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8614   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8615                                Vec, StVal.getOperand(1));
8616   dl = SDLoc(N);
8617   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8618   // Make the DAGCombiner fold the bitcasts.
8619   DCI.AddToWorklist(Vec.getNode());
8620   DCI.AddToWorklist(ExtElt.getNode());
8621   DCI.AddToWorklist(V.getNode());
8622   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8623                       St->getPointerInfo(), St->isVolatile(),
8624                       St->isNonTemporal(), St->getAlignment(),
8625                       St->getAAInfo());
8626 }
8627
8628 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8629 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8630 /// i64 vector to have f64 elements, since the value can then be loaded
8631 /// directly into a VFP register.
8632 static bool hasNormalLoadOperand(SDNode *N) {
8633   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8634   for (unsigned i = 0; i < NumElts; ++i) {
8635     SDNode *Elt = N->getOperand(i).getNode();
8636     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8637       return true;
8638   }
8639   return false;
8640 }
8641
8642 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8643 /// ISD::BUILD_VECTOR.
8644 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8645                                           TargetLowering::DAGCombinerInfo &DCI){
8646   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8647   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8648   // into a pair of GPRs, which is fine when the value is used as a scalar,
8649   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8650   SelectionDAG &DAG = DCI.DAG;
8651   if (N->getNumOperands() == 2) {
8652     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8653     if (RV.getNode())
8654       return RV;
8655   }
8656
8657   // Load i64 elements as f64 values so that type legalization does not split
8658   // them up into i32 values.
8659   EVT VT = N->getValueType(0);
8660   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8661     return SDValue();
8662   SDLoc dl(N);
8663   SmallVector<SDValue, 8> Ops;
8664   unsigned NumElts = VT.getVectorNumElements();
8665   for (unsigned i = 0; i < NumElts; ++i) {
8666     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8667     Ops.push_back(V);
8668     // Make the DAGCombiner fold the bitcast.
8669     DCI.AddToWorklist(V.getNode());
8670   }
8671   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8672   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8673   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8674 }
8675
8676 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8677 static SDValue
8678 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8679   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8680   // At that time, we may have inserted bitcasts from integer to float.
8681   // If these bitcasts have survived DAGCombine, change the lowering of this
8682   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8683   // force to use floating point types.
8684
8685   // Make sure we can change the type of the vector.
8686   // This is possible iff:
8687   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8688   //    1.1. Vector is used only once.
8689   //    1.2. Use is a bit convert to an integer type.
8690   // 2. The size of its operands are 32-bits (64-bits are not legal).
8691   EVT VT = N->getValueType(0);
8692   EVT EltVT = VT.getVectorElementType();
8693
8694   // Check 1.1. and 2.
8695   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8696     return SDValue();
8697
8698   // By construction, the input type must be float.
8699   assert(EltVT == MVT::f32 && "Unexpected type!");
8700
8701   // Check 1.2.
8702   SDNode *Use = *N->use_begin();
8703   if (Use->getOpcode() != ISD::BITCAST ||
8704       Use->getValueType(0).isFloatingPoint())
8705     return SDValue();
8706
8707   // Check profitability.
8708   // Model is, if more than half of the relevant operands are bitcast from
8709   // i32, turn the build_vector into a sequence of insert_vector_elt.
8710   // Relevant operands are everything that is not statically
8711   // (i.e., at compile time) bitcasted.
8712   unsigned NumOfBitCastedElts = 0;
8713   unsigned NumElts = VT.getVectorNumElements();
8714   unsigned NumOfRelevantElts = NumElts;
8715   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8716     SDValue Elt = N->getOperand(Idx);
8717     if (Elt->getOpcode() == ISD::BITCAST) {
8718       // Assume only bit cast to i32 will go away.
8719       if (Elt->getOperand(0).getValueType() == MVT::i32)
8720         ++NumOfBitCastedElts;
8721     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8722       // Constants are statically casted, thus do not count them as
8723       // relevant operands.
8724       --NumOfRelevantElts;
8725   }
8726
8727   // Check if more than half of the elements require a non-free bitcast.
8728   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8729     return SDValue();
8730
8731   SelectionDAG &DAG = DCI.DAG;
8732   // Create the new vector type.
8733   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8734   // Check if the type is legal.
8735   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8736   if (!TLI.isTypeLegal(VecVT))
8737     return SDValue();
8738
8739   // Combine:
8740   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8741   // => BITCAST INSERT_VECTOR_ELT
8742   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8743   //                      (BITCAST EN), N.
8744   SDValue Vec = DAG.getUNDEF(VecVT);
8745   SDLoc dl(N);
8746   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8747     SDValue V = N->getOperand(Idx);
8748     if (V.getOpcode() == ISD::UNDEF)
8749       continue;
8750     if (V.getOpcode() == ISD::BITCAST &&
8751         V->getOperand(0).getValueType() == MVT::i32)
8752       // Fold obvious case.
8753       V = V.getOperand(0);
8754     else {
8755       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8756       // Make the DAGCombiner fold the bitcasts.
8757       DCI.AddToWorklist(V.getNode());
8758     }
8759     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8760     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8761   }
8762   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8763   // Make the DAGCombiner fold the bitcasts.
8764   DCI.AddToWorklist(Vec.getNode());
8765   return Vec;
8766 }
8767
8768 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8769 /// ISD::INSERT_VECTOR_ELT.
8770 static SDValue PerformInsertEltCombine(SDNode *N,
8771                                        TargetLowering::DAGCombinerInfo &DCI) {
8772   // Bitcast an i64 load inserted into a vector to f64.
8773   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8774   EVT VT = N->getValueType(0);
8775   SDNode *Elt = N->getOperand(1).getNode();
8776   if (VT.getVectorElementType() != MVT::i64 ||
8777       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8778     return SDValue();
8779
8780   SelectionDAG &DAG = DCI.DAG;
8781   SDLoc dl(N);
8782   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8783                                  VT.getVectorNumElements());
8784   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8785   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8786   // Make the DAGCombiner fold the bitcasts.
8787   DCI.AddToWorklist(Vec.getNode());
8788   DCI.AddToWorklist(V.getNode());
8789   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8790                                Vec, V, N->getOperand(2));
8791   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8792 }
8793
8794 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8795 /// ISD::VECTOR_SHUFFLE.
8796 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8797   // The LLVM shufflevector instruction does not require the shuffle mask
8798   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8799   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8800   // operands do not match the mask length, they are extended by concatenating
8801   // them with undef vectors.  That is probably the right thing for other
8802   // targets, but for NEON it is better to concatenate two double-register
8803   // size vector operands into a single quad-register size vector.  Do that
8804   // transformation here:
8805   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8806   //   shuffle(concat(v1, v2), undef)
8807   SDValue Op0 = N->getOperand(0);
8808   SDValue Op1 = N->getOperand(1);
8809   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8810       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8811       Op0.getNumOperands() != 2 ||
8812       Op1.getNumOperands() != 2)
8813     return SDValue();
8814   SDValue Concat0Op1 = Op0.getOperand(1);
8815   SDValue Concat1Op1 = Op1.getOperand(1);
8816   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8817       Concat1Op1.getOpcode() != ISD::UNDEF)
8818     return SDValue();
8819   // Skip the transformation if any of the types are illegal.
8820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8821   EVT VT = N->getValueType(0);
8822   if (!TLI.isTypeLegal(VT) ||
8823       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8824       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8825     return SDValue();
8826
8827   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8828                                   Op0.getOperand(0), Op1.getOperand(0));
8829   // Translate the shuffle mask.
8830   SmallVector<int, 16> NewMask;
8831   unsigned NumElts = VT.getVectorNumElements();
8832   unsigned HalfElts = NumElts/2;
8833   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8834   for (unsigned n = 0; n < NumElts; ++n) {
8835     int MaskElt = SVN->getMaskElt(n);
8836     int NewElt = -1;
8837     if (MaskElt < (int)HalfElts)
8838       NewElt = MaskElt;
8839     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8840       NewElt = HalfElts + MaskElt - NumElts;
8841     NewMask.push_back(NewElt);
8842   }
8843   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8844                               DAG.getUNDEF(VT), NewMask.data());
8845 }
8846
8847 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8848 /// NEON load/store intrinsics to merge base address updates.
8849 static SDValue CombineBaseUpdate(SDNode *N,
8850                                  TargetLowering::DAGCombinerInfo &DCI) {
8851   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8852     return SDValue();
8853
8854   SelectionDAG &DAG = DCI.DAG;
8855   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8856                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8857   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8858   SDValue Addr = N->getOperand(AddrOpIdx);
8859
8860   // Search for a use of the address operand that is an increment.
8861   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8862          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8863     SDNode *User = *UI;
8864     if (User->getOpcode() != ISD::ADD ||
8865         UI.getUse().getResNo() != Addr.getResNo())
8866       continue;
8867
8868     // Check that the add is independent of the load/store.  Otherwise, folding
8869     // it would create a cycle.
8870     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8871       continue;
8872
8873     // Find the new opcode for the updating load/store.
8874     bool isLoad = true;
8875     bool isLaneOp = false;
8876     unsigned NewOpc = 0;
8877     unsigned NumVecs = 0;
8878     if (isIntrinsic) {
8879       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8880       switch (IntNo) {
8881       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8882       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8883         NumVecs = 1; break;
8884       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8885         NumVecs = 2; break;
8886       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8887         NumVecs = 3; break;
8888       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8889         NumVecs = 4; break;
8890       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8891         NumVecs = 2; isLaneOp = true; break;
8892       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8893         NumVecs = 3; isLaneOp = true; break;
8894       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8895         NumVecs = 4; isLaneOp = true; break;
8896       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8897         NumVecs = 1; isLoad = false; break;
8898       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8899         NumVecs = 2; isLoad = false; break;
8900       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8901         NumVecs = 3; isLoad = false; break;
8902       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8903         NumVecs = 4; isLoad = false; break;
8904       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8905         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8906       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8907         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8908       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8909         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8910       }
8911     } else {
8912       isLaneOp = true;
8913       switch (N->getOpcode()) {
8914       default: llvm_unreachable("unexpected opcode for Neon base update");
8915       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8916       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8917       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8918       }
8919     }
8920
8921     // Find the size of memory referenced by the load/store.
8922     EVT VecTy;
8923     if (isLoad)
8924       VecTy = N->getValueType(0);
8925     else
8926       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8927     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8928     if (isLaneOp)
8929       NumBytes /= VecTy.getVectorNumElements();
8930
8931     // If the increment is a constant, it must match the memory ref size.
8932     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8933     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8934       uint64_t IncVal = CInc->getZExtValue();
8935       if (IncVal != NumBytes)
8936         continue;
8937     } else if (NumBytes >= 3 * 16) {
8938       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8939       // separate instructions that make it harder to use a non-constant update.
8940       continue;
8941     }
8942
8943     // Create the new updating load/store node.
8944     EVT Tys[6];
8945     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8946     unsigned n;
8947     for (n = 0; n < NumResultVecs; ++n)
8948       Tys[n] = VecTy;
8949     Tys[n++] = MVT::i32;
8950     Tys[n] = MVT::Other;
8951     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8952     SmallVector<SDValue, 8> Ops;
8953     Ops.push_back(N->getOperand(0)); // incoming chain
8954     Ops.push_back(N->getOperand(AddrOpIdx));
8955     Ops.push_back(Inc);
8956     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8957       Ops.push_back(N->getOperand(i));
8958     }
8959     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8960     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8961                                            Ops, MemInt->getMemoryVT(),
8962                                            MemInt->getMemOperand());
8963
8964     // Update the uses.
8965     std::vector<SDValue> NewResults;
8966     for (unsigned i = 0; i < NumResultVecs; ++i) {
8967       NewResults.push_back(SDValue(UpdN.getNode(), i));
8968     }
8969     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8970     DCI.CombineTo(N, NewResults);
8971     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8972
8973     break;
8974   }
8975   return SDValue();
8976 }
8977
8978 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8979 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8980 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8981 /// return true.
8982 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8983   SelectionDAG &DAG = DCI.DAG;
8984   EVT VT = N->getValueType(0);
8985   // vldN-dup instructions only support 64-bit vectors for N > 1.
8986   if (!VT.is64BitVector())
8987     return false;
8988
8989   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8990   SDNode *VLD = N->getOperand(0).getNode();
8991   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8992     return false;
8993   unsigned NumVecs = 0;
8994   unsigned NewOpc = 0;
8995   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8996   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8997     NumVecs = 2;
8998     NewOpc = ARMISD::VLD2DUP;
8999   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9000     NumVecs = 3;
9001     NewOpc = ARMISD::VLD3DUP;
9002   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9003     NumVecs = 4;
9004     NewOpc = ARMISD::VLD4DUP;
9005   } else {
9006     return false;
9007   }
9008
9009   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9010   // numbers match the load.
9011   unsigned VLDLaneNo =
9012     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9013   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9014        UI != UE; ++UI) {
9015     // Ignore uses of the chain result.
9016     if (UI.getUse().getResNo() == NumVecs)
9017       continue;
9018     SDNode *User = *UI;
9019     if (User->getOpcode() != ARMISD::VDUPLANE ||
9020         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9021       return false;
9022   }
9023
9024   // Create the vldN-dup node.
9025   EVT Tys[5];
9026   unsigned n;
9027   for (n = 0; n < NumVecs; ++n)
9028     Tys[n] = VT;
9029   Tys[n] = MVT::Other;
9030   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9031   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9032   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9033   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9034                                            Ops, VLDMemInt->getMemoryVT(),
9035                                            VLDMemInt->getMemOperand());
9036
9037   // Update the uses.
9038   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9039        UI != UE; ++UI) {
9040     unsigned ResNo = UI.getUse().getResNo();
9041     // Ignore uses of the chain result.
9042     if (ResNo == NumVecs)
9043       continue;
9044     SDNode *User = *UI;
9045     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9046   }
9047
9048   // Now the vldN-lane intrinsic is dead except for its chain result.
9049   // Update uses of the chain.
9050   std::vector<SDValue> VLDDupResults;
9051   for (unsigned n = 0; n < NumVecs; ++n)
9052     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9053   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9054   DCI.CombineTo(VLD, VLDDupResults);
9055
9056   return true;
9057 }
9058
9059 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9060 /// ARMISD::VDUPLANE.
9061 static SDValue PerformVDUPLANECombine(SDNode *N,
9062                                       TargetLowering::DAGCombinerInfo &DCI) {
9063   SDValue Op = N->getOperand(0);
9064
9065   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9066   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9067   if (CombineVLDDUP(N, DCI))
9068     return SDValue(N, 0);
9069
9070   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9071   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9072   while (Op.getOpcode() == ISD::BITCAST)
9073     Op = Op.getOperand(0);
9074   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9075     return SDValue();
9076
9077   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9078   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9079   // The canonical VMOV for a zero vector uses a 32-bit element size.
9080   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9081   unsigned EltBits;
9082   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9083     EltSize = 8;
9084   EVT VT = N->getValueType(0);
9085   if (EltSize > VT.getVectorElementType().getSizeInBits())
9086     return SDValue();
9087
9088   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9089 }
9090
9091 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9092 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9093 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9094 {
9095   integerPart cN;
9096   integerPart c0 = 0;
9097   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9098        I != E; I++) {
9099     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9100     if (!C)
9101       return false;
9102
9103     bool isExact;
9104     APFloat APF = C->getValueAPF();
9105     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9106         != APFloat::opOK || !isExact)
9107       return false;
9108
9109     c0 = (I == 0) ? cN : c0;
9110     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9111       return false;
9112   }
9113   C = c0;
9114   return true;
9115 }
9116
9117 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9118 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9119 /// when the VMUL has a constant operand that is a power of 2.
9120 ///
9121 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9122 ///  vmul.f32        d16, d17, d16
9123 ///  vcvt.s32.f32    d16, d16
9124 /// becomes:
9125 ///  vcvt.s32.f32    d16, d16, #3
9126 static SDValue PerformVCVTCombine(SDNode *N,
9127                                   TargetLowering::DAGCombinerInfo &DCI,
9128                                   const ARMSubtarget *Subtarget) {
9129   SelectionDAG &DAG = DCI.DAG;
9130   SDValue Op = N->getOperand(0);
9131
9132   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9133       Op.getOpcode() != ISD::FMUL)
9134     return SDValue();
9135
9136   uint64_t C;
9137   SDValue N0 = Op->getOperand(0);
9138   SDValue ConstVec = Op->getOperand(1);
9139   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9140
9141   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9142       !isConstVecPow2(ConstVec, isSigned, C))
9143     return SDValue();
9144
9145   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9146   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9147   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9148     // These instructions only exist converting from f32 to i32. We can handle
9149     // smaller integers by generating an extra truncate, but larger ones would
9150     // be lossy.
9151     return SDValue();
9152   }
9153
9154   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9155     Intrinsic::arm_neon_vcvtfp2fxu;
9156   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9157   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9158                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9159                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9160                                  DAG.getConstant(Log2_64(C), MVT::i32));
9161
9162   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9163     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9164
9165   return FixConv;
9166 }
9167
9168 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9169 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9170 /// when the VDIV has a constant operand that is a power of 2.
9171 ///
9172 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9173 ///  vcvt.f32.s32    d16, d16
9174 ///  vdiv.f32        d16, d17, d16
9175 /// becomes:
9176 ///  vcvt.f32.s32    d16, d16, #3
9177 static SDValue PerformVDIVCombine(SDNode *N,
9178                                   TargetLowering::DAGCombinerInfo &DCI,
9179                                   const ARMSubtarget *Subtarget) {
9180   SelectionDAG &DAG = DCI.DAG;
9181   SDValue Op = N->getOperand(0);
9182   unsigned OpOpcode = Op.getNode()->getOpcode();
9183
9184   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9185       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9186     return SDValue();
9187
9188   uint64_t C;
9189   SDValue ConstVec = N->getOperand(1);
9190   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9191
9192   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9193       !isConstVecPow2(ConstVec, isSigned, C))
9194     return SDValue();
9195
9196   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9197   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9198   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9199     // These instructions only exist converting from i32 to f32. We can handle
9200     // smaller integers by generating an extra extend, but larger ones would
9201     // be lossy.
9202     return SDValue();
9203   }
9204
9205   SDValue ConvInput = Op.getOperand(0);
9206   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9207   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9208     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9209                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9210                             ConvInput);
9211
9212   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9213     Intrinsic::arm_neon_vcvtfxu2fp;
9214   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9215                      Op.getValueType(),
9216                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9217                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9218 }
9219
9220 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9221 /// operand of a vector shift operation, where all the elements of the
9222 /// build_vector must have the same constant integer value.
9223 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9224   // Ignore bit_converts.
9225   while (Op.getOpcode() == ISD::BITCAST)
9226     Op = Op.getOperand(0);
9227   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9228   APInt SplatBits, SplatUndef;
9229   unsigned SplatBitSize;
9230   bool HasAnyUndefs;
9231   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9232                                       HasAnyUndefs, ElementBits) ||
9233       SplatBitSize > ElementBits)
9234     return false;
9235   Cnt = SplatBits.getSExtValue();
9236   return true;
9237 }
9238
9239 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9240 /// operand of a vector shift left operation.  That value must be in the range:
9241 ///   0 <= Value < ElementBits for a left shift; or
9242 ///   0 <= Value <= ElementBits for a long left shift.
9243 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9244   assert(VT.isVector() && "vector shift count is not a vector type");
9245   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9246   if (! getVShiftImm(Op, ElementBits, Cnt))
9247     return false;
9248   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9249 }
9250
9251 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9252 /// operand of a vector shift right operation.  For a shift opcode, the value
9253 /// is positive, but for an intrinsic the value count must be negative. The
9254 /// absolute value must be in the range:
9255 ///   1 <= |Value| <= ElementBits for a right shift; or
9256 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9257 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9258                          int64_t &Cnt) {
9259   assert(VT.isVector() && "vector shift count is not a vector type");
9260   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9261   if (! getVShiftImm(Op, ElementBits, Cnt))
9262     return false;
9263   if (isIntrinsic)
9264     Cnt = -Cnt;
9265   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9266 }
9267
9268 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9269 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9270   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9271   switch (IntNo) {
9272   default:
9273     // Don't do anything for most intrinsics.
9274     break;
9275
9276   // Vector shifts: check for immediate versions and lower them.
9277   // Note: This is done during DAG combining instead of DAG legalizing because
9278   // the build_vectors for 64-bit vector element shift counts are generally
9279   // not legal, and it is hard to see their values after they get legalized to
9280   // loads from a constant pool.
9281   case Intrinsic::arm_neon_vshifts:
9282   case Intrinsic::arm_neon_vshiftu:
9283   case Intrinsic::arm_neon_vrshifts:
9284   case Intrinsic::arm_neon_vrshiftu:
9285   case Intrinsic::arm_neon_vrshiftn:
9286   case Intrinsic::arm_neon_vqshifts:
9287   case Intrinsic::arm_neon_vqshiftu:
9288   case Intrinsic::arm_neon_vqshiftsu:
9289   case Intrinsic::arm_neon_vqshiftns:
9290   case Intrinsic::arm_neon_vqshiftnu:
9291   case Intrinsic::arm_neon_vqshiftnsu:
9292   case Intrinsic::arm_neon_vqrshiftns:
9293   case Intrinsic::arm_neon_vqrshiftnu:
9294   case Intrinsic::arm_neon_vqrshiftnsu: {
9295     EVT VT = N->getOperand(1).getValueType();
9296     int64_t Cnt;
9297     unsigned VShiftOpc = 0;
9298
9299     switch (IntNo) {
9300     case Intrinsic::arm_neon_vshifts:
9301     case Intrinsic::arm_neon_vshiftu:
9302       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9303         VShiftOpc = ARMISD::VSHL;
9304         break;
9305       }
9306       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9307         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9308                      ARMISD::VSHRs : ARMISD::VSHRu);
9309         break;
9310       }
9311       return SDValue();
9312
9313     case Intrinsic::arm_neon_vrshifts:
9314     case Intrinsic::arm_neon_vrshiftu:
9315       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9316         break;
9317       return SDValue();
9318
9319     case Intrinsic::arm_neon_vqshifts:
9320     case Intrinsic::arm_neon_vqshiftu:
9321       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9322         break;
9323       return SDValue();
9324
9325     case Intrinsic::arm_neon_vqshiftsu:
9326       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9327         break;
9328       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9329
9330     case Intrinsic::arm_neon_vrshiftn:
9331     case Intrinsic::arm_neon_vqshiftns:
9332     case Intrinsic::arm_neon_vqshiftnu:
9333     case Intrinsic::arm_neon_vqshiftnsu:
9334     case Intrinsic::arm_neon_vqrshiftns:
9335     case Intrinsic::arm_neon_vqrshiftnu:
9336     case Intrinsic::arm_neon_vqrshiftnsu:
9337       // Narrowing shifts require an immediate right shift.
9338       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9339         break;
9340       llvm_unreachable("invalid shift count for narrowing vector shift "
9341                        "intrinsic");
9342
9343     default:
9344       llvm_unreachable("unhandled vector shift");
9345     }
9346
9347     switch (IntNo) {
9348     case Intrinsic::arm_neon_vshifts:
9349     case Intrinsic::arm_neon_vshiftu:
9350       // Opcode already set above.
9351       break;
9352     case Intrinsic::arm_neon_vrshifts:
9353       VShiftOpc = ARMISD::VRSHRs; break;
9354     case Intrinsic::arm_neon_vrshiftu:
9355       VShiftOpc = ARMISD::VRSHRu; break;
9356     case Intrinsic::arm_neon_vrshiftn:
9357       VShiftOpc = ARMISD::VRSHRN; break;
9358     case Intrinsic::arm_neon_vqshifts:
9359       VShiftOpc = ARMISD::VQSHLs; break;
9360     case Intrinsic::arm_neon_vqshiftu:
9361       VShiftOpc = ARMISD::VQSHLu; break;
9362     case Intrinsic::arm_neon_vqshiftsu:
9363       VShiftOpc = ARMISD::VQSHLsu; break;
9364     case Intrinsic::arm_neon_vqshiftns:
9365       VShiftOpc = ARMISD::VQSHRNs; break;
9366     case Intrinsic::arm_neon_vqshiftnu:
9367       VShiftOpc = ARMISD::VQSHRNu; break;
9368     case Intrinsic::arm_neon_vqshiftnsu:
9369       VShiftOpc = ARMISD::VQSHRNsu; break;
9370     case Intrinsic::arm_neon_vqrshiftns:
9371       VShiftOpc = ARMISD::VQRSHRNs; break;
9372     case Intrinsic::arm_neon_vqrshiftnu:
9373       VShiftOpc = ARMISD::VQRSHRNu; break;
9374     case Intrinsic::arm_neon_vqrshiftnsu:
9375       VShiftOpc = ARMISD::VQRSHRNsu; break;
9376     }
9377
9378     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9379                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9380   }
9381
9382   case Intrinsic::arm_neon_vshiftins: {
9383     EVT VT = N->getOperand(1).getValueType();
9384     int64_t Cnt;
9385     unsigned VShiftOpc = 0;
9386
9387     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9388       VShiftOpc = ARMISD::VSLI;
9389     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9390       VShiftOpc = ARMISD::VSRI;
9391     else {
9392       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9393     }
9394
9395     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9396                        N->getOperand(1), N->getOperand(2),
9397                        DAG.getConstant(Cnt, MVT::i32));
9398   }
9399
9400   case Intrinsic::arm_neon_vqrshifts:
9401   case Intrinsic::arm_neon_vqrshiftu:
9402     // No immediate versions of these to check for.
9403     break;
9404   }
9405
9406   return SDValue();
9407 }
9408
9409 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9410 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9411 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9412 /// vector element shift counts are generally not legal, and it is hard to see
9413 /// their values after they get legalized to loads from a constant pool.
9414 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9415                                    const ARMSubtarget *ST) {
9416   EVT VT = N->getValueType(0);
9417   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9418     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9419     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9420     SDValue N1 = N->getOperand(1);
9421     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9422       SDValue N0 = N->getOperand(0);
9423       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9424           DAG.MaskedValueIsZero(N0.getOperand(0),
9425                                 APInt::getHighBitsSet(32, 16)))
9426         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9427     }
9428   }
9429
9430   // Nothing to be done for scalar shifts.
9431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9432   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9433     return SDValue();
9434
9435   assert(ST->hasNEON() && "unexpected vector shift");
9436   int64_t Cnt;
9437
9438   switch (N->getOpcode()) {
9439   default: llvm_unreachable("unexpected shift opcode");
9440
9441   case ISD::SHL:
9442     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9443       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9444                          DAG.getConstant(Cnt, MVT::i32));
9445     break;
9446
9447   case ISD::SRA:
9448   case ISD::SRL:
9449     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9450       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9451                             ARMISD::VSHRs : ARMISD::VSHRu);
9452       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9453                          DAG.getConstant(Cnt, MVT::i32));
9454     }
9455   }
9456   return SDValue();
9457 }
9458
9459 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9460 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9461 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9462                                     const ARMSubtarget *ST) {
9463   SDValue N0 = N->getOperand(0);
9464
9465   // Check for sign- and zero-extensions of vector extract operations of 8-
9466   // and 16-bit vector elements.  NEON supports these directly.  They are
9467   // handled during DAG combining because type legalization will promote them
9468   // to 32-bit types and it is messy to recognize the operations after that.
9469   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9470     SDValue Vec = N0.getOperand(0);
9471     SDValue Lane = N0.getOperand(1);
9472     EVT VT = N->getValueType(0);
9473     EVT EltVT = N0.getValueType();
9474     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9475
9476     if (VT == MVT::i32 &&
9477         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9478         TLI.isTypeLegal(Vec.getValueType()) &&
9479         isa<ConstantSDNode>(Lane)) {
9480
9481       unsigned Opc = 0;
9482       switch (N->getOpcode()) {
9483       default: llvm_unreachable("unexpected opcode");
9484       case ISD::SIGN_EXTEND:
9485         Opc = ARMISD::VGETLANEs;
9486         break;
9487       case ISD::ZERO_EXTEND:
9488       case ISD::ANY_EXTEND:
9489         Opc = ARMISD::VGETLANEu;
9490         break;
9491       }
9492       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9493     }
9494   }
9495
9496   return SDValue();
9497 }
9498
9499 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9500 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9501 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9502                                        const ARMSubtarget *ST) {
9503   // If the target supports NEON, try to use vmax/vmin instructions for f32
9504   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9505   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9506   // a NaN; only do the transformation when it matches that behavior.
9507
9508   // For now only do this when using NEON for FP operations; if using VFP, it
9509   // is not obvious that the benefit outweighs the cost of switching to the
9510   // NEON pipeline.
9511   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9512       N->getValueType(0) != MVT::f32)
9513     return SDValue();
9514
9515   SDValue CondLHS = N->getOperand(0);
9516   SDValue CondRHS = N->getOperand(1);
9517   SDValue LHS = N->getOperand(2);
9518   SDValue RHS = N->getOperand(3);
9519   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9520
9521   unsigned Opcode = 0;
9522   bool IsReversed;
9523   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9524     IsReversed = false; // x CC y ? x : y
9525   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9526     IsReversed = true ; // x CC y ? y : x
9527   } else {
9528     return SDValue();
9529   }
9530
9531   bool IsUnordered;
9532   switch (CC) {
9533   default: break;
9534   case ISD::SETOLT:
9535   case ISD::SETOLE:
9536   case ISD::SETLT:
9537   case ISD::SETLE:
9538   case ISD::SETULT:
9539   case ISD::SETULE:
9540     // If LHS is NaN, an ordered comparison will be false and the result will
9541     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9542     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9543     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9544     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9545       break;
9546     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9547     // will return -0, so vmin can only be used for unsafe math or if one of
9548     // the operands is known to be nonzero.
9549     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9550         !DAG.getTarget().Options.UnsafeFPMath &&
9551         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9552       break;
9553     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9554     break;
9555
9556   case ISD::SETOGT:
9557   case ISD::SETOGE:
9558   case ISD::SETGT:
9559   case ISD::SETGE:
9560   case ISD::SETUGT:
9561   case ISD::SETUGE:
9562     // If LHS is NaN, an ordered comparison will be false and the result will
9563     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9564     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9565     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9566     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9567       break;
9568     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9569     // will return +0, so vmax can only be used for unsafe math or if one of
9570     // the operands is known to be nonzero.
9571     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9572         !DAG.getTarget().Options.UnsafeFPMath &&
9573         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9574       break;
9575     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9576     break;
9577   }
9578
9579   if (!Opcode)
9580     return SDValue();
9581   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9582 }
9583
9584 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9585 SDValue
9586 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9587   SDValue Cmp = N->getOperand(4);
9588   if (Cmp.getOpcode() != ARMISD::CMPZ)
9589     // Only looking at EQ and NE cases.
9590     return SDValue();
9591
9592   EVT VT = N->getValueType(0);
9593   SDLoc dl(N);
9594   SDValue LHS = Cmp.getOperand(0);
9595   SDValue RHS = Cmp.getOperand(1);
9596   SDValue FalseVal = N->getOperand(0);
9597   SDValue TrueVal = N->getOperand(1);
9598   SDValue ARMcc = N->getOperand(2);
9599   ARMCC::CondCodes CC =
9600     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9601
9602   // Simplify
9603   //   mov     r1, r0
9604   //   cmp     r1, x
9605   //   mov     r0, y
9606   //   moveq   r0, x
9607   // to
9608   //   cmp     r0, x
9609   //   movne   r0, y
9610   //
9611   //   mov     r1, r0
9612   //   cmp     r1, x
9613   //   mov     r0, x
9614   //   movne   r0, y
9615   // to
9616   //   cmp     r0, x
9617   //   movne   r0, y
9618   /// FIXME: Turn this into a target neutral optimization?
9619   SDValue Res;
9620   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9621     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9622                       N->getOperand(3), Cmp);
9623   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9624     SDValue ARMcc;
9625     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9626     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9627                       N->getOperand(3), NewCmp);
9628   }
9629
9630   if (Res.getNode()) {
9631     APInt KnownZero, KnownOne;
9632     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9633     // Capture demanded bits information that would be otherwise lost.
9634     if (KnownZero == 0xfffffffe)
9635       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9636                         DAG.getValueType(MVT::i1));
9637     else if (KnownZero == 0xffffff00)
9638       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9639                         DAG.getValueType(MVT::i8));
9640     else if (KnownZero == 0xffff0000)
9641       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9642                         DAG.getValueType(MVT::i16));
9643   }
9644
9645   return Res;
9646 }
9647
9648 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9649                                              DAGCombinerInfo &DCI) const {
9650   switch (N->getOpcode()) {
9651   default: break;
9652   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9653   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9654   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9655   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9656   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9657   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9658   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9659   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9660   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9661   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9662   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9663   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9664   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9665   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9666   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9667   case ISD::FP_TO_SINT:
9668   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9669   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9670   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9671   case ISD::SHL:
9672   case ISD::SRA:
9673   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9674   case ISD::SIGN_EXTEND:
9675   case ISD::ZERO_EXTEND:
9676   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9677   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9678   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9679   case ARMISD::VLD2DUP:
9680   case ARMISD::VLD3DUP:
9681   case ARMISD::VLD4DUP:
9682     return CombineBaseUpdate(N, DCI);
9683   case ARMISD::BUILD_VECTOR:
9684     return PerformARMBUILD_VECTORCombine(N, DCI);
9685   case ISD::INTRINSIC_VOID:
9686   case ISD::INTRINSIC_W_CHAIN:
9687     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9688     case Intrinsic::arm_neon_vld1:
9689     case Intrinsic::arm_neon_vld2:
9690     case Intrinsic::arm_neon_vld3:
9691     case Intrinsic::arm_neon_vld4:
9692     case Intrinsic::arm_neon_vld2lane:
9693     case Intrinsic::arm_neon_vld3lane:
9694     case Intrinsic::arm_neon_vld4lane:
9695     case Intrinsic::arm_neon_vst1:
9696     case Intrinsic::arm_neon_vst2:
9697     case Intrinsic::arm_neon_vst3:
9698     case Intrinsic::arm_neon_vst4:
9699     case Intrinsic::arm_neon_vst2lane:
9700     case Intrinsic::arm_neon_vst3lane:
9701     case Intrinsic::arm_neon_vst4lane:
9702       return CombineBaseUpdate(N, DCI);
9703     default: break;
9704     }
9705     break;
9706   }
9707   return SDValue();
9708 }
9709
9710 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9711                                                           EVT VT) const {
9712   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9713 }
9714
9715 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9716                                                        unsigned,
9717                                                        unsigned,
9718                                                        bool *Fast) const {
9719   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9720   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9721
9722   switch (VT.getSimpleVT().SimpleTy) {
9723   default:
9724     return false;
9725   case MVT::i8:
9726   case MVT::i16:
9727   case MVT::i32: {
9728     // Unaligned access can use (for example) LRDB, LRDH, LDR
9729     if (AllowsUnaligned) {
9730       if (Fast)
9731         *Fast = Subtarget->hasV7Ops();
9732       return true;
9733     }
9734     return false;
9735   }
9736   case MVT::f64:
9737   case MVT::v2f64: {
9738     // For any little-endian targets with neon, we can support unaligned ld/st
9739     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9740     // A big-endian target may also explicitly support unaligned accesses
9741     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9742       if (Fast)
9743         *Fast = true;
9744       return true;
9745     }
9746     return false;
9747   }
9748   }
9749 }
9750
9751 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9752                        unsigned AlignCheck) {
9753   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9754           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9755 }
9756
9757 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9758                                            unsigned DstAlign, unsigned SrcAlign,
9759                                            bool IsMemset, bool ZeroMemset,
9760                                            bool MemcpyStrSrc,
9761                                            MachineFunction &MF) const {
9762   const Function *F = MF.getFunction();
9763
9764   // See if we can use NEON instructions for this...
9765   if ((!IsMemset || ZeroMemset) &&
9766       Subtarget->hasNEON() &&
9767       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9768                                        Attribute::NoImplicitFloat)) {
9769     bool Fast;
9770     if (Size >= 16 &&
9771         (memOpAlign(SrcAlign, DstAlign, 16) ||
9772          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9773       return MVT::v2f64;
9774     } else if (Size >= 8 &&
9775                (memOpAlign(SrcAlign, DstAlign, 8) ||
9776                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9777                  Fast))) {
9778       return MVT::f64;
9779     }
9780   }
9781
9782   // Lowering to i32/i16 if the size permits.
9783   if (Size >= 4)
9784     return MVT::i32;
9785   else if (Size >= 2)
9786     return MVT::i16;
9787
9788   // Let the target-independent logic figure it out.
9789   return MVT::Other;
9790 }
9791
9792 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9793   if (Val.getOpcode() != ISD::LOAD)
9794     return false;
9795
9796   EVT VT1 = Val.getValueType();
9797   if (!VT1.isSimple() || !VT1.isInteger() ||
9798       !VT2.isSimple() || !VT2.isInteger())
9799     return false;
9800
9801   switch (VT1.getSimpleVT().SimpleTy) {
9802   default: break;
9803   case MVT::i1:
9804   case MVT::i8:
9805   case MVT::i16:
9806     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9807     return true;
9808   }
9809
9810   return false;
9811 }
9812
9813 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9814   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9815     return false;
9816
9817   if (!isTypeLegal(EVT::getEVT(Ty1)))
9818     return false;
9819
9820   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9821
9822   // Assuming the caller doesn't have a zeroext or signext return parameter,
9823   // truncation all the way down to i1 is valid.
9824   return true;
9825 }
9826
9827
9828 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9829   if (V < 0)
9830     return false;
9831
9832   unsigned Scale = 1;
9833   switch (VT.getSimpleVT().SimpleTy) {
9834   default: return false;
9835   case MVT::i1:
9836   case MVT::i8:
9837     // Scale == 1;
9838     break;
9839   case MVT::i16:
9840     // Scale == 2;
9841     Scale = 2;
9842     break;
9843   case MVT::i32:
9844     // Scale == 4;
9845     Scale = 4;
9846     break;
9847   }
9848
9849   if ((V & (Scale - 1)) != 0)
9850     return false;
9851   V /= Scale;
9852   return V == (V & ((1LL << 5) - 1));
9853 }
9854
9855 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9856                                       const ARMSubtarget *Subtarget) {
9857   bool isNeg = false;
9858   if (V < 0) {
9859     isNeg = true;
9860     V = - V;
9861   }
9862
9863   switch (VT.getSimpleVT().SimpleTy) {
9864   default: return false;
9865   case MVT::i1:
9866   case MVT::i8:
9867   case MVT::i16:
9868   case MVT::i32:
9869     // + imm12 or - imm8
9870     if (isNeg)
9871       return V == (V & ((1LL << 8) - 1));
9872     return V == (V & ((1LL << 12) - 1));
9873   case MVT::f32:
9874   case MVT::f64:
9875     // Same as ARM mode. FIXME: NEON?
9876     if (!Subtarget->hasVFP2())
9877       return false;
9878     if ((V & 3) != 0)
9879       return false;
9880     V >>= 2;
9881     return V == (V & ((1LL << 8) - 1));
9882   }
9883 }
9884
9885 /// isLegalAddressImmediate - Return true if the integer value can be used
9886 /// as the offset of the target addressing mode for load / store of the
9887 /// given type.
9888 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9889                                     const ARMSubtarget *Subtarget) {
9890   if (V == 0)
9891     return true;
9892
9893   if (!VT.isSimple())
9894     return false;
9895
9896   if (Subtarget->isThumb1Only())
9897     return isLegalT1AddressImmediate(V, VT);
9898   else if (Subtarget->isThumb2())
9899     return isLegalT2AddressImmediate(V, VT, Subtarget);
9900
9901   // ARM mode.
9902   if (V < 0)
9903     V = - V;
9904   switch (VT.getSimpleVT().SimpleTy) {
9905   default: return false;
9906   case MVT::i1:
9907   case MVT::i8:
9908   case MVT::i32:
9909     // +- imm12
9910     return V == (V & ((1LL << 12) - 1));
9911   case MVT::i16:
9912     // +- imm8
9913     return V == (V & ((1LL << 8) - 1));
9914   case MVT::f32:
9915   case MVT::f64:
9916     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9917       return false;
9918     if ((V & 3) != 0)
9919       return false;
9920     V >>= 2;
9921     return V == (V & ((1LL << 8) - 1));
9922   }
9923 }
9924
9925 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9926                                                       EVT VT) const {
9927   int Scale = AM.Scale;
9928   if (Scale < 0)
9929     return false;
9930
9931   switch (VT.getSimpleVT().SimpleTy) {
9932   default: return false;
9933   case MVT::i1:
9934   case MVT::i8:
9935   case MVT::i16:
9936   case MVT::i32:
9937     if (Scale == 1)
9938       return true;
9939     // r + r << imm
9940     Scale = Scale & ~1;
9941     return Scale == 2 || Scale == 4 || Scale == 8;
9942   case MVT::i64:
9943     // r + r
9944     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9945       return true;
9946     return false;
9947   case MVT::isVoid:
9948     // Note, we allow "void" uses (basically, uses that aren't loads or
9949     // stores), because arm allows folding a scale into many arithmetic
9950     // operations.  This should be made more precise and revisited later.
9951
9952     // Allow r << imm, but the imm has to be a multiple of two.
9953     if (Scale & 1) return false;
9954     return isPowerOf2_32(Scale);
9955   }
9956 }
9957
9958 /// isLegalAddressingMode - Return true if the addressing mode represented
9959 /// by AM is legal for this target, for a load/store of the specified type.
9960 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9961                                               Type *Ty) const {
9962   EVT VT = getValueType(Ty, true);
9963   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9964     return false;
9965
9966   // Can never fold addr of global into load/store.
9967   if (AM.BaseGV)
9968     return false;
9969
9970   switch (AM.Scale) {
9971   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9972     break;
9973   case 1:
9974     if (Subtarget->isThumb1Only())
9975       return false;
9976     // FALL THROUGH.
9977   default:
9978     // ARM doesn't support any R+R*scale+imm addr modes.
9979     if (AM.BaseOffs)
9980       return false;
9981
9982     if (!VT.isSimple())
9983       return false;
9984
9985     if (Subtarget->isThumb2())
9986       return isLegalT2ScaledAddressingMode(AM, VT);
9987
9988     int Scale = AM.Scale;
9989     switch (VT.getSimpleVT().SimpleTy) {
9990     default: return false;
9991     case MVT::i1:
9992     case MVT::i8:
9993     case MVT::i32:
9994       if (Scale < 0) Scale = -Scale;
9995       if (Scale == 1)
9996         return true;
9997       // r + r << imm
9998       return isPowerOf2_32(Scale & ~1);
9999     case MVT::i16:
10000     case MVT::i64:
10001       // r + r
10002       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10003         return true;
10004       return false;
10005
10006     case MVT::isVoid:
10007       // Note, we allow "void" uses (basically, uses that aren't loads or
10008       // stores), because arm allows folding a scale into many arithmetic
10009       // operations.  This should be made more precise and revisited later.
10010
10011       // Allow r << imm, but the imm has to be a multiple of two.
10012       if (Scale & 1) return false;
10013       return isPowerOf2_32(Scale);
10014     }
10015   }
10016   return true;
10017 }
10018
10019 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10020 /// icmp immediate, that is the target has icmp instructions which can compare
10021 /// a register against the immediate without having to materialize the
10022 /// immediate into a register.
10023 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10024   // Thumb2 and ARM modes can use cmn for negative immediates.
10025   if (!Subtarget->isThumb())
10026     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10027   if (Subtarget->isThumb2())
10028     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10029   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10030   return Imm >= 0 && Imm <= 255;
10031 }
10032
10033 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10034 /// *or sub* immediate, that is the target has add or sub instructions which can
10035 /// add a register with the immediate without having to materialize the
10036 /// immediate into a register.
10037 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10038   // Same encoding for add/sub, just flip the sign.
10039   int64_t AbsImm = llvm::abs64(Imm);
10040   if (!Subtarget->isThumb())
10041     return ARM_AM::getSOImmVal(AbsImm) != -1;
10042   if (Subtarget->isThumb2())
10043     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10044   // Thumb1 only has 8-bit unsigned immediate.
10045   return AbsImm >= 0 && AbsImm <= 255;
10046 }
10047
10048 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10049                                       bool isSEXTLoad, SDValue &Base,
10050                                       SDValue &Offset, bool &isInc,
10051                                       SelectionDAG &DAG) {
10052   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10053     return false;
10054
10055   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10056     // AddressingMode 3
10057     Base = Ptr->getOperand(0);
10058     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10059       int RHSC = (int)RHS->getZExtValue();
10060       if (RHSC < 0 && RHSC > -256) {
10061         assert(Ptr->getOpcode() == ISD::ADD);
10062         isInc = false;
10063         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10064         return true;
10065       }
10066     }
10067     isInc = (Ptr->getOpcode() == ISD::ADD);
10068     Offset = Ptr->getOperand(1);
10069     return true;
10070   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10071     // AddressingMode 2
10072     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10073       int RHSC = (int)RHS->getZExtValue();
10074       if (RHSC < 0 && RHSC > -0x1000) {
10075         assert(Ptr->getOpcode() == ISD::ADD);
10076         isInc = false;
10077         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10078         Base = Ptr->getOperand(0);
10079         return true;
10080       }
10081     }
10082
10083     if (Ptr->getOpcode() == ISD::ADD) {
10084       isInc = true;
10085       ARM_AM::ShiftOpc ShOpcVal=
10086         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10087       if (ShOpcVal != ARM_AM::no_shift) {
10088         Base = Ptr->getOperand(1);
10089         Offset = Ptr->getOperand(0);
10090       } else {
10091         Base = Ptr->getOperand(0);
10092         Offset = Ptr->getOperand(1);
10093       }
10094       return true;
10095     }
10096
10097     isInc = (Ptr->getOpcode() == ISD::ADD);
10098     Base = Ptr->getOperand(0);
10099     Offset = Ptr->getOperand(1);
10100     return true;
10101   }
10102
10103   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10104   return false;
10105 }
10106
10107 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10108                                      bool isSEXTLoad, SDValue &Base,
10109                                      SDValue &Offset, bool &isInc,
10110                                      SelectionDAG &DAG) {
10111   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10112     return false;
10113
10114   Base = Ptr->getOperand(0);
10115   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10116     int RHSC = (int)RHS->getZExtValue();
10117     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10118       assert(Ptr->getOpcode() == ISD::ADD);
10119       isInc = false;
10120       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10121       return true;
10122     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10123       isInc = Ptr->getOpcode() == ISD::ADD;
10124       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10125       return true;
10126     }
10127   }
10128
10129   return false;
10130 }
10131
10132 /// getPreIndexedAddressParts - returns true by value, base pointer and
10133 /// offset pointer and addressing mode by reference if the node's address
10134 /// can be legally represented as pre-indexed load / store address.
10135 bool
10136 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10137                                              SDValue &Offset,
10138                                              ISD::MemIndexedMode &AM,
10139                                              SelectionDAG &DAG) const {
10140   if (Subtarget->isThumb1Only())
10141     return false;
10142
10143   EVT VT;
10144   SDValue Ptr;
10145   bool isSEXTLoad = false;
10146   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10147     Ptr = LD->getBasePtr();
10148     VT  = LD->getMemoryVT();
10149     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10150   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10151     Ptr = ST->getBasePtr();
10152     VT  = ST->getMemoryVT();
10153   } else
10154     return false;
10155
10156   bool isInc;
10157   bool isLegal = false;
10158   if (Subtarget->isThumb2())
10159     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10160                                        Offset, isInc, DAG);
10161   else
10162     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10163                                         Offset, isInc, DAG);
10164   if (!isLegal)
10165     return false;
10166
10167   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10168   return true;
10169 }
10170
10171 /// getPostIndexedAddressParts - returns true by value, base pointer and
10172 /// offset pointer and addressing mode by reference if this node can be
10173 /// combined with a load / store to form a post-indexed load / store.
10174 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10175                                                    SDValue &Base,
10176                                                    SDValue &Offset,
10177                                                    ISD::MemIndexedMode &AM,
10178                                                    SelectionDAG &DAG) const {
10179   if (Subtarget->isThumb1Only())
10180     return false;
10181
10182   EVT VT;
10183   SDValue Ptr;
10184   bool isSEXTLoad = false;
10185   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10186     VT  = LD->getMemoryVT();
10187     Ptr = LD->getBasePtr();
10188     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10189   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10190     VT  = ST->getMemoryVT();
10191     Ptr = ST->getBasePtr();
10192   } else
10193     return false;
10194
10195   bool isInc;
10196   bool isLegal = false;
10197   if (Subtarget->isThumb2())
10198     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10199                                        isInc, DAG);
10200   else
10201     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10202                                         isInc, DAG);
10203   if (!isLegal)
10204     return false;
10205
10206   if (Ptr != Base) {
10207     // Swap base ptr and offset to catch more post-index load / store when
10208     // it's legal. In Thumb2 mode, offset must be an immediate.
10209     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10210         !Subtarget->isThumb2())
10211       std::swap(Base, Offset);
10212
10213     // Post-indexed load / store update the base pointer.
10214     if (Ptr != Base)
10215       return false;
10216   }
10217
10218   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10219   return true;
10220 }
10221
10222 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10223                                                       APInt &KnownZero,
10224                                                       APInt &KnownOne,
10225                                                       const SelectionDAG &DAG,
10226                                                       unsigned Depth) const {
10227   unsigned BitWidth = KnownOne.getBitWidth();
10228   KnownZero = KnownOne = APInt(BitWidth, 0);
10229   switch (Op.getOpcode()) {
10230   default: break;
10231   case ARMISD::ADDC:
10232   case ARMISD::ADDE:
10233   case ARMISD::SUBC:
10234   case ARMISD::SUBE:
10235     // These nodes' second result is a boolean
10236     if (Op.getResNo() == 0)
10237       break;
10238     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10239     break;
10240   case ARMISD::CMOV: {
10241     // Bits are known zero/one if known on the LHS and RHS.
10242     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10243     if (KnownZero == 0 && KnownOne == 0) return;
10244
10245     APInt KnownZeroRHS, KnownOneRHS;
10246     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10247     KnownZero &= KnownZeroRHS;
10248     KnownOne  &= KnownOneRHS;
10249     return;
10250   }
10251   case ISD::INTRINSIC_W_CHAIN: {
10252     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10253     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10254     switch (IntID) {
10255     default: return;
10256     case Intrinsic::arm_ldaex:
10257     case Intrinsic::arm_ldrex: {
10258       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10259       unsigned MemBits = VT.getScalarType().getSizeInBits();
10260       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10261       return;
10262     }
10263     }
10264   }
10265   }
10266 }
10267
10268 //===----------------------------------------------------------------------===//
10269 //                           ARM Inline Assembly Support
10270 //===----------------------------------------------------------------------===//
10271
10272 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10273   // Looking for "rev" which is V6+.
10274   if (!Subtarget->hasV6Ops())
10275     return false;
10276
10277   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10278   std::string AsmStr = IA->getAsmString();
10279   SmallVector<StringRef, 4> AsmPieces;
10280   SplitString(AsmStr, AsmPieces, ";\n");
10281
10282   switch (AsmPieces.size()) {
10283   default: return false;
10284   case 1:
10285     AsmStr = AsmPieces[0];
10286     AsmPieces.clear();
10287     SplitString(AsmStr, AsmPieces, " \t,");
10288
10289     // rev $0, $1
10290     if (AsmPieces.size() == 3 &&
10291         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10292         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10293       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10294       if (Ty && Ty->getBitWidth() == 32)
10295         return IntrinsicLowering::LowerToByteSwap(CI);
10296     }
10297     break;
10298   }
10299
10300   return false;
10301 }
10302
10303 /// getConstraintType - Given a constraint letter, return the type of
10304 /// constraint it is for this target.
10305 ARMTargetLowering::ConstraintType
10306 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10307   if (Constraint.size() == 1) {
10308     switch (Constraint[0]) {
10309     default:  break;
10310     case 'l': return C_RegisterClass;
10311     case 'w': return C_RegisterClass;
10312     case 'h': return C_RegisterClass;
10313     case 'x': return C_RegisterClass;
10314     case 't': return C_RegisterClass;
10315     case 'j': return C_Other; // Constant for movw.
10316       // An address with a single base register. Due to the way we
10317       // currently handle addresses it is the same as an 'r' memory constraint.
10318     case 'Q': return C_Memory;
10319     }
10320   } else if (Constraint.size() == 2) {
10321     switch (Constraint[0]) {
10322     default: break;
10323     // All 'U+' constraints are addresses.
10324     case 'U': return C_Memory;
10325     }
10326   }
10327   return TargetLowering::getConstraintType(Constraint);
10328 }
10329
10330 /// Examine constraint type and operand type and determine a weight value.
10331 /// This object must already have been set up with the operand type
10332 /// and the current alternative constraint selected.
10333 TargetLowering::ConstraintWeight
10334 ARMTargetLowering::getSingleConstraintMatchWeight(
10335     AsmOperandInfo &info, const char *constraint) const {
10336   ConstraintWeight weight = CW_Invalid;
10337   Value *CallOperandVal = info.CallOperandVal;
10338     // If we don't have a value, we can't do a match,
10339     // but allow it at the lowest weight.
10340   if (!CallOperandVal)
10341     return CW_Default;
10342   Type *type = CallOperandVal->getType();
10343   // Look at the constraint type.
10344   switch (*constraint) {
10345   default:
10346     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10347     break;
10348   case 'l':
10349     if (type->isIntegerTy()) {
10350       if (Subtarget->isThumb())
10351         weight = CW_SpecificReg;
10352       else
10353         weight = CW_Register;
10354     }
10355     break;
10356   case 'w':
10357     if (type->isFloatingPointTy())
10358       weight = CW_Register;
10359     break;
10360   }
10361   return weight;
10362 }
10363
10364 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10365 RCPair
10366 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10367                                                 MVT VT) const {
10368   if (Constraint.size() == 1) {
10369     // GCC ARM Constraint Letters
10370     switch (Constraint[0]) {
10371     case 'l': // Low regs or general regs.
10372       if (Subtarget->isThumb())
10373         return RCPair(0U, &ARM::tGPRRegClass);
10374       return RCPair(0U, &ARM::GPRRegClass);
10375     case 'h': // High regs or no regs.
10376       if (Subtarget->isThumb())
10377         return RCPair(0U, &ARM::hGPRRegClass);
10378       break;
10379     case 'r':
10380       return RCPair(0U, &ARM::GPRRegClass);
10381     case 'w':
10382       if (VT == MVT::Other)
10383         break;
10384       if (VT == MVT::f32)
10385         return RCPair(0U, &ARM::SPRRegClass);
10386       if (VT.getSizeInBits() == 64)
10387         return RCPair(0U, &ARM::DPRRegClass);
10388       if (VT.getSizeInBits() == 128)
10389         return RCPair(0U, &ARM::QPRRegClass);
10390       break;
10391     case 'x':
10392       if (VT == MVT::Other)
10393         break;
10394       if (VT == MVT::f32)
10395         return RCPair(0U, &ARM::SPR_8RegClass);
10396       if (VT.getSizeInBits() == 64)
10397         return RCPair(0U, &ARM::DPR_8RegClass);
10398       if (VT.getSizeInBits() == 128)
10399         return RCPair(0U, &ARM::QPR_8RegClass);
10400       break;
10401     case 't':
10402       if (VT == MVT::f32)
10403         return RCPair(0U, &ARM::SPRRegClass);
10404       break;
10405     }
10406   }
10407   if (StringRef("{cc}").equals_lower(Constraint))
10408     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10409
10410   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10411 }
10412
10413 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10414 /// vector.  If it is invalid, don't add anything to Ops.
10415 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10416                                                      std::string &Constraint,
10417                                                      std::vector<SDValue>&Ops,
10418                                                      SelectionDAG &DAG) const {
10419   SDValue Result;
10420
10421   // Currently only support length 1 constraints.
10422   if (Constraint.length() != 1) return;
10423
10424   char ConstraintLetter = Constraint[0];
10425   switch (ConstraintLetter) {
10426   default: break;
10427   case 'j':
10428   case 'I': case 'J': case 'K': case 'L':
10429   case 'M': case 'N': case 'O':
10430     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10431     if (!C)
10432       return;
10433
10434     int64_t CVal64 = C->getSExtValue();
10435     int CVal = (int) CVal64;
10436     // None of these constraints allow values larger than 32 bits.  Check
10437     // that the value fits in an int.
10438     if (CVal != CVal64)
10439       return;
10440
10441     switch (ConstraintLetter) {
10442       case 'j':
10443         // Constant suitable for movw, must be between 0 and
10444         // 65535.
10445         if (Subtarget->hasV6T2Ops())
10446           if (CVal >= 0 && CVal <= 65535)
10447             break;
10448         return;
10449       case 'I':
10450         if (Subtarget->isThumb1Only()) {
10451           // This must be a constant between 0 and 255, for ADD
10452           // immediates.
10453           if (CVal >= 0 && CVal <= 255)
10454             break;
10455         } else if (Subtarget->isThumb2()) {
10456           // A constant that can be used as an immediate value in a
10457           // data-processing instruction.
10458           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10459             break;
10460         } else {
10461           // A constant that can be used as an immediate value in a
10462           // data-processing instruction.
10463           if (ARM_AM::getSOImmVal(CVal) != -1)
10464             break;
10465         }
10466         return;
10467
10468       case 'J':
10469         if (Subtarget->isThumb()) {  // FIXME thumb2
10470           // This must be a constant between -255 and -1, for negated ADD
10471           // immediates. This can be used in GCC with an "n" modifier that
10472           // prints the negated value, for use with SUB instructions. It is
10473           // not useful otherwise but is implemented for compatibility.
10474           if (CVal >= -255 && CVal <= -1)
10475             break;
10476         } else {
10477           // This must be a constant between -4095 and 4095. It is not clear
10478           // what this constraint is intended for. Implemented for
10479           // compatibility with GCC.
10480           if (CVal >= -4095 && CVal <= 4095)
10481             break;
10482         }
10483         return;
10484
10485       case 'K':
10486         if (Subtarget->isThumb1Only()) {
10487           // A 32-bit value where only one byte has a nonzero value. Exclude
10488           // zero to match GCC. This constraint is used by GCC internally for
10489           // constants that can be loaded with a move/shift combination.
10490           // It is not useful otherwise but is implemented for compatibility.
10491           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10492             break;
10493         } else if (Subtarget->isThumb2()) {
10494           // A constant whose bitwise inverse can be used as an immediate
10495           // value in a data-processing instruction. This can be used in GCC
10496           // with a "B" modifier that prints the inverted value, for use with
10497           // BIC and MVN instructions. It is not useful otherwise but is
10498           // implemented for compatibility.
10499           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10500             break;
10501         } else {
10502           // A constant whose bitwise inverse can be used as an immediate
10503           // value in a data-processing instruction. This can be used in GCC
10504           // with a "B" modifier that prints the inverted value, for use with
10505           // BIC and MVN instructions. It is not useful otherwise but is
10506           // implemented for compatibility.
10507           if (ARM_AM::getSOImmVal(~CVal) != -1)
10508             break;
10509         }
10510         return;
10511
10512       case 'L':
10513         if (Subtarget->isThumb1Only()) {
10514           // This must be a constant between -7 and 7,
10515           // for 3-operand ADD/SUB immediate instructions.
10516           if (CVal >= -7 && CVal < 7)
10517             break;
10518         } else if (Subtarget->isThumb2()) {
10519           // A constant whose negation can be used as an immediate value in a
10520           // data-processing instruction. This can be used in GCC with an "n"
10521           // modifier that prints the negated value, for use with SUB
10522           // instructions. It is not useful otherwise but is implemented for
10523           // compatibility.
10524           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10525             break;
10526         } else {
10527           // A constant whose negation can be used as an immediate value in a
10528           // data-processing instruction. This can be used in GCC with an "n"
10529           // modifier that prints the negated value, for use with SUB
10530           // instructions. It is not useful otherwise but is implemented for
10531           // compatibility.
10532           if (ARM_AM::getSOImmVal(-CVal) != -1)
10533             break;
10534         }
10535         return;
10536
10537       case 'M':
10538         if (Subtarget->isThumb()) { // FIXME thumb2
10539           // This must be a multiple of 4 between 0 and 1020, for
10540           // ADD sp + immediate.
10541           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10542             break;
10543         } else {
10544           // A power of two or a constant between 0 and 32.  This is used in
10545           // GCC for the shift amount on shifted register operands, but it is
10546           // useful in general for any shift amounts.
10547           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10548             break;
10549         }
10550         return;
10551
10552       case 'N':
10553         if (Subtarget->isThumb()) {  // FIXME thumb2
10554           // This must be a constant between 0 and 31, for shift amounts.
10555           if (CVal >= 0 && CVal <= 31)
10556             break;
10557         }
10558         return;
10559
10560       case 'O':
10561         if (Subtarget->isThumb()) {  // FIXME thumb2
10562           // This must be a multiple of 4 between -508 and 508, for
10563           // ADD/SUB sp = sp + immediate.
10564           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10565             break;
10566         }
10567         return;
10568     }
10569     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10570     break;
10571   }
10572
10573   if (Result.getNode()) {
10574     Ops.push_back(Result);
10575     return;
10576   }
10577   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10578 }
10579
10580 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10581   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10582   unsigned Opcode = Op->getOpcode();
10583   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10584       "Invalid opcode for Div/Rem lowering");
10585   bool isSigned = (Opcode == ISD::SDIVREM);
10586   EVT VT = Op->getValueType(0);
10587   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10588
10589   RTLIB::Libcall LC;
10590   switch (VT.getSimpleVT().SimpleTy) {
10591   default: llvm_unreachable("Unexpected request for libcall!");
10592   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10593   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10594   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10595   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10596   }
10597
10598   SDValue InChain = DAG.getEntryNode();
10599
10600   TargetLowering::ArgListTy Args;
10601   TargetLowering::ArgListEntry Entry;
10602   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10603     EVT ArgVT = Op->getOperand(i).getValueType();
10604     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10605     Entry.Node = Op->getOperand(i);
10606     Entry.Ty = ArgTy;
10607     Entry.isSExt = isSigned;
10608     Entry.isZExt = !isSigned;
10609     Args.push_back(Entry);
10610   }
10611
10612   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10613                                          getPointerTy());
10614
10615   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10616
10617   SDLoc dl(Op);
10618   TargetLowering::CallLoweringInfo CLI(DAG);
10619   CLI.setDebugLoc(dl).setChain(InChain)
10620     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10621     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10622
10623   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10624   return CallInfo.first;
10625 }
10626
10627 SDValue
10628 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10629   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10630   SDLoc DL(Op);
10631
10632   // Get the inputs.
10633   SDValue Chain = Op.getOperand(0);
10634   SDValue Size  = Op.getOperand(1);
10635
10636   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10637                               DAG.getConstant(2, MVT::i32));
10638
10639   SDValue Flag;
10640   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10641   Flag = Chain.getValue(1);
10642
10643   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10644   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10645
10646   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10647   Chain = NewSP.getValue(1);
10648
10649   SDValue Ops[2] = { NewSP, Chain };
10650   return DAG.getMergeValues(Ops, DL);
10651 }
10652
10653 bool
10654 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10655   // The ARM target isn't yet aware of offsets.
10656   return false;
10657 }
10658
10659 bool ARM::isBitFieldInvertedMask(unsigned v) {
10660   if (v == 0xffffffff)
10661     return false;
10662
10663   // there can be 1's on either or both "outsides", all the "inside"
10664   // bits must be 0's
10665   unsigned TO = CountTrailingOnes_32(v);
10666   unsigned LO = CountLeadingOnes_32(v);
10667   v = (v >> TO) << TO;
10668   v = (v << LO) >> LO;
10669   return v == 0;
10670 }
10671
10672 /// isFPImmLegal - Returns true if the target can instruction select the
10673 /// specified FP immediate natively. If false, the legalizer will
10674 /// materialize the FP immediate as a load from a constant pool.
10675 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10676   if (!Subtarget->hasVFP3())
10677     return false;
10678   if (VT == MVT::f32)
10679     return ARM_AM::getFP32Imm(Imm) != -1;
10680   if (VT == MVT::f64)
10681     return ARM_AM::getFP64Imm(Imm) != -1;
10682   return false;
10683 }
10684
10685 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10686 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10687 /// specified in the intrinsic calls.
10688 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10689                                            const CallInst &I,
10690                                            unsigned Intrinsic) const {
10691   switch (Intrinsic) {
10692   case Intrinsic::arm_neon_vld1:
10693   case Intrinsic::arm_neon_vld2:
10694   case Intrinsic::arm_neon_vld3:
10695   case Intrinsic::arm_neon_vld4:
10696   case Intrinsic::arm_neon_vld2lane:
10697   case Intrinsic::arm_neon_vld3lane:
10698   case Intrinsic::arm_neon_vld4lane: {
10699     Info.opc = ISD::INTRINSIC_W_CHAIN;
10700     // Conservatively set memVT to the entire set of vectors loaded.
10701     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10702     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10703     Info.ptrVal = I.getArgOperand(0);
10704     Info.offset = 0;
10705     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10706     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10707     Info.vol = false; // volatile loads with NEON intrinsics not supported
10708     Info.readMem = true;
10709     Info.writeMem = false;
10710     return true;
10711   }
10712   case Intrinsic::arm_neon_vst1:
10713   case Intrinsic::arm_neon_vst2:
10714   case Intrinsic::arm_neon_vst3:
10715   case Intrinsic::arm_neon_vst4:
10716   case Intrinsic::arm_neon_vst2lane:
10717   case Intrinsic::arm_neon_vst3lane:
10718   case Intrinsic::arm_neon_vst4lane: {
10719     Info.opc = ISD::INTRINSIC_VOID;
10720     // Conservatively set memVT to the entire set of vectors stored.
10721     unsigned NumElts = 0;
10722     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10723       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10724       if (!ArgTy->isVectorTy())
10725         break;
10726       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10727     }
10728     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10729     Info.ptrVal = I.getArgOperand(0);
10730     Info.offset = 0;
10731     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10732     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10733     Info.vol = false; // volatile stores with NEON intrinsics not supported
10734     Info.readMem = false;
10735     Info.writeMem = true;
10736     return true;
10737   }
10738   case Intrinsic::arm_ldaex:
10739   case Intrinsic::arm_ldrex: {
10740     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10741     Info.opc = ISD::INTRINSIC_W_CHAIN;
10742     Info.memVT = MVT::getVT(PtrTy->getElementType());
10743     Info.ptrVal = I.getArgOperand(0);
10744     Info.offset = 0;
10745     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10746     Info.vol = true;
10747     Info.readMem = true;
10748     Info.writeMem = false;
10749     return true;
10750   }
10751   case Intrinsic::arm_stlex:
10752   case Intrinsic::arm_strex: {
10753     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10754     Info.opc = ISD::INTRINSIC_W_CHAIN;
10755     Info.memVT = MVT::getVT(PtrTy->getElementType());
10756     Info.ptrVal = I.getArgOperand(1);
10757     Info.offset = 0;
10758     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10759     Info.vol = true;
10760     Info.readMem = false;
10761     Info.writeMem = true;
10762     return true;
10763   }
10764   case Intrinsic::arm_stlexd:
10765   case Intrinsic::arm_strexd: {
10766     Info.opc = ISD::INTRINSIC_W_CHAIN;
10767     Info.memVT = MVT::i64;
10768     Info.ptrVal = I.getArgOperand(2);
10769     Info.offset = 0;
10770     Info.align = 8;
10771     Info.vol = true;
10772     Info.readMem = false;
10773     Info.writeMem = true;
10774     return true;
10775   }
10776   case Intrinsic::arm_ldaexd:
10777   case Intrinsic::arm_ldrexd: {
10778     Info.opc = ISD::INTRINSIC_W_CHAIN;
10779     Info.memVT = MVT::i64;
10780     Info.ptrVal = I.getArgOperand(0);
10781     Info.offset = 0;
10782     Info.align = 8;
10783     Info.vol = true;
10784     Info.readMem = true;
10785     Info.writeMem = false;
10786     return true;
10787   }
10788   default:
10789     break;
10790   }
10791
10792   return false;
10793 }
10794
10795 /// \brief Returns true if it is beneficial to convert a load of a constant
10796 /// to just the constant itself.
10797 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10798                                                           Type *Ty) const {
10799   assert(Ty->isIntegerTy());
10800
10801   unsigned Bits = Ty->getPrimitiveSizeInBits();
10802   if (Bits == 0 || Bits > 32)
10803     return false;
10804   return true;
10805 }
10806
10807 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10808   // Loads and stores less than 64-bits are already atomic; ones above that
10809   // are doomed anyway, so defer to the default libcall and blame the OS when
10810   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10811   // anything for those.
10812   bool IsMClass = Subtarget->isMClass();
10813   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10814     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10815     return Size == 64 && !IsMClass;
10816   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10817     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10818   }
10819
10820   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10821   // and up to 64 bits on the non-M profiles
10822   unsigned AtomicLimit = IsMClass ? 32 : 64;
10823   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10824 }
10825
10826 // This has so far only been implemented for MachO.
10827 bool ARMTargetLowering::useLoadStackGuardNode() const {
10828   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10829 }
10830
10831 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10832                                          AtomicOrdering Ord) const {
10833   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10834   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10835   bool IsAcquire =
10836       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10837
10838   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10839   // intrinsic must return {i32, i32} and we have to recombine them into a
10840   // single i64 here.
10841   if (ValTy->getPrimitiveSizeInBits() == 64) {
10842     Intrinsic::ID Int =
10843         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10844     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10845
10846     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10847     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10848
10849     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10850     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10851     if (!Subtarget->isLittle())
10852       std::swap (Lo, Hi);
10853     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10854     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10855     return Builder.CreateOr(
10856         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10857   }
10858
10859   Type *Tys[] = { Addr->getType() };
10860   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10861   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10862
10863   return Builder.CreateTruncOrBitCast(
10864       Builder.CreateCall(Ldrex, Addr),
10865       cast<PointerType>(Addr->getType())->getElementType());
10866 }
10867
10868 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10869                                                Value *Addr,
10870                                                AtomicOrdering Ord) const {
10871   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10872   bool IsRelease =
10873       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10874
10875   // Since the intrinsics must have legal type, the i64 intrinsics take two
10876   // parameters: "i32, i32". We must marshal Val into the appropriate form
10877   // before the call.
10878   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10879     Intrinsic::ID Int =
10880         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10881     Function *Strex = Intrinsic::getDeclaration(M, Int);
10882     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10883
10884     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10885     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10886     if (!Subtarget->isLittle())
10887       std::swap (Lo, Hi);
10888     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10889     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10890   }
10891
10892   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10893   Type *Tys[] = { Addr->getType() };
10894   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10895
10896   return Builder.CreateCall2(
10897       Strex, Builder.CreateZExtOrBitCast(
10898                  Val, Strex->getFunctionType()->getParamType(0)),
10899       Addr);
10900 }
10901
10902 enum HABaseType {
10903   HA_UNKNOWN = 0,
10904   HA_FLOAT,
10905   HA_DOUBLE,
10906   HA_VECT64,
10907   HA_VECT128
10908 };
10909
10910 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10911                                    uint64_t &Members) {
10912   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10913     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10914       uint64_t SubMembers = 0;
10915       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10916         return false;
10917       Members += SubMembers;
10918     }
10919   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10920     uint64_t SubMembers = 0;
10921     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10922       return false;
10923     Members += SubMembers * AT->getNumElements();
10924   } else if (Ty->isFloatTy()) {
10925     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10926       return false;
10927     Members = 1;
10928     Base = HA_FLOAT;
10929   } else if (Ty->isDoubleTy()) {
10930     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10931       return false;
10932     Members = 1;
10933     Base = HA_DOUBLE;
10934   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10935     Members = 1;
10936     switch (Base) {
10937     case HA_FLOAT:
10938     case HA_DOUBLE:
10939       return false;
10940     case HA_VECT64:
10941       return VT->getBitWidth() == 64;
10942     case HA_VECT128:
10943       return VT->getBitWidth() == 128;
10944     case HA_UNKNOWN:
10945       switch (VT->getBitWidth()) {
10946       case 64:
10947         Base = HA_VECT64;
10948         return true;
10949       case 128:
10950         Base = HA_VECT128;
10951         return true;
10952       default:
10953         return false;
10954       }
10955     }
10956   }
10957
10958   return (Members > 0 && Members <= 4);
10959 }
10960
10961 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10962 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10963     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10964   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10965       CallingConv::ARM_AAPCS_VFP)
10966     return false;
10967
10968   HABaseType Base = HA_UNKNOWN;
10969   uint64_t Members = 0;
10970   bool result = isHomogeneousAggregate(Ty, Base, Members);
10971   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10972   return result;
10973 }