dbcd42343174828a4e9cc2e7d522332157ce6dfa
[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                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74                LLVMContext &C, ParmContext PC)
75         : CCState(CC, isVarArg, MF, TM, 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.getRegisterInfo();
170   Itins = TM.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::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316
317       // Integer to floating-point conversions.
318       // RTABI chapter 4.1.2, Table 8
319       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327
328       // Long long helper functions
329       // RTABI chapter 4.2, Table 9
330       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334
335       // Integer division functions
336       // RTABI chapter 4.3.1
337       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345
346       // Memory operations
347       // RTABI chapter 4.3.4
348       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351     };
352
353     for (const auto &LC : LibraryCalls) {
354       setLibcallName(LC.Op, LC.Name);
355       setLibcallCallingConv(LC.Op, LC.CC);
356       if (LC.Cond != ISD::SETCC_INVALID)
357         setCmpLibcallCC(LC.Op, LC.Cond);
358     }
359   }
360
361   if (Subtarget->isTargetWindows()) {
362     static const struct {
363       const RTLIB::Libcall Op;
364       const char * const Name;
365       const CallingConv::ID CC;
366     } LibraryCalls[] = {
367       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
375     };
376
377     for (const auto &LC : LibraryCalls) {
378       setLibcallName(LC.Op, LC.Name);
379       setLibcallCallingConv(LC.Op, LC.CC);
380     }
381   }
382
383   // Use divmod compiler-rt calls for iOS 5.0 and later.
384   if (Subtarget->getTargetTriple().isiOS() &&
385       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
386     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
387     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
388   }
389
390   if (Subtarget->isThumb1Only())
391     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
392   else
393     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
394   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
395       !Subtarget->isThumb1Only()) {
396     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
397     if (!Subtarget->isFPOnlySP())
398       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
399
400     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
401   }
402
403   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
405     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
407       setTruncStoreAction((MVT::SimpleValueType)VT,
408                           (MVT::SimpleValueType)InnerVT, Expand);
409     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
411     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
412
413     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
416     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
417
418     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
419   }
420
421   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423
424   if (Subtarget->hasNEON()) {
425     addDRTypeForNEON(MVT::v2f32);
426     addDRTypeForNEON(MVT::v8i8);
427     addDRTypeForNEON(MVT::v4i16);
428     addDRTypeForNEON(MVT::v2i32);
429     addDRTypeForNEON(MVT::v1i64);
430
431     addQRTypeForNEON(MVT::v4f32);
432     addQRTypeForNEON(MVT::v2f64);
433     addQRTypeForNEON(MVT::v16i8);
434     addQRTypeForNEON(MVT::v8i16);
435     addQRTypeForNEON(MVT::v4i32);
436     addQRTypeForNEON(MVT::v2i64);
437
438     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
439     // neither Neon nor VFP support any arithmetic operations on it.
440     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
441     // supported for v4f32.
442     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
443     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
444     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
445     // FIXME: Code duplication: FDIV and FREM are expanded always, see
446     // ARMTargetLowering::addTypeForNEON method for details.
447     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
448     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
449     // FIXME: Create unittest.
450     // In another words, find a way when "copysign" appears in DAG with vector
451     // operands.
452     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
453     // FIXME: Code duplication: SETCC has custom operation action, see
454     // ARMTargetLowering::addTypeForNEON method for details.
455     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
456     // FIXME: Create unittest for FNEG and for FABS.
457     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
458     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
459     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
460     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
461     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
463     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
467     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
468     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
469     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
470     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
471     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
472     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
474     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
476
477     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
478     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
479     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
480     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
481     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
483     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
485     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
486     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
488     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
489     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
491     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
492
493     // Mark v2f32 intrinsics.
494     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
505     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
506     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
508     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
509
510     // Neon does not support some operations on v1i64 and v2i64 types.
511     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
512     // Custom handling for some quad-vector types to detect VMULL.
513     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
516     // Custom handling for some vector types to avoid expensive expansions
517     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
518     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
519     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
522     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
523     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
524     // a destination type that is wider than the source, and nor does
525     // it have a FP_TO_[SU]INT instruction with a narrower destination than
526     // source.
527     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
529     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
530     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
531
532     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
533     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
534
535     // NEON does not have single instruction CTPOP for vectors with element
536     // types wider than 8-bits.  However, custom lowering can leverage the
537     // v8i8/v16i8 vcnt instruction.
538     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
540     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
542
543     // NEON only has FMA instructions as of VFP4.
544     if (!Subtarget->hasVFP4()) {
545       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
546       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
547     }
548
549     setTargetDAGCombine(ISD::INTRINSIC_VOID);
550     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552     setTargetDAGCombine(ISD::SHL);
553     setTargetDAGCombine(ISD::SRL);
554     setTargetDAGCombine(ISD::SRA);
555     setTargetDAGCombine(ISD::SIGN_EXTEND);
556     setTargetDAGCombine(ISD::ZERO_EXTEND);
557     setTargetDAGCombine(ISD::ANY_EXTEND);
558     setTargetDAGCombine(ISD::SELECT_CC);
559     setTargetDAGCombine(ISD::BUILD_VECTOR);
560     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562     setTargetDAGCombine(ISD::STORE);
563     setTargetDAGCombine(ISD::FP_TO_SINT);
564     setTargetDAGCombine(ISD::FP_TO_UINT);
565     setTargetDAGCombine(ISD::FDIV);
566
567     // It is legal to extload from v4i8 to v4i16 or v4i32.
568     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569                   MVT::v4i16, MVT::v2i16,
570                   MVT::v2i32};
571     for (unsigned i = 0; i < 6; ++i) {
572       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
575     }
576   }
577
578   // ARM and Thumb2 support UMLAL/SMLAL.
579   if (!Subtarget->isThumb1Only())
580     setTargetDAGCombine(ISD::ADDC);
581
582
583   computeRegisterProperties();
584
585   // ARM does not have f32 extending load.
586   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
587
588   // ARM does not have i1 sign extending load.
589   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
590
591   // ARM supports all 4 flavors of integer indexed load / store.
592   if (!Subtarget->isThumb1Only()) {
593     for (unsigned im = (unsigned)ISD::PRE_INC;
594          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
595       setIndexedLoadAction(im,  MVT::i1,  Legal);
596       setIndexedLoadAction(im,  MVT::i8,  Legal);
597       setIndexedLoadAction(im,  MVT::i16, Legal);
598       setIndexedLoadAction(im,  MVT::i32, Legal);
599       setIndexedStoreAction(im, MVT::i1,  Legal);
600       setIndexedStoreAction(im, MVT::i8,  Legal);
601       setIndexedStoreAction(im, MVT::i16, Legal);
602       setIndexedStoreAction(im, MVT::i32, Legal);
603     }
604   }
605
606   setOperationAction(ISD::SADDO, MVT::i32, Custom);
607   setOperationAction(ISD::UADDO, MVT::i32, Custom);
608   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
609   setOperationAction(ISD::USUBO, MVT::i32, Custom);
610
611   // i64 operation support.
612   setOperationAction(ISD::MUL,     MVT::i64, Expand);
613   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
614   if (Subtarget->isThumb1Only()) {
615     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
616     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
617   }
618   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
619       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
620     setOperationAction(ISD::MULHS, MVT::i32, Expand);
621
622   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
623   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
624   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
625   setOperationAction(ISD::SRL,       MVT::i64, Custom);
626   setOperationAction(ISD::SRA,       MVT::i64, Custom);
627
628   if (!Subtarget->isThumb1Only()) {
629     // FIXME: We should do this for Thumb1 as well.
630     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
631     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
632     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
633     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
634   }
635
636   // ARM does not have ROTL.
637   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
638   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
639   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
640   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
641     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
642
643   // These just redirect to CTTZ and CTLZ on ARM.
644   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
645   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
646
647   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
648
649   // Only ARMv6 has BSWAP.
650   if (!Subtarget->hasV6Ops())
651     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
652
653   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
654       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
655     // These are expanded into libcalls if the cpu doesn't have HW divider.
656     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
657     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
658   }
659
660   // FIXME: Also set divmod for SREM on EABI
661   setOperationAction(ISD::SREM,  MVT::i32, Expand);
662   setOperationAction(ISD::UREM,  MVT::i32, Expand);
663   // Register based DivRem for AEABI (RTABI 4.2)
664   if (Subtarget->isTargetAEABI()) {
665     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
666     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
667     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
668     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
669     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
670     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
671     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
672     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
673
674     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
675     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
676     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
677     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
678     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
679     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
680     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
682
683     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
684     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
685   } else {
686     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
687     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
688   }
689
690   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
691   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
692   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
693   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
694   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
695
696   setOperationAction(ISD::TRAP, MVT::Other, Legal);
697
698   // Use the default implementation.
699   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
700   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
701   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
702   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
703   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
704   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
705
706   if (!Subtarget->isTargetMachO()) {
707     // Non-MachO platforms may return values in these registers via the
708     // personality function.
709     setExceptionPointerRegister(ARM::R0);
710     setExceptionSelectorRegister(ARM::R1);
711   }
712
713   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
714   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
715   // the default expansion.
716   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
717     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
718     // to ldrex/strex loops already.
719     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
720
721     // On v8, we have particularly efficient implementations of atomic fences
722     // if they can be combined with nearby atomic loads and stores.
723     if (!Subtarget->hasV8Ops()) {
724       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
725       setInsertFencesForAtomic(true);
726     }
727   } else {
728     // If there's anything we can use as a barrier, go through custom lowering
729     // for ATOMIC_FENCE.
730     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
731                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
732
733     // Set them all for expansion, which will force libcalls.
734     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
735     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
736     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
737     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
738     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
739     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
740     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
741     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
742     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
743     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
744     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
746     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
747     // Unordered/Monotonic case.
748     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
749     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
750   }
751
752   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
753
754   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
755   if (!Subtarget->hasV6Ops()) {
756     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
757     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
758   }
759   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
760
761   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
762       !Subtarget->isThumb1Only()) {
763     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
764     // iff target supports vfp2.
765     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
766     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
767   }
768
769   // We want to custom lower some of our intrinsics.
770   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
771   if (Subtarget->isTargetDarwin()) {
772     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
773     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
774     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
775   }
776
777   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
778   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
779   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
780   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
781   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
782   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
783   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
784   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
785   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
786
787   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
788   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
789   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
790   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
791   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
792
793   // We don't support sin/cos/fmod/copysign/pow
794   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
795   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
796   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
797   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
798   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
799   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
800   setOperationAction(ISD::FREM,      MVT::f64, Expand);
801   setOperationAction(ISD::FREM,      MVT::f32, Expand);
802   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
803       !Subtarget->isThumb1Only()) {
804     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
805     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
806   }
807   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
808   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
809
810   if (!Subtarget->hasVFP4()) {
811     setOperationAction(ISD::FMA, MVT::f64, Expand);
812     setOperationAction(ISD::FMA, MVT::f32, Expand);
813   }
814
815   // Various VFP goodness
816   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
817     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
818     if (Subtarget->hasVFP2()) {
819       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
820       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
821       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
822       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
823     }
824     // Special handling for half-precision FP.
825     if (!Subtarget->hasFP16()) {
826       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
827       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
828     }
829   }
830
831   // Combine sin / cos into one node or libcall if possible.
832   if (Subtarget->hasSinCos()) {
833     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
834     setLibcallName(RTLIB::SINCOS_F64, "sincos");
835     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
836       // For iOS, we don't want to the normal expansion of a libcall to
837       // sincos. We want to issue a libcall to __sincos_stret.
838       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
839       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
840     }
841   }
842
843   // We have target-specific dag combine patterns for the following nodes:
844   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
845   setTargetDAGCombine(ISD::ADD);
846   setTargetDAGCombine(ISD::SUB);
847   setTargetDAGCombine(ISD::MUL);
848   setTargetDAGCombine(ISD::AND);
849   setTargetDAGCombine(ISD::OR);
850   setTargetDAGCombine(ISD::XOR);
851
852   if (Subtarget->hasV6Ops())
853     setTargetDAGCombine(ISD::SRL);
854
855   setStackPointerRegisterToSaveRestore(ARM::SP);
856
857   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
858       !Subtarget->hasVFP2())
859     setSchedulingPreference(Sched::RegPressure);
860   else
861     setSchedulingPreference(Sched::Hybrid);
862
863   //// temporary - rewrite interface to use type
864   MaxStoresPerMemset = 8;
865   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
866   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
867   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
868   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
869   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
870
871   // On ARM arguments smaller than 4 bytes are extended, so all arguments
872   // are at least 4 bytes aligned.
873   setMinStackArgumentAlignment(4);
874
875   // Prefer likely predicted branches to selects on out-of-order cores.
876   PredictableSelectIsExpensive = Subtarget->isLikeA9();
877
878   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
879 }
880
881 // FIXME: It might make sense to define the representative register class as the
882 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
883 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
884 // SPR's representative would be DPR_VFP2. This should work well if register
885 // pressure tracking were modified such that a register use would increment the
886 // pressure of the register class's representative and all of it's super
887 // classes' representatives transitively. We have not implemented this because
888 // of the difficulty prior to coalescing of modeling operand register classes
889 // due to the common occurrence of cross class copies and subregister insertions
890 // and extractions.
891 std::pair<const TargetRegisterClass*, uint8_t>
892 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
893   const TargetRegisterClass *RRC = nullptr;
894   uint8_t Cost = 1;
895   switch (VT.SimpleTy) {
896   default:
897     return TargetLowering::findRepresentativeClass(VT);
898   // Use DPR as representative register class for all floating point
899   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
900   // the cost is 1 for both f32 and f64.
901   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
902   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
903     RRC = &ARM::DPRRegClass;
904     // When NEON is used for SP, only half of the register file is available
905     // because operations that define both SP and DP results will be constrained
906     // to the VFP2 class (D0-D15). We currently model this constraint prior to
907     // coalescing by double-counting the SP regs. See the FIXME above.
908     if (Subtarget->useNEONForSinglePrecisionFP())
909       Cost = 2;
910     break;
911   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
912   case MVT::v4f32: case MVT::v2f64:
913     RRC = &ARM::DPRRegClass;
914     Cost = 2;
915     break;
916   case MVT::v4i64:
917     RRC = &ARM::DPRRegClass;
918     Cost = 4;
919     break;
920   case MVT::v8i64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 8;
923     break;
924   }
925   return std::make_pair(RRC, Cost);
926 }
927
928 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
929   switch (Opcode) {
930   default: return nullptr;
931   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
932   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
933   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
934   case ARMISD::CALL:          return "ARMISD::CALL";
935   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
936   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
937   case ARMISD::tCALL:         return "ARMISD::tCALL";
938   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
939   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
940   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
941   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
942   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
943   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
944   case ARMISD::CMP:           return "ARMISD::CMP";
945   case ARMISD::CMN:           return "ARMISD::CMN";
946   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
947   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
948   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
949   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
950   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
951
952   case ARMISD::CMOV:          return "ARMISD::CMOV";
953
954   case ARMISD::RBIT:          return "ARMISD::RBIT";
955
956   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
957   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
958   case ARMISD::SITOF:         return "ARMISD::SITOF";
959   case ARMISD::UITOF:         return "ARMISD::UITOF";
960
961   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
962   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
963   case ARMISD::RRX:           return "ARMISD::RRX";
964
965   case ARMISD::ADDC:          return "ARMISD::ADDC";
966   case ARMISD::ADDE:          return "ARMISD::ADDE";
967   case ARMISD::SUBC:          return "ARMISD::SUBC";
968   case ARMISD::SUBE:          return "ARMISD::SUBE";
969
970   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
971   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
972
973   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
974   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
975
976   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
977
978   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
979
980   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
981
982   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
983
984   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
985
986   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
987   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
988   case ARMISD::VCGE:          return "ARMISD::VCGE";
989   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
990   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
991   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
992   case ARMISD::VCGT:          return "ARMISD::VCGT";
993   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
994   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
995   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
996   case ARMISD::VTST:          return "ARMISD::VTST";
997
998   case ARMISD::VSHL:          return "ARMISD::VSHL";
999   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1000   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1001   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1002   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1003   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1004   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1005   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1006   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1007   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1008   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1009   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1010   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1011   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1012   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1013   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1014   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1015   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1016   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1017   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1018   case ARMISD::VDUP:          return "ARMISD::VDUP";
1019   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1020   case ARMISD::VEXT:          return "ARMISD::VEXT";
1021   case ARMISD::VREV64:        return "ARMISD::VREV64";
1022   case ARMISD::VREV32:        return "ARMISD::VREV32";
1023   case ARMISD::VREV16:        return "ARMISD::VREV16";
1024   case ARMISD::VZIP:          return "ARMISD::VZIP";
1025   case ARMISD::VUZP:          return "ARMISD::VUZP";
1026   case ARMISD::VTRN:          return "ARMISD::VTRN";
1027   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1028   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1029   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1030   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1031   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1032   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1033   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1034   case ARMISD::FMAX:          return "ARMISD::FMAX";
1035   case ARMISD::FMIN:          return "ARMISD::FMIN";
1036   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1037   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1038   case ARMISD::BFI:           return "ARMISD::BFI";
1039   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1040   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1041   case ARMISD::VBSL:          return "ARMISD::VBSL";
1042   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1043   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1044   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1045   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1046   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1047   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1048   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1049   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1050   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1051   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1052   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1053   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1054   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1055   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1056   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1057   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1058   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1059   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1060   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1061   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1062   }
1063 }
1064
1065 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1066   if (!VT.isVector()) return getPointerTy();
1067   return VT.changeVectorElementTypeToInteger();
1068 }
1069
1070 /// getRegClassFor - Return the register class that should be used for the
1071 /// specified value type.
1072 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1073   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1074   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1075   // load / store 4 to 8 consecutive D registers.
1076   if (Subtarget->hasNEON()) {
1077     if (VT == MVT::v4i64)
1078       return &ARM::QQPRRegClass;
1079     if (VT == MVT::v8i64)
1080       return &ARM::QQQQPRRegClass;
1081   }
1082   return TargetLowering::getRegClassFor(VT);
1083 }
1084
1085 // Create a fast isel object.
1086 FastISel *
1087 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1088                                   const TargetLibraryInfo *libInfo) const {
1089   return ARM::createFastISel(funcInfo, libInfo);
1090 }
1091
1092 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1093 /// be used for loads / stores from the global.
1094 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1095   return (Subtarget->isThumb1Only() ? 127 : 4095);
1096 }
1097
1098 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1099   unsigned NumVals = N->getNumValues();
1100   if (!NumVals)
1101     return Sched::RegPressure;
1102
1103   for (unsigned i = 0; i != NumVals; ++i) {
1104     EVT VT = N->getValueType(i);
1105     if (VT == MVT::Glue || VT == MVT::Other)
1106       continue;
1107     if (VT.isFloatingPoint() || VT.isVector())
1108       return Sched::ILP;
1109   }
1110
1111   if (!N->isMachineOpcode())
1112     return Sched::RegPressure;
1113
1114   // Load are scheduled for latency even if there instruction itinerary
1115   // is not available.
1116   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1117   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1118
1119   if (MCID.getNumDefs() == 0)
1120     return Sched::RegPressure;
1121   if (!Itins->isEmpty() &&
1122       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1123     return Sched::ILP;
1124
1125   return Sched::RegPressure;
1126 }
1127
1128 //===----------------------------------------------------------------------===//
1129 // Lowering Code
1130 //===----------------------------------------------------------------------===//
1131
1132 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1133 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1134   switch (CC) {
1135   default: llvm_unreachable("Unknown condition code!");
1136   case ISD::SETNE:  return ARMCC::NE;
1137   case ISD::SETEQ:  return ARMCC::EQ;
1138   case ISD::SETGT:  return ARMCC::GT;
1139   case ISD::SETGE:  return ARMCC::GE;
1140   case ISD::SETLT:  return ARMCC::LT;
1141   case ISD::SETLE:  return ARMCC::LE;
1142   case ISD::SETUGT: return ARMCC::HI;
1143   case ISD::SETUGE: return ARMCC::HS;
1144   case ISD::SETULT: return ARMCC::LO;
1145   case ISD::SETULE: return ARMCC::LS;
1146   }
1147 }
1148
1149 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1150 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1151                         ARMCC::CondCodes &CondCode2) {
1152   CondCode2 = ARMCC::AL;
1153   switch (CC) {
1154   default: llvm_unreachable("Unknown FP condition!");
1155   case ISD::SETEQ:
1156   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1157   case ISD::SETGT:
1158   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1159   case ISD::SETGE:
1160   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1161   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1162   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1163   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1164   case ISD::SETO:   CondCode = ARMCC::VC; break;
1165   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1166   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1167   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1168   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1169   case ISD::SETLT:
1170   case ISD::SETULT: CondCode = ARMCC::LT; break;
1171   case ISD::SETLE:
1172   case ISD::SETULE: CondCode = ARMCC::LE; break;
1173   case ISD::SETNE:
1174   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1175   }
1176 }
1177
1178 //===----------------------------------------------------------------------===//
1179 //                      Calling Convention Implementation
1180 //===----------------------------------------------------------------------===//
1181
1182 #include "ARMGenCallingConv.inc"
1183
1184 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1185 /// account presence of floating point hardware and calling convention
1186 /// limitations, such as support for variadic functions.
1187 CallingConv::ID
1188 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1189                                            bool isVarArg) const {
1190   switch (CC) {
1191   default:
1192     llvm_unreachable("Unsupported calling convention");
1193   case CallingConv::ARM_AAPCS:
1194   case CallingConv::ARM_APCS:
1195   case CallingConv::GHC:
1196     return CC;
1197   case CallingConv::ARM_AAPCS_VFP:
1198     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1199   case CallingConv::C:
1200     if (!Subtarget->isAAPCS_ABI())
1201       return CallingConv::ARM_APCS;
1202     else if (Subtarget->hasVFP2() &&
1203              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1204              !isVarArg)
1205       return CallingConv::ARM_AAPCS_VFP;
1206     else
1207       return CallingConv::ARM_AAPCS;
1208   case CallingConv::Fast:
1209     if (!Subtarget->isAAPCS_ABI()) {
1210       if (Subtarget->hasVFP2() && !isVarArg)
1211         return CallingConv::Fast;
1212       return CallingConv::ARM_APCS;
1213     } else if (Subtarget->hasVFP2() && !isVarArg)
1214       return CallingConv::ARM_AAPCS_VFP;
1215     else
1216       return CallingConv::ARM_AAPCS;
1217   }
1218 }
1219
1220 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1221 /// CallingConvention.
1222 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1223                                                  bool Return,
1224                                                  bool isVarArg) const {
1225   switch (getEffectiveCallingConv(CC, isVarArg)) {
1226   default:
1227     llvm_unreachable("Unsupported calling convention");
1228   case CallingConv::ARM_APCS:
1229     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1230   case CallingConv::ARM_AAPCS:
1231     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1232   case CallingConv::ARM_AAPCS_VFP:
1233     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1234   case CallingConv::Fast:
1235     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1236   case CallingConv::GHC:
1237     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1238   }
1239 }
1240
1241 /// LowerCallResult - Lower the result values of a call into the
1242 /// appropriate copies out of appropriate physical registers.
1243 SDValue
1244 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1245                                    CallingConv::ID CallConv, bool isVarArg,
1246                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1247                                    SDLoc dl, SelectionDAG &DAG,
1248                                    SmallVectorImpl<SDValue> &InVals,
1249                                    bool isThisReturn, SDValue ThisVal) const {
1250
1251   // Assign locations to each value returned by this call.
1252   SmallVector<CCValAssign, 16> RVLocs;
1253   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1254                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1255   CCInfo.AnalyzeCallResult(Ins,
1256                            CCAssignFnForNode(CallConv, /* Return*/ true,
1257                                              isVarArg));
1258
1259   // Copy all of the result registers out of their specified physreg.
1260   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1261     CCValAssign VA = RVLocs[i];
1262
1263     // Pass 'this' value directly from the argument to return value, to avoid
1264     // reg unit interference
1265     if (i == 0 && isThisReturn) {
1266       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1267              "unexpected return calling convention register assignment");
1268       InVals.push_back(ThisVal);
1269       continue;
1270     }
1271
1272     SDValue Val;
1273     if (VA.needsCustom()) {
1274       // Handle f64 or half of a v2f64.
1275       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1276                                       InFlag);
1277       Chain = Lo.getValue(1);
1278       InFlag = Lo.getValue(2);
1279       VA = RVLocs[++i]; // skip ahead to next loc
1280       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1281                                       InFlag);
1282       Chain = Hi.getValue(1);
1283       InFlag = Hi.getValue(2);
1284       if (!Subtarget->isLittle())
1285         std::swap (Lo, Hi);
1286       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1287
1288       if (VA.getLocVT() == MVT::v2f64) {
1289         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1290         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1291                           DAG.getConstant(0, MVT::i32));
1292
1293         VA = RVLocs[++i]; // skip ahead to next loc
1294         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1295         Chain = Lo.getValue(1);
1296         InFlag = Lo.getValue(2);
1297         VA = RVLocs[++i]; // skip ahead to next loc
1298         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1299         Chain = Hi.getValue(1);
1300         InFlag = Hi.getValue(2);
1301         if (!Subtarget->isLittle())
1302           std::swap (Lo, Hi);
1303         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1304         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1305                           DAG.getConstant(1, MVT::i32));
1306       }
1307     } else {
1308       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1309                                InFlag);
1310       Chain = Val.getValue(1);
1311       InFlag = Val.getValue(2);
1312     }
1313
1314     switch (VA.getLocInfo()) {
1315     default: llvm_unreachable("Unknown loc info!");
1316     case CCValAssign::Full: break;
1317     case CCValAssign::BCvt:
1318       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1319       break;
1320     }
1321
1322     InVals.push_back(Val);
1323   }
1324
1325   return Chain;
1326 }
1327
1328 /// LowerMemOpCallTo - Store the argument to the stack.
1329 SDValue
1330 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1331                                     SDValue StackPtr, SDValue Arg,
1332                                     SDLoc dl, SelectionDAG &DAG,
1333                                     const CCValAssign &VA,
1334                                     ISD::ArgFlagsTy Flags) const {
1335   unsigned LocMemOffset = VA.getLocMemOffset();
1336   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1337   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1338   return DAG.getStore(Chain, dl, Arg, PtrOff,
1339                       MachinePointerInfo::getStack(LocMemOffset),
1340                       false, false, 0);
1341 }
1342
1343 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1344                                          SDValue Chain, SDValue &Arg,
1345                                          RegsToPassVector &RegsToPass,
1346                                          CCValAssign &VA, CCValAssign &NextVA,
1347                                          SDValue &StackPtr,
1348                                          SmallVectorImpl<SDValue> &MemOpChains,
1349                                          ISD::ArgFlagsTy Flags) const {
1350
1351   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1352                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1353   unsigned id = Subtarget->isLittle() ? 0 : 1;
1354   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1355
1356   if (NextVA.isRegLoc())
1357     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1358   else {
1359     assert(NextVA.isMemLoc());
1360     if (!StackPtr.getNode())
1361       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1362
1363     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1364                                            dl, DAG, NextVA,
1365                                            Flags));
1366   }
1367 }
1368
1369 /// LowerCall - Lowering a call into a callseq_start <-
1370 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1371 /// nodes.
1372 SDValue
1373 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1374                              SmallVectorImpl<SDValue> &InVals) const {
1375   SelectionDAG &DAG                     = CLI.DAG;
1376   SDLoc &dl                          = CLI.DL;
1377   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1378   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1379   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1380   SDValue Chain                         = CLI.Chain;
1381   SDValue Callee                        = CLI.Callee;
1382   bool &isTailCall                      = CLI.IsTailCall;
1383   CallingConv::ID CallConv              = CLI.CallConv;
1384   bool doesNotRet                       = CLI.DoesNotReturn;
1385   bool isVarArg                         = CLI.IsVarArg;
1386
1387   MachineFunction &MF = DAG.getMachineFunction();
1388   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1389   bool isThisReturn   = false;
1390   bool isSibCall      = false;
1391
1392   // Disable tail calls if they're not supported.
1393   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1394     isTailCall = false;
1395
1396   if (isTailCall) {
1397     // Check if it's really possible to do a tail call.
1398     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1399                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1400                                                    Outs, OutVals, Ins, DAG);
1401     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1402       report_fatal_error("failed to perform tail call elimination on a call "
1403                          "site marked musttail");
1404     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1405     // detected sibcalls.
1406     if (isTailCall) {
1407       ++NumTailCalls;
1408       isSibCall = true;
1409     }
1410   }
1411
1412   // Analyze operands of the call, assigning locations to each operand.
1413   SmallVector<CCValAssign, 16> ArgLocs;
1414   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1415                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1416   CCInfo.AnalyzeCallOperands(Outs,
1417                              CCAssignFnForNode(CallConv, /* Return*/ false,
1418                                                isVarArg));
1419
1420   // Get a count of how many bytes are to be pushed on the stack.
1421   unsigned NumBytes = CCInfo.getNextStackOffset();
1422
1423   // For tail calls, memory operands are available in our caller's stack.
1424   if (isSibCall)
1425     NumBytes = 0;
1426
1427   // Adjust the stack pointer for the new arguments...
1428   // These operations are automatically eliminated by the prolog/epilog pass
1429   if (!isSibCall)
1430     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1431                                  dl);
1432
1433   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1434
1435   RegsToPassVector RegsToPass;
1436   SmallVector<SDValue, 8> MemOpChains;
1437
1438   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1439   // of tail call optimization, arguments are handled later.
1440   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1441        i != e;
1442        ++i, ++realArgIdx) {
1443     CCValAssign &VA = ArgLocs[i];
1444     SDValue Arg = OutVals[realArgIdx];
1445     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1446     bool isByVal = Flags.isByVal();
1447
1448     // Promote the value if needed.
1449     switch (VA.getLocInfo()) {
1450     default: llvm_unreachable("Unknown loc info!");
1451     case CCValAssign::Full: break;
1452     case CCValAssign::SExt:
1453       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1454       break;
1455     case CCValAssign::ZExt:
1456       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1457       break;
1458     case CCValAssign::AExt:
1459       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1460       break;
1461     case CCValAssign::BCvt:
1462       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1463       break;
1464     }
1465
1466     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1467     if (VA.needsCustom()) {
1468       if (VA.getLocVT() == MVT::v2f64) {
1469         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1470                                   DAG.getConstant(0, MVT::i32));
1471         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1472                                   DAG.getConstant(1, MVT::i32));
1473
1474         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1475                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1476
1477         VA = ArgLocs[++i]; // skip ahead to next loc
1478         if (VA.isRegLoc()) {
1479           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1480                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1481         } else {
1482           assert(VA.isMemLoc());
1483
1484           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1485                                                  dl, DAG, VA, Flags));
1486         }
1487       } else {
1488         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1489                          StackPtr, MemOpChains, Flags);
1490       }
1491     } else if (VA.isRegLoc()) {
1492       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1493         assert(VA.getLocVT() == MVT::i32 &&
1494                "unexpected calling convention register assignment");
1495         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1496                "unexpected use of 'returned'");
1497         isThisReturn = true;
1498       }
1499       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1500     } else if (isByVal) {
1501       assert(VA.isMemLoc());
1502       unsigned offset = 0;
1503
1504       // True if this byval aggregate will be split between registers
1505       // and memory.
1506       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1507       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1508
1509       if (CurByValIdx < ByValArgsCount) {
1510
1511         unsigned RegBegin, RegEnd;
1512         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1513
1514         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1515         unsigned int i, j;
1516         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1517           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1518           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1519           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1520                                      MachinePointerInfo(),
1521                                      false, false, false,
1522                                      DAG.InferPtrAlignment(AddArg));
1523           MemOpChains.push_back(Load.getValue(1));
1524           RegsToPass.push_back(std::make_pair(j, Load));
1525         }
1526
1527         // If parameter size outsides register area, "offset" value
1528         // helps us to calculate stack slot for remained part properly.
1529         offset = RegEnd - RegBegin;
1530
1531         CCInfo.nextInRegsParam();
1532       }
1533
1534       if (Flags.getByValSize() > 4*offset) {
1535         unsigned LocMemOffset = VA.getLocMemOffset();
1536         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1537         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1538                                   StkPtrOff);
1539         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1540         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1541         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1542                                            MVT::i32);
1543         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1544
1545         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1546         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1547         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1548                                           Ops));
1549       }
1550     } else if (!isSibCall) {
1551       assert(VA.isMemLoc());
1552
1553       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1554                                              dl, DAG, VA, Flags));
1555     }
1556   }
1557
1558   if (!MemOpChains.empty())
1559     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1560
1561   // Build a sequence of copy-to-reg nodes chained together with token chain
1562   // and flag operands which copy the outgoing args into the appropriate regs.
1563   SDValue InFlag;
1564   // Tail call byval lowering might overwrite argument registers so in case of
1565   // tail call optimization the copies to registers are lowered later.
1566   if (!isTailCall)
1567     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1568       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1569                                RegsToPass[i].second, InFlag);
1570       InFlag = Chain.getValue(1);
1571     }
1572
1573   // For tail calls lower the arguments to the 'real' stack slot.
1574   if (isTailCall) {
1575     // Force all the incoming stack arguments to be loaded from the stack
1576     // before any new outgoing arguments are stored to the stack, because the
1577     // outgoing stack slots may alias the incoming argument stack slots, and
1578     // the alias isn't otherwise explicit. This is slightly more conservative
1579     // than necessary, because it means that each store effectively depends
1580     // on every argument instead of just those arguments it would clobber.
1581
1582     // Do not flag preceding copytoreg stuff together with the following stuff.
1583     InFlag = SDValue();
1584     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1585       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1586                                RegsToPass[i].second, InFlag);
1587       InFlag = Chain.getValue(1);
1588     }
1589     InFlag = SDValue();
1590   }
1591
1592   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1593   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1594   // node so that legalize doesn't hack it.
1595   bool isDirect = false;
1596   bool isARMFunc = false;
1597   bool isLocalARMFunc = false;
1598   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1599
1600   if (EnableARMLongCalls) {
1601     assert((Subtarget->isTargetWindows() ||
1602             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1603            "long-calls with non-static relocation model!");
1604     // Handle a global address or an external symbol. If it's not one of
1605     // those, the target's already in a register, so we don't need to do
1606     // anything extra.
1607     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1608       const GlobalValue *GV = G->getGlobal();
1609       // Create a constant pool entry for the callee address
1610       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1611       ARMConstantPoolValue *CPV =
1612         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1613
1614       // Get the address of the callee into a register
1615       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1616       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1617       Callee = DAG.getLoad(getPointerTy(), dl,
1618                            DAG.getEntryNode(), CPAddr,
1619                            MachinePointerInfo::getConstantPool(),
1620                            false, false, false, 0);
1621     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1622       const char *Sym = S->getSymbol();
1623
1624       // Create a constant pool entry for the callee address
1625       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1626       ARMConstantPoolValue *CPV =
1627         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1628                                       ARMPCLabelIndex, 0);
1629       // Get the address of the callee into a register
1630       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1631       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1632       Callee = DAG.getLoad(getPointerTy(), dl,
1633                            DAG.getEntryNode(), CPAddr,
1634                            MachinePointerInfo::getConstantPool(),
1635                            false, false, false, 0);
1636     }
1637   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1638     const GlobalValue *GV = G->getGlobal();
1639     isDirect = true;
1640     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1641     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1642                    getTargetMachine().getRelocationModel() != Reloc::Static;
1643     isARMFunc = !Subtarget->isThumb() || isStub;
1644     // ARM call to a local ARM function is predicable.
1645     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1646     // tBX takes a register source operand.
1647     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1648       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1649       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1650                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1651     } else {
1652       // On ELF targets for PIC code, direct calls should go through the PLT
1653       unsigned OpFlags = 0;
1654       if (Subtarget->isTargetELF() &&
1655           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1656         OpFlags = ARMII::MO_PLT;
1657       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1658     }
1659   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1660     isDirect = true;
1661     bool isStub = Subtarget->isTargetMachO() &&
1662                   getTargetMachine().getRelocationModel() != Reloc::Static;
1663     isARMFunc = !Subtarget->isThumb() || isStub;
1664     // tBX takes a register source operand.
1665     const char *Sym = S->getSymbol();
1666     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1667       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1668       ARMConstantPoolValue *CPV =
1669         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1670                                       ARMPCLabelIndex, 4);
1671       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1672       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1673       Callee = DAG.getLoad(getPointerTy(), dl,
1674                            DAG.getEntryNode(), CPAddr,
1675                            MachinePointerInfo::getConstantPool(),
1676                            false, false, false, 0);
1677       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1678       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1679                            getPointerTy(), Callee, PICLabel);
1680     } else {
1681       unsigned OpFlags = 0;
1682       // On ELF targets for PIC code, direct calls should go through the PLT
1683       if (Subtarget->isTargetELF() &&
1684                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1685         OpFlags = ARMII::MO_PLT;
1686       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1687     }
1688   }
1689
1690   // FIXME: handle tail calls differently.
1691   unsigned CallOpc;
1692   bool HasMinSizeAttr = Subtarget->isMinSize();
1693   if (Subtarget->isThumb()) {
1694     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1695       CallOpc = ARMISD::CALL_NOLINK;
1696     else
1697       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1698   } else {
1699     if (!isDirect && !Subtarget->hasV5TOps())
1700       CallOpc = ARMISD::CALL_NOLINK;
1701     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1702                // Emit regular call when code size is the priority
1703                !HasMinSizeAttr)
1704       // "mov lr, pc; b _foo" to avoid confusing the RSP
1705       CallOpc = ARMISD::CALL_NOLINK;
1706     else
1707       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1708   }
1709
1710   std::vector<SDValue> Ops;
1711   Ops.push_back(Chain);
1712   Ops.push_back(Callee);
1713
1714   // Add argument registers to the end of the list so that they are known live
1715   // into the call.
1716   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1717     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1718                                   RegsToPass[i].second.getValueType()));
1719
1720   // Add a register mask operand representing the call-preserved registers.
1721   if (!isTailCall) {
1722     const uint32_t *Mask;
1723     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1724     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1725     if (isThisReturn) {
1726       // For 'this' returns, use the R0-preserving mask if applicable
1727       Mask = ARI->getThisReturnPreservedMask(CallConv);
1728       if (!Mask) {
1729         // Set isThisReturn to false if the calling convention is not one that
1730         // allows 'returned' to be modeled in this way, so LowerCallResult does
1731         // not try to pass 'this' straight through
1732         isThisReturn = false;
1733         Mask = ARI->getCallPreservedMask(CallConv);
1734       }
1735     } else
1736       Mask = ARI->getCallPreservedMask(CallConv);
1737
1738     assert(Mask && "Missing call preserved mask for calling convention");
1739     Ops.push_back(DAG.getRegisterMask(Mask));
1740   }
1741
1742   if (InFlag.getNode())
1743     Ops.push_back(InFlag);
1744
1745   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1746   if (isTailCall)
1747     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1748
1749   // Returns a chain and a flag for retval copy to use.
1750   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1751   InFlag = Chain.getValue(1);
1752
1753   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1754                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1755   if (!Ins.empty())
1756     InFlag = Chain.getValue(1);
1757
1758   // Handle result values, copying them out of physregs into vregs that we
1759   // return.
1760   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1761                          InVals, isThisReturn,
1762                          isThisReturn ? OutVals[0] : SDValue());
1763 }
1764
1765 /// HandleByVal - Every parameter *after* a byval parameter is passed
1766 /// on the stack.  Remember the next parameter register to allocate,
1767 /// and then confiscate the rest of the parameter registers to insure
1768 /// this.
1769 void
1770 ARMTargetLowering::HandleByVal(
1771     CCState *State, unsigned &size, unsigned Align) const {
1772   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1773   assert((State->getCallOrPrologue() == Prologue ||
1774           State->getCallOrPrologue() == Call) &&
1775          "unhandled ParmContext");
1776
1777   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1778     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1779       unsigned AlignInRegs = Align / 4;
1780       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1781       for (unsigned i = 0; i < Waste; ++i)
1782         reg = State->AllocateReg(GPRArgRegs, 4);
1783     }
1784     if (reg != 0) {
1785       unsigned excess = 4 * (ARM::R4 - reg);
1786
1787       // Special case when NSAA != SP and parameter size greater than size of
1788       // all remained GPR regs. In that case we can't split parameter, we must
1789       // send it to stack. We also must set NCRN to R4, so waste all
1790       // remained registers.
1791       const unsigned NSAAOffset = State->getNextStackOffset();
1792       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1793         while (State->AllocateReg(GPRArgRegs, 4))
1794           ;
1795         return;
1796       }
1797
1798       // First register for byval parameter is the first register that wasn't
1799       // allocated before this method call, so it would be "reg".
1800       // If parameter is small enough to be saved in range [reg, r4), then
1801       // the end (first after last) register would be reg + param-size-in-regs,
1802       // else parameter would be splitted between registers and stack,
1803       // end register would be r4 in this case.
1804       unsigned ByValRegBegin = reg;
1805       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1806       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1807       // Note, first register is allocated in the beginning of function already,
1808       // allocate remained amount of registers we need.
1809       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1810         State->AllocateReg(GPRArgRegs, 4);
1811       // A byval parameter that is split between registers and memory needs its
1812       // size truncated here.
1813       // In the case where the entire structure fits in registers, we set the
1814       // size in memory to zero.
1815       if (size < excess)
1816         size = 0;
1817       else
1818         size -= excess;
1819     }
1820   }
1821 }
1822
1823 /// MatchingStackOffset - Return true if the given stack call argument is
1824 /// already available in the same position (relatively) of the caller's
1825 /// incoming argument stack.
1826 static
1827 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1828                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1829                          const TargetInstrInfo *TII) {
1830   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1831   int FI = INT_MAX;
1832   if (Arg.getOpcode() == ISD::CopyFromReg) {
1833     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1834     if (!TargetRegisterInfo::isVirtualRegister(VR))
1835       return false;
1836     MachineInstr *Def = MRI->getVRegDef(VR);
1837     if (!Def)
1838       return false;
1839     if (!Flags.isByVal()) {
1840       if (!TII->isLoadFromStackSlot(Def, FI))
1841         return false;
1842     } else {
1843       return false;
1844     }
1845   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1846     if (Flags.isByVal())
1847       // ByVal argument is passed in as a pointer but it's now being
1848       // dereferenced. e.g.
1849       // define @foo(%struct.X* %A) {
1850       //   tail call @bar(%struct.X* byval %A)
1851       // }
1852       return false;
1853     SDValue Ptr = Ld->getBasePtr();
1854     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1855     if (!FINode)
1856       return false;
1857     FI = FINode->getIndex();
1858   } else
1859     return false;
1860
1861   assert(FI != INT_MAX);
1862   if (!MFI->isFixedObjectIndex(FI))
1863     return false;
1864   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1865 }
1866
1867 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1868 /// for tail call optimization. Targets which want to do tail call
1869 /// optimization should implement this function.
1870 bool
1871 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1872                                                      CallingConv::ID CalleeCC,
1873                                                      bool isVarArg,
1874                                                      bool isCalleeStructRet,
1875                                                      bool isCallerStructRet,
1876                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1877                                     const SmallVectorImpl<SDValue> &OutVals,
1878                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1879                                                      SelectionDAG& DAG) const {
1880   const Function *CallerF = DAG.getMachineFunction().getFunction();
1881   CallingConv::ID CallerCC = CallerF->getCallingConv();
1882   bool CCMatch = CallerCC == CalleeCC;
1883
1884   // Look for obvious safe cases to perform tail call optimization that do not
1885   // require ABI changes. This is what gcc calls sibcall.
1886
1887   // Do not sibcall optimize vararg calls unless the call site is not passing
1888   // any arguments.
1889   if (isVarArg && !Outs.empty())
1890     return false;
1891
1892   // Exception-handling functions need a special set of instructions to indicate
1893   // a return to the hardware. Tail-calling another function would probably
1894   // break this.
1895   if (CallerF->hasFnAttribute("interrupt"))
1896     return false;
1897
1898   // Also avoid sibcall optimization if either caller or callee uses struct
1899   // return semantics.
1900   if (isCalleeStructRet || isCallerStructRet)
1901     return false;
1902
1903   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1904   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1905   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1906   // support in the assembler and linker to be used. This would need to be
1907   // fixed to fully support tail calls in Thumb1.
1908   //
1909   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1910   // LR.  This means if we need to reload LR, it takes an extra instructions,
1911   // which outweighs the value of the tail call; but here we don't know yet
1912   // whether LR is going to be used.  Probably the right approach is to
1913   // generate the tail call here and turn it back into CALL/RET in
1914   // emitEpilogue if LR is used.
1915
1916   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1917   // but we need to make sure there are enough registers; the only valid
1918   // registers are the 4 used for parameters.  We don't currently do this
1919   // case.
1920   if (Subtarget->isThumb1Only())
1921     return false;
1922
1923   // If the calling conventions do not match, then we'd better make sure the
1924   // results are returned in the same way as what the caller expects.
1925   if (!CCMatch) {
1926     SmallVector<CCValAssign, 16> RVLocs1;
1927     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1928                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1929     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1930
1931     SmallVector<CCValAssign, 16> RVLocs2;
1932     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1933                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1934     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1935
1936     if (RVLocs1.size() != RVLocs2.size())
1937       return false;
1938     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1939       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1940         return false;
1941       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1942         return false;
1943       if (RVLocs1[i].isRegLoc()) {
1944         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1945           return false;
1946       } else {
1947         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1948           return false;
1949       }
1950     }
1951   }
1952
1953   // If Caller's vararg or byval argument has been split between registers and
1954   // stack, do not perform tail call, since part of the argument is in caller's
1955   // local frame.
1956   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1957                                       getInfo<ARMFunctionInfo>();
1958   if (AFI_Caller->getArgRegsSaveSize())
1959     return false;
1960
1961   // If the callee takes no arguments then go on to check the results of the
1962   // call.
1963   if (!Outs.empty()) {
1964     // Check if stack adjustment is needed. For now, do not do this if any
1965     // argument is passed on the stack.
1966     SmallVector<CCValAssign, 16> ArgLocs;
1967     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1968                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1969     CCInfo.AnalyzeCallOperands(Outs,
1970                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1971     if (CCInfo.getNextStackOffset()) {
1972       MachineFunction &MF = DAG.getMachineFunction();
1973
1974       // Check if the arguments are already laid out in the right way as
1975       // the caller's fixed stack objects.
1976       MachineFrameInfo *MFI = MF.getFrameInfo();
1977       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1978       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1979       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1980            i != e;
1981            ++i, ++realArgIdx) {
1982         CCValAssign &VA = ArgLocs[i];
1983         EVT RegVT = VA.getLocVT();
1984         SDValue Arg = OutVals[realArgIdx];
1985         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1986         if (VA.getLocInfo() == CCValAssign::Indirect)
1987           return false;
1988         if (VA.needsCustom()) {
1989           // f64 and vector types are split into multiple registers or
1990           // register/stack-slot combinations.  The types will not match
1991           // the registers; give up on memory f64 refs until we figure
1992           // out what to do about this.
1993           if (!VA.isRegLoc())
1994             return false;
1995           if (!ArgLocs[++i].isRegLoc())
1996             return false;
1997           if (RegVT == MVT::v2f64) {
1998             if (!ArgLocs[++i].isRegLoc())
1999               return false;
2000             if (!ArgLocs[++i].isRegLoc())
2001               return false;
2002           }
2003         } else if (!VA.isRegLoc()) {
2004           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2005                                    MFI, MRI, TII))
2006             return false;
2007         }
2008       }
2009     }
2010   }
2011
2012   return true;
2013 }
2014
2015 bool
2016 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2017                                   MachineFunction &MF, bool isVarArg,
2018                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2019                                   LLVMContext &Context) const {
2020   SmallVector<CCValAssign, 16> RVLocs;
2021   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2022   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2023                                                     isVarArg));
2024 }
2025
2026 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2027                                     SDLoc DL, SelectionDAG &DAG) {
2028   const MachineFunction &MF = DAG.getMachineFunction();
2029   const Function *F = MF.getFunction();
2030
2031   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2032
2033   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2034   // version of the "preferred return address". These offsets affect the return
2035   // instruction if this is a return from PL1 without hypervisor extensions.
2036   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2037   //    SWI:     0      "subs pc, lr, #0"
2038   //    ABORT:   +4     "subs pc, lr, #4"
2039   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2040   // UNDEF varies depending on where the exception came from ARM or Thumb
2041   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2042
2043   int64_t LROffset;
2044   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2045       IntKind == "ABORT")
2046     LROffset = 4;
2047   else if (IntKind == "SWI" || IntKind == "UNDEF")
2048     LROffset = 0;
2049   else
2050     report_fatal_error("Unsupported interrupt attribute. If present, value "
2051                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2052
2053   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2054
2055   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2056 }
2057
2058 SDValue
2059 ARMTargetLowering::LowerReturn(SDValue Chain,
2060                                CallingConv::ID CallConv, bool isVarArg,
2061                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2062                                const SmallVectorImpl<SDValue> &OutVals,
2063                                SDLoc dl, SelectionDAG &DAG) const {
2064
2065   // CCValAssign - represent the assignment of the return value to a location.
2066   SmallVector<CCValAssign, 16> RVLocs;
2067
2068   // CCState - Info about the registers and stack slots.
2069   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2070                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2071
2072   // Analyze outgoing return values.
2073   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2074                                                isVarArg));
2075
2076   SDValue Flag;
2077   SmallVector<SDValue, 4> RetOps;
2078   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2079   bool isLittleEndian = Subtarget->isLittle();
2080
2081   // Copy the result values into the output registers.
2082   for (unsigned i = 0, realRVLocIdx = 0;
2083        i != RVLocs.size();
2084        ++i, ++realRVLocIdx) {
2085     CCValAssign &VA = RVLocs[i];
2086     assert(VA.isRegLoc() && "Can only return in registers!");
2087
2088     SDValue Arg = OutVals[realRVLocIdx];
2089
2090     switch (VA.getLocInfo()) {
2091     default: llvm_unreachable("Unknown loc info!");
2092     case CCValAssign::Full: break;
2093     case CCValAssign::BCvt:
2094       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2095       break;
2096     }
2097
2098     if (VA.needsCustom()) {
2099       if (VA.getLocVT() == MVT::v2f64) {
2100         // Extract the first half and return it in two registers.
2101         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2102                                    DAG.getConstant(0, MVT::i32));
2103         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2104                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2105
2106         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2107                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2108                                  Flag);
2109         Flag = Chain.getValue(1);
2110         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2111         VA = RVLocs[++i]; // skip ahead to next loc
2112         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2113                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2114                                  Flag);
2115         Flag = Chain.getValue(1);
2116         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2117         VA = RVLocs[++i]; // skip ahead to next loc
2118
2119         // Extract the 2nd half and fall through to handle it as an f64 value.
2120         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2121                           DAG.getConstant(1, MVT::i32));
2122       }
2123       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2124       // available.
2125       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2126                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2127       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2128                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2129                                Flag);
2130       Flag = Chain.getValue(1);
2131       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2132       VA = RVLocs[++i]; // skip ahead to next loc
2133       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2134                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2135                                Flag);
2136     } else
2137       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2138
2139     // Guarantee that all emitted copies are
2140     // stuck together, avoiding something bad.
2141     Flag = Chain.getValue(1);
2142     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2143   }
2144
2145   // Update chain and glue.
2146   RetOps[0] = Chain;
2147   if (Flag.getNode())
2148     RetOps.push_back(Flag);
2149
2150   // CPUs which aren't M-class use a special sequence to return from
2151   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2152   // though we use "subs pc, lr, #N").
2153   //
2154   // M-class CPUs actually use a normal return sequence with a special
2155   // (hardware-provided) value in LR, so the normal code path works.
2156   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2157       !Subtarget->isMClass()) {
2158     if (Subtarget->isThumb1Only())
2159       report_fatal_error("interrupt attribute is not supported in Thumb1");
2160     return LowerInterruptReturn(RetOps, dl, DAG);
2161   }
2162
2163   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2164 }
2165
2166 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2167   if (N->getNumValues() != 1)
2168     return false;
2169   if (!N->hasNUsesOfValue(1, 0))
2170     return false;
2171
2172   SDValue TCChain = Chain;
2173   SDNode *Copy = *N->use_begin();
2174   if (Copy->getOpcode() == ISD::CopyToReg) {
2175     // If the copy has a glue operand, we conservatively assume it isn't safe to
2176     // perform a tail call.
2177     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2178       return false;
2179     TCChain = Copy->getOperand(0);
2180   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2181     SDNode *VMov = Copy;
2182     // f64 returned in a pair of GPRs.
2183     SmallPtrSet<SDNode*, 2> Copies;
2184     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2185          UI != UE; ++UI) {
2186       if (UI->getOpcode() != ISD::CopyToReg)
2187         return false;
2188       Copies.insert(*UI);
2189     }
2190     if (Copies.size() > 2)
2191       return false;
2192
2193     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2194          UI != UE; ++UI) {
2195       SDValue UseChain = UI->getOperand(0);
2196       if (Copies.count(UseChain.getNode()))
2197         // Second CopyToReg
2198         Copy = *UI;
2199       else
2200         // First CopyToReg
2201         TCChain = UseChain;
2202     }
2203   } else if (Copy->getOpcode() == ISD::BITCAST) {
2204     // f32 returned in a single GPR.
2205     if (!Copy->hasOneUse())
2206       return false;
2207     Copy = *Copy->use_begin();
2208     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2209       return false;
2210     TCChain = Copy->getOperand(0);
2211   } else {
2212     return false;
2213   }
2214
2215   bool HasRet = false;
2216   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2217        UI != UE; ++UI) {
2218     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2219         UI->getOpcode() != ARMISD::INTRET_FLAG)
2220       return false;
2221     HasRet = true;
2222   }
2223
2224   if (!HasRet)
2225     return false;
2226
2227   Chain = TCChain;
2228   return true;
2229 }
2230
2231 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2232   if (!Subtarget->supportsTailCall())
2233     return false;
2234
2235   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2236     return false;
2237
2238   return !Subtarget->isThumb1Only();
2239 }
2240
2241 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2242 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2243 // one of the above mentioned nodes. It has to be wrapped because otherwise
2244 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2245 // be used to form addressing mode. These wrapped nodes will be selected
2246 // into MOVi.
2247 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2248   EVT PtrVT = Op.getValueType();
2249   // FIXME there is no actual debug info here
2250   SDLoc dl(Op);
2251   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2252   SDValue Res;
2253   if (CP->isMachineConstantPoolEntry())
2254     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2255                                     CP->getAlignment());
2256   else
2257     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2258                                     CP->getAlignment());
2259   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2260 }
2261
2262 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2263   return MachineJumpTableInfo::EK_Inline;
2264 }
2265
2266 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2267                                              SelectionDAG &DAG) const {
2268   MachineFunction &MF = DAG.getMachineFunction();
2269   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2270   unsigned ARMPCLabelIndex = 0;
2271   SDLoc DL(Op);
2272   EVT PtrVT = getPointerTy();
2273   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2274   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2275   SDValue CPAddr;
2276   if (RelocM == Reloc::Static) {
2277     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2278   } else {
2279     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2280     ARMPCLabelIndex = AFI->createPICLabelUId();
2281     ARMConstantPoolValue *CPV =
2282       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2283                                       ARMCP::CPBlockAddress, PCAdj);
2284     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2285   }
2286   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2287   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2288                                MachinePointerInfo::getConstantPool(),
2289                                false, false, false, 0);
2290   if (RelocM == Reloc::Static)
2291     return Result;
2292   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2293   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2294 }
2295
2296 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2297 SDValue
2298 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2299                                                  SelectionDAG &DAG) const {
2300   SDLoc dl(GA);
2301   EVT PtrVT = getPointerTy();
2302   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2303   MachineFunction &MF = DAG.getMachineFunction();
2304   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2306   ARMConstantPoolValue *CPV =
2307     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2308                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2309   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2310   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2311   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2312                          MachinePointerInfo::getConstantPool(),
2313                          false, false, false, 0);
2314   SDValue Chain = Argument.getValue(1);
2315
2316   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2317   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2318
2319   // call __tls_get_addr.
2320   ArgListTy Args;
2321   ArgListEntry Entry;
2322   Entry.Node = Argument;
2323   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2324   Args.push_back(Entry);
2325
2326   // FIXME: is there useful debug info available here?
2327   TargetLowering::CallLoweringInfo CLI(DAG);
2328   CLI.setDebugLoc(dl).setChain(Chain)
2329     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2330                DAG.getExternalSymbol("__tls_get_addr", PtrVT), &Args, 0);
2331
2332   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2333   return CallResult.first;
2334 }
2335
2336 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2337 // "local exec" model.
2338 SDValue
2339 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2340                                         SelectionDAG &DAG,
2341                                         TLSModel::Model model) const {
2342   const GlobalValue *GV = GA->getGlobal();
2343   SDLoc dl(GA);
2344   SDValue Offset;
2345   SDValue Chain = DAG.getEntryNode();
2346   EVT PtrVT = getPointerTy();
2347   // Get the Thread Pointer
2348   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2349
2350   if (model == TLSModel::InitialExec) {
2351     MachineFunction &MF = DAG.getMachineFunction();
2352     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2353     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2354     // Initial exec model.
2355     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2356     ARMConstantPoolValue *CPV =
2357       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2358                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2359                                       true);
2360     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2361     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2362     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2363                          MachinePointerInfo::getConstantPool(),
2364                          false, false, false, 0);
2365     Chain = Offset.getValue(1);
2366
2367     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2368     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2369
2370     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2371                          MachinePointerInfo::getConstantPool(),
2372                          false, false, false, 0);
2373   } else {
2374     // local exec model
2375     assert(model == TLSModel::LocalExec);
2376     ARMConstantPoolValue *CPV =
2377       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2378     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2379     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2380     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2381                          MachinePointerInfo::getConstantPool(),
2382                          false, false, false, 0);
2383   }
2384
2385   // The address of the thread local variable is the add of the thread
2386   // pointer with the offset of the variable.
2387   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2388 }
2389
2390 SDValue
2391 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2392   // TODO: implement the "local dynamic" model
2393   assert(Subtarget->isTargetELF() &&
2394          "TLS not implemented for non-ELF targets");
2395   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2396
2397   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2398
2399   switch (model) {
2400     case TLSModel::GeneralDynamic:
2401     case TLSModel::LocalDynamic:
2402       return LowerToTLSGeneralDynamicModel(GA, DAG);
2403     case TLSModel::InitialExec:
2404     case TLSModel::LocalExec:
2405       return LowerToTLSExecModels(GA, DAG, model);
2406   }
2407   llvm_unreachable("bogus TLS model");
2408 }
2409
2410 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2411                                                  SelectionDAG &DAG) const {
2412   EVT PtrVT = getPointerTy();
2413   SDLoc dl(Op);
2414   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2415   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2416     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2417     ARMConstantPoolValue *CPV =
2418       ARMConstantPoolConstant::Create(GV,
2419                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2420     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2421     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2422     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2423                                  CPAddr,
2424                                  MachinePointerInfo::getConstantPool(),
2425                                  false, false, false, 0);
2426     SDValue Chain = Result.getValue(1);
2427     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2428     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2429     if (!UseGOTOFF)
2430       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2431                            MachinePointerInfo::getGOT(),
2432                            false, false, false, 0);
2433     return Result;
2434   }
2435
2436   // If we have T2 ops, we can materialize the address directly via movt/movw
2437   // pair. This is always cheaper.
2438   if (Subtarget->useMovt()) {
2439     ++NumMovwMovt;
2440     // FIXME: Once remat is capable of dealing with instructions with register
2441     // operands, expand this into two nodes.
2442     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2443                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2444   } else {
2445     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2446     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2447     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2448                        MachinePointerInfo::getConstantPool(),
2449                        false, false, false, 0);
2450   }
2451 }
2452
2453 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2454                                                     SelectionDAG &DAG) const {
2455   EVT PtrVT = getPointerTy();
2456   SDLoc dl(Op);
2457   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2458   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2459
2460   if (Subtarget->useMovt())
2461     ++NumMovwMovt;
2462
2463   // FIXME: Once remat is capable of dealing with instructions with register
2464   // operands, expand this into multiple nodes
2465   unsigned Wrapper =
2466       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2467
2468   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2469   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2470
2471   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2472     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2473                          MachinePointerInfo::getGOT(), false, false, false, 0);
2474   return Result;
2475 }
2476
2477 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2478                                                      SelectionDAG &DAG) const {
2479   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2480   assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2481
2482   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2483   EVT PtrVT = getPointerTy();
2484   SDLoc DL(Op);
2485
2486   ++NumMovwMovt;
2487
2488   // FIXME: Once remat is capable of dealing with instructions with register
2489   // operands, expand this into two nodes.
2490   return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2491                      DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2492 }
2493
2494 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2495                                                     SelectionDAG &DAG) const {
2496   assert(Subtarget->isTargetELF() &&
2497          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2498   MachineFunction &MF = DAG.getMachineFunction();
2499   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2500   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2501   EVT PtrVT = getPointerTy();
2502   SDLoc dl(Op);
2503   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2504   ARMConstantPoolValue *CPV =
2505     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2506                                   ARMPCLabelIndex, PCAdj);
2507   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2508   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2509   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2510                                MachinePointerInfo::getConstantPool(),
2511                                false, false, false, 0);
2512   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2513   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2514 }
2515
2516 SDValue
2517 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2518   SDLoc dl(Op);
2519   SDValue Val = DAG.getConstant(0, MVT::i32);
2520   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2521                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2522                      Op.getOperand(1), Val);
2523 }
2524
2525 SDValue
2526 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2527   SDLoc dl(Op);
2528   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2529                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2530 }
2531
2532 SDValue
2533 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2534                                           const ARMSubtarget *Subtarget) const {
2535   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2536   SDLoc dl(Op);
2537   switch (IntNo) {
2538   default: return SDValue();    // Don't custom lower most intrinsics.
2539   case Intrinsic::arm_thread_pointer: {
2540     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2541     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2542   }
2543   case Intrinsic::eh_sjlj_lsda: {
2544     MachineFunction &MF = DAG.getMachineFunction();
2545     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2546     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2547     EVT PtrVT = getPointerTy();
2548     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2549     SDValue CPAddr;
2550     unsigned PCAdj = (RelocM != Reloc::PIC_)
2551       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2552     ARMConstantPoolValue *CPV =
2553       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2554                                       ARMCP::CPLSDA, PCAdj);
2555     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2556     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2557     SDValue Result =
2558       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2559                   MachinePointerInfo::getConstantPool(),
2560                   false, false, false, 0);
2561
2562     if (RelocM == Reloc::PIC_) {
2563       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2564       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2565     }
2566     return Result;
2567   }
2568   case Intrinsic::arm_neon_vmulls:
2569   case Intrinsic::arm_neon_vmullu: {
2570     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2571       ? ARMISD::VMULLs : ARMISD::VMULLu;
2572     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2573                        Op.getOperand(1), Op.getOperand(2));
2574   }
2575   }
2576 }
2577
2578 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2579                                  const ARMSubtarget *Subtarget) {
2580   // FIXME: handle "fence singlethread" more efficiently.
2581   SDLoc dl(Op);
2582   if (!Subtarget->hasDataBarrier()) {
2583     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2584     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2585     // here.
2586     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2587            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2588     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2589                        DAG.getConstant(0, MVT::i32));
2590   }
2591
2592   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2593   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2594   unsigned Domain = ARM_MB::ISH;
2595   if (Subtarget->isMClass()) {
2596     // Only a full system barrier exists in the M-class architectures.
2597     Domain = ARM_MB::SY;
2598   } else if (Subtarget->isSwift() && Ord == Release) {
2599     // Swift happens to implement ISHST barriers in a way that's compatible with
2600     // Release semantics but weaker than ISH so we'd be fools not to use
2601     // it. Beware: other processors probably don't!
2602     Domain = ARM_MB::ISHST;
2603   }
2604
2605   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2606                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2607                      DAG.getConstant(Domain, MVT::i32));
2608 }
2609
2610 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2611                              const ARMSubtarget *Subtarget) {
2612   // ARM pre v5TE and Thumb1 does not have preload instructions.
2613   if (!(Subtarget->isThumb2() ||
2614         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2615     // Just preserve the chain.
2616     return Op.getOperand(0);
2617
2618   SDLoc dl(Op);
2619   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2620   if (!isRead &&
2621       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2622     // ARMv7 with MP extension has PLDW.
2623     return Op.getOperand(0);
2624
2625   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2626   if (Subtarget->isThumb()) {
2627     // Invert the bits.
2628     isRead = ~isRead & 1;
2629     isData = ~isData & 1;
2630   }
2631
2632   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2633                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2634                      DAG.getConstant(isData, MVT::i32));
2635 }
2636
2637 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2638   MachineFunction &MF = DAG.getMachineFunction();
2639   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2640
2641   // vastart just stores the address of the VarArgsFrameIndex slot into the
2642   // memory location argument.
2643   SDLoc dl(Op);
2644   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2645   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2646   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2647   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2648                       MachinePointerInfo(SV), false, false, 0);
2649 }
2650
2651 SDValue
2652 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2653                                         SDValue &Root, SelectionDAG &DAG,
2654                                         SDLoc dl) const {
2655   MachineFunction &MF = DAG.getMachineFunction();
2656   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2657
2658   const TargetRegisterClass *RC;
2659   if (AFI->isThumb1OnlyFunction())
2660     RC = &ARM::tGPRRegClass;
2661   else
2662     RC = &ARM::GPRRegClass;
2663
2664   // Transform the arguments stored in physical registers into virtual ones.
2665   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2666   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2667
2668   SDValue ArgValue2;
2669   if (NextVA.isMemLoc()) {
2670     MachineFrameInfo *MFI = MF.getFrameInfo();
2671     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2672
2673     // Create load node to retrieve arguments from the stack.
2674     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2675     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2676                             MachinePointerInfo::getFixedStack(FI),
2677                             false, false, false, 0);
2678   } else {
2679     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2680     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2681   }
2682   if (!Subtarget->isLittle())
2683     std::swap (ArgValue, ArgValue2);
2684   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2685 }
2686
2687 void
2688 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2689                                   unsigned InRegsParamRecordIdx,
2690                                   unsigned ArgSize,
2691                                   unsigned &ArgRegsSize,
2692                                   unsigned &ArgRegsSaveSize)
2693   const {
2694   unsigned NumGPRs;
2695   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2696     unsigned RBegin, REnd;
2697     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2698     NumGPRs = REnd - RBegin;
2699   } else {
2700     unsigned int firstUnalloced;
2701     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2702                                                 sizeof(GPRArgRegs) /
2703                                                 sizeof(GPRArgRegs[0]));
2704     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2705   }
2706
2707   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2708   ArgRegsSize = NumGPRs * 4;
2709
2710   // If parameter is split between stack and GPRs...
2711   if (NumGPRs && Align > 4 &&
2712       (ArgRegsSize < ArgSize ||
2713         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2714     // Add padding for part of param recovered from GPRs.  For example,
2715     // if Align == 8, its last byte must be at address K*8 - 1.
2716     // We need to do it, since remained (stack) part of parameter has
2717     // stack alignment, and we need to "attach" "GPRs head" without gaps
2718     // to it:
2719     // Stack:
2720     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2721     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2722     //
2723     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2724     unsigned Padding =
2725         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2726     ArgRegsSaveSize = ArgRegsSize + Padding;
2727   } else
2728     // We don't need to extend regs save size for byval parameters if they
2729     // are passed via GPRs only.
2730     ArgRegsSaveSize = ArgRegsSize;
2731 }
2732
2733 // The remaining GPRs hold either the beginning of variable-argument
2734 // data, or the beginning of an aggregate passed by value (usually
2735 // byval).  Either way, we allocate stack slots adjacent to the data
2736 // provided by our caller, and store the unallocated registers there.
2737 // If this is a variadic function, the va_list pointer will begin with
2738 // these values; otherwise, this reassembles a (byval) structure that
2739 // was split between registers and memory.
2740 // Return: The frame index registers were stored into.
2741 int
2742 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2743                                   SDLoc dl, SDValue &Chain,
2744                                   const Value *OrigArg,
2745                                   unsigned InRegsParamRecordIdx,
2746                                   unsigned OffsetFromOrigArg,
2747                                   unsigned ArgOffset,
2748                                   unsigned ArgSize,
2749                                   bool ForceMutable,
2750                                   unsigned ByValStoreOffset,
2751                                   unsigned TotalArgRegsSaveSize) const {
2752
2753   // Currently, two use-cases possible:
2754   // Case #1. Non-var-args function, and we meet first byval parameter.
2755   //          Setup first unallocated register as first byval register;
2756   //          eat all remained registers
2757   //          (these two actions are performed by HandleByVal method).
2758   //          Then, here, we initialize stack frame with
2759   //          "store-reg" instructions.
2760   // Case #2. Var-args function, that doesn't contain byval parameters.
2761   //          The same: eat all remained unallocated registers,
2762   //          initialize stack frame.
2763
2764   MachineFunction &MF = DAG.getMachineFunction();
2765   MachineFrameInfo *MFI = MF.getFrameInfo();
2766   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2767   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2768   unsigned RBegin, REnd;
2769   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2770     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2771     firstRegToSaveIndex = RBegin - ARM::R0;
2772     lastRegToSaveIndex = REnd - ARM::R0;
2773   } else {
2774     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2775       (GPRArgRegs, array_lengthof(GPRArgRegs));
2776     lastRegToSaveIndex = 4;
2777   }
2778
2779   unsigned ArgRegsSize, ArgRegsSaveSize;
2780   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2781                  ArgRegsSize, ArgRegsSaveSize);
2782
2783   // Store any by-val regs to their spots on the stack so that they may be
2784   // loaded by deferencing the result of formal parameter pointer or va_next.
2785   // Note: once stack area for byval/varargs registers
2786   // was initialized, it can't be initialized again.
2787   if (ArgRegsSaveSize) {
2788     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2789
2790     if (Padding) {
2791       assert(AFI->getStoredByValParamsPadding() == 0 &&
2792              "The only parameter may be padded.");
2793       AFI->setStoredByValParamsPadding(Padding);
2794     }
2795
2796     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2797                                             Padding +
2798                                               ByValStoreOffset -
2799                                               (int64_t)TotalArgRegsSaveSize,
2800                                             false);
2801     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2802     if (Padding) {
2803        MFI->CreateFixedObject(Padding,
2804                               ArgOffset + ByValStoreOffset -
2805                                 (int64_t)ArgRegsSaveSize,
2806                               false);
2807     }
2808
2809     SmallVector<SDValue, 4> MemOps;
2810     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2811          ++firstRegToSaveIndex, ++i) {
2812       const TargetRegisterClass *RC;
2813       if (AFI->isThumb1OnlyFunction())
2814         RC = &ARM::tGPRRegClass;
2815       else
2816         RC = &ARM::GPRRegClass;
2817
2818       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2819       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2820       SDValue Store =
2821         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2822                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2823                      false, false, 0);
2824       MemOps.push_back(Store);
2825       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2826                         DAG.getConstant(4, getPointerTy()));
2827     }
2828
2829     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2830
2831     if (!MemOps.empty())
2832       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2833     return FrameIndex;
2834   } else {
2835     if (ArgSize == 0) {
2836       // We cannot allocate a zero-byte object for the first variadic argument,
2837       // so just make up a size.
2838       ArgSize = 4;
2839     }
2840     // This will point to the next argument passed via stack.
2841     return MFI->CreateFixedObject(
2842       ArgSize, ArgOffset, !ForceMutable);
2843   }
2844 }
2845
2846 // Setup stack frame, the va_list pointer will start from.
2847 void
2848 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2849                                         SDLoc dl, SDValue &Chain,
2850                                         unsigned ArgOffset,
2851                                         unsigned TotalArgRegsSaveSize,
2852                                         bool ForceMutable) const {
2853   MachineFunction &MF = DAG.getMachineFunction();
2854   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2855
2856   // Try to store any remaining integer argument regs
2857   // to their spots on the stack so that they may be loaded by deferencing
2858   // the result of va_next.
2859   // If there is no regs to be stored, just point address after last
2860   // argument passed via stack.
2861   int FrameIndex =
2862     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2863                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2864                    0, TotalArgRegsSaveSize);
2865
2866   AFI->setVarArgsFrameIndex(FrameIndex);
2867 }
2868
2869 SDValue
2870 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2871                                         CallingConv::ID CallConv, bool isVarArg,
2872                                         const SmallVectorImpl<ISD::InputArg>
2873                                           &Ins,
2874                                         SDLoc dl, SelectionDAG &DAG,
2875                                         SmallVectorImpl<SDValue> &InVals)
2876                                           const {
2877   MachineFunction &MF = DAG.getMachineFunction();
2878   MachineFrameInfo *MFI = MF.getFrameInfo();
2879
2880   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2881
2882   // Assign locations to all of the incoming arguments.
2883   SmallVector<CCValAssign, 16> ArgLocs;
2884   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2885                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2886   CCInfo.AnalyzeFormalArguments(Ins,
2887                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2888                                                   isVarArg));
2889
2890   SmallVector<SDValue, 16> ArgValues;
2891   int lastInsIndex = -1;
2892   SDValue ArgValue;
2893   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2894   unsigned CurArgIdx = 0;
2895
2896   // Initially ArgRegsSaveSize is zero.
2897   // Then we increase this value each time we meet byval parameter.
2898   // We also increase this value in case of varargs function.
2899   AFI->setArgRegsSaveSize(0);
2900
2901   unsigned ByValStoreOffset = 0;
2902   unsigned TotalArgRegsSaveSize = 0;
2903   unsigned ArgRegsSaveSizeMaxAlign = 4;
2904
2905   // Calculate the amount of stack space that we need to allocate to store
2906   // byval and variadic arguments that are passed in registers.
2907   // We need to know this before we allocate the first byval or variadic
2908   // argument, as they will be allocated a stack slot below the CFA (Canonical
2909   // Frame Address, the stack pointer at entry to the function).
2910   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2911     CCValAssign &VA = ArgLocs[i];
2912     if (VA.isMemLoc()) {
2913       int index = VA.getValNo();
2914       if (index != lastInsIndex) {
2915         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2916         if (Flags.isByVal()) {
2917           unsigned ExtraArgRegsSize;
2918           unsigned ExtraArgRegsSaveSize;
2919           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2920                          Flags.getByValSize(),
2921                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2922
2923           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2924           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2925               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2926           CCInfo.nextInRegsParam();
2927         }
2928         lastInsIndex = index;
2929       }
2930     }
2931   }
2932   CCInfo.rewindByValRegsInfo();
2933   lastInsIndex = -1;
2934   if (isVarArg) {
2935     unsigned ExtraArgRegsSize;
2936     unsigned ExtraArgRegsSaveSize;
2937     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2938                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2939     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2940   }
2941   // If the arg regs save area contains N-byte aligned values, the
2942   // bottom of it must be at least N-byte aligned.
2943   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2944   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2945
2946   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2947     CCValAssign &VA = ArgLocs[i];
2948     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2949     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2950     // Arguments stored in registers.
2951     if (VA.isRegLoc()) {
2952       EVT RegVT = VA.getLocVT();
2953
2954       if (VA.needsCustom()) {
2955         // f64 and vector types are split up into multiple registers or
2956         // combinations of registers and stack slots.
2957         if (VA.getLocVT() == MVT::v2f64) {
2958           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2959                                                    Chain, DAG, dl);
2960           VA = ArgLocs[++i]; // skip ahead to next loc
2961           SDValue ArgValue2;
2962           if (VA.isMemLoc()) {
2963             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2964             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2965             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2966                                     MachinePointerInfo::getFixedStack(FI),
2967                                     false, false, false, 0);
2968           } else {
2969             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2970                                              Chain, DAG, dl);
2971           }
2972           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2973           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2974                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2975           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2976                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2977         } else
2978           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2979
2980       } else {
2981         const TargetRegisterClass *RC;
2982
2983         if (RegVT == MVT::f32)
2984           RC = &ARM::SPRRegClass;
2985         else if (RegVT == MVT::f64)
2986           RC = &ARM::DPRRegClass;
2987         else if (RegVT == MVT::v2f64)
2988           RC = &ARM::QPRRegClass;
2989         else if (RegVT == MVT::i32)
2990           RC = AFI->isThumb1OnlyFunction() ?
2991             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2992             (const TargetRegisterClass*)&ARM::GPRRegClass;
2993         else
2994           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2995
2996         // Transform the arguments in physical registers into virtual ones.
2997         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2998         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2999       }
3000
3001       // If this is an 8 or 16-bit value, it is really passed promoted
3002       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3003       // truncate to the right size.
3004       switch (VA.getLocInfo()) {
3005       default: llvm_unreachable("Unknown loc info!");
3006       case CCValAssign::Full: break;
3007       case CCValAssign::BCvt:
3008         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3009         break;
3010       case CCValAssign::SExt:
3011         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3012                                DAG.getValueType(VA.getValVT()));
3013         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3014         break;
3015       case CCValAssign::ZExt:
3016         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3017                                DAG.getValueType(VA.getValVT()));
3018         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3019         break;
3020       }
3021
3022       InVals.push_back(ArgValue);
3023
3024     } else { // VA.isRegLoc()
3025
3026       // sanity check
3027       assert(VA.isMemLoc());
3028       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3029
3030       int index = ArgLocs[i].getValNo();
3031
3032       // Some Ins[] entries become multiple ArgLoc[] entries.
3033       // Process them only once.
3034       if (index != lastInsIndex)
3035         {
3036           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3037           // FIXME: For now, all byval parameter objects are marked mutable.
3038           // This can be changed with more analysis.
3039           // In case of tail call optimization mark all arguments mutable.
3040           // Since they could be overwritten by lowering of arguments in case of
3041           // a tail call.
3042           if (Flags.isByVal()) {
3043             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3044
3045             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3046             int FrameIndex = StoreByValRegs(
3047                 CCInfo, DAG, dl, Chain, CurOrigArg,
3048                 CurByValIndex,
3049                 Ins[VA.getValNo()].PartOffset,
3050                 VA.getLocMemOffset(),
3051                 Flags.getByValSize(),
3052                 true /*force mutable frames*/,
3053                 ByValStoreOffset,
3054                 TotalArgRegsSaveSize);
3055             ByValStoreOffset += Flags.getByValSize();
3056             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3057             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3058             CCInfo.nextInRegsParam();
3059           } else {
3060             unsigned FIOffset = VA.getLocMemOffset();
3061             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3062                                             FIOffset, true);
3063
3064             // Create load nodes to retrieve arguments from the stack.
3065             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3066             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3067                                          MachinePointerInfo::getFixedStack(FI),
3068                                          false, false, false, 0));
3069           }
3070           lastInsIndex = index;
3071         }
3072     }
3073   }
3074
3075   // varargs
3076   if (isVarArg)
3077     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3078                          CCInfo.getNextStackOffset(),
3079                          TotalArgRegsSaveSize);
3080
3081   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3082
3083   return Chain;
3084 }
3085
3086 /// isFloatingPointZero - Return true if this is +0.0.
3087 static bool isFloatingPointZero(SDValue Op) {
3088   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3089     return CFP->getValueAPF().isPosZero();
3090   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3091     // Maybe this has already been legalized into the constant pool?
3092     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3093       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3094       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3095         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3096           return CFP->getValueAPF().isPosZero();
3097     }
3098   }
3099   return false;
3100 }
3101
3102 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3103 /// the given operands.
3104 SDValue
3105 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3106                              SDValue &ARMcc, SelectionDAG &DAG,
3107                              SDLoc dl) const {
3108   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3109     unsigned C = RHSC->getZExtValue();
3110     if (!isLegalICmpImmediate(C)) {
3111       // Constant does not fit, try adjusting it by one?
3112       switch (CC) {
3113       default: break;
3114       case ISD::SETLT:
3115       case ISD::SETGE:
3116         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3117           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3118           RHS = DAG.getConstant(C-1, MVT::i32);
3119         }
3120         break;
3121       case ISD::SETULT:
3122       case ISD::SETUGE:
3123         if (C != 0 && isLegalICmpImmediate(C-1)) {
3124           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3125           RHS = DAG.getConstant(C-1, MVT::i32);
3126         }
3127         break;
3128       case ISD::SETLE:
3129       case ISD::SETGT:
3130         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3131           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3132           RHS = DAG.getConstant(C+1, MVT::i32);
3133         }
3134         break;
3135       case ISD::SETULE:
3136       case ISD::SETUGT:
3137         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3138           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3139           RHS = DAG.getConstant(C+1, MVT::i32);
3140         }
3141         break;
3142       }
3143     }
3144   }
3145
3146   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3147   ARMISD::NodeType CompareType;
3148   switch (CondCode) {
3149   default:
3150     CompareType = ARMISD::CMP;
3151     break;
3152   case ARMCC::EQ:
3153   case ARMCC::NE:
3154     // Uses only Z Flag
3155     CompareType = ARMISD::CMPZ;
3156     break;
3157   }
3158   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3159   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3160 }
3161
3162 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3163 SDValue
3164 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3165                              SDLoc dl) const {
3166   SDValue Cmp;
3167   if (!isFloatingPointZero(RHS))
3168     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3169   else
3170     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3171   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3172 }
3173
3174 /// duplicateCmp - Glue values can have only one use, so this function
3175 /// duplicates a comparison node.
3176 SDValue
3177 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3178   unsigned Opc = Cmp.getOpcode();
3179   SDLoc DL(Cmp);
3180   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3181     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3182
3183   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3184   Cmp = Cmp.getOperand(0);
3185   Opc = Cmp.getOpcode();
3186   if (Opc == ARMISD::CMPFP)
3187     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3188   else {
3189     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3190     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3191   }
3192   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3193 }
3194
3195 std::pair<SDValue, SDValue>
3196 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3197                                  SDValue &ARMcc) const {
3198   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3199
3200   SDValue Value, OverflowCmp;
3201   SDValue LHS = Op.getOperand(0);
3202   SDValue RHS = Op.getOperand(1);
3203
3204
3205   // FIXME: We are currently always generating CMPs because we don't support
3206   // generating CMN through the backend. This is not as good as the natural
3207   // CMP case because it causes a register dependency and cannot be folded
3208   // later.
3209
3210   switch (Op.getOpcode()) {
3211   default:
3212     llvm_unreachable("Unknown overflow instruction!");
3213   case ISD::SADDO:
3214     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3215     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3216     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3217     break;
3218   case ISD::UADDO:
3219     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3220     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3221     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3222     break;
3223   case ISD::SSUBO:
3224     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3225     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3226     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3227     break;
3228   case ISD::USUBO:
3229     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3230     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3231     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3232     break;
3233   } // switch (...)
3234
3235   return std::make_pair(Value, OverflowCmp);
3236 }
3237
3238
3239 SDValue
3240 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3241   // Let legalize expand this if it isn't a legal type yet.
3242   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3243     return SDValue();
3244
3245   SDValue Value, OverflowCmp;
3246   SDValue ARMcc;
3247   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3248   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3249   // We use 0 and 1 as false and true values.
3250   SDValue TVal = DAG.getConstant(1, MVT::i32);
3251   SDValue FVal = DAG.getConstant(0, MVT::i32);
3252   EVT VT = Op.getValueType();
3253
3254   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3255                                  ARMcc, CCR, OverflowCmp);
3256
3257   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3258   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3259 }
3260
3261
3262 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3263   SDValue Cond = Op.getOperand(0);
3264   SDValue SelectTrue = Op.getOperand(1);
3265   SDValue SelectFalse = Op.getOperand(2);
3266   SDLoc dl(Op);
3267   unsigned Opc = Cond.getOpcode();
3268
3269   if (Cond.getResNo() == 1 &&
3270       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3271        Opc == ISD::USUBO)) {
3272     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3273       return SDValue();
3274
3275     SDValue Value, OverflowCmp;
3276     SDValue ARMcc;
3277     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3278     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3279     EVT VT = Op.getValueType();
3280
3281     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3282                        ARMcc, CCR, OverflowCmp);
3283
3284   }
3285
3286   // Convert:
3287   //
3288   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3289   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3290   //
3291   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3292     const ConstantSDNode *CMOVTrue =
3293       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3294     const ConstantSDNode *CMOVFalse =
3295       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3296
3297     if (CMOVTrue && CMOVFalse) {
3298       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3299       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3300
3301       SDValue True;
3302       SDValue False;
3303       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3304         True = SelectTrue;
3305         False = SelectFalse;
3306       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3307         True = SelectFalse;
3308         False = SelectTrue;
3309       }
3310
3311       if (True.getNode() && False.getNode()) {
3312         EVT VT = Op.getValueType();
3313         SDValue ARMcc = Cond.getOperand(2);
3314         SDValue CCR = Cond.getOperand(3);
3315         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3316         assert(True.getValueType() == VT);
3317         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3318       }
3319     }
3320   }
3321
3322   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3323   // undefined bits before doing a full-word comparison with zero.
3324   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3325                      DAG.getConstant(1, Cond.getValueType()));
3326
3327   return DAG.getSelectCC(dl, Cond,
3328                          DAG.getConstant(0, Cond.getValueType()),
3329                          SelectTrue, SelectFalse, ISD::SETNE);
3330 }
3331
3332 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3333   if (CC == ISD::SETNE)
3334     return ISD::SETEQ;
3335   return ISD::getSetCCInverse(CC, true);
3336 }
3337
3338 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3339                                  bool &swpCmpOps, bool &swpVselOps) {
3340   // Start by selecting the GE condition code for opcodes that return true for
3341   // 'equality'
3342   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3343       CC == ISD::SETULE)
3344     CondCode = ARMCC::GE;
3345
3346   // and GT for opcodes that return false for 'equality'.
3347   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3348            CC == ISD::SETULT)
3349     CondCode = ARMCC::GT;
3350
3351   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3352   // to swap the compare operands.
3353   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3354       CC == ISD::SETULT)
3355     swpCmpOps = true;
3356
3357   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3358   // If we have an unordered opcode, we need to swap the operands to the VSEL
3359   // instruction (effectively negating the condition).
3360   //
3361   // This also has the effect of swapping which one of 'less' or 'greater'
3362   // returns true, so we also swap the compare operands. It also switches
3363   // whether we return true for 'equality', so we compensate by picking the
3364   // opposite condition code to our original choice.
3365   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3366       CC == ISD::SETUGT) {
3367     swpCmpOps = !swpCmpOps;
3368     swpVselOps = !swpVselOps;
3369     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3370   }
3371
3372   // 'ordered' is 'anything but unordered', so use the VS condition code and
3373   // swap the VSEL operands.
3374   if (CC == ISD::SETO) {
3375     CondCode = ARMCC::VS;
3376     swpVselOps = true;
3377   }
3378
3379   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3380   // code and swap the VSEL operands.
3381   if (CC == ISD::SETUNE) {
3382     CondCode = ARMCC::EQ;
3383     swpVselOps = true;
3384   }
3385 }
3386
3387 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3388   EVT VT = Op.getValueType();
3389   SDValue LHS = Op.getOperand(0);
3390   SDValue RHS = Op.getOperand(1);
3391   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3392   SDValue TrueVal = Op.getOperand(2);
3393   SDValue FalseVal = Op.getOperand(3);
3394   SDLoc dl(Op);
3395
3396   if (LHS.getValueType() == MVT::i32) {
3397     // Try to generate VSEL on ARMv8.
3398     // The VSEL instruction can't use all the usual ARM condition
3399     // codes: it only has two bits to select the condition code, so it's
3400     // constrained to use only GE, GT, VS and EQ.
3401     //
3402     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3403     // swap the operands of the previous compare instruction (effectively
3404     // inverting the compare condition, swapping 'less' and 'greater') and
3405     // sometimes need to swap the operands to the VSEL (which inverts the
3406     // condition in the sense of firing whenever the previous condition didn't)
3407     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3408                                       TrueVal.getValueType() == MVT::f64)) {
3409       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3410       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3411           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3412         CC = getInverseCCForVSEL(CC);
3413         std::swap(TrueVal, FalseVal);
3414       }
3415     }
3416
3417     SDValue ARMcc;
3418     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3419     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3420     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3421                        Cmp);
3422   }
3423
3424   ARMCC::CondCodes CondCode, CondCode2;
3425   FPCCToARMCC(CC, CondCode, CondCode2);
3426
3427   // Try to generate VSEL on ARMv8.
3428   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3429                                     TrueVal.getValueType() == MVT::f64)) {
3430     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3431     // same operands, as follows:
3432     //   c = fcmp [ogt, olt, ugt, ult] a, b
3433     //   select c, a, b
3434     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3435     // handled differently than the original code sequence.
3436     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3437         RHS == FalseVal) {
3438       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3439         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3440       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3441         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3442     }
3443
3444     bool swpCmpOps = false;
3445     bool swpVselOps = false;
3446     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3447
3448     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3449         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3450       if (swpCmpOps)
3451         std::swap(LHS, RHS);
3452       if (swpVselOps)
3453         std::swap(TrueVal, FalseVal);
3454     }
3455   }
3456
3457   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3458   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3459   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3460   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3461                                ARMcc, CCR, Cmp);
3462   if (CondCode2 != ARMCC::AL) {
3463     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3464     // FIXME: Needs another CMP because flag can have but one use.
3465     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3466     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3467                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3468   }
3469   return Result;
3470 }
3471
3472 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3473 /// to morph to an integer compare sequence.
3474 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3475                            const ARMSubtarget *Subtarget) {
3476   SDNode *N = Op.getNode();
3477   if (!N->hasOneUse())
3478     // Otherwise it requires moving the value from fp to integer registers.
3479     return false;
3480   if (!N->getNumValues())
3481     return false;
3482   EVT VT = Op.getValueType();
3483   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3484     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3485     // vmrs are very slow, e.g. cortex-a8.
3486     return false;
3487
3488   if (isFloatingPointZero(Op)) {
3489     SeenZero = true;
3490     return true;
3491   }
3492   return ISD::isNormalLoad(N);
3493 }
3494
3495 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3496   if (isFloatingPointZero(Op))
3497     return DAG.getConstant(0, MVT::i32);
3498
3499   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3500     return DAG.getLoad(MVT::i32, SDLoc(Op),
3501                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3502                        Ld->isVolatile(), Ld->isNonTemporal(),
3503                        Ld->isInvariant(), Ld->getAlignment());
3504
3505   llvm_unreachable("Unknown VFP cmp argument!");
3506 }
3507
3508 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3509                            SDValue &RetVal1, SDValue &RetVal2) {
3510   if (isFloatingPointZero(Op)) {
3511     RetVal1 = DAG.getConstant(0, MVT::i32);
3512     RetVal2 = DAG.getConstant(0, MVT::i32);
3513     return;
3514   }
3515
3516   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3517     SDValue Ptr = Ld->getBasePtr();
3518     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3519                           Ld->getChain(), Ptr,
3520                           Ld->getPointerInfo(),
3521                           Ld->isVolatile(), Ld->isNonTemporal(),
3522                           Ld->isInvariant(), Ld->getAlignment());
3523
3524     EVT PtrType = Ptr.getValueType();
3525     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3526     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3527                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3528     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3529                           Ld->getChain(), NewPtr,
3530                           Ld->getPointerInfo().getWithOffset(4),
3531                           Ld->isVolatile(), Ld->isNonTemporal(),
3532                           Ld->isInvariant(), NewAlign);
3533     return;
3534   }
3535
3536   llvm_unreachable("Unknown VFP cmp argument!");
3537 }
3538
3539 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3540 /// f32 and even f64 comparisons to integer ones.
3541 SDValue
3542 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3543   SDValue Chain = Op.getOperand(0);
3544   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3545   SDValue LHS = Op.getOperand(2);
3546   SDValue RHS = Op.getOperand(3);
3547   SDValue Dest = Op.getOperand(4);
3548   SDLoc dl(Op);
3549
3550   bool LHSSeenZero = false;
3551   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3552   bool RHSSeenZero = false;
3553   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3554   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3555     // If unsafe fp math optimization is enabled and there are no other uses of
3556     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3557     // to an integer comparison.
3558     if (CC == ISD::SETOEQ)
3559       CC = ISD::SETEQ;
3560     else if (CC == ISD::SETUNE)
3561       CC = ISD::SETNE;
3562
3563     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3564     SDValue ARMcc;
3565     if (LHS.getValueType() == MVT::f32) {
3566       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3567                         bitcastf32Toi32(LHS, DAG), Mask);
3568       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3569                         bitcastf32Toi32(RHS, DAG), Mask);
3570       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3571       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3572       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3573                          Chain, Dest, ARMcc, CCR, Cmp);
3574     }
3575
3576     SDValue LHS1, LHS2;
3577     SDValue RHS1, RHS2;
3578     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3579     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3580     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3581     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3582     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3583     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3584     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3585     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3586     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3587   }
3588
3589   return SDValue();
3590 }
3591
3592 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3593   SDValue Chain = Op.getOperand(0);
3594   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3595   SDValue LHS = Op.getOperand(2);
3596   SDValue RHS = Op.getOperand(3);
3597   SDValue Dest = Op.getOperand(4);
3598   SDLoc dl(Op);
3599
3600   if (LHS.getValueType() == MVT::i32) {
3601     SDValue ARMcc;
3602     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3603     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3604     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3605                        Chain, Dest, ARMcc, CCR, Cmp);
3606   }
3607
3608   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3609
3610   if (getTargetMachine().Options.UnsafeFPMath &&
3611       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3612        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3613     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3614     if (Result.getNode())
3615       return Result;
3616   }
3617
3618   ARMCC::CondCodes CondCode, CondCode2;
3619   FPCCToARMCC(CC, CondCode, CondCode2);
3620
3621   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3622   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3623   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3624   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3625   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3626   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3627   if (CondCode2 != ARMCC::AL) {
3628     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3629     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3630     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3631   }
3632   return Res;
3633 }
3634
3635 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3636   SDValue Chain = Op.getOperand(0);
3637   SDValue Table = Op.getOperand(1);
3638   SDValue Index = Op.getOperand(2);
3639   SDLoc dl(Op);
3640
3641   EVT PTy = getPointerTy();
3642   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3643   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3644   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3645   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3646   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3647   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3648   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3649   if (Subtarget->isThumb2()) {
3650     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3651     // which does another jump to the destination. This also makes it easier
3652     // to translate it to TBB / TBH later.
3653     // FIXME: This might not work if the function is extremely large.
3654     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3655                        Addr, Op.getOperand(2), JTI, UId);
3656   }
3657   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3658     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3659                        MachinePointerInfo::getJumpTable(),
3660                        false, false, false, 0);
3661     Chain = Addr.getValue(1);
3662     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3663     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3664   } else {
3665     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3666                        MachinePointerInfo::getJumpTable(),
3667                        false, false, false, 0);
3668     Chain = Addr.getValue(1);
3669     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3670   }
3671 }
3672
3673 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3674   EVT VT = Op.getValueType();
3675   SDLoc dl(Op);
3676
3677   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3678     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3679       return Op;
3680     return DAG.UnrollVectorOp(Op.getNode());
3681   }
3682
3683   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3684          "Invalid type for custom lowering!");
3685   if (VT != MVT::v4i16)
3686     return DAG.UnrollVectorOp(Op.getNode());
3687
3688   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3689   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3690 }
3691
3692 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3693   EVT VT = Op.getValueType();
3694   if (VT.isVector())
3695     return LowerVectorFP_TO_INT(Op, DAG);
3696
3697   SDLoc dl(Op);
3698   unsigned Opc;
3699
3700   switch (Op.getOpcode()) {
3701   default: llvm_unreachable("Invalid opcode!");
3702   case ISD::FP_TO_SINT:
3703     Opc = ARMISD::FTOSI;
3704     break;
3705   case ISD::FP_TO_UINT:
3706     Opc = ARMISD::FTOUI;
3707     break;
3708   }
3709   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3710   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3711 }
3712
3713 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3714   EVT VT = Op.getValueType();
3715   SDLoc dl(Op);
3716
3717   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3718     if (VT.getVectorElementType() == MVT::f32)
3719       return Op;
3720     return DAG.UnrollVectorOp(Op.getNode());
3721   }
3722
3723   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3724          "Invalid type for custom lowering!");
3725   if (VT != MVT::v4f32)
3726     return DAG.UnrollVectorOp(Op.getNode());
3727
3728   unsigned CastOpc;
3729   unsigned Opc;
3730   switch (Op.getOpcode()) {
3731   default: llvm_unreachable("Invalid opcode!");
3732   case ISD::SINT_TO_FP:
3733     CastOpc = ISD::SIGN_EXTEND;
3734     Opc = ISD::SINT_TO_FP;
3735     break;
3736   case ISD::UINT_TO_FP:
3737     CastOpc = ISD::ZERO_EXTEND;
3738     Opc = ISD::UINT_TO_FP;
3739     break;
3740   }
3741
3742   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3743   return DAG.getNode(Opc, dl, VT, Op);
3744 }
3745
3746 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3747   EVT VT = Op.getValueType();
3748   if (VT.isVector())
3749     return LowerVectorINT_TO_FP(Op, DAG);
3750
3751   SDLoc dl(Op);
3752   unsigned Opc;
3753
3754   switch (Op.getOpcode()) {
3755   default: llvm_unreachable("Invalid opcode!");
3756   case ISD::SINT_TO_FP:
3757     Opc = ARMISD::SITOF;
3758     break;
3759   case ISD::UINT_TO_FP:
3760     Opc = ARMISD::UITOF;
3761     break;
3762   }
3763
3764   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3765   return DAG.getNode(Opc, dl, VT, Op);
3766 }
3767
3768 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3769   // Implement fcopysign with a fabs and a conditional fneg.
3770   SDValue Tmp0 = Op.getOperand(0);
3771   SDValue Tmp1 = Op.getOperand(1);
3772   SDLoc dl(Op);
3773   EVT VT = Op.getValueType();
3774   EVT SrcVT = Tmp1.getValueType();
3775   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3776     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3777   bool UseNEON = !InGPR && Subtarget->hasNEON();
3778
3779   if (UseNEON) {
3780     // Use VBSL to copy the sign bit.
3781     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3782     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3783                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3784     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3785     if (VT == MVT::f64)
3786       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3787                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3788                          DAG.getConstant(32, MVT::i32));
3789     else /*if (VT == MVT::f32)*/
3790       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3791     if (SrcVT == MVT::f32) {
3792       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3793       if (VT == MVT::f64)
3794         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3795                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3796                            DAG.getConstant(32, MVT::i32));
3797     } else if (VT == MVT::f32)
3798       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3799                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3800                          DAG.getConstant(32, MVT::i32));
3801     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3802     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3803
3804     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3805                                             MVT::i32);
3806     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3807     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3808                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3809
3810     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3811                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3812                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3813     if (VT == MVT::f32) {
3814       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3815       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3816                         DAG.getConstant(0, MVT::i32));
3817     } else {
3818       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3819     }
3820
3821     return Res;
3822   }
3823
3824   // Bitcast operand 1 to i32.
3825   if (SrcVT == MVT::f64)
3826     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3827                        Tmp1).getValue(1);
3828   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3829
3830   // Or in the signbit with integer operations.
3831   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3832   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3833   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3834   if (VT == MVT::f32) {
3835     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3836                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3837     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3838                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3839   }
3840
3841   // f64: Or the high part with signbit and then combine two parts.
3842   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3843                      Tmp0);
3844   SDValue Lo = Tmp0.getValue(0);
3845   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3846   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3847   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3848 }
3849
3850 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3851   MachineFunction &MF = DAG.getMachineFunction();
3852   MachineFrameInfo *MFI = MF.getFrameInfo();
3853   MFI->setReturnAddressIsTaken(true);
3854
3855   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3856     return SDValue();
3857
3858   EVT VT = Op.getValueType();
3859   SDLoc dl(Op);
3860   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3861   if (Depth) {
3862     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3863     SDValue Offset = DAG.getConstant(4, MVT::i32);
3864     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3865                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3866                        MachinePointerInfo(), false, false, false, 0);
3867   }
3868
3869   // Return LR, which contains the return address. Mark it an implicit live-in.
3870   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3871   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3872 }
3873
3874 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3875   const ARMBaseRegisterInfo &ARI =
3876     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3877   MachineFunction &MF = DAG.getMachineFunction();
3878   MachineFrameInfo *MFI = MF.getFrameInfo();
3879   MFI->setFrameAddressIsTaken(true);
3880
3881   EVT VT = Op.getValueType();
3882   SDLoc dl(Op);  // FIXME probably not meaningful
3883   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3884   unsigned FrameReg = ARI.getFrameRegister(MF);
3885   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3886   while (Depth--)
3887     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3888                             MachinePointerInfo(),
3889                             false, false, false, 0);
3890   return FrameAddr;
3891 }
3892
3893 // FIXME? Maybe this could be a TableGen attribute on some registers and
3894 // this table could be generated automatically from RegInfo.
3895 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3896                                               EVT VT) const {
3897   unsigned Reg = StringSwitch<unsigned>(RegName)
3898                        .Case("sp", ARM::SP)
3899                        .Default(0);
3900   if (Reg)
3901     return Reg;
3902   report_fatal_error("Invalid register name global variable");
3903 }
3904
3905 /// ExpandBITCAST - If the target supports VFP, this function is called to
3906 /// expand a bit convert where either the source or destination type is i64 to
3907 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3908 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3909 /// vectors), since the legalizer won't know what to do with that.
3910 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3912   SDLoc dl(N);
3913   SDValue Op = N->getOperand(0);
3914
3915   // This function is only supposed to be called for i64 types, either as the
3916   // source or destination of the bit convert.
3917   EVT SrcVT = Op.getValueType();
3918   EVT DstVT = N->getValueType(0);
3919   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3920          "ExpandBITCAST called for non-i64 type");
3921
3922   // Turn i64->f64 into VMOVDRR.
3923   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3924     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3925                              DAG.getConstant(0, MVT::i32));
3926     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3927                              DAG.getConstant(1, MVT::i32));
3928     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3929                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3930   }
3931
3932   // Turn f64->i64 into VMOVRRD.
3933   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3934     SDValue Cvt;
3935     if (TLI.isBigEndian() && SrcVT.isVector() &&
3936         SrcVT.getVectorNumElements() > 1)
3937       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3938                         DAG.getVTList(MVT::i32, MVT::i32),
3939                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3940     else
3941       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3942                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3943     // Merge the pieces into a single i64 value.
3944     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3945   }
3946
3947   return SDValue();
3948 }
3949
3950 /// getZeroVector - Returns a vector of specified type with all zero elements.
3951 /// Zero vectors are used to represent vector negation and in those cases
3952 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3953 /// not support i64 elements, so sometimes the zero vectors will need to be
3954 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3955 /// zero vector.
3956 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3957   assert(VT.isVector() && "Expected a vector type");
3958   // The canonical modified immediate encoding of a zero vector is....0!
3959   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3960   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3961   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3962   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3963 }
3964
3965 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3966 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3967 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3968                                                 SelectionDAG &DAG) const {
3969   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3970   EVT VT = Op.getValueType();
3971   unsigned VTBits = VT.getSizeInBits();
3972   SDLoc dl(Op);
3973   SDValue ShOpLo = Op.getOperand(0);
3974   SDValue ShOpHi = Op.getOperand(1);
3975   SDValue ShAmt  = Op.getOperand(2);
3976   SDValue ARMcc;
3977   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3978
3979   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3980
3981   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3982                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3983   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3984   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3985                                    DAG.getConstant(VTBits, MVT::i32));
3986   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3987   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3988   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3989
3990   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3991   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3992                           ARMcc, DAG, dl);
3993   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3994   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3995                            CCR, Cmp);
3996
3997   SDValue Ops[2] = { Lo, Hi };
3998   return DAG.getMergeValues(Ops, dl);
3999 }
4000
4001 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4002 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4003 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4004                                                SelectionDAG &DAG) const {
4005   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4006   EVT VT = Op.getValueType();
4007   unsigned VTBits = VT.getSizeInBits();
4008   SDLoc dl(Op);
4009   SDValue ShOpLo = Op.getOperand(0);
4010   SDValue ShOpHi = Op.getOperand(1);
4011   SDValue ShAmt  = Op.getOperand(2);
4012   SDValue ARMcc;
4013
4014   assert(Op.getOpcode() == ISD::SHL_PARTS);
4015   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4016                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4017   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4018   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4019                                    DAG.getConstant(VTBits, MVT::i32));
4020   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4021   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4022
4023   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4024   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4025   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4026                           ARMcc, DAG, dl);
4027   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4028   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4029                            CCR, Cmp);
4030
4031   SDValue Ops[2] = { Lo, Hi };
4032   return DAG.getMergeValues(Ops, dl);
4033 }
4034
4035 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4036                                             SelectionDAG &DAG) const {
4037   // The rounding mode is in bits 23:22 of the FPSCR.
4038   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4039   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4040   // so that the shift + and get folded into a bitfield extract.
4041   SDLoc dl(Op);
4042   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4043                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4044                                               MVT::i32));
4045   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4046                                   DAG.getConstant(1U << 22, MVT::i32));
4047   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4048                               DAG.getConstant(22, MVT::i32));
4049   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4050                      DAG.getConstant(3, MVT::i32));
4051 }
4052
4053 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4054                          const ARMSubtarget *ST) {
4055   EVT VT = N->getValueType(0);
4056   SDLoc dl(N);
4057
4058   if (!ST->hasV6T2Ops())
4059     return SDValue();
4060
4061   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4062   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4063 }
4064
4065 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4066 /// for each 16-bit element from operand, repeated.  The basic idea is to
4067 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4068 ///
4069 /// Trace for v4i16:
4070 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4071 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4072 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4073 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4074 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4075 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4076 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4077 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4078 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4079   EVT VT = N->getValueType(0);
4080   SDLoc DL(N);
4081
4082   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4083   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4084   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4085   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4086   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4087   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4088 }
4089
4090 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4091 /// bit-count for each 16-bit element from the operand.  We need slightly
4092 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4093 /// 64/128-bit registers.
4094 ///
4095 /// Trace for v4i16:
4096 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4097 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4098 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4099 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4100 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4101   EVT VT = N->getValueType(0);
4102   SDLoc DL(N);
4103
4104   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4105   if (VT.is64BitVector()) {
4106     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4107     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4108                        DAG.getIntPtrConstant(0));
4109   } else {
4110     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4111                                     BitCounts, DAG.getIntPtrConstant(0));
4112     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4113   }
4114 }
4115
4116 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4117 /// bit-count for each 32-bit element from the operand.  The idea here is
4118 /// to split the vector into 16-bit elements, leverage the 16-bit count
4119 /// routine, and then combine the results.
4120 ///
4121 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4122 /// input    = [v0    v1    ] (vi: 32-bit elements)
4123 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4124 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4125 /// vrev: N0 = [k1 k0 k3 k2 ]
4126 ///            [k0 k1 k2 k3 ]
4127 ///       N1 =+[k1 k0 k3 k2 ]
4128 ///            [k0 k2 k1 k3 ]
4129 ///       N2 =+[k1 k3 k0 k2 ]
4130 ///            [k0    k2    k1    k3    ]
4131 /// Extended =+[k1    k3    k0    k2    ]
4132 ///            [k0    k2    ]
4133 /// Extracted=+[k1    k3    ]
4134 ///
4135 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4136   EVT VT = N->getValueType(0);
4137   SDLoc DL(N);
4138
4139   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4140
4141   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4142   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4143   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4144   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4145   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4146
4147   if (VT.is64BitVector()) {
4148     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4149     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4150                        DAG.getIntPtrConstant(0));
4151   } else {
4152     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4153                                     DAG.getIntPtrConstant(0));
4154     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4155   }
4156 }
4157
4158 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4159                           const ARMSubtarget *ST) {
4160   EVT VT = N->getValueType(0);
4161
4162   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4163   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4164           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4165          "Unexpected type for custom ctpop lowering");
4166
4167   if (VT.getVectorElementType() == MVT::i32)
4168     return lowerCTPOP32BitElements(N, DAG);
4169   else
4170     return lowerCTPOP16BitElements(N, DAG);
4171 }
4172
4173 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4174                           const ARMSubtarget *ST) {
4175   EVT VT = N->getValueType(0);
4176   SDLoc dl(N);
4177
4178   if (!VT.isVector())
4179     return SDValue();
4180
4181   // Lower vector shifts on NEON to use VSHL.
4182   assert(ST->hasNEON() && "unexpected vector shift");
4183
4184   // Left shifts translate directly to the vshiftu intrinsic.
4185   if (N->getOpcode() == ISD::SHL)
4186     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4187                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4188                        N->getOperand(0), N->getOperand(1));
4189
4190   assert((N->getOpcode() == ISD::SRA ||
4191           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4192
4193   // NEON uses the same intrinsics for both left and right shifts.  For
4194   // right shifts, the shift amounts are negative, so negate the vector of
4195   // shift amounts.
4196   EVT ShiftVT = N->getOperand(1).getValueType();
4197   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4198                                      getZeroVector(ShiftVT, DAG, dl),
4199                                      N->getOperand(1));
4200   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4201                              Intrinsic::arm_neon_vshifts :
4202                              Intrinsic::arm_neon_vshiftu);
4203   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4204                      DAG.getConstant(vshiftInt, MVT::i32),
4205                      N->getOperand(0), NegatedCount);
4206 }
4207
4208 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4209                                 const ARMSubtarget *ST) {
4210   EVT VT = N->getValueType(0);
4211   SDLoc dl(N);
4212
4213   // We can get here for a node like i32 = ISD::SHL i32, i64
4214   if (VT != MVT::i64)
4215     return SDValue();
4216
4217   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4218          "Unknown shift to lower!");
4219
4220   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4221   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4222       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4223     return SDValue();
4224
4225   // If we are in thumb mode, we don't have RRX.
4226   if (ST->isThumb1Only()) return SDValue();
4227
4228   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4229   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4230                            DAG.getConstant(0, MVT::i32));
4231   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4232                            DAG.getConstant(1, MVT::i32));
4233
4234   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4235   // captures the result into a carry flag.
4236   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4237   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4238
4239   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4240   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4241
4242   // Merge the pieces into a single i64 value.
4243  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4244 }
4245
4246 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4247   SDValue TmpOp0, TmpOp1;
4248   bool Invert = false;
4249   bool Swap = false;
4250   unsigned Opc = 0;
4251
4252   SDValue Op0 = Op.getOperand(0);
4253   SDValue Op1 = Op.getOperand(1);
4254   SDValue CC = Op.getOperand(2);
4255   EVT VT = Op.getValueType();
4256   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4257   SDLoc dl(Op);
4258
4259   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4260     switch (SetCCOpcode) {
4261     default: llvm_unreachable("Illegal FP comparison");
4262     case ISD::SETUNE:
4263     case ISD::SETNE:  Invert = true; // Fallthrough
4264     case ISD::SETOEQ:
4265     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4266     case ISD::SETOLT:
4267     case ISD::SETLT: Swap = true; // Fallthrough
4268     case ISD::SETOGT:
4269     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4270     case ISD::SETOLE:
4271     case ISD::SETLE:  Swap = true; // Fallthrough
4272     case ISD::SETOGE:
4273     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4274     case ISD::SETUGE: Swap = true; // Fallthrough
4275     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4276     case ISD::SETUGT: Swap = true; // Fallthrough
4277     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4278     case ISD::SETUEQ: Invert = true; // Fallthrough
4279     case ISD::SETONE:
4280       // Expand this to (OLT | OGT).
4281       TmpOp0 = Op0;
4282       TmpOp1 = Op1;
4283       Opc = ISD::OR;
4284       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4285       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4286       break;
4287     case ISD::SETUO: Invert = true; // Fallthrough
4288     case ISD::SETO:
4289       // Expand this to (OLT | OGE).
4290       TmpOp0 = Op0;
4291       TmpOp1 = Op1;
4292       Opc = ISD::OR;
4293       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4294       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4295       break;
4296     }
4297   } else {
4298     // Integer comparisons.
4299     switch (SetCCOpcode) {
4300     default: llvm_unreachable("Illegal integer comparison");
4301     case ISD::SETNE:  Invert = true;
4302     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4303     case ISD::SETLT:  Swap = true;
4304     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4305     case ISD::SETLE:  Swap = true;
4306     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4307     case ISD::SETULT: Swap = true;
4308     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4309     case ISD::SETULE: Swap = true;
4310     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4311     }
4312
4313     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4314     if (Opc == ARMISD::VCEQ) {
4315
4316       SDValue AndOp;
4317       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4318         AndOp = Op0;
4319       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4320         AndOp = Op1;
4321
4322       // Ignore bitconvert.
4323       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4324         AndOp = AndOp.getOperand(0);
4325
4326       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4327         Opc = ARMISD::VTST;
4328         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4329         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4330         Invert = !Invert;
4331       }
4332     }
4333   }
4334
4335   if (Swap)
4336     std::swap(Op0, Op1);
4337
4338   // If one of the operands is a constant vector zero, attempt to fold the
4339   // comparison to a specialized compare-against-zero form.
4340   SDValue SingleOp;
4341   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4342     SingleOp = Op0;
4343   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4344     if (Opc == ARMISD::VCGE)
4345       Opc = ARMISD::VCLEZ;
4346     else if (Opc == ARMISD::VCGT)
4347       Opc = ARMISD::VCLTZ;
4348     SingleOp = Op1;
4349   }
4350
4351   SDValue Result;
4352   if (SingleOp.getNode()) {
4353     switch (Opc) {
4354     case ARMISD::VCEQ:
4355       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4356     case ARMISD::VCGE:
4357       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4358     case ARMISD::VCLEZ:
4359       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4360     case ARMISD::VCGT:
4361       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4362     case ARMISD::VCLTZ:
4363       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4364     default:
4365       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4366     }
4367   } else {
4368      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4369   }
4370
4371   if (Invert)
4372     Result = DAG.getNOT(dl, Result, VT);
4373
4374   return Result;
4375 }
4376
4377 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4378 /// valid vector constant for a NEON instruction with a "modified immediate"
4379 /// operand (e.g., VMOV).  If so, return the encoded value.
4380 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4381                                  unsigned SplatBitSize, SelectionDAG &DAG,
4382                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4383   unsigned OpCmode, Imm;
4384
4385   // SplatBitSize is set to the smallest size that splats the vector, so a
4386   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4387   // immediate instructions others than VMOV do not support the 8-bit encoding
4388   // of a zero vector, and the default encoding of zero is supposed to be the
4389   // 32-bit version.
4390   if (SplatBits == 0)
4391     SplatBitSize = 32;
4392
4393   switch (SplatBitSize) {
4394   case 8:
4395     if (type != VMOVModImm)
4396       return SDValue();
4397     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4398     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4399     OpCmode = 0xe;
4400     Imm = SplatBits;
4401     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4402     break;
4403
4404   case 16:
4405     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4406     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4407     if ((SplatBits & ~0xff) == 0) {
4408       // Value = 0x00nn: Op=x, Cmode=100x.
4409       OpCmode = 0x8;
4410       Imm = SplatBits;
4411       break;
4412     }
4413     if ((SplatBits & ~0xff00) == 0) {
4414       // Value = 0xnn00: Op=x, Cmode=101x.
4415       OpCmode = 0xa;
4416       Imm = SplatBits >> 8;
4417       break;
4418     }
4419     return SDValue();
4420
4421   case 32:
4422     // NEON's 32-bit VMOV supports splat values where:
4423     // * only one byte is nonzero, or
4424     // * the least significant byte is 0xff and the second byte is nonzero, or
4425     // * the least significant 2 bytes are 0xff and the third is nonzero.
4426     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4427     if ((SplatBits & ~0xff) == 0) {
4428       // Value = 0x000000nn: Op=x, Cmode=000x.
4429       OpCmode = 0;
4430       Imm = SplatBits;
4431       break;
4432     }
4433     if ((SplatBits & ~0xff00) == 0) {
4434       // Value = 0x0000nn00: Op=x, Cmode=001x.
4435       OpCmode = 0x2;
4436       Imm = SplatBits >> 8;
4437       break;
4438     }
4439     if ((SplatBits & ~0xff0000) == 0) {
4440       // Value = 0x00nn0000: Op=x, Cmode=010x.
4441       OpCmode = 0x4;
4442       Imm = SplatBits >> 16;
4443       break;
4444     }
4445     if ((SplatBits & ~0xff000000) == 0) {
4446       // Value = 0xnn000000: Op=x, Cmode=011x.
4447       OpCmode = 0x6;
4448       Imm = SplatBits >> 24;
4449       break;
4450     }
4451
4452     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4453     if (type == OtherModImm) return SDValue();
4454
4455     if ((SplatBits & ~0xffff) == 0 &&
4456         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4457       // Value = 0x0000nnff: Op=x, Cmode=1100.
4458       OpCmode = 0xc;
4459       Imm = SplatBits >> 8;
4460       break;
4461     }
4462
4463     if ((SplatBits & ~0xffffff) == 0 &&
4464         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4465       // Value = 0x00nnffff: Op=x, Cmode=1101.
4466       OpCmode = 0xd;
4467       Imm = SplatBits >> 16;
4468       break;
4469     }
4470
4471     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4472     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4473     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4474     // and fall through here to test for a valid 64-bit splat.  But, then the
4475     // caller would also need to check and handle the change in size.
4476     return SDValue();
4477
4478   case 64: {
4479     if (type != VMOVModImm)
4480       return SDValue();
4481     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4482     uint64_t BitMask = 0xff;
4483     uint64_t Val = 0;
4484     unsigned ImmMask = 1;
4485     Imm = 0;
4486     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4487       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4488         Val |= BitMask;
4489         Imm |= ImmMask;
4490       } else if ((SplatBits & BitMask) != 0) {
4491         return SDValue();
4492       }
4493       BitMask <<= 8;
4494       ImmMask <<= 1;
4495     }
4496     // Op=1, Cmode=1110.
4497     OpCmode = 0x1e;
4498     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4499     break;
4500   }
4501
4502   default:
4503     llvm_unreachable("unexpected size for isNEONModifiedImm");
4504   }
4505
4506   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4507   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4508 }
4509
4510 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4511                                            const ARMSubtarget *ST) const {
4512   if (!ST->hasVFP3())
4513     return SDValue();
4514
4515   bool IsDouble = Op.getValueType() == MVT::f64;
4516   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4517
4518   // Try splatting with a VMOV.f32...
4519   APFloat FPVal = CFP->getValueAPF();
4520   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4521
4522   if (ImmVal != -1) {
4523     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4524       // We have code in place to select a valid ConstantFP already, no need to
4525       // do any mangling.
4526       return Op;
4527     }
4528
4529     // It's a float and we are trying to use NEON operations where
4530     // possible. Lower it to a splat followed by an extract.
4531     SDLoc DL(Op);
4532     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4533     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4534                                       NewVal);
4535     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4536                        DAG.getConstant(0, MVT::i32));
4537   }
4538
4539   // The rest of our options are NEON only, make sure that's allowed before
4540   // proceeding..
4541   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4542     return SDValue();
4543
4544   EVT VMovVT;
4545   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4546
4547   // It wouldn't really be worth bothering for doubles except for one very
4548   // important value, which does happen to match: 0.0. So make sure we don't do
4549   // anything stupid.
4550   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4551     return SDValue();
4552
4553   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4554   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4555                                      false, VMOVModImm);
4556   if (NewVal != SDValue()) {
4557     SDLoc DL(Op);
4558     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4559                                       NewVal);
4560     if (IsDouble)
4561       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4562
4563     // It's a float: cast and extract a vector element.
4564     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4565                                        VecConstant);
4566     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4567                        DAG.getConstant(0, MVT::i32));
4568   }
4569
4570   // Finally, try a VMVN.i32
4571   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4572                              false, VMVNModImm);
4573   if (NewVal != SDValue()) {
4574     SDLoc DL(Op);
4575     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4576
4577     if (IsDouble)
4578       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4579
4580     // It's a float: cast and extract a vector element.
4581     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4582                                        VecConstant);
4583     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4584                        DAG.getConstant(0, MVT::i32));
4585   }
4586
4587   return SDValue();
4588 }
4589
4590 // check if an VEXT instruction can handle the shuffle mask when the
4591 // vector sources of the shuffle are the same.
4592 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4593   unsigned NumElts = VT.getVectorNumElements();
4594
4595   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4596   if (M[0] < 0)
4597     return false;
4598
4599   Imm = M[0];
4600
4601   // If this is a VEXT shuffle, the immediate value is the index of the first
4602   // element.  The other shuffle indices must be the successive elements after
4603   // the first one.
4604   unsigned ExpectedElt = Imm;
4605   for (unsigned i = 1; i < NumElts; ++i) {
4606     // Increment the expected index.  If it wraps around, just follow it
4607     // back to index zero and keep going.
4608     ++ExpectedElt;
4609     if (ExpectedElt == NumElts)
4610       ExpectedElt = 0;
4611
4612     if (M[i] < 0) continue; // ignore UNDEF indices
4613     if (ExpectedElt != static_cast<unsigned>(M[i]))
4614       return false;
4615   }
4616
4617   return true;
4618 }
4619
4620
4621 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4622                        bool &ReverseVEXT, unsigned &Imm) {
4623   unsigned NumElts = VT.getVectorNumElements();
4624   ReverseVEXT = false;
4625
4626   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4627   if (M[0] < 0)
4628     return false;
4629
4630   Imm = M[0];
4631
4632   // If this is a VEXT shuffle, the immediate value is the index of the first
4633   // element.  The other shuffle indices must be the successive elements after
4634   // the first one.
4635   unsigned ExpectedElt = Imm;
4636   for (unsigned i = 1; i < NumElts; ++i) {
4637     // Increment the expected index.  If it wraps around, it may still be
4638     // a VEXT but the source vectors must be swapped.
4639     ExpectedElt += 1;
4640     if (ExpectedElt == NumElts * 2) {
4641       ExpectedElt = 0;
4642       ReverseVEXT = true;
4643     }
4644
4645     if (M[i] < 0) continue; // ignore UNDEF indices
4646     if (ExpectedElt != static_cast<unsigned>(M[i]))
4647       return false;
4648   }
4649
4650   // Adjust the index value if the source operands will be swapped.
4651   if (ReverseVEXT)
4652     Imm -= NumElts;
4653
4654   return true;
4655 }
4656
4657 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4658 /// instruction with the specified blocksize.  (The order of the elements
4659 /// within each block of the vector is reversed.)
4660 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4661   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4662          "Only possible block sizes for VREV are: 16, 32, 64");
4663
4664   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4665   if (EltSz == 64)
4666     return false;
4667
4668   unsigned NumElts = VT.getVectorNumElements();
4669   unsigned BlockElts = M[0] + 1;
4670   // If the first shuffle index is UNDEF, be optimistic.
4671   if (M[0] < 0)
4672     BlockElts = BlockSize / EltSz;
4673
4674   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4675     return false;
4676
4677   for (unsigned i = 0; i < NumElts; ++i) {
4678     if (M[i] < 0) continue; // ignore UNDEF indices
4679     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4680       return false;
4681   }
4682
4683   return true;
4684 }
4685
4686 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4687   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4688   // range, then 0 is placed into the resulting vector. So pretty much any mask
4689   // of 8 elements can work here.
4690   return VT == MVT::v8i8 && M.size() == 8;
4691 }
4692
4693 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4694   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4695   if (EltSz == 64)
4696     return false;
4697
4698   unsigned NumElts = VT.getVectorNumElements();
4699   WhichResult = (M[0] == 0 ? 0 : 1);
4700   for (unsigned i = 0; i < NumElts; i += 2) {
4701     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4702         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4703       return false;
4704   }
4705   return true;
4706 }
4707
4708 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4709 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4710 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4711 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4712   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4713   if (EltSz == 64)
4714     return false;
4715
4716   unsigned NumElts = VT.getVectorNumElements();
4717   WhichResult = (M[0] == 0 ? 0 : 1);
4718   for (unsigned i = 0; i < NumElts; i += 2) {
4719     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4720         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4721       return false;
4722   }
4723   return true;
4724 }
4725
4726 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4727   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4728   if (EltSz == 64)
4729     return false;
4730
4731   unsigned NumElts = VT.getVectorNumElements();
4732   WhichResult = (M[0] == 0 ? 0 : 1);
4733   for (unsigned i = 0; i != NumElts; ++i) {
4734     if (M[i] < 0) continue; // ignore UNDEF indices
4735     if ((unsigned) M[i] != 2 * i + WhichResult)
4736       return false;
4737   }
4738
4739   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4740   if (VT.is64BitVector() && EltSz == 32)
4741     return false;
4742
4743   return true;
4744 }
4745
4746 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4747 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4748 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4749 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4750   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4751   if (EltSz == 64)
4752     return false;
4753
4754   unsigned Half = VT.getVectorNumElements() / 2;
4755   WhichResult = (M[0] == 0 ? 0 : 1);
4756   for (unsigned j = 0; j != 2; ++j) {
4757     unsigned Idx = WhichResult;
4758     for (unsigned i = 0; i != Half; ++i) {
4759       int MIdx = M[i + j * Half];
4760       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4761         return false;
4762       Idx += 2;
4763     }
4764   }
4765
4766   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4767   if (VT.is64BitVector() && EltSz == 32)
4768     return false;
4769
4770   return true;
4771 }
4772
4773 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4774   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4775   if (EltSz == 64)
4776     return false;
4777
4778   unsigned NumElts = VT.getVectorNumElements();
4779   WhichResult = (M[0] == 0 ? 0 : 1);
4780   unsigned Idx = WhichResult * NumElts / 2;
4781   for (unsigned i = 0; i != NumElts; i += 2) {
4782     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4783         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4784       return false;
4785     Idx += 1;
4786   }
4787
4788   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4789   if (VT.is64BitVector() && EltSz == 32)
4790     return false;
4791
4792   return true;
4793 }
4794
4795 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4796 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4797 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4798 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4799   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4800   if (EltSz == 64)
4801     return false;
4802
4803   unsigned NumElts = VT.getVectorNumElements();
4804   WhichResult = (M[0] == 0 ? 0 : 1);
4805   unsigned Idx = WhichResult * NumElts / 2;
4806   for (unsigned i = 0; i != NumElts; i += 2) {
4807     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4808         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4809       return false;
4810     Idx += 1;
4811   }
4812
4813   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4814   if (VT.is64BitVector() && EltSz == 32)
4815     return false;
4816
4817   return true;
4818 }
4819
4820 /// \return true if this is a reverse operation on an vector.
4821 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4822   unsigned NumElts = VT.getVectorNumElements();
4823   // Make sure the mask has the right size.
4824   if (NumElts != M.size())
4825       return false;
4826
4827   // Look for <15, ..., 3, -1, 1, 0>.
4828   for (unsigned i = 0; i != NumElts; ++i)
4829     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4830       return false;
4831
4832   return true;
4833 }
4834
4835 // If N is an integer constant that can be moved into a register in one
4836 // instruction, return an SDValue of such a constant (will become a MOV
4837 // instruction).  Otherwise return null.
4838 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4839                                      const ARMSubtarget *ST, SDLoc dl) {
4840   uint64_t Val;
4841   if (!isa<ConstantSDNode>(N))
4842     return SDValue();
4843   Val = cast<ConstantSDNode>(N)->getZExtValue();
4844
4845   if (ST->isThumb1Only()) {
4846     if (Val <= 255 || ~Val <= 255)
4847       return DAG.getConstant(Val, MVT::i32);
4848   } else {
4849     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4850       return DAG.getConstant(Val, MVT::i32);
4851   }
4852   return SDValue();
4853 }
4854
4855 // If this is a case we can't handle, return null and let the default
4856 // expansion code take care of it.
4857 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4858                                              const ARMSubtarget *ST) const {
4859   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4860   SDLoc dl(Op);
4861   EVT VT = Op.getValueType();
4862
4863   APInt SplatBits, SplatUndef;
4864   unsigned SplatBitSize;
4865   bool HasAnyUndefs;
4866   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4867     if (SplatBitSize <= 64) {
4868       // Check if an immediate VMOV works.
4869       EVT VmovVT;
4870       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4871                                       SplatUndef.getZExtValue(), SplatBitSize,
4872                                       DAG, VmovVT, VT.is128BitVector(),
4873                                       VMOVModImm);
4874       if (Val.getNode()) {
4875         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4876         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4877       }
4878
4879       // Try an immediate VMVN.
4880       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4881       Val = isNEONModifiedImm(NegatedImm,
4882                                       SplatUndef.getZExtValue(), SplatBitSize,
4883                                       DAG, VmovVT, VT.is128BitVector(),
4884                                       VMVNModImm);
4885       if (Val.getNode()) {
4886         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4887         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4888       }
4889
4890       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4891       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4892         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4893         if (ImmVal != -1) {
4894           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4895           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4896         }
4897       }
4898     }
4899   }
4900
4901   // Scan through the operands to see if only one value is used.
4902   //
4903   // As an optimisation, even if more than one value is used it may be more
4904   // profitable to splat with one value then change some lanes.
4905   //
4906   // Heuristically we decide to do this if the vector has a "dominant" value,
4907   // defined as splatted to more than half of the lanes.
4908   unsigned NumElts = VT.getVectorNumElements();
4909   bool isOnlyLowElement = true;
4910   bool usesOnlyOneValue = true;
4911   bool hasDominantValue = false;
4912   bool isConstant = true;
4913
4914   // Map of the number of times a particular SDValue appears in the
4915   // element list.
4916   DenseMap<SDValue, unsigned> ValueCounts;
4917   SDValue Value;
4918   for (unsigned i = 0; i < NumElts; ++i) {
4919     SDValue V = Op.getOperand(i);
4920     if (V.getOpcode() == ISD::UNDEF)
4921       continue;
4922     if (i > 0)
4923       isOnlyLowElement = false;
4924     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4925       isConstant = false;
4926
4927     ValueCounts.insert(std::make_pair(V, 0));
4928     unsigned &Count = ValueCounts[V];
4929
4930     // Is this value dominant? (takes up more than half of the lanes)
4931     if (++Count > (NumElts / 2)) {
4932       hasDominantValue = true;
4933       Value = V;
4934     }
4935   }
4936   if (ValueCounts.size() != 1)
4937     usesOnlyOneValue = false;
4938   if (!Value.getNode() && ValueCounts.size() > 0)
4939     Value = ValueCounts.begin()->first;
4940
4941   if (ValueCounts.size() == 0)
4942     return DAG.getUNDEF(VT);
4943
4944   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4945   // Keep going if we are hitting this case.
4946   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4947     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4948
4949   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4950
4951   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4952   // i32 and try again.
4953   if (hasDominantValue && EltSize <= 32) {
4954     if (!isConstant) {
4955       SDValue N;
4956
4957       // If we are VDUPing a value that comes directly from a vector, that will
4958       // cause an unnecessary move to and from a GPR, where instead we could
4959       // just use VDUPLANE. We can only do this if the lane being extracted
4960       // is at a constant index, as the VDUP from lane instructions only have
4961       // constant-index forms.
4962       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4963           isa<ConstantSDNode>(Value->getOperand(1))) {
4964         // We need to create a new undef vector to use for the VDUPLANE if the
4965         // size of the vector from which we get the value is different than the
4966         // size of the vector that we need to create. We will insert the element
4967         // such that the register coalescer will remove unnecessary copies.
4968         if (VT != Value->getOperand(0).getValueType()) {
4969           ConstantSDNode *constIndex;
4970           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4971           assert(constIndex && "The index is not a constant!");
4972           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4973                              VT.getVectorNumElements();
4974           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4975                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4976                         Value, DAG.getConstant(index, MVT::i32)),
4977                            DAG.getConstant(index, MVT::i32));
4978         } else
4979           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4980                         Value->getOperand(0), Value->getOperand(1));
4981       } else
4982         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4983
4984       if (!usesOnlyOneValue) {
4985         // The dominant value was splatted as 'N', but we now have to insert
4986         // all differing elements.
4987         for (unsigned I = 0; I < NumElts; ++I) {
4988           if (Op.getOperand(I) == Value)
4989             continue;
4990           SmallVector<SDValue, 3> Ops;
4991           Ops.push_back(N);
4992           Ops.push_back(Op.getOperand(I));
4993           Ops.push_back(DAG.getConstant(I, MVT::i32));
4994           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
4995         }
4996       }
4997       return N;
4998     }
4999     if (VT.getVectorElementType().isFloatingPoint()) {
5000       SmallVector<SDValue, 8> Ops;
5001       for (unsigned i = 0; i < NumElts; ++i)
5002         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5003                                   Op.getOperand(i)));
5004       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5005       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5006       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5007       if (Val.getNode())
5008         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5009     }
5010     if (usesOnlyOneValue) {
5011       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5012       if (isConstant && Val.getNode())
5013         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5014     }
5015   }
5016
5017   // If all elements are constants and the case above didn't get hit, fall back
5018   // to the default expansion, which will generate a load from the constant
5019   // pool.
5020   if (isConstant)
5021     return SDValue();
5022
5023   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5024   if (NumElts >= 4) {
5025     SDValue shuffle = ReconstructShuffle(Op, DAG);
5026     if (shuffle != SDValue())
5027       return shuffle;
5028   }
5029
5030   // Vectors with 32- or 64-bit elements can be built by directly assigning
5031   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5032   // will be legalized.
5033   if (EltSize >= 32) {
5034     // Do the expansion with floating-point types, since that is what the VFP
5035     // registers are defined to use, and since i64 is not legal.
5036     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5037     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5038     SmallVector<SDValue, 8> Ops;
5039     for (unsigned i = 0; i < NumElts; ++i)
5040       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5041     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5042     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5043   }
5044
5045   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5046   // know the default expansion would otherwise fall back on something even
5047   // worse. For a vector with one or two non-undef values, that's
5048   // scalar_to_vector for the elements followed by a shuffle (provided the
5049   // shuffle is valid for the target) and materialization element by element
5050   // on the stack followed by a load for everything else.
5051   if (!isConstant && !usesOnlyOneValue) {
5052     SDValue Vec = DAG.getUNDEF(VT);
5053     for (unsigned i = 0 ; i < NumElts; ++i) {
5054       SDValue V = Op.getOperand(i);
5055       if (V.getOpcode() == ISD::UNDEF)
5056         continue;
5057       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5058       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5059     }
5060     return Vec;
5061   }
5062
5063   return SDValue();
5064 }
5065
5066 // Gather data to see if the operation can be modelled as a
5067 // shuffle in combination with VEXTs.
5068 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5069                                               SelectionDAG &DAG) const {
5070   SDLoc dl(Op);
5071   EVT VT = Op.getValueType();
5072   unsigned NumElts = VT.getVectorNumElements();
5073
5074   SmallVector<SDValue, 2> SourceVecs;
5075   SmallVector<unsigned, 2> MinElts;
5076   SmallVector<unsigned, 2> MaxElts;
5077
5078   for (unsigned i = 0; i < NumElts; ++i) {
5079     SDValue V = Op.getOperand(i);
5080     if (V.getOpcode() == ISD::UNDEF)
5081       continue;
5082     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5083       // A shuffle can only come from building a vector from various
5084       // elements of other vectors.
5085       return SDValue();
5086     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5087                VT.getVectorElementType()) {
5088       // This code doesn't know how to handle shuffles where the vector
5089       // element types do not match (this happens because type legalization
5090       // promotes the return type of EXTRACT_VECTOR_ELT).
5091       // FIXME: It might be appropriate to extend this code to handle
5092       // mismatched types.
5093       return SDValue();
5094     }
5095
5096     // Record this extraction against the appropriate vector if possible...
5097     SDValue SourceVec = V.getOperand(0);
5098     // If the element number isn't a constant, we can't effectively
5099     // analyze what's going on.
5100     if (!isa<ConstantSDNode>(V.getOperand(1)))
5101       return SDValue();
5102     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5103     bool FoundSource = false;
5104     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5105       if (SourceVecs[j] == SourceVec) {
5106         if (MinElts[j] > EltNo)
5107           MinElts[j] = EltNo;
5108         if (MaxElts[j] < EltNo)
5109           MaxElts[j] = EltNo;
5110         FoundSource = true;
5111         break;
5112       }
5113     }
5114
5115     // Or record a new source if not...
5116     if (!FoundSource) {
5117       SourceVecs.push_back(SourceVec);
5118       MinElts.push_back(EltNo);
5119       MaxElts.push_back(EltNo);
5120     }
5121   }
5122
5123   // Currently only do something sane when at most two source vectors
5124   // involved.
5125   if (SourceVecs.size() > 2)
5126     return SDValue();
5127
5128   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5129   int VEXTOffsets[2] = {0, 0};
5130
5131   // This loop extracts the usage patterns of the source vectors
5132   // and prepares appropriate SDValues for a shuffle if possible.
5133   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5134     if (SourceVecs[i].getValueType() == VT) {
5135       // No VEXT necessary
5136       ShuffleSrcs[i] = SourceVecs[i];
5137       VEXTOffsets[i] = 0;
5138       continue;
5139     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5140       // It probably isn't worth padding out a smaller vector just to
5141       // break it down again in a shuffle.
5142       return SDValue();
5143     }
5144
5145     // Since only 64-bit and 128-bit vectors are legal on ARM and
5146     // we've eliminated the other cases...
5147     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5148            "unexpected vector sizes in ReconstructShuffle");
5149
5150     if (MaxElts[i] - MinElts[i] >= NumElts) {
5151       // Span too large for a VEXT to cope
5152       return SDValue();
5153     }
5154
5155     if (MinElts[i] >= NumElts) {
5156       // The extraction can just take the second half
5157       VEXTOffsets[i] = NumElts;
5158       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5159                                    SourceVecs[i],
5160                                    DAG.getIntPtrConstant(NumElts));
5161     } else if (MaxElts[i] < NumElts) {
5162       // The extraction can just take the first half
5163       VEXTOffsets[i] = 0;
5164       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5165                                    SourceVecs[i],
5166                                    DAG.getIntPtrConstant(0));
5167     } else {
5168       // An actual VEXT is needed
5169       VEXTOffsets[i] = MinElts[i];
5170       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5171                                      SourceVecs[i],
5172                                      DAG.getIntPtrConstant(0));
5173       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5174                                      SourceVecs[i],
5175                                      DAG.getIntPtrConstant(NumElts));
5176       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5177                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5178     }
5179   }
5180
5181   SmallVector<int, 8> Mask;
5182
5183   for (unsigned i = 0; i < NumElts; ++i) {
5184     SDValue Entry = Op.getOperand(i);
5185     if (Entry.getOpcode() == ISD::UNDEF) {
5186       Mask.push_back(-1);
5187       continue;
5188     }
5189
5190     SDValue ExtractVec = Entry.getOperand(0);
5191     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5192                                           .getOperand(1))->getSExtValue();
5193     if (ExtractVec == SourceVecs[0]) {
5194       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5195     } else {
5196       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5197     }
5198   }
5199
5200   // Final check before we try to produce nonsense...
5201   if (isShuffleMaskLegal(Mask, VT))
5202     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5203                                 &Mask[0]);
5204
5205   return SDValue();
5206 }
5207
5208 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5209 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5210 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5211 /// are assumed to be legal.
5212 bool
5213 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5214                                       EVT VT) const {
5215   if (VT.getVectorNumElements() == 4 &&
5216       (VT.is128BitVector() || VT.is64BitVector())) {
5217     unsigned PFIndexes[4];
5218     for (unsigned i = 0; i != 4; ++i) {
5219       if (M[i] < 0)
5220         PFIndexes[i] = 8;
5221       else
5222         PFIndexes[i] = M[i];
5223     }
5224
5225     // Compute the index in the perfect shuffle table.
5226     unsigned PFTableIndex =
5227       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5228     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5229     unsigned Cost = (PFEntry >> 30);
5230
5231     if (Cost <= 4)
5232       return true;
5233   }
5234
5235   bool ReverseVEXT;
5236   unsigned Imm, WhichResult;
5237
5238   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5239   return (EltSize >= 32 ||
5240           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5241           isVREVMask(M, VT, 64) ||
5242           isVREVMask(M, VT, 32) ||
5243           isVREVMask(M, VT, 16) ||
5244           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5245           isVTBLMask(M, VT) ||
5246           isVTRNMask(M, VT, WhichResult) ||
5247           isVUZPMask(M, VT, WhichResult) ||
5248           isVZIPMask(M, VT, WhichResult) ||
5249           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5250           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5251           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5252           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5253 }
5254
5255 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5256 /// the specified operations to build the shuffle.
5257 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5258                                       SDValue RHS, SelectionDAG &DAG,
5259                                       SDLoc dl) {
5260   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5261   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5262   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5263
5264   enum {
5265     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5266     OP_VREV,
5267     OP_VDUP0,
5268     OP_VDUP1,
5269     OP_VDUP2,
5270     OP_VDUP3,
5271     OP_VEXT1,
5272     OP_VEXT2,
5273     OP_VEXT3,
5274     OP_VUZPL, // VUZP, left result
5275     OP_VUZPR, // VUZP, right result
5276     OP_VZIPL, // VZIP, left result
5277     OP_VZIPR, // VZIP, right result
5278     OP_VTRNL, // VTRN, left result
5279     OP_VTRNR  // VTRN, right result
5280   };
5281
5282   if (OpNum == OP_COPY) {
5283     if (LHSID == (1*9+2)*9+3) return LHS;
5284     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5285     return RHS;
5286   }
5287
5288   SDValue OpLHS, OpRHS;
5289   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5290   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5291   EVT VT = OpLHS.getValueType();
5292
5293   switch (OpNum) {
5294   default: llvm_unreachable("Unknown shuffle opcode!");
5295   case OP_VREV:
5296     // VREV divides the vector in half and swaps within the half.
5297     if (VT.getVectorElementType() == MVT::i32 ||
5298         VT.getVectorElementType() == MVT::f32)
5299       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5300     // vrev <4 x i16> -> VREV32
5301     if (VT.getVectorElementType() == MVT::i16)
5302       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5303     // vrev <4 x i8> -> VREV16
5304     assert(VT.getVectorElementType() == MVT::i8);
5305     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5306   case OP_VDUP0:
5307   case OP_VDUP1:
5308   case OP_VDUP2:
5309   case OP_VDUP3:
5310     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5311                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5312   case OP_VEXT1:
5313   case OP_VEXT2:
5314   case OP_VEXT3:
5315     return DAG.getNode(ARMISD::VEXT, dl, VT,
5316                        OpLHS, OpRHS,
5317                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5318   case OP_VUZPL:
5319   case OP_VUZPR:
5320     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5321                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5322   case OP_VZIPL:
5323   case OP_VZIPR:
5324     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5325                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5326   case OP_VTRNL:
5327   case OP_VTRNR:
5328     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5329                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5330   }
5331 }
5332
5333 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5334                                        ArrayRef<int> ShuffleMask,
5335                                        SelectionDAG &DAG) {
5336   // Check to see if we can use the VTBL instruction.
5337   SDValue V1 = Op.getOperand(0);
5338   SDValue V2 = Op.getOperand(1);
5339   SDLoc DL(Op);
5340
5341   SmallVector<SDValue, 8> VTBLMask;
5342   for (ArrayRef<int>::iterator
5343          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5344     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5345
5346   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5347     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5348                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5349
5350   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5351                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5352 }
5353
5354 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5355                                                       SelectionDAG &DAG) {
5356   SDLoc DL(Op);
5357   SDValue OpLHS = Op.getOperand(0);
5358   EVT VT = OpLHS.getValueType();
5359
5360   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5361          "Expect an v8i16/v16i8 type");
5362   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5363   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5364   // extract the first 8 bytes into the top double word and the last 8 bytes
5365   // into the bottom double word. The v8i16 case is similar.
5366   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5367   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5368                      DAG.getConstant(ExtractNum, MVT::i32));
5369 }
5370
5371 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5372   SDValue V1 = Op.getOperand(0);
5373   SDValue V2 = Op.getOperand(1);
5374   SDLoc dl(Op);
5375   EVT VT = Op.getValueType();
5376   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5377
5378   // Convert shuffles that are directly supported on NEON to target-specific
5379   // DAG nodes, instead of keeping them as shuffles and matching them again
5380   // during code selection.  This is more efficient and avoids the possibility
5381   // of inconsistencies between legalization and selection.
5382   // FIXME: floating-point vectors should be canonicalized to integer vectors
5383   // of the same time so that they get CSEd properly.
5384   ArrayRef<int> ShuffleMask = SVN->getMask();
5385
5386   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5387   if (EltSize <= 32) {
5388     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5389       int Lane = SVN->getSplatIndex();
5390       // If this is undef splat, generate it via "just" vdup, if possible.
5391       if (Lane == -1) Lane = 0;
5392
5393       // Test if V1 is a SCALAR_TO_VECTOR.
5394       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5395         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5396       }
5397       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5398       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5399       // reaches it).
5400       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5401           !isa<ConstantSDNode>(V1.getOperand(0))) {
5402         bool IsScalarToVector = true;
5403         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5404           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5405             IsScalarToVector = false;
5406             break;
5407           }
5408         if (IsScalarToVector)
5409           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5410       }
5411       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5412                          DAG.getConstant(Lane, MVT::i32));
5413     }
5414
5415     bool ReverseVEXT;
5416     unsigned Imm;
5417     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5418       if (ReverseVEXT)
5419         std::swap(V1, V2);
5420       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5421                          DAG.getConstant(Imm, MVT::i32));
5422     }
5423
5424     if (isVREVMask(ShuffleMask, VT, 64))
5425       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5426     if (isVREVMask(ShuffleMask, VT, 32))
5427       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5428     if (isVREVMask(ShuffleMask, VT, 16))
5429       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5430
5431     if (V2->getOpcode() == ISD::UNDEF &&
5432         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5433       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5434                          DAG.getConstant(Imm, MVT::i32));
5435     }
5436
5437     // Check for Neon shuffles that modify both input vectors in place.
5438     // If both results are used, i.e., if there are two shuffles with the same
5439     // source operands and with masks corresponding to both results of one of
5440     // these operations, DAG memoization will ensure that a single node is
5441     // used for both shuffles.
5442     unsigned WhichResult;
5443     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5444       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5445                          V1, V2).getValue(WhichResult);
5446     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5447       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5448                          V1, V2).getValue(WhichResult);
5449     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5450       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5451                          V1, V2).getValue(WhichResult);
5452
5453     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5454       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5455                          V1, V1).getValue(WhichResult);
5456     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5457       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5458                          V1, V1).getValue(WhichResult);
5459     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5460       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5461                          V1, V1).getValue(WhichResult);
5462   }
5463
5464   // If the shuffle is not directly supported and it has 4 elements, use
5465   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5466   unsigned NumElts = VT.getVectorNumElements();
5467   if (NumElts == 4) {
5468     unsigned PFIndexes[4];
5469     for (unsigned i = 0; i != 4; ++i) {
5470       if (ShuffleMask[i] < 0)
5471         PFIndexes[i] = 8;
5472       else
5473         PFIndexes[i] = ShuffleMask[i];
5474     }
5475
5476     // Compute the index in the perfect shuffle table.
5477     unsigned PFTableIndex =
5478       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5479     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5480     unsigned Cost = (PFEntry >> 30);
5481
5482     if (Cost <= 4)
5483       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5484   }
5485
5486   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5487   if (EltSize >= 32) {
5488     // Do the expansion with floating-point types, since that is what the VFP
5489     // registers are defined to use, and since i64 is not legal.
5490     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5491     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5492     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5493     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5494     SmallVector<SDValue, 8> Ops;
5495     for (unsigned i = 0; i < NumElts; ++i) {
5496       if (ShuffleMask[i] < 0)
5497         Ops.push_back(DAG.getUNDEF(EltVT));
5498       else
5499         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5500                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5501                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5502                                                   MVT::i32)));
5503     }
5504     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5505     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5506   }
5507
5508   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5509     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5510
5511   if (VT == MVT::v8i8) {
5512     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5513     if (NewOp.getNode())
5514       return NewOp;
5515   }
5516
5517   return SDValue();
5518 }
5519
5520 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5521   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5522   SDValue Lane = Op.getOperand(2);
5523   if (!isa<ConstantSDNode>(Lane))
5524     return SDValue();
5525
5526   return Op;
5527 }
5528
5529 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5530   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5531   SDValue Lane = Op.getOperand(1);
5532   if (!isa<ConstantSDNode>(Lane))
5533     return SDValue();
5534
5535   SDValue Vec = Op.getOperand(0);
5536   if (Op.getValueType() == MVT::i32 &&
5537       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5538     SDLoc dl(Op);
5539     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5540   }
5541
5542   return Op;
5543 }
5544
5545 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5546   // The only time a CONCAT_VECTORS operation can have legal types is when
5547   // two 64-bit vectors are concatenated to a 128-bit vector.
5548   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5549          "unexpected CONCAT_VECTORS");
5550   SDLoc dl(Op);
5551   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5552   SDValue Op0 = Op.getOperand(0);
5553   SDValue Op1 = Op.getOperand(1);
5554   if (Op0.getOpcode() != ISD::UNDEF)
5555     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5556                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5557                       DAG.getIntPtrConstant(0));
5558   if (Op1.getOpcode() != ISD::UNDEF)
5559     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5560                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5561                       DAG.getIntPtrConstant(1));
5562   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5563 }
5564
5565 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5566 /// element has been zero/sign-extended, depending on the isSigned parameter,
5567 /// from an integer type half its size.
5568 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5569                                    bool isSigned) {
5570   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5571   EVT VT = N->getValueType(0);
5572   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5573     SDNode *BVN = N->getOperand(0).getNode();
5574     if (BVN->getValueType(0) != MVT::v4i32 ||
5575         BVN->getOpcode() != ISD::BUILD_VECTOR)
5576       return false;
5577     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5578     unsigned HiElt = 1 - LoElt;
5579     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5580     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5581     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5582     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5583     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5584       return false;
5585     if (isSigned) {
5586       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5587           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5588         return true;
5589     } else {
5590       if (Hi0->isNullValue() && Hi1->isNullValue())
5591         return true;
5592     }
5593     return false;
5594   }
5595
5596   if (N->getOpcode() != ISD::BUILD_VECTOR)
5597     return false;
5598
5599   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5600     SDNode *Elt = N->getOperand(i).getNode();
5601     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5602       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5603       unsigned HalfSize = EltSize / 2;
5604       if (isSigned) {
5605         if (!isIntN(HalfSize, C->getSExtValue()))
5606           return false;
5607       } else {
5608         if (!isUIntN(HalfSize, C->getZExtValue()))
5609           return false;
5610       }
5611       continue;
5612     }
5613     return false;
5614   }
5615
5616   return true;
5617 }
5618
5619 /// isSignExtended - Check if a node is a vector value that is sign-extended
5620 /// or a constant BUILD_VECTOR with sign-extended elements.
5621 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5622   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5623     return true;
5624   if (isExtendedBUILD_VECTOR(N, DAG, true))
5625     return true;
5626   return false;
5627 }
5628
5629 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5630 /// or a constant BUILD_VECTOR with zero-extended elements.
5631 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5632   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5633     return true;
5634   if (isExtendedBUILD_VECTOR(N, DAG, false))
5635     return true;
5636   return false;
5637 }
5638
5639 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5640   if (OrigVT.getSizeInBits() >= 64)
5641     return OrigVT;
5642
5643   assert(OrigVT.isSimple() && "Expecting a simple value type");
5644
5645   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5646   switch (OrigSimpleTy) {
5647   default: llvm_unreachable("Unexpected Vector Type");
5648   case MVT::v2i8:
5649   case MVT::v2i16:
5650      return MVT::v2i32;
5651   case MVT::v4i8:
5652     return  MVT::v4i16;
5653   }
5654 }
5655
5656 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5657 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5658 /// We insert the required extension here to get the vector to fill a D register.
5659 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5660                                             const EVT &OrigTy,
5661                                             const EVT &ExtTy,
5662                                             unsigned ExtOpcode) {
5663   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5664   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5665   // 64-bits we need to insert a new extension so that it will be 64-bits.
5666   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5667   if (OrigTy.getSizeInBits() >= 64)
5668     return N;
5669
5670   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5671   EVT NewVT = getExtensionTo64Bits(OrigTy);
5672
5673   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5674 }
5675
5676 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5677 /// does not do any sign/zero extension. If the original vector is less
5678 /// than 64 bits, an appropriate extension will be added after the load to
5679 /// reach a total size of 64 bits. We have to add the extension separately
5680 /// because ARM does not have a sign/zero extending load for vectors.
5681 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5682   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5683
5684   // The load already has the right type.
5685   if (ExtendedTy == LD->getMemoryVT())
5686     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5687                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5688                 LD->isNonTemporal(), LD->isInvariant(),
5689                 LD->getAlignment());
5690
5691   // We need to create a zextload/sextload. We cannot just create a load
5692   // followed by a zext/zext node because LowerMUL is also run during normal
5693   // operation legalization where we can't create illegal types.
5694   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5695                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5696                         LD->getMemoryVT(), LD->isVolatile(),
5697                         LD->isNonTemporal(), LD->getAlignment());
5698 }
5699
5700 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5701 /// extending load, or BUILD_VECTOR with extended elements, return the
5702 /// unextended value. The unextended vector should be 64 bits so that it can
5703 /// be used as an operand to a VMULL instruction. If the original vector size
5704 /// before extension is less than 64 bits we add a an extension to resize
5705 /// the vector to 64 bits.
5706 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5707   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5708     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5709                                         N->getOperand(0)->getValueType(0),
5710                                         N->getValueType(0),
5711                                         N->getOpcode());
5712
5713   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5714     return SkipLoadExtensionForVMULL(LD, DAG);
5715
5716   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5717   // have been legalized as a BITCAST from v4i32.
5718   if (N->getOpcode() == ISD::BITCAST) {
5719     SDNode *BVN = N->getOperand(0).getNode();
5720     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5721            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5722     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5723     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5724                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5725   }
5726   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5727   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5728   EVT VT = N->getValueType(0);
5729   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5730   unsigned NumElts = VT.getVectorNumElements();
5731   MVT TruncVT = MVT::getIntegerVT(EltSize);
5732   SmallVector<SDValue, 8> Ops;
5733   for (unsigned i = 0; i != NumElts; ++i) {
5734     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5735     const APInt &CInt = C->getAPIntValue();
5736     // Element types smaller than 32 bits are not legal, so use i32 elements.
5737     // The values are implicitly truncated so sext vs. zext doesn't matter.
5738     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5739   }
5740   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5741                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5742 }
5743
5744 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5745   unsigned Opcode = N->getOpcode();
5746   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5747     SDNode *N0 = N->getOperand(0).getNode();
5748     SDNode *N1 = N->getOperand(1).getNode();
5749     return N0->hasOneUse() && N1->hasOneUse() &&
5750       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5751   }
5752   return false;
5753 }
5754
5755 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5756   unsigned Opcode = N->getOpcode();
5757   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5758     SDNode *N0 = N->getOperand(0).getNode();
5759     SDNode *N1 = N->getOperand(1).getNode();
5760     return N0->hasOneUse() && N1->hasOneUse() &&
5761       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5762   }
5763   return false;
5764 }
5765
5766 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5767   // Multiplications are only custom-lowered for 128-bit vectors so that
5768   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5769   EVT VT = Op.getValueType();
5770   assert(VT.is128BitVector() && VT.isInteger() &&
5771          "unexpected type for custom-lowering ISD::MUL");
5772   SDNode *N0 = Op.getOperand(0).getNode();
5773   SDNode *N1 = Op.getOperand(1).getNode();
5774   unsigned NewOpc = 0;
5775   bool isMLA = false;
5776   bool isN0SExt = isSignExtended(N0, DAG);
5777   bool isN1SExt = isSignExtended(N1, DAG);
5778   if (isN0SExt && isN1SExt)
5779     NewOpc = ARMISD::VMULLs;
5780   else {
5781     bool isN0ZExt = isZeroExtended(N0, DAG);
5782     bool isN1ZExt = isZeroExtended(N1, DAG);
5783     if (isN0ZExt && isN1ZExt)
5784       NewOpc = ARMISD::VMULLu;
5785     else if (isN1SExt || isN1ZExt) {
5786       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5787       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5788       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5789         NewOpc = ARMISD::VMULLs;
5790         isMLA = true;
5791       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5792         NewOpc = ARMISD::VMULLu;
5793         isMLA = true;
5794       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5795         std::swap(N0, N1);
5796         NewOpc = ARMISD::VMULLu;
5797         isMLA = true;
5798       }
5799     }
5800
5801     if (!NewOpc) {
5802       if (VT == MVT::v2i64)
5803         // Fall through to expand this.  It is not legal.
5804         return SDValue();
5805       else
5806         // Other vector multiplications are legal.
5807         return Op;
5808     }
5809   }
5810
5811   // Legalize to a VMULL instruction.
5812   SDLoc DL(Op);
5813   SDValue Op0;
5814   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5815   if (!isMLA) {
5816     Op0 = SkipExtensionForVMULL(N0, DAG);
5817     assert(Op0.getValueType().is64BitVector() &&
5818            Op1.getValueType().is64BitVector() &&
5819            "unexpected types for extended operands to VMULL");
5820     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5821   }
5822
5823   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5824   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5825   //   vmull q0, d4, d6
5826   //   vmlal q0, d5, d6
5827   // is faster than
5828   //   vaddl q0, d4, d5
5829   //   vmovl q1, d6
5830   //   vmul  q0, q0, q1
5831   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5832   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5833   EVT Op1VT = Op1.getValueType();
5834   return DAG.getNode(N0->getOpcode(), DL, VT,
5835                      DAG.getNode(NewOpc, DL, VT,
5836                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5837                      DAG.getNode(NewOpc, DL, VT,
5838                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5839 }
5840
5841 static SDValue
5842 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5843   // Convert to float
5844   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5845   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5846   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5847   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5848   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5849   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5850   // Get reciprocal estimate.
5851   // float4 recip = vrecpeq_f32(yf);
5852   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5853                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5854   // Because char has a smaller range than uchar, we can actually get away
5855   // without any newton steps.  This requires that we use a weird bias
5856   // of 0xb000, however (again, this has been exhaustively tested).
5857   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5858   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5859   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5860   Y = DAG.getConstant(0xb000, MVT::i32);
5861   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5862   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5863   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5864   // Convert back to short.
5865   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5866   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5867   return X;
5868 }
5869
5870 static SDValue
5871 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5872   SDValue N2;
5873   // Convert to float.
5874   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5875   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5876   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5877   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5878   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5879   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5880
5881   // Use reciprocal estimate and one refinement step.
5882   // float4 recip = vrecpeq_f32(yf);
5883   // recip *= vrecpsq_f32(yf, recip);
5884   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5885                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5886   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5887                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5888                    N1, N2);
5889   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5890   // Because short has a smaller range than ushort, we can actually get away
5891   // with only a single newton step.  This requires that we use a weird bias
5892   // of 89, however (again, this has been exhaustively tested).
5893   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5894   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5895   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5896   N1 = DAG.getConstant(0x89, MVT::i32);
5897   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5898   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5899   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5900   // Convert back to integer and return.
5901   // return vmovn_s32(vcvt_s32_f32(result));
5902   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5903   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5904   return N0;
5905 }
5906
5907 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5908   EVT VT = Op.getValueType();
5909   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5910          "unexpected type for custom-lowering ISD::SDIV");
5911
5912   SDLoc dl(Op);
5913   SDValue N0 = Op.getOperand(0);
5914   SDValue N1 = Op.getOperand(1);
5915   SDValue N2, N3;
5916
5917   if (VT == MVT::v8i8) {
5918     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5919     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5920
5921     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5922                      DAG.getIntPtrConstant(4));
5923     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5924                      DAG.getIntPtrConstant(4));
5925     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5926                      DAG.getIntPtrConstant(0));
5927     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5928                      DAG.getIntPtrConstant(0));
5929
5930     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5931     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5932
5933     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5934     N0 = LowerCONCAT_VECTORS(N0, DAG);
5935
5936     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5937     return N0;
5938   }
5939   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5940 }
5941
5942 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5943   EVT VT = Op.getValueType();
5944   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5945          "unexpected type for custom-lowering ISD::UDIV");
5946
5947   SDLoc dl(Op);
5948   SDValue N0 = Op.getOperand(0);
5949   SDValue N1 = Op.getOperand(1);
5950   SDValue N2, N3;
5951
5952   if (VT == MVT::v8i8) {
5953     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5954     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5955
5956     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5957                      DAG.getIntPtrConstant(4));
5958     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5959                      DAG.getIntPtrConstant(4));
5960     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5961                      DAG.getIntPtrConstant(0));
5962     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5963                      DAG.getIntPtrConstant(0));
5964
5965     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5966     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5967
5968     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5969     N0 = LowerCONCAT_VECTORS(N0, DAG);
5970
5971     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5972                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5973                      N0);
5974     return N0;
5975   }
5976
5977   // v4i16 sdiv ... Convert to float.
5978   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5979   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5980   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5981   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5982   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5983   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5984
5985   // Use reciprocal estimate and two refinement steps.
5986   // float4 recip = vrecpeq_f32(yf);
5987   // recip *= vrecpsq_f32(yf, recip);
5988   // recip *= vrecpsq_f32(yf, recip);
5989   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5990                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5991   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5992                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5993                    BN1, N2);
5994   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5995   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5996                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5997                    BN1, N2);
5998   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5999   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6000   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6001   // and that it will never cause us to return an answer too large).
6002   // float4 result = as_float4(as_int4(xf*recip) + 2);
6003   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6004   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6005   N1 = DAG.getConstant(2, MVT::i32);
6006   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6007   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6008   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6009   // Convert back to integer and return.
6010   // return vmovn_u32(vcvt_s32_f32(result));
6011   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6012   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6013   return N0;
6014 }
6015
6016 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6017   EVT VT = Op.getNode()->getValueType(0);
6018   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6019
6020   unsigned Opc;
6021   bool ExtraOp = false;
6022   switch (Op.getOpcode()) {
6023   default: llvm_unreachable("Invalid code");
6024   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6025   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6026   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6027   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6028   }
6029
6030   if (!ExtraOp)
6031     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6032                        Op.getOperand(1));
6033   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6034                      Op.getOperand(1), Op.getOperand(2));
6035 }
6036
6037 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6038   assert(Subtarget->isTargetDarwin());
6039
6040   // For iOS, we want to call an alternative entry point: __sincos_stret,
6041   // return values are passed via sret.
6042   SDLoc dl(Op);
6043   SDValue Arg = Op.getOperand(0);
6044   EVT ArgVT = Arg.getValueType();
6045   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6046
6047   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6049
6050   // Pair of floats / doubles used to pass the result.
6051   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6052
6053   // Create stack object for sret.
6054   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6055   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6056   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6057   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6058
6059   ArgListTy Args;
6060   ArgListEntry Entry;
6061
6062   Entry.Node = SRet;
6063   Entry.Ty = RetTy->getPointerTo();
6064   Entry.isSExt = false;
6065   Entry.isZExt = false;
6066   Entry.isSRet = true;
6067   Args.push_back(Entry);
6068
6069   Entry.Node = Arg;
6070   Entry.Ty = ArgTy;
6071   Entry.isSExt = false;
6072   Entry.isZExt = false;
6073   Args.push_back(Entry);
6074
6075   const char *LibcallName  = (ArgVT == MVT::f64)
6076   ? "__sincos_stret" : "__sincosf_stret";
6077   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6078
6079   TargetLowering::CallLoweringInfo CLI(DAG);
6080   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6081     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6082                &Args, 0)
6083     .setDiscardResult();
6084
6085   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6086
6087   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6088                                 MachinePointerInfo(), false, false, false, 0);
6089
6090   // Address of cos field.
6091   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6092                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6093   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6094                                 MachinePointerInfo(), false, false, false, 0);
6095
6096   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6097   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6098                      LoadSin.getValue(0), LoadCos.getValue(0));
6099 }
6100
6101 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6102   // Monotonic load/store is legal for all targets
6103   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6104     return Op;
6105
6106   // Acquire/Release load/store is not legal for targets without a
6107   // dmb or equivalent available.
6108   return SDValue();
6109 }
6110
6111 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6112                                     SmallVectorImpl<SDValue> &Results,
6113                                     SelectionDAG &DAG,
6114                                     const ARMSubtarget *Subtarget) {
6115   SDLoc DL(N);
6116   SDValue Cycles32, OutChain;
6117
6118   if (Subtarget->hasPerfMon()) {
6119     // Under Power Management extensions, the cycle-count is:
6120     //    mrc p15, #0, <Rt>, c9, c13, #0
6121     SDValue Ops[] = { N->getOperand(0), // Chain
6122                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6123                       DAG.getConstant(15, MVT::i32),
6124                       DAG.getConstant(0, MVT::i32),
6125                       DAG.getConstant(9, MVT::i32),
6126                       DAG.getConstant(13, MVT::i32),
6127                       DAG.getConstant(0, MVT::i32)
6128     };
6129
6130     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6131                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6132     OutChain = Cycles32.getValue(1);
6133   } else {
6134     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6135     // there are older ARM CPUs that have implementation-specific ways of
6136     // obtaining this information (FIXME!).
6137     Cycles32 = DAG.getConstant(0, MVT::i32);
6138     OutChain = DAG.getEntryNode();
6139   }
6140
6141
6142   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6143                                  Cycles32, DAG.getConstant(0, MVT::i32));
6144   Results.push_back(Cycles64);
6145   Results.push_back(OutChain);
6146 }
6147
6148 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6149   switch (Op.getOpcode()) {
6150   default: llvm_unreachable("Don't know how to custom lower this!");
6151   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6152   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6153   case ISD::GlobalAddress:
6154     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6155     default: llvm_unreachable("unknown object format");
6156     case Triple::COFF:
6157       return LowerGlobalAddressWindows(Op, DAG);
6158     case Triple::ELF:
6159       return LowerGlobalAddressELF(Op, DAG);
6160     case Triple::MachO:
6161       return LowerGlobalAddressDarwin(Op, DAG);
6162     }
6163   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6164   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6165   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6166   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6167   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6168   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6169   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6170   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6171   case ISD::SINT_TO_FP:
6172   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6173   case ISD::FP_TO_SINT:
6174   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6175   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6176   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6177   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6178   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6179   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6180   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6181   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6182                                                                Subtarget);
6183   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6184   case ISD::SHL:
6185   case ISD::SRL:
6186   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6187   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6188   case ISD::SRL_PARTS:
6189   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6190   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6191   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6192   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6193   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6194   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6195   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6196   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6197   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6198   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6199   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6200   case ISD::MUL:           return LowerMUL(Op, DAG);
6201   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6202   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6203   case ISD::ADDC:
6204   case ISD::ADDE:
6205   case ISD::SUBC:
6206   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6207   case ISD::SADDO:
6208   case ISD::UADDO:
6209   case ISD::SSUBO:
6210   case ISD::USUBO:
6211     return LowerXALUO(Op, DAG);
6212   case ISD::ATOMIC_LOAD:
6213   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6214   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6215   case ISD::SDIVREM:
6216   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6217   }
6218 }
6219
6220 /// ReplaceNodeResults - Replace the results of node with an illegal result
6221 /// type with new values built out of custom code.
6222 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6223                                            SmallVectorImpl<SDValue>&Results,
6224                                            SelectionDAG &DAG) const {
6225   SDValue Res;
6226   switch (N->getOpcode()) {
6227   default:
6228     llvm_unreachable("Don't know how to custom expand this!");
6229   case ISD::BITCAST:
6230     Res = ExpandBITCAST(N, DAG);
6231     break;
6232   case ISD::SRL:
6233   case ISD::SRA:
6234     Res = Expand64BitShift(N, DAG, Subtarget);
6235     break;
6236   case ISD::READCYCLECOUNTER:
6237     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6238     return;
6239   }
6240   if (Res.getNode())
6241     Results.push_back(Res);
6242 }
6243
6244 //===----------------------------------------------------------------------===//
6245 //                           ARM Scheduler Hooks
6246 //===----------------------------------------------------------------------===//
6247
6248 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6249 /// registers the function context.
6250 void ARMTargetLowering::
6251 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6252                        MachineBasicBlock *DispatchBB, int FI) const {
6253   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6254   DebugLoc dl = MI->getDebugLoc();
6255   MachineFunction *MF = MBB->getParent();
6256   MachineRegisterInfo *MRI = &MF->getRegInfo();
6257   MachineConstantPool *MCP = MF->getConstantPool();
6258   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6259   const Function *F = MF->getFunction();
6260
6261   bool isThumb = Subtarget->isThumb();
6262   bool isThumb2 = Subtarget->isThumb2();
6263
6264   unsigned PCLabelId = AFI->createPICLabelUId();
6265   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6266   ARMConstantPoolValue *CPV =
6267     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6268   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6269
6270   const TargetRegisterClass *TRC = isThumb ?
6271     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6272     (const TargetRegisterClass*)&ARM::GPRRegClass;
6273
6274   // Grab constant pool and fixed stack memory operands.
6275   MachineMemOperand *CPMMO =
6276     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6277                              MachineMemOperand::MOLoad, 4, 4);
6278
6279   MachineMemOperand *FIMMOSt =
6280     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6281                              MachineMemOperand::MOStore, 4, 4);
6282
6283   // Load the address of the dispatch MBB into the jump buffer.
6284   if (isThumb2) {
6285     // Incoming value: jbuf
6286     //   ldr.n  r5, LCPI1_1
6287     //   orr    r5, r5, #1
6288     //   add    r5, pc
6289     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6290     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6291     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6292                    .addConstantPoolIndex(CPI)
6293                    .addMemOperand(CPMMO));
6294     // Set the low bit because of thumb mode.
6295     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6296     AddDefaultCC(
6297       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6298                      .addReg(NewVReg1, RegState::Kill)
6299                      .addImm(0x01)));
6300     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6301     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6302       .addReg(NewVReg2, RegState::Kill)
6303       .addImm(PCLabelId);
6304     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6305                    .addReg(NewVReg3, RegState::Kill)
6306                    .addFrameIndex(FI)
6307                    .addImm(36)  // &jbuf[1] :: pc
6308                    .addMemOperand(FIMMOSt));
6309   } else if (isThumb) {
6310     // Incoming value: jbuf
6311     //   ldr.n  r1, LCPI1_4
6312     //   add    r1, pc
6313     //   mov    r2, #1
6314     //   orrs   r1, r2
6315     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6316     //   str    r1, [r2]
6317     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6318     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6319                    .addConstantPoolIndex(CPI)
6320                    .addMemOperand(CPMMO));
6321     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6322     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6323       .addReg(NewVReg1, RegState::Kill)
6324       .addImm(PCLabelId);
6325     // Set the low bit because of thumb mode.
6326     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6327     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6328                    .addReg(ARM::CPSR, RegState::Define)
6329                    .addImm(1));
6330     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6331     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6332                    .addReg(ARM::CPSR, RegState::Define)
6333                    .addReg(NewVReg2, RegState::Kill)
6334                    .addReg(NewVReg3, RegState::Kill));
6335     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6336     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6337                    .addFrameIndex(FI)
6338                    .addImm(36)); // &jbuf[1] :: pc
6339     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6340                    .addReg(NewVReg4, RegState::Kill)
6341                    .addReg(NewVReg5, RegState::Kill)
6342                    .addImm(0)
6343                    .addMemOperand(FIMMOSt));
6344   } else {
6345     // Incoming value: jbuf
6346     //   ldr  r1, LCPI1_1
6347     //   add  r1, pc, r1
6348     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6349     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6350     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6351                    .addConstantPoolIndex(CPI)
6352                    .addImm(0)
6353                    .addMemOperand(CPMMO));
6354     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6355     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6356                    .addReg(NewVReg1, RegState::Kill)
6357                    .addImm(PCLabelId));
6358     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6359                    .addReg(NewVReg2, RegState::Kill)
6360                    .addFrameIndex(FI)
6361                    .addImm(36)  // &jbuf[1] :: pc
6362                    .addMemOperand(FIMMOSt));
6363   }
6364 }
6365
6366 MachineBasicBlock *ARMTargetLowering::
6367 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6368   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6369   DebugLoc dl = MI->getDebugLoc();
6370   MachineFunction *MF = MBB->getParent();
6371   MachineRegisterInfo *MRI = &MF->getRegInfo();
6372   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6373   MachineFrameInfo *MFI = MF->getFrameInfo();
6374   int FI = MFI->getFunctionContextIndex();
6375
6376   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6377     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6378     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6379
6380   // Get a mapping of the call site numbers to all of the landing pads they're
6381   // associated with.
6382   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6383   unsigned MaxCSNum = 0;
6384   MachineModuleInfo &MMI = MF->getMMI();
6385   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6386        ++BB) {
6387     if (!BB->isLandingPad()) continue;
6388
6389     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6390     // pad.
6391     for (MachineBasicBlock::iterator
6392            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6393       if (!II->isEHLabel()) continue;
6394
6395       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6396       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6397
6398       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6399       for (SmallVectorImpl<unsigned>::iterator
6400              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6401            CSI != CSE; ++CSI) {
6402         CallSiteNumToLPad[*CSI].push_back(BB);
6403         MaxCSNum = std::max(MaxCSNum, *CSI);
6404       }
6405       break;
6406     }
6407   }
6408
6409   // Get an ordered list of the machine basic blocks for the jump table.
6410   std::vector<MachineBasicBlock*> LPadList;
6411   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6412   LPadList.reserve(CallSiteNumToLPad.size());
6413   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6414     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6415     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6416            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6417       LPadList.push_back(*II);
6418       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6419     }
6420   }
6421
6422   assert(!LPadList.empty() &&
6423          "No landing pad destinations for the dispatch jump table!");
6424
6425   // Create the jump table and associated information.
6426   MachineJumpTableInfo *JTI =
6427     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6428   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6429   unsigned UId = AFI->createJumpTableUId();
6430   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6431
6432   // Create the MBBs for the dispatch code.
6433
6434   // Shove the dispatch's address into the return slot in the function context.
6435   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6436   DispatchBB->setIsLandingPad();
6437
6438   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6439   unsigned trap_opcode;
6440   if (Subtarget->isThumb())
6441     trap_opcode = ARM::tTRAP;
6442   else
6443     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6444
6445   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6446   DispatchBB->addSuccessor(TrapBB);
6447
6448   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6449   DispatchBB->addSuccessor(DispContBB);
6450
6451   // Insert and MBBs.
6452   MF->insert(MF->end(), DispatchBB);
6453   MF->insert(MF->end(), DispContBB);
6454   MF->insert(MF->end(), TrapBB);
6455
6456   // Insert code into the entry block that creates and registers the function
6457   // context.
6458   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6459
6460   MachineMemOperand *FIMMOLd =
6461     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6462                              MachineMemOperand::MOLoad |
6463                              MachineMemOperand::MOVolatile, 4, 4);
6464
6465   MachineInstrBuilder MIB;
6466   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6467
6468   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6469   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6470
6471   // Add a register mask with no preserved registers.  This results in all
6472   // registers being marked as clobbered.
6473   MIB.addRegMask(RI.getNoPreservedMask());
6474
6475   unsigned NumLPads = LPadList.size();
6476   if (Subtarget->isThumb2()) {
6477     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6478     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6479                    .addFrameIndex(FI)
6480                    .addImm(4)
6481                    .addMemOperand(FIMMOLd));
6482
6483     if (NumLPads < 256) {
6484       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6485                      .addReg(NewVReg1)
6486                      .addImm(LPadList.size()));
6487     } else {
6488       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6489       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6490                      .addImm(NumLPads & 0xFFFF));
6491
6492       unsigned VReg2 = VReg1;
6493       if ((NumLPads & 0xFFFF0000) != 0) {
6494         VReg2 = MRI->createVirtualRegister(TRC);
6495         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6496                        .addReg(VReg1)
6497                        .addImm(NumLPads >> 16));
6498       }
6499
6500       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6501                      .addReg(NewVReg1)
6502                      .addReg(VReg2));
6503     }
6504
6505     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6506       .addMBB(TrapBB)
6507       .addImm(ARMCC::HI)
6508       .addReg(ARM::CPSR);
6509
6510     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6511     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6512                    .addJumpTableIndex(MJTI)
6513                    .addImm(UId));
6514
6515     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6516     AddDefaultCC(
6517       AddDefaultPred(
6518         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6519         .addReg(NewVReg3, RegState::Kill)
6520         .addReg(NewVReg1)
6521         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6522
6523     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6524       .addReg(NewVReg4, RegState::Kill)
6525       .addReg(NewVReg1)
6526       .addJumpTableIndex(MJTI)
6527       .addImm(UId);
6528   } else if (Subtarget->isThumb()) {
6529     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6530     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6531                    .addFrameIndex(FI)
6532                    .addImm(1)
6533                    .addMemOperand(FIMMOLd));
6534
6535     if (NumLPads < 256) {
6536       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6537                      .addReg(NewVReg1)
6538                      .addImm(NumLPads));
6539     } else {
6540       MachineConstantPool *ConstantPool = MF->getConstantPool();
6541       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6542       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6543
6544       // MachineConstantPool wants an explicit alignment.
6545       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6546       if (Align == 0)
6547         Align = getDataLayout()->getTypeAllocSize(C->getType());
6548       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6549
6550       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6551       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6552                      .addReg(VReg1, RegState::Define)
6553                      .addConstantPoolIndex(Idx));
6554       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6555                      .addReg(NewVReg1)
6556                      .addReg(VReg1));
6557     }
6558
6559     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6560       .addMBB(TrapBB)
6561       .addImm(ARMCC::HI)
6562       .addReg(ARM::CPSR);
6563
6564     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6565     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6566                    .addReg(ARM::CPSR, RegState::Define)
6567                    .addReg(NewVReg1)
6568                    .addImm(2));
6569
6570     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6571     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6572                    .addJumpTableIndex(MJTI)
6573                    .addImm(UId));
6574
6575     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6576     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6577                    .addReg(ARM::CPSR, RegState::Define)
6578                    .addReg(NewVReg2, RegState::Kill)
6579                    .addReg(NewVReg3));
6580
6581     MachineMemOperand *JTMMOLd =
6582       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6583                                MachineMemOperand::MOLoad, 4, 4);
6584
6585     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6586     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6587                    .addReg(NewVReg4, RegState::Kill)
6588                    .addImm(0)
6589                    .addMemOperand(JTMMOLd));
6590
6591     unsigned NewVReg6 = NewVReg5;
6592     if (RelocM == Reloc::PIC_) {
6593       NewVReg6 = MRI->createVirtualRegister(TRC);
6594       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6595                      .addReg(ARM::CPSR, RegState::Define)
6596                      .addReg(NewVReg5, RegState::Kill)
6597                      .addReg(NewVReg3));
6598     }
6599
6600     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6601       .addReg(NewVReg6, RegState::Kill)
6602       .addJumpTableIndex(MJTI)
6603       .addImm(UId);
6604   } else {
6605     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6606     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6607                    .addFrameIndex(FI)
6608                    .addImm(4)
6609                    .addMemOperand(FIMMOLd));
6610
6611     if (NumLPads < 256) {
6612       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6613                      .addReg(NewVReg1)
6614                      .addImm(NumLPads));
6615     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6616       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6617       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6618                      .addImm(NumLPads & 0xFFFF));
6619
6620       unsigned VReg2 = VReg1;
6621       if ((NumLPads & 0xFFFF0000) != 0) {
6622         VReg2 = MRI->createVirtualRegister(TRC);
6623         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6624                        .addReg(VReg1)
6625                        .addImm(NumLPads >> 16));
6626       }
6627
6628       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6629                      .addReg(NewVReg1)
6630                      .addReg(VReg2));
6631     } else {
6632       MachineConstantPool *ConstantPool = MF->getConstantPool();
6633       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6634       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6635
6636       // MachineConstantPool wants an explicit alignment.
6637       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6638       if (Align == 0)
6639         Align = getDataLayout()->getTypeAllocSize(C->getType());
6640       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6641
6642       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6643       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6644                      .addReg(VReg1, RegState::Define)
6645                      .addConstantPoolIndex(Idx)
6646                      .addImm(0));
6647       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6648                      .addReg(NewVReg1)
6649                      .addReg(VReg1, RegState::Kill));
6650     }
6651
6652     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6653       .addMBB(TrapBB)
6654       .addImm(ARMCC::HI)
6655       .addReg(ARM::CPSR);
6656
6657     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6658     AddDefaultCC(
6659       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6660                      .addReg(NewVReg1)
6661                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6662     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6663     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6664                    .addJumpTableIndex(MJTI)
6665                    .addImm(UId));
6666
6667     MachineMemOperand *JTMMOLd =
6668       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6669                                MachineMemOperand::MOLoad, 4, 4);
6670     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6671     AddDefaultPred(
6672       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6673       .addReg(NewVReg3, RegState::Kill)
6674       .addReg(NewVReg4)
6675       .addImm(0)
6676       .addMemOperand(JTMMOLd));
6677
6678     if (RelocM == Reloc::PIC_) {
6679       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6680         .addReg(NewVReg5, RegState::Kill)
6681         .addReg(NewVReg4)
6682         .addJumpTableIndex(MJTI)
6683         .addImm(UId);
6684     } else {
6685       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6686         .addReg(NewVReg5, RegState::Kill)
6687         .addJumpTableIndex(MJTI)
6688         .addImm(UId);
6689     }
6690   }
6691
6692   // Add the jump table entries as successors to the MBB.
6693   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6694   for (std::vector<MachineBasicBlock*>::iterator
6695          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6696     MachineBasicBlock *CurMBB = *I;
6697     if (SeenMBBs.insert(CurMBB))
6698       DispContBB->addSuccessor(CurMBB);
6699   }
6700
6701   // N.B. the order the invoke BBs are processed in doesn't matter here.
6702   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6703   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6704   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6705          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6706     MachineBasicBlock *BB = *I;
6707
6708     // Remove the landing pad successor from the invoke block and replace it
6709     // with the new dispatch block.
6710     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6711                                                   BB->succ_end());
6712     while (!Successors.empty()) {
6713       MachineBasicBlock *SMBB = Successors.pop_back_val();
6714       if (SMBB->isLandingPad()) {
6715         BB->removeSuccessor(SMBB);
6716         MBBLPads.push_back(SMBB);
6717       }
6718     }
6719
6720     BB->addSuccessor(DispatchBB);
6721
6722     // Find the invoke call and mark all of the callee-saved registers as
6723     // 'implicit defined' so that they're spilled. This prevents code from
6724     // moving instructions to before the EH block, where they will never be
6725     // executed.
6726     for (MachineBasicBlock::reverse_iterator
6727            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6728       if (!II->isCall()) continue;
6729
6730       DenseMap<unsigned, bool> DefRegs;
6731       for (MachineInstr::mop_iterator
6732              OI = II->operands_begin(), OE = II->operands_end();
6733            OI != OE; ++OI) {
6734         if (!OI->isReg()) continue;
6735         DefRegs[OI->getReg()] = true;
6736       }
6737
6738       MachineInstrBuilder MIB(*MF, &*II);
6739
6740       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6741         unsigned Reg = SavedRegs[i];
6742         if (Subtarget->isThumb2() &&
6743             !ARM::tGPRRegClass.contains(Reg) &&
6744             !ARM::hGPRRegClass.contains(Reg))
6745           continue;
6746         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6747           continue;
6748         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6749           continue;
6750         if (!DefRegs[Reg])
6751           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6752       }
6753
6754       break;
6755     }
6756   }
6757
6758   // Mark all former landing pads as non-landing pads. The dispatch is the only
6759   // landing pad now.
6760   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6761          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6762     (*I)->setIsLandingPad(false);
6763
6764   // The instruction is gone now.
6765   MI->eraseFromParent();
6766
6767   return MBB;
6768 }
6769
6770 static
6771 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6772   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6773        E = MBB->succ_end(); I != E; ++I)
6774     if (*I != Succ)
6775       return *I;
6776   llvm_unreachable("Expecting a BB with two successors!");
6777 }
6778
6779 /// Return the load opcode for a given load size. If load size >= 8,
6780 /// neon opcode will be returned.
6781 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6782   if (LdSize >= 8)
6783     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6784                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6785   if (IsThumb1)
6786     return LdSize == 4 ? ARM::tLDRi
6787                        : LdSize == 2 ? ARM::tLDRHi
6788                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6789   if (IsThumb2)
6790     return LdSize == 4 ? ARM::t2LDR_POST
6791                        : LdSize == 2 ? ARM::t2LDRH_POST
6792                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6793   return LdSize == 4 ? ARM::LDR_POST_IMM
6794                      : LdSize == 2 ? ARM::LDRH_POST
6795                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6796 }
6797
6798 /// Return the store opcode for a given store size. If store size >= 8,
6799 /// neon opcode will be returned.
6800 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6801   if (StSize >= 8)
6802     return StSize == 16 ? ARM::VST1q32wb_fixed
6803                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6804   if (IsThumb1)
6805     return StSize == 4 ? ARM::tSTRi
6806                        : StSize == 2 ? ARM::tSTRHi
6807                                      : StSize == 1 ? ARM::tSTRBi : 0;
6808   if (IsThumb2)
6809     return StSize == 4 ? ARM::t2STR_POST
6810                        : StSize == 2 ? ARM::t2STRH_POST
6811                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6812   return StSize == 4 ? ARM::STR_POST_IMM
6813                      : StSize == 2 ? ARM::STRH_POST
6814                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6815 }
6816
6817 /// Emit a post-increment load operation with given size. The instructions
6818 /// will be added to BB at Pos.
6819 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6820                        const TargetInstrInfo *TII, DebugLoc dl,
6821                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6822                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6823   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6824   assert(LdOpc != 0 && "Should have a load opcode");
6825   if (LdSize >= 8) {
6826     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6827                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6828                        .addImm(0));
6829   } else if (IsThumb1) {
6830     // load + update AddrIn
6831     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6832                        .addReg(AddrIn).addImm(0));
6833     MachineInstrBuilder MIB =
6834         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6835     MIB = AddDefaultT1CC(MIB);
6836     MIB.addReg(AddrIn).addImm(LdSize);
6837     AddDefaultPred(MIB);
6838   } else if (IsThumb2) {
6839     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6840                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6841                        .addImm(LdSize));
6842   } else { // arm
6843     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6844                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6845                        .addReg(0).addImm(LdSize));
6846   }
6847 }
6848
6849 /// Emit a post-increment store operation with given size. The instructions
6850 /// will be added to BB at Pos.
6851 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6852                        const TargetInstrInfo *TII, DebugLoc dl,
6853                        unsigned StSize, unsigned Data, unsigned AddrIn,
6854                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6855   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6856   assert(StOpc != 0 && "Should have a store opcode");
6857   if (StSize >= 8) {
6858     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6859                        .addReg(AddrIn).addImm(0).addReg(Data));
6860   } else if (IsThumb1) {
6861     // store + update AddrIn
6862     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6863                        .addReg(AddrIn).addImm(0));
6864     MachineInstrBuilder MIB =
6865         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6866     MIB = AddDefaultT1CC(MIB);
6867     MIB.addReg(AddrIn).addImm(StSize);
6868     AddDefaultPred(MIB);
6869   } else if (IsThumb2) {
6870     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6871                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6872   } else { // arm
6873     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6874                        .addReg(Data).addReg(AddrIn).addReg(0)
6875                        .addImm(StSize));
6876   }
6877 }
6878
6879 MachineBasicBlock *
6880 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6881                                    MachineBasicBlock *BB) const {
6882   // This pseudo instruction has 3 operands: dst, src, size
6883   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6884   // Otherwise, we will generate unrolled scalar copies.
6885   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6886   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6887   MachineFunction::iterator It = BB;
6888   ++It;
6889
6890   unsigned dest = MI->getOperand(0).getReg();
6891   unsigned src = MI->getOperand(1).getReg();
6892   unsigned SizeVal = MI->getOperand(2).getImm();
6893   unsigned Align = MI->getOperand(3).getImm();
6894   DebugLoc dl = MI->getDebugLoc();
6895
6896   MachineFunction *MF = BB->getParent();
6897   MachineRegisterInfo &MRI = MF->getRegInfo();
6898   unsigned UnitSize = 0;
6899   const TargetRegisterClass *TRC = nullptr;
6900   const TargetRegisterClass *VecTRC = nullptr;
6901
6902   bool IsThumb1 = Subtarget->isThumb1Only();
6903   bool IsThumb2 = Subtarget->isThumb2();
6904
6905   if (Align & 1) {
6906     UnitSize = 1;
6907   } else if (Align & 2) {
6908     UnitSize = 2;
6909   } else {
6910     // Check whether we can use NEON instructions.
6911     if (!MF->getFunction()->getAttributes().
6912           hasAttribute(AttributeSet::FunctionIndex,
6913                        Attribute::NoImplicitFloat) &&
6914         Subtarget->hasNEON()) {
6915       if ((Align % 16 == 0) && SizeVal >= 16)
6916         UnitSize = 16;
6917       else if ((Align % 8 == 0) && SizeVal >= 8)
6918         UnitSize = 8;
6919     }
6920     // Can't use NEON instructions.
6921     if (UnitSize == 0)
6922       UnitSize = 4;
6923   }
6924
6925   // Select the correct opcode and register class for unit size load/store
6926   bool IsNeon = UnitSize >= 8;
6927   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6928                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6929   if (IsNeon)
6930     VecTRC = UnitSize == 16
6931                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6932                  : UnitSize == 8
6933                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6934                        : nullptr;
6935
6936   unsigned BytesLeft = SizeVal % UnitSize;
6937   unsigned LoopSize = SizeVal - BytesLeft;
6938
6939   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6940     // Use LDR and STR to copy.
6941     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6942     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6943     unsigned srcIn = src;
6944     unsigned destIn = dest;
6945     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6946       unsigned srcOut = MRI.createVirtualRegister(TRC);
6947       unsigned destOut = MRI.createVirtualRegister(TRC);
6948       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6949       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6950                  IsThumb1, IsThumb2);
6951       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6952                  IsThumb1, IsThumb2);
6953       srcIn = srcOut;
6954       destIn = destOut;
6955     }
6956
6957     // Handle the leftover bytes with LDRB and STRB.
6958     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6959     // [destOut] = STRB_POST(scratch, destIn, 1)
6960     for (unsigned i = 0; i < BytesLeft; i++) {
6961       unsigned srcOut = MRI.createVirtualRegister(TRC);
6962       unsigned destOut = MRI.createVirtualRegister(TRC);
6963       unsigned scratch = MRI.createVirtualRegister(TRC);
6964       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6965                  IsThumb1, IsThumb2);
6966       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6967                  IsThumb1, IsThumb2);
6968       srcIn = srcOut;
6969       destIn = destOut;
6970     }
6971     MI->eraseFromParent();   // The instruction is gone now.
6972     return BB;
6973   }
6974
6975   // Expand the pseudo op to a loop.
6976   // thisMBB:
6977   //   ...
6978   //   movw varEnd, # --> with thumb2
6979   //   movt varEnd, #
6980   //   ldrcp varEnd, idx --> without thumb2
6981   //   fallthrough --> loopMBB
6982   // loopMBB:
6983   //   PHI varPhi, varEnd, varLoop
6984   //   PHI srcPhi, src, srcLoop
6985   //   PHI destPhi, dst, destLoop
6986   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6987   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6988   //   subs varLoop, varPhi, #UnitSize
6989   //   bne loopMBB
6990   //   fallthrough --> exitMBB
6991   // exitMBB:
6992   //   epilogue to handle left-over bytes
6993   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6994   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6995   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6996   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6997   MF->insert(It, loopMBB);
6998   MF->insert(It, exitMBB);
6999
7000   // Transfer the remainder of BB and its successor edges to exitMBB.
7001   exitMBB->splice(exitMBB->begin(), BB,
7002                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7003   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7004
7005   // Load an immediate to varEnd.
7006   unsigned varEnd = MRI.createVirtualRegister(TRC);
7007   if (IsThumb2) {
7008     unsigned Vtmp = varEnd;
7009     if ((LoopSize & 0xFFFF0000) != 0)
7010       Vtmp = MRI.createVirtualRegister(TRC);
7011     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7012                        .addImm(LoopSize & 0xFFFF));
7013
7014     if ((LoopSize & 0xFFFF0000) != 0)
7015       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7016                          .addReg(Vtmp).addImm(LoopSize >> 16));
7017   } else {
7018     MachineConstantPool *ConstantPool = MF->getConstantPool();
7019     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7020     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7021
7022     // MachineConstantPool wants an explicit alignment.
7023     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7024     if (Align == 0)
7025       Align = getDataLayout()->getTypeAllocSize(C->getType());
7026     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7027
7028     if (IsThumb1)
7029       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7030           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7031     else
7032       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7033           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7034   }
7035   BB->addSuccessor(loopMBB);
7036
7037   // Generate the loop body:
7038   //   varPhi = PHI(varLoop, varEnd)
7039   //   srcPhi = PHI(srcLoop, src)
7040   //   destPhi = PHI(destLoop, dst)
7041   MachineBasicBlock *entryBB = BB;
7042   BB = loopMBB;
7043   unsigned varLoop = MRI.createVirtualRegister(TRC);
7044   unsigned varPhi = MRI.createVirtualRegister(TRC);
7045   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7046   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7047   unsigned destLoop = MRI.createVirtualRegister(TRC);
7048   unsigned destPhi = MRI.createVirtualRegister(TRC);
7049
7050   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7051     .addReg(varLoop).addMBB(loopMBB)
7052     .addReg(varEnd).addMBB(entryBB);
7053   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7054     .addReg(srcLoop).addMBB(loopMBB)
7055     .addReg(src).addMBB(entryBB);
7056   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7057     .addReg(destLoop).addMBB(loopMBB)
7058     .addReg(dest).addMBB(entryBB);
7059
7060   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7061   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7062   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7063   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7064              IsThumb1, IsThumb2);
7065   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7066              IsThumb1, IsThumb2);
7067
7068   // Decrement loop variable by UnitSize.
7069   if (IsThumb1) {
7070     MachineInstrBuilder MIB =
7071         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7072     MIB = AddDefaultT1CC(MIB);
7073     MIB.addReg(varPhi).addImm(UnitSize);
7074     AddDefaultPred(MIB);
7075   } else {
7076     MachineInstrBuilder MIB =
7077         BuildMI(*BB, BB->end(), dl,
7078                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7079     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7080     MIB->getOperand(5).setReg(ARM::CPSR);
7081     MIB->getOperand(5).setIsDef(true);
7082   }
7083   BuildMI(*BB, BB->end(), dl,
7084           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7085       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7086
7087   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7088   BB->addSuccessor(loopMBB);
7089   BB->addSuccessor(exitMBB);
7090
7091   // Add epilogue to handle BytesLeft.
7092   BB = exitMBB;
7093   MachineInstr *StartOfExit = exitMBB->begin();
7094
7095   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7096   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7097   unsigned srcIn = srcLoop;
7098   unsigned destIn = destLoop;
7099   for (unsigned i = 0; i < BytesLeft; i++) {
7100     unsigned srcOut = MRI.createVirtualRegister(TRC);
7101     unsigned destOut = MRI.createVirtualRegister(TRC);
7102     unsigned scratch = MRI.createVirtualRegister(TRC);
7103     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7104                IsThumb1, IsThumb2);
7105     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7106                IsThumb1, IsThumb2);
7107     srcIn = srcOut;
7108     destIn = destOut;
7109   }
7110
7111   MI->eraseFromParent();   // The instruction is gone now.
7112   return BB;
7113 }
7114
7115 MachineBasicBlock *
7116 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7117                                                MachineBasicBlock *BB) const {
7118   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7119   DebugLoc dl = MI->getDebugLoc();
7120   bool isThumb2 = Subtarget->isThumb2();
7121   switch (MI->getOpcode()) {
7122   default: {
7123     MI->dump();
7124     llvm_unreachable("Unexpected instr type to insert");
7125   }
7126   // The Thumb2 pre-indexed stores have the same MI operands, they just
7127   // define them differently in the .td files from the isel patterns, so
7128   // they need pseudos.
7129   case ARM::t2STR_preidx:
7130     MI->setDesc(TII->get(ARM::t2STR_PRE));
7131     return BB;
7132   case ARM::t2STRB_preidx:
7133     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7134     return BB;
7135   case ARM::t2STRH_preidx:
7136     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7137     return BB;
7138
7139   case ARM::STRi_preidx:
7140   case ARM::STRBi_preidx: {
7141     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7142       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7143     // Decode the offset.
7144     unsigned Offset = MI->getOperand(4).getImm();
7145     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7146     Offset = ARM_AM::getAM2Offset(Offset);
7147     if (isSub)
7148       Offset = -Offset;
7149
7150     MachineMemOperand *MMO = *MI->memoperands_begin();
7151     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7152       .addOperand(MI->getOperand(0))  // Rn_wb
7153       .addOperand(MI->getOperand(1))  // Rt
7154       .addOperand(MI->getOperand(2))  // Rn
7155       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7156       .addOperand(MI->getOperand(5))  // pred
7157       .addOperand(MI->getOperand(6))
7158       .addMemOperand(MMO);
7159     MI->eraseFromParent();
7160     return BB;
7161   }
7162   case ARM::STRr_preidx:
7163   case ARM::STRBr_preidx:
7164   case ARM::STRH_preidx: {
7165     unsigned NewOpc;
7166     switch (MI->getOpcode()) {
7167     default: llvm_unreachable("unexpected opcode!");
7168     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7169     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7170     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7171     }
7172     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7173     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7174       MIB.addOperand(MI->getOperand(i));
7175     MI->eraseFromParent();
7176     return BB;
7177   }
7178
7179   case ARM::tMOVCCr_pseudo: {
7180     // To "insert" a SELECT_CC instruction, we actually have to insert the
7181     // diamond control-flow pattern.  The incoming instruction knows the
7182     // destination vreg to set, the condition code register to branch on, the
7183     // true/false values to select between, and a branch opcode to use.
7184     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7185     MachineFunction::iterator It = BB;
7186     ++It;
7187
7188     //  thisMBB:
7189     //  ...
7190     //   TrueVal = ...
7191     //   cmpTY ccX, r1, r2
7192     //   bCC copy1MBB
7193     //   fallthrough --> copy0MBB
7194     MachineBasicBlock *thisMBB  = BB;
7195     MachineFunction *F = BB->getParent();
7196     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7197     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7198     F->insert(It, copy0MBB);
7199     F->insert(It, sinkMBB);
7200
7201     // Transfer the remainder of BB and its successor edges to sinkMBB.
7202     sinkMBB->splice(sinkMBB->begin(), BB,
7203                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7204     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7205
7206     BB->addSuccessor(copy0MBB);
7207     BB->addSuccessor(sinkMBB);
7208
7209     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7210       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7211
7212     //  copy0MBB:
7213     //   %FalseValue = ...
7214     //   # fallthrough to sinkMBB
7215     BB = copy0MBB;
7216
7217     // Update machine-CFG edges
7218     BB->addSuccessor(sinkMBB);
7219
7220     //  sinkMBB:
7221     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7222     //  ...
7223     BB = sinkMBB;
7224     BuildMI(*BB, BB->begin(), dl,
7225             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7226       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7227       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7228
7229     MI->eraseFromParent();   // The pseudo instruction is gone now.
7230     return BB;
7231   }
7232
7233   case ARM::BCCi64:
7234   case ARM::BCCZi64: {
7235     // If there is an unconditional branch to the other successor, remove it.
7236     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7237
7238     // Compare both parts that make up the double comparison separately for
7239     // equality.
7240     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7241
7242     unsigned LHS1 = MI->getOperand(1).getReg();
7243     unsigned LHS2 = MI->getOperand(2).getReg();
7244     if (RHSisZero) {
7245       AddDefaultPred(BuildMI(BB, dl,
7246                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7247                      .addReg(LHS1).addImm(0));
7248       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7249         .addReg(LHS2).addImm(0)
7250         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7251     } else {
7252       unsigned RHS1 = MI->getOperand(3).getReg();
7253       unsigned RHS2 = MI->getOperand(4).getReg();
7254       AddDefaultPred(BuildMI(BB, dl,
7255                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7256                      .addReg(LHS1).addReg(RHS1));
7257       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7258         .addReg(LHS2).addReg(RHS2)
7259         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7260     }
7261
7262     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7263     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7264     if (MI->getOperand(0).getImm() == ARMCC::NE)
7265       std::swap(destMBB, exitMBB);
7266
7267     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7268       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7269     if (isThumb2)
7270       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7271     else
7272       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7273
7274     MI->eraseFromParent();   // The pseudo instruction is gone now.
7275     return BB;
7276   }
7277
7278   case ARM::Int_eh_sjlj_setjmp:
7279   case ARM::Int_eh_sjlj_setjmp_nofp:
7280   case ARM::tInt_eh_sjlj_setjmp:
7281   case ARM::t2Int_eh_sjlj_setjmp:
7282   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7283     EmitSjLjDispatchBlock(MI, BB);
7284     return BB;
7285
7286   case ARM::ABS:
7287   case ARM::t2ABS: {
7288     // To insert an ABS instruction, we have to insert the
7289     // diamond control-flow pattern.  The incoming instruction knows the
7290     // source vreg to test against 0, the destination vreg to set,
7291     // the condition code register to branch on, the
7292     // true/false values to select between, and a branch opcode to use.
7293     // It transforms
7294     //     V1 = ABS V0
7295     // into
7296     //     V2 = MOVS V0
7297     //     BCC                      (branch to SinkBB if V0 >= 0)
7298     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7299     //     SinkBB: V1 = PHI(V2, V3)
7300     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7301     MachineFunction::iterator BBI = BB;
7302     ++BBI;
7303     MachineFunction *Fn = BB->getParent();
7304     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7305     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7306     Fn->insert(BBI, RSBBB);
7307     Fn->insert(BBI, SinkBB);
7308
7309     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7310     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7311     bool isThumb2 = Subtarget->isThumb2();
7312     MachineRegisterInfo &MRI = Fn->getRegInfo();
7313     // In Thumb mode S must not be specified if source register is the SP or
7314     // PC and if destination register is the SP, so restrict register class
7315     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7316       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7317       (const TargetRegisterClass*)&ARM::GPRRegClass);
7318
7319     // Transfer the remainder of BB and its successor edges to sinkMBB.
7320     SinkBB->splice(SinkBB->begin(), BB,
7321                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7322     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7323
7324     BB->addSuccessor(RSBBB);
7325     BB->addSuccessor(SinkBB);
7326
7327     // fall through to SinkMBB
7328     RSBBB->addSuccessor(SinkBB);
7329
7330     // insert a cmp at the end of BB
7331     AddDefaultPred(BuildMI(BB, dl,
7332                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7333                    .addReg(ABSSrcReg).addImm(0));
7334
7335     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7336     BuildMI(BB, dl,
7337       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7338       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7339
7340     // insert rsbri in RSBBB
7341     // Note: BCC and rsbri will be converted into predicated rsbmi
7342     // by if-conversion pass
7343     BuildMI(*RSBBB, RSBBB->begin(), dl,
7344       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7345       .addReg(ABSSrcReg, RegState::Kill)
7346       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7347
7348     // insert PHI in SinkBB,
7349     // reuse ABSDstReg to not change uses of ABS instruction
7350     BuildMI(*SinkBB, SinkBB->begin(), dl,
7351       TII->get(ARM::PHI), ABSDstReg)
7352       .addReg(NewRsbDstReg).addMBB(RSBBB)
7353       .addReg(ABSSrcReg).addMBB(BB);
7354
7355     // remove ABS instruction
7356     MI->eraseFromParent();
7357
7358     // return last added BB
7359     return SinkBB;
7360   }
7361   case ARM::COPY_STRUCT_BYVAL_I32:
7362     ++NumLoopByVals;
7363     return EmitStructByval(MI, BB);
7364   }
7365 }
7366
7367 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7368                                                       SDNode *Node) const {
7369   if (!MI->hasPostISelHook()) {
7370     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7371            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7372     return;
7373   }
7374
7375   const MCInstrDesc *MCID = &MI->getDesc();
7376   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7377   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7378   // operand is still set to noreg. If needed, set the optional operand's
7379   // register to CPSR, and remove the redundant implicit def.
7380   //
7381   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7382
7383   // Rename pseudo opcodes.
7384   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7385   if (NewOpc) {
7386     const ARMBaseInstrInfo *TII =
7387       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7388     MCID = &TII->get(NewOpc);
7389
7390     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7391            "converted opcode should be the same except for cc_out");
7392
7393     MI->setDesc(*MCID);
7394
7395     // Add the optional cc_out operand
7396     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7397   }
7398   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7399
7400   // Any ARM instruction that sets the 's' bit should specify an optional
7401   // "cc_out" operand in the last operand position.
7402   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7403     assert(!NewOpc && "Optional cc_out operand required");
7404     return;
7405   }
7406   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7407   // since we already have an optional CPSR def.
7408   bool definesCPSR = false;
7409   bool deadCPSR = false;
7410   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7411        i != e; ++i) {
7412     const MachineOperand &MO = MI->getOperand(i);
7413     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7414       definesCPSR = true;
7415       if (MO.isDead())
7416         deadCPSR = true;
7417       MI->RemoveOperand(i);
7418       break;
7419     }
7420   }
7421   if (!definesCPSR) {
7422     assert(!NewOpc && "Optional cc_out operand required");
7423     return;
7424   }
7425   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7426   if (deadCPSR) {
7427     assert(!MI->getOperand(ccOutIdx).getReg() &&
7428            "expect uninitialized optional cc_out operand");
7429     return;
7430   }
7431
7432   // If this instruction was defined with an optional CPSR def and its dag node
7433   // had a live implicit CPSR def, then activate the optional CPSR def.
7434   MachineOperand &MO = MI->getOperand(ccOutIdx);
7435   MO.setReg(ARM::CPSR);
7436   MO.setIsDef(true);
7437 }
7438
7439 //===----------------------------------------------------------------------===//
7440 //                           ARM Optimization Hooks
7441 //===----------------------------------------------------------------------===//
7442
7443 // Helper function that checks if N is a null or all ones constant.
7444 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7445   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7446   if (!C)
7447     return false;
7448   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7449 }
7450
7451 // Return true if N is conditionally 0 or all ones.
7452 // Detects these expressions where cc is an i1 value:
7453 //
7454 //   (select cc 0, y)   [AllOnes=0]
7455 //   (select cc y, 0)   [AllOnes=0]
7456 //   (zext cc)          [AllOnes=0]
7457 //   (sext cc)          [AllOnes=0/1]
7458 //   (select cc -1, y)  [AllOnes=1]
7459 //   (select cc y, -1)  [AllOnes=1]
7460 //
7461 // Invert is set when N is the null/all ones constant when CC is false.
7462 // OtherOp is set to the alternative value of N.
7463 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7464                                        SDValue &CC, bool &Invert,
7465                                        SDValue &OtherOp,
7466                                        SelectionDAG &DAG) {
7467   switch (N->getOpcode()) {
7468   default: return false;
7469   case ISD::SELECT: {
7470     CC = N->getOperand(0);
7471     SDValue N1 = N->getOperand(1);
7472     SDValue N2 = N->getOperand(2);
7473     if (isZeroOrAllOnes(N1, AllOnes)) {
7474       Invert = false;
7475       OtherOp = N2;
7476       return true;
7477     }
7478     if (isZeroOrAllOnes(N2, AllOnes)) {
7479       Invert = true;
7480       OtherOp = N1;
7481       return true;
7482     }
7483     return false;
7484   }
7485   case ISD::ZERO_EXTEND:
7486     // (zext cc) can never be the all ones value.
7487     if (AllOnes)
7488       return false;
7489     // Fall through.
7490   case ISD::SIGN_EXTEND: {
7491     EVT VT = N->getValueType(0);
7492     CC = N->getOperand(0);
7493     if (CC.getValueType() != MVT::i1)
7494       return false;
7495     Invert = !AllOnes;
7496     if (AllOnes)
7497       // When looking for an AllOnes constant, N is an sext, and the 'other'
7498       // value is 0.
7499       OtherOp = DAG.getConstant(0, VT);
7500     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7501       // When looking for a 0 constant, N can be zext or sext.
7502       OtherOp = DAG.getConstant(1, VT);
7503     else
7504       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7505     return true;
7506   }
7507   }
7508 }
7509
7510 // Combine a constant select operand into its use:
7511 //
7512 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7513 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7514 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7515 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7516 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7517 //
7518 // The transform is rejected if the select doesn't have a constant operand that
7519 // is null, or all ones when AllOnes is set.
7520 //
7521 // Also recognize sext/zext from i1:
7522 //
7523 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7524 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7525 //
7526 // These transformations eventually create predicated instructions.
7527 //
7528 // @param N       The node to transform.
7529 // @param Slct    The N operand that is a select.
7530 // @param OtherOp The other N operand (x above).
7531 // @param DCI     Context.
7532 // @param AllOnes Require the select constant to be all ones instead of null.
7533 // @returns The new node, or SDValue() on failure.
7534 static
7535 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7536                             TargetLowering::DAGCombinerInfo &DCI,
7537                             bool AllOnes = false) {
7538   SelectionDAG &DAG = DCI.DAG;
7539   EVT VT = N->getValueType(0);
7540   SDValue NonConstantVal;
7541   SDValue CCOp;
7542   bool SwapSelectOps;
7543   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7544                                   NonConstantVal, DAG))
7545     return SDValue();
7546
7547   // Slct is now know to be the desired identity constant when CC is true.
7548   SDValue TrueVal = OtherOp;
7549   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7550                                  OtherOp, NonConstantVal);
7551   // Unless SwapSelectOps says CC should be false.
7552   if (SwapSelectOps)
7553     std::swap(TrueVal, FalseVal);
7554
7555   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7556                      CCOp, TrueVal, FalseVal);
7557 }
7558
7559 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7560 static
7561 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7562                                        TargetLowering::DAGCombinerInfo &DCI) {
7563   SDValue N0 = N->getOperand(0);
7564   SDValue N1 = N->getOperand(1);
7565   if (N0.getNode()->hasOneUse()) {
7566     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7567     if (Result.getNode())
7568       return Result;
7569   }
7570   if (N1.getNode()->hasOneUse()) {
7571     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7572     if (Result.getNode())
7573       return Result;
7574   }
7575   return SDValue();
7576 }
7577
7578 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7579 // (only after legalization).
7580 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7581                                  TargetLowering::DAGCombinerInfo &DCI,
7582                                  const ARMSubtarget *Subtarget) {
7583
7584   // Only perform optimization if after legalize, and if NEON is available. We
7585   // also expected both operands to be BUILD_VECTORs.
7586   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7587       || N0.getOpcode() != ISD::BUILD_VECTOR
7588       || N1.getOpcode() != ISD::BUILD_VECTOR)
7589     return SDValue();
7590
7591   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7592   EVT VT = N->getValueType(0);
7593   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7594     return SDValue();
7595
7596   // Check that the vector operands are of the right form.
7597   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7598   // operands, where N is the size of the formed vector.
7599   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7600   // index such that we have a pair wise add pattern.
7601
7602   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7603   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7604     return SDValue();
7605   SDValue Vec = N0->getOperand(0)->getOperand(0);
7606   SDNode *V = Vec.getNode();
7607   unsigned nextIndex = 0;
7608
7609   // For each operands to the ADD which are BUILD_VECTORs,
7610   // check to see if each of their operands are an EXTRACT_VECTOR with
7611   // the same vector and appropriate index.
7612   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7613     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7614         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7615
7616       SDValue ExtVec0 = N0->getOperand(i);
7617       SDValue ExtVec1 = N1->getOperand(i);
7618
7619       // First operand is the vector, verify its the same.
7620       if (V != ExtVec0->getOperand(0).getNode() ||
7621           V != ExtVec1->getOperand(0).getNode())
7622         return SDValue();
7623
7624       // Second is the constant, verify its correct.
7625       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7626       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7627
7628       // For the constant, we want to see all the even or all the odd.
7629       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7630           || C1->getZExtValue() != nextIndex+1)
7631         return SDValue();
7632
7633       // Increment index.
7634       nextIndex+=2;
7635     } else
7636       return SDValue();
7637   }
7638
7639   // Create VPADDL node.
7640   SelectionDAG &DAG = DCI.DAG;
7641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7642
7643   // Build operand list.
7644   SmallVector<SDValue, 8> Ops;
7645   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7646                                 TLI.getPointerTy()));
7647
7648   // Input is the vector.
7649   Ops.push_back(Vec);
7650
7651   // Get widened type and narrowed type.
7652   MVT widenType;
7653   unsigned numElem = VT.getVectorNumElements();
7654   
7655   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7656   switch (inputLaneType.getSimpleVT().SimpleTy) {
7657     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7658     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7659     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7660     default:
7661       llvm_unreachable("Invalid vector element type for padd optimization.");
7662   }
7663
7664   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7665   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7666   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7667 }
7668
7669 static SDValue findMUL_LOHI(SDValue V) {
7670   if (V->getOpcode() == ISD::UMUL_LOHI ||
7671       V->getOpcode() == ISD::SMUL_LOHI)
7672     return V;
7673   return SDValue();
7674 }
7675
7676 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7677                                      TargetLowering::DAGCombinerInfo &DCI,
7678                                      const ARMSubtarget *Subtarget) {
7679
7680   if (Subtarget->isThumb1Only()) return SDValue();
7681
7682   // Only perform the checks after legalize when the pattern is available.
7683   if (DCI.isBeforeLegalize()) return SDValue();
7684
7685   // Look for multiply add opportunities.
7686   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7687   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7688   // a glue link from the first add to the second add.
7689   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7690   // a S/UMLAL instruction.
7691   //          loAdd   UMUL_LOHI
7692   //            \    / :lo    \ :hi
7693   //             \  /          \          [no multiline comment]
7694   //              ADDC         |  hiAdd
7695   //                 \ :glue  /  /
7696   //                  \      /  /
7697   //                    ADDE
7698   //
7699   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7700   SDValue AddcOp0 = AddcNode->getOperand(0);
7701   SDValue AddcOp1 = AddcNode->getOperand(1);
7702
7703   // Check if the two operands are from the same mul_lohi node.
7704   if (AddcOp0.getNode() == AddcOp1.getNode())
7705     return SDValue();
7706
7707   assert(AddcNode->getNumValues() == 2 &&
7708          AddcNode->getValueType(0) == MVT::i32 &&
7709          "Expect ADDC with two result values. First: i32");
7710
7711   // Check that we have a glued ADDC node.
7712   if (AddcNode->getValueType(1) != MVT::Glue)
7713     return SDValue();
7714
7715   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7716   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7717       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7718       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7719       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7720     return SDValue();
7721
7722   // Look for the glued ADDE.
7723   SDNode* AddeNode = AddcNode->getGluedUser();
7724   if (!AddeNode)
7725     return SDValue();
7726
7727   // Make sure it is really an ADDE.
7728   if (AddeNode->getOpcode() != ISD::ADDE)
7729     return SDValue();
7730
7731   assert(AddeNode->getNumOperands() == 3 &&
7732          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7733          "ADDE node has the wrong inputs");
7734
7735   // Check for the triangle shape.
7736   SDValue AddeOp0 = AddeNode->getOperand(0);
7737   SDValue AddeOp1 = AddeNode->getOperand(1);
7738
7739   // Make sure that the ADDE operands are not coming from the same node.
7740   if (AddeOp0.getNode() == AddeOp1.getNode())
7741     return SDValue();
7742
7743   // Find the MUL_LOHI node walking up ADDE's operands.
7744   bool IsLeftOperandMUL = false;
7745   SDValue MULOp = findMUL_LOHI(AddeOp0);
7746   if (MULOp == SDValue())
7747    MULOp = findMUL_LOHI(AddeOp1);
7748   else
7749     IsLeftOperandMUL = true;
7750   if (MULOp == SDValue())
7751      return SDValue();
7752
7753   // Figure out the right opcode.
7754   unsigned Opc = MULOp->getOpcode();
7755   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7756
7757   // Figure out the high and low input values to the MLAL node.
7758   SDValue* HiMul = &MULOp;
7759   SDValue* HiAdd = nullptr;
7760   SDValue* LoMul = nullptr;
7761   SDValue* LowAdd = nullptr;
7762
7763   if (IsLeftOperandMUL)
7764     HiAdd = &AddeOp1;
7765   else
7766     HiAdd = &AddeOp0;
7767
7768
7769   if (AddcOp0->getOpcode() == Opc) {
7770     LoMul = &AddcOp0;
7771     LowAdd = &AddcOp1;
7772   }
7773   if (AddcOp1->getOpcode() == Opc) {
7774     LoMul = &AddcOp1;
7775     LowAdd = &AddcOp0;
7776   }
7777
7778   if (!LoMul)
7779     return SDValue();
7780
7781   if (LoMul->getNode() != HiMul->getNode())
7782     return SDValue();
7783
7784   // Create the merged node.
7785   SelectionDAG &DAG = DCI.DAG;
7786
7787   // Build operand list.
7788   SmallVector<SDValue, 8> Ops;
7789   Ops.push_back(LoMul->getOperand(0));
7790   Ops.push_back(LoMul->getOperand(1));
7791   Ops.push_back(*LowAdd);
7792   Ops.push_back(*HiAdd);
7793
7794   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7795                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7796
7797   // Replace the ADDs' nodes uses by the MLA node's values.
7798   SDValue HiMLALResult(MLALNode.getNode(), 1);
7799   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7800
7801   SDValue LoMLALResult(MLALNode.getNode(), 0);
7802   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7803
7804   // Return original node to notify the driver to stop replacing.
7805   SDValue resNode(AddcNode, 0);
7806   return resNode;
7807 }
7808
7809 /// PerformADDCCombine - Target-specific dag combine transform from
7810 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7811 static SDValue PerformADDCCombine(SDNode *N,
7812                                  TargetLowering::DAGCombinerInfo &DCI,
7813                                  const ARMSubtarget *Subtarget) {
7814
7815   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7816
7817 }
7818
7819 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7820 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7821 /// called with the default operands, and if that fails, with commuted
7822 /// operands.
7823 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7824                                           TargetLowering::DAGCombinerInfo &DCI,
7825                                           const ARMSubtarget *Subtarget){
7826
7827   // Attempt to create vpaddl for this add.
7828   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7829   if (Result.getNode())
7830     return Result;
7831
7832   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7833   if (N0.getNode()->hasOneUse()) {
7834     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7835     if (Result.getNode()) return Result;
7836   }
7837   return SDValue();
7838 }
7839
7840 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7841 ///
7842 static SDValue PerformADDCombine(SDNode *N,
7843                                  TargetLowering::DAGCombinerInfo &DCI,
7844                                  const ARMSubtarget *Subtarget) {
7845   SDValue N0 = N->getOperand(0);
7846   SDValue N1 = N->getOperand(1);
7847
7848   // First try with the default operand order.
7849   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7850   if (Result.getNode())
7851     return Result;
7852
7853   // If that didn't work, try again with the operands commuted.
7854   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7855 }
7856
7857 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7858 ///
7859 static SDValue PerformSUBCombine(SDNode *N,
7860                                  TargetLowering::DAGCombinerInfo &DCI) {
7861   SDValue N0 = N->getOperand(0);
7862   SDValue N1 = N->getOperand(1);
7863
7864   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7865   if (N1.getNode()->hasOneUse()) {
7866     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7867     if (Result.getNode()) return Result;
7868   }
7869
7870   return SDValue();
7871 }
7872
7873 /// PerformVMULCombine
7874 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7875 /// special multiplier accumulator forwarding.
7876 ///   vmul d3, d0, d2
7877 ///   vmla d3, d1, d2
7878 /// is faster than
7879 ///   vadd d3, d0, d1
7880 ///   vmul d3, d3, d2
7881 //  However, for (A + B) * (A + B),
7882 //    vadd d2, d0, d1
7883 //    vmul d3, d0, d2
7884 //    vmla d3, d1, d2
7885 //  is slower than
7886 //    vadd d2, d0, d1
7887 //    vmul d3, d2, d2
7888 static SDValue PerformVMULCombine(SDNode *N,
7889                                   TargetLowering::DAGCombinerInfo &DCI,
7890                                   const ARMSubtarget *Subtarget) {
7891   if (!Subtarget->hasVMLxForwarding())
7892     return SDValue();
7893
7894   SelectionDAG &DAG = DCI.DAG;
7895   SDValue N0 = N->getOperand(0);
7896   SDValue N1 = N->getOperand(1);
7897   unsigned Opcode = N0.getOpcode();
7898   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7899       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7900     Opcode = N1.getOpcode();
7901     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7902         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7903       return SDValue();
7904     std::swap(N0, N1);
7905   }
7906
7907   if (N0 == N1)
7908     return SDValue();
7909
7910   EVT VT = N->getValueType(0);
7911   SDLoc DL(N);
7912   SDValue N00 = N0->getOperand(0);
7913   SDValue N01 = N0->getOperand(1);
7914   return DAG.getNode(Opcode, DL, VT,
7915                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7916                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7917 }
7918
7919 static SDValue PerformMULCombine(SDNode *N,
7920                                  TargetLowering::DAGCombinerInfo &DCI,
7921                                  const ARMSubtarget *Subtarget) {
7922   SelectionDAG &DAG = DCI.DAG;
7923
7924   if (Subtarget->isThumb1Only())
7925     return SDValue();
7926
7927   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7928     return SDValue();
7929
7930   EVT VT = N->getValueType(0);
7931   if (VT.is64BitVector() || VT.is128BitVector())
7932     return PerformVMULCombine(N, DCI, Subtarget);
7933   if (VT != MVT::i32)
7934     return SDValue();
7935
7936   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7937   if (!C)
7938     return SDValue();
7939
7940   int64_t MulAmt = C->getSExtValue();
7941   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7942
7943   ShiftAmt = ShiftAmt & (32 - 1);
7944   SDValue V = N->getOperand(0);
7945   SDLoc DL(N);
7946
7947   SDValue Res;
7948   MulAmt >>= ShiftAmt;
7949
7950   if (MulAmt >= 0) {
7951     if (isPowerOf2_32(MulAmt - 1)) {
7952       // (mul x, 2^N + 1) => (add (shl x, N), x)
7953       Res = DAG.getNode(ISD::ADD, DL, VT,
7954                         V,
7955                         DAG.getNode(ISD::SHL, DL, VT,
7956                                     V,
7957                                     DAG.getConstant(Log2_32(MulAmt - 1),
7958                                                     MVT::i32)));
7959     } else if (isPowerOf2_32(MulAmt + 1)) {
7960       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7961       Res = DAG.getNode(ISD::SUB, DL, VT,
7962                         DAG.getNode(ISD::SHL, DL, VT,
7963                                     V,
7964                                     DAG.getConstant(Log2_32(MulAmt + 1),
7965                                                     MVT::i32)),
7966                         V);
7967     } else
7968       return SDValue();
7969   } else {
7970     uint64_t MulAmtAbs = -MulAmt;
7971     if (isPowerOf2_32(MulAmtAbs + 1)) {
7972       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7973       Res = DAG.getNode(ISD::SUB, DL, VT,
7974                         V,
7975                         DAG.getNode(ISD::SHL, DL, VT,
7976                                     V,
7977                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7978                                                     MVT::i32)));
7979     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7980       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7981       Res = DAG.getNode(ISD::ADD, DL, VT,
7982                         V,
7983                         DAG.getNode(ISD::SHL, DL, VT,
7984                                     V,
7985                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7986                                                     MVT::i32)));
7987       Res = DAG.getNode(ISD::SUB, DL, VT,
7988                         DAG.getConstant(0, MVT::i32),Res);
7989
7990     } else
7991       return SDValue();
7992   }
7993
7994   if (ShiftAmt != 0)
7995     Res = DAG.getNode(ISD::SHL, DL, VT,
7996                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7997
7998   // Do not add new nodes to DAG combiner worklist.
7999   DCI.CombineTo(N, Res, false);
8000   return SDValue();
8001 }
8002
8003 static SDValue PerformANDCombine(SDNode *N,
8004                                  TargetLowering::DAGCombinerInfo &DCI,
8005                                  const ARMSubtarget *Subtarget) {
8006
8007   // Attempt to use immediate-form VBIC
8008   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8009   SDLoc dl(N);
8010   EVT VT = N->getValueType(0);
8011   SelectionDAG &DAG = DCI.DAG;
8012
8013   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8014     return SDValue();
8015
8016   APInt SplatBits, SplatUndef;
8017   unsigned SplatBitSize;
8018   bool HasAnyUndefs;
8019   if (BVN &&
8020       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8021     if (SplatBitSize <= 64) {
8022       EVT VbicVT;
8023       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8024                                       SplatUndef.getZExtValue(), SplatBitSize,
8025                                       DAG, VbicVT, VT.is128BitVector(),
8026                                       OtherModImm);
8027       if (Val.getNode()) {
8028         SDValue Input =
8029           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8030         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8031         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8032       }
8033     }
8034   }
8035
8036   if (!Subtarget->isThumb1Only()) {
8037     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8038     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8039     if (Result.getNode())
8040       return Result;
8041   }
8042
8043   return SDValue();
8044 }
8045
8046 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8047 static SDValue PerformORCombine(SDNode *N,
8048                                 TargetLowering::DAGCombinerInfo &DCI,
8049                                 const ARMSubtarget *Subtarget) {
8050   // Attempt to use immediate-form VORR
8051   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8052   SDLoc dl(N);
8053   EVT VT = N->getValueType(0);
8054   SelectionDAG &DAG = DCI.DAG;
8055
8056   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8057     return SDValue();
8058
8059   APInt SplatBits, SplatUndef;
8060   unsigned SplatBitSize;
8061   bool HasAnyUndefs;
8062   if (BVN && Subtarget->hasNEON() &&
8063       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8064     if (SplatBitSize <= 64) {
8065       EVT VorrVT;
8066       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8067                                       SplatUndef.getZExtValue(), SplatBitSize,
8068                                       DAG, VorrVT, VT.is128BitVector(),
8069                                       OtherModImm);
8070       if (Val.getNode()) {
8071         SDValue Input =
8072           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8073         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8074         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8075       }
8076     }
8077   }
8078
8079   if (!Subtarget->isThumb1Only()) {
8080     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8081     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8082     if (Result.getNode())
8083       return Result;
8084   }
8085
8086   // The code below optimizes (or (and X, Y), Z).
8087   // The AND operand needs to have a single user to make these optimizations
8088   // profitable.
8089   SDValue N0 = N->getOperand(0);
8090   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8091     return SDValue();
8092   SDValue N1 = N->getOperand(1);
8093
8094   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8095   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8096       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8097     APInt SplatUndef;
8098     unsigned SplatBitSize;
8099     bool HasAnyUndefs;
8100
8101     APInt SplatBits0, SplatBits1;
8102     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8103     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8104     // Ensure that the second operand of both ands are constants
8105     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8106                                       HasAnyUndefs) && !HasAnyUndefs) {
8107         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8108                                           HasAnyUndefs) && !HasAnyUndefs) {
8109             // Ensure that the bit width of the constants are the same and that
8110             // the splat arguments are logical inverses as per the pattern we
8111             // are trying to simplify.
8112             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8113                 SplatBits0 == ~SplatBits1) {
8114                 // Canonicalize the vector type to make instruction selection
8115                 // simpler.
8116                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8117                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8118                                              N0->getOperand(1),
8119                                              N0->getOperand(0),
8120                                              N1->getOperand(0));
8121                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8122             }
8123         }
8124     }
8125   }
8126
8127   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8128   // reasonable.
8129
8130   // BFI is only available on V6T2+
8131   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8132     return SDValue();
8133
8134   SDLoc DL(N);
8135   // 1) or (and A, mask), val => ARMbfi A, val, mask
8136   //      iff (val & mask) == val
8137   //
8138   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8139   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8140   //          && mask == ~mask2
8141   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8142   //          && ~mask == mask2
8143   //  (i.e., copy a bitfield value into another bitfield of the same width)
8144
8145   if (VT != MVT::i32)
8146     return SDValue();
8147
8148   SDValue N00 = N0.getOperand(0);
8149
8150   // The value and the mask need to be constants so we can verify this is
8151   // actually a bitfield set. If the mask is 0xffff, we can do better
8152   // via a movt instruction, so don't use BFI in that case.
8153   SDValue MaskOp = N0.getOperand(1);
8154   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8155   if (!MaskC)
8156     return SDValue();
8157   unsigned Mask = MaskC->getZExtValue();
8158   if (Mask == 0xffff)
8159     return SDValue();
8160   SDValue Res;
8161   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8162   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8163   if (N1C) {
8164     unsigned Val = N1C->getZExtValue();
8165     if ((Val & ~Mask) != Val)
8166       return SDValue();
8167
8168     if (ARM::isBitFieldInvertedMask(Mask)) {
8169       Val >>= countTrailingZeros(~Mask);
8170
8171       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8172                         DAG.getConstant(Val, MVT::i32),
8173                         DAG.getConstant(Mask, MVT::i32));
8174
8175       // Do not add new nodes to DAG combiner worklist.
8176       DCI.CombineTo(N, Res, false);
8177       return SDValue();
8178     }
8179   } else if (N1.getOpcode() == ISD::AND) {
8180     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8181     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8182     if (!N11C)
8183       return SDValue();
8184     unsigned Mask2 = N11C->getZExtValue();
8185
8186     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8187     // as is to match.
8188     if (ARM::isBitFieldInvertedMask(Mask) &&
8189         (Mask == ~Mask2)) {
8190       // The pack halfword instruction works better for masks that fit it,
8191       // so use that when it's available.
8192       if (Subtarget->hasT2ExtractPack() &&
8193           (Mask == 0xffff || Mask == 0xffff0000))
8194         return SDValue();
8195       // 2a
8196       unsigned amt = countTrailingZeros(Mask2);
8197       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8198                         DAG.getConstant(amt, MVT::i32));
8199       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8200                         DAG.getConstant(Mask, MVT::i32));
8201       // Do not add new nodes to DAG combiner worklist.
8202       DCI.CombineTo(N, Res, false);
8203       return SDValue();
8204     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8205                (~Mask == Mask2)) {
8206       // The pack halfword instruction works better for masks that fit it,
8207       // so use that when it's available.
8208       if (Subtarget->hasT2ExtractPack() &&
8209           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8210         return SDValue();
8211       // 2b
8212       unsigned lsb = countTrailingZeros(Mask);
8213       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8214                         DAG.getConstant(lsb, MVT::i32));
8215       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8216                         DAG.getConstant(Mask2, MVT::i32));
8217       // Do not add new nodes to DAG combiner worklist.
8218       DCI.CombineTo(N, Res, false);
8219       return SDValue();
8220     }
8221   }
8222
8223   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8224       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8225       ARM::isBitFieldInvertedMask(~Mask)) {
8226     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8227     // where lsb(mask) == #shamt and masked bits of B are known zero.
8228     SDValue ShAmt = N00.getOperand(1);
8229     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8230     unsigned LSB = countTrailingZeros(Mask);
8231     if (ShAmtC != LSB)
8232       return SDValue();
8233
8234     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8235                       DAG.getConstant(~Mask, MVT::i32));
8236
8237     // Do not add new nodes to DAG combiner worklist.
8238     DCI.CombineTo(N, Res, false);
8239   }
8240
8241   return SDValue();
8242 }
8243
8244 static SDValue PerformXORCombine(SDNode *N,
8245                                  TargetLowering::DAGCombinerInfo &DCI,
8246                                  const ARMSubtarget *Subtarget) {
8247   EVT VT = N->getValueType(0);
8248   SelectionDAG &DAG = DCI.DAG;
8249
8250   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8251     return SDValue();
8252
8253   if (!Subtarget->isThumb1Only()) {
8254     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8255     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8256     if (Result.getNode())
8257       return Result;
8258   }
8259
8260   return SDValue();
8261 }
8262
8263 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8264 /// the bits being cleared by the AND are not demanded by the BFI.
8265 static SDValue PerformBFICombine(SDNode *N,
8266                                  TargetLowering::DAGCombinerInfo &DCI) {
8267   SDValue N1 = N->getOperand(1);
8268   if (N1.getOpcode() == ISD::AND) {
8269     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8270     if (!N11C)
8271       return SDValue();
8272     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8273     unsigned LSB = countTrailingZeros(~InvMask);
8274     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8275     unsigned Mask = (1 << Width)-1;
8276     unsigned Mask2 = N11C->getZExtValue();
8277     if ((Mask & (~Mask2)) == 0)
8278       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8279                              N->getOperand(0), N1.getOperand(0),
8280                              N->getOperand(2));
8281   }
8282   return SDValue();
8283 }
8284
8285 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8286 /// ARMISD::VMOVRRD.
8287 static SDValue PerformVMOVRRDCombine(SDNode *N,
8288                                      TargetLowering::DAGCombinerInfo &DCI) {
8289   // vmovrrd(vmovdrr x, y) -> x,y
8290   SDValue InDouble = N->getOperand(0);
8291   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8292     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8293
8294   // vmovrrd(load f64) -> (load i32), (load i32)
8295   SDNode *InNode = InDouble.getNode();
8296   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8297       InNode->getValueType(0) == MVT::f64 &&
8298       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8299       !cast<LoadSDNode>(InNode)->isVolatile()) {
8300     // TODO: Should this be done for non-FrameIndex operands?
8301     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8302
8303     SelectionDAG &DAG = DCI.DAG;
8304     SDLoc DL(LD);
8305     SDValue BasePtr = LD->getBasePtr();
8306     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8307                                  LD->getPointerInfo(), LD->isVolatile(),
8308                                  LD->isNonTemporal(), LD->isInvariant(),
8309                                  LD->getAlignment());
8310
8311     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8312                                     DAG.getConstant(4, MVT::i32));
8313     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8314                                  LD->getPointerInfo(), LD->isVolatile(),
8315                                  LD->isNonTemporal(), LD->isInvariant(),
8316                                  std::min(4U, LD->getAlignment() / 2));
8317
8318     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8319     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8320       std::swap (NewLD1, NewLD2);
8321     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8322     DCI.RemoveFromWorklist(LD);
8323     DAG.DeleteNode(LD);
8324     return Result;
8325   }
8326
8327   return SDValue();
8328 }
8329
8330 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8331 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8332 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8333   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8334   SDValue Op0 = N->getOperand(0);
8335   SDValue Op1 = N->getOperand(1);
8336   if (Op0.getOpcode() == ISD::BITCAST)
8337     Op0 = Op0.getOperand(0);
8338   if (Op1.getOpcode() == ISD::BITCAST)
8339     Op1 = Op1.getOperand(0);
8340   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8341       Op0.getNode() == Op1.getNode() &&
8342       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8343     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8344                        N->getValueType(0), Op0.getOperand(0));
8345   return SDValue();
8346 }
8347
8348 /// PerformSTORECombine - Target-specific dag combine xforms for
8349 /// ISD::STORE.
8350 static SDValue PerformSTORECombine(SDNode *N,
8351                                    TargetLowering::DAGCombinerInfo &DCI) {
8352   StoreSDNode *St = cast<StoreSDNode>(N);
8353   if (St->isVolatile())
8354     return SDValue();
8355
8356   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8357   // pack all of the elements in one place.  Next, store to memory in fewer
8358   // chunks.
8359   SDValue StVal = St->getValue();
8360   EVT VT = StVal.getValueType();
8361   if (St->isTruncatingStore() && VT.isVector()) {
8362     SelectionDAG &DAG = DCI.DAG;
8363     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8364     EVT StVT = St->getMemoryVT();
8365     unsigned NumElems = VT.getVectorNumElements();
8366     assert(StVT != VT && "Cannot truncate to the same type");
8367     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8368     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8369
8370     // From, To sizes and ElemCount must be pow of two
8371     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8372
8373     // We are going to use the original vector elt for storing.
8374     // Accumulated smaller vector elements must be a multiple of the store size.
8375     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8376
8377     unsigned SizeRatio  = FromEltSz / ToEltSz;
8378     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8379
8380     // Create a type on which we perform the shuffle.
8381     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8382                                      NumElems*SizeRatio);
8383     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8384
8385     SDLoc DL(St);
8386     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8387     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8388     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8389
8390     // Can't shuffle using an illegal type.
8391     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8392
8393     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8394                                 DAG.getUNDEF(WideVec.getValueType()),
8395                                 ShuffleVec.data());
8396     // At this point all of the data is stored at the bottom of the
8397     // register. We now need to save it to mem.
8398
8399     // Find the largest store unit
8400     MVT StoreType = MVT::i8;
8401     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8402          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8403       MVT Tp = (MVT::SimpleValueType)tp;
8404       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8405         StoreType = Tp;
8406     }
8407     // Didn't find a legal store type.
8408     if (!TLI.isTypeLegal(StoreType))
8409       return SDValue();
8410
8411     // Bitcast the original vector into a vector of store-size units
8412     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8413             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8414     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8415     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8416     SmallVector<SDValue, 8> Chains;
8417     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8418                                         TLI.getPointerTy());
8419     SDValue BasePtr = St->getBasePtr();
8420
8421     // Perform one or more big stores into memory.
8422     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8423     for (unsigned I = 0; I < E; I++) {
8424       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8425                                    StoreType, ShuffWide,
8426                                    DAG.getIntPtrConstant(I));
8427       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8428                                 St->getPointerInfo(), St->isVolatile(),
8429                                 St->isNonTemporal(), St->getAlignment());
8430       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8431                             Increment);
8432       Chains.push_back(Ch);
8433     }
8434     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8435   }
8436
8437   if (!ISD::isNormalStore(St))
8438     return SDValue();
8439
8440   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8441   // ARM stores of arguments in the same cache line.
8442   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8443       StVal.getNode()->hasOneUse()) {
8444     SelectionDAG  &DAG = DCI.DAG;
8445     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8446     SDLoc DL(St);
8447     SDValue BasePtr = St->getBasePtr();
8448     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8449                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8450                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8451                                   St->isNonTemporal(), St->getAlignment());
8452
8453     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8454                                     DAG.getConstant(4, MVT::i32));
8455     return DAG.getStore(NewST1.getValue(0), DL,
8456                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8457                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8458                         St->isNonTemporal(),
8459                         std::min(4U, St->getAlignment() / 2));
8460   }
8461
8462   if (StVal.getValueType() != MVT::i64 ||
8463       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8464     return SDValue();
8465
8466   // Bitcast an i64 store extracted from a vector to f64.
8467   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8468   SelectionDAG &DAG = DCI.DAG;
8469   SDLoc dl(StVal);
8470   SDValue IntVec = StVal.getOperand(0);
8471   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8472                                  IntVec.getValueType().getVectorNumElements());
8473   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8474   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8475                                Vec, StVal.getOperand(1));
8476   dl = SDLoc(N);
8477   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8478   // Make the DAGCombiner fold the bitcasts.
8479   DCI.AddToWorklist(Vec.getNode());
8480   DCI.AddToWorklist(ExtElt.getNode());
8481   DCI.AddToWorklist(V.getNode());
8482   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8483                       St->getPointerInfo(), St->isVolatile(),
8484                       St->isNonTemporal(), St->getAlignment(),
8485                       St->getTBAAInfo());
8486 }
8487
8488 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8489 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8490 /// i64 vector to have f64 elements, since the value can then be loaded
8491 /// directly into a VFP register.
8492 static bool hasNormalLoadOperand(SDNode *N) {
8493   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8494   for (unsigned i = 0; i < NumElts; ++i) {
8495     SDNode *Elt = N->getOperand(i).getNode();
8496     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8497       return true;
8498   }
8499   return false;
8500 }
8501
8502 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8503 /// ISD::BUILD_VECTOR.
8504 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8505                                           TargetLowering::DAGCombinerInfo &DCI){
8506   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8507   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8508   // into a pair of GPRs, which is fine when the value is used as a scalar,
8509   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8510   SelectionDAG &DAG = DCI.DAG;
8511   if (N->getNumOperands() == 2) {
8512     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8513     if (RV.getNode())
8514       return RV;
8515   }
8516
8517   // Load i64 elements as f64 values so that type legalization does not split
8518   // them up into i32 values.
8519   EVT VT = N->getValueType(0);
8520   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8521     return SDValue();
8522   SDLoc dl(N);
8523   SmallVector<SDValue, 8> Ops;
8524   unsigned NumElts = VT.getVectorNumElements();
8525   for (unsigned i = 0; i < NumElts; ++i) {
8526     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8527     Ops.push_back(V);
8528     // Make the DAGCombiner fold the bitcast.
8529     DCI.AddToWorklist(V.getNode());
8530   }
8531   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8532   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8533   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8534 }
8535
8536 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8537 static SDValue
8538 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8539   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8540   // At that time, we may have inserted bitcasts from integer to float.
8541   // If these bitcasts have survived DAGCombine, change the lowering of this
8542   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8543   // force to use floating point types.
8544
8545   // Make sure we can change the type of the vector.
8546   // This is possible iff:
8547   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8548   //    1.1. Vector is used only once.
8549   //    1.2. Use is a bit convert to an integer type.
8550   // 2. The size of its operands are 32-bits (64-bits are not legal).
8551   EVT VT = N->getValueType(0);
8552   EVT EltVT = VT.getVectorElementType();
8553
8554   // Check 1.1. and 2.
8555   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8556     return SDValue();
8557
8558   // By construction, the input type must be float.
8559   assert(EltVT == MVT::f32 && "Unexpected type!");
8560
8561   // Check 1.2.
8562   SDNode *Use = *N->use_begin();
8563   if (Use->getOpcode() != ISD::BITCAST ||
8564       Use->getValueType(0).isFloatingPoint())
8565     return SDValue();
8566
8567   // Check profitability.
8568   // Model is, if more than half of the relevant operands are bitcast from
8569   // i32, turn the build_vector into a sequence of insert_vector_elt.
8570   // Relevant operands are everything that is not statically
8571   // (i.e., at compile time) bitcasted.
8572   unsigned NumOfBitCastedElts = 0;
8573   unsigned NumElts = VT.getVectorNumElements();
8574   unsigned NumOfRelevantElts = NumElts;
8575   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8576     SDValue Elt = N->getOperand(Idx);
8577     if (Elt->getOpcode() == ISD::BITCAST) {
8578       // Assume only bit cast to i32 will go away.
8579       if (Elt->getOperand(0).getValueType() == MVT::i32)
8580         ++NumOfBitCastedElts;
8581     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8582       // Constants are statically casted, thus do not count them as
8583       // relevant operands.
8584       --NumOfRelevantElts;
8585   }
8586
8587   // Check if more than half of the elements require a non-free bitcast.
8588   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8589     return SDValue();
8590
8591   SelectionDAG &DAG = DCI.DAG;
8592   // Create the new vector type.
8593   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8594   // Check if the type is legal.
8595   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8596   if (!TLI.isTypeLegal(VecVT))
8597     return SDValue();
8598
8599   // Combine:
8600   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8601   // => BITCAST INSERT_VECTOR_ELT
8602   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8603   //                      (BITCAST EN), N.
8604   SDValue Vec = DAG.getUNDEF(VecVT);
8605   SDLoc dl(N);
8606   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8607     SDValue V = N->getOperand(Idx);
8608     if (V.getOpcode() == ISD::UNDEF)
8609       continue;
8610     if (V.getOpcode() == ISD::BITCAST &&
8611         V->getOperand(0).getValueType() == MVT::i32)
8612       // Fold obvious case.
8613       V = V.getOperand(0);
8614     else {
8615       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8616       // Make the DAGCombiner fold the bitcasts.
8617       DCI.AddToWorklist(V.getNode());
8618     }
8619     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8620     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8621   }
8622   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8623   // Make the DAGCombiner fold the bitcasts.
8624   DCI.AddToWorklist(Vec.getNode());
8625   return Vec;
8626 }
8627
8628 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8629 /// ISD::INSERT_VECTOR_ELT.
8630 static SDValue PerformInsertEltCombine(SDNode *N,
8631                                        TargetLowering::DAGCombinerInfo &DCI) {
8632   // Bitcast an i64 load inserted into a vector to f64.
8633   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8634   EVT VT = N->getValueType(0);
8635   SDNode *Elt = N->getOperand(1).getNode();
8636   if (VT.getVectorElementType() != MVT::i64 ||
8637       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8638     return SDValue();
8639
8640   SelectionDAG &DAG = DCI.DAG;
8641   SDLoc dl(N);
8642   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8643                                  VT.getVectorNumElements());
8644   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8645   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8646   // Make the DAGCombiner fold the bitcasts.
8647   DCI.AddToWorklist(Vec.getNode());
8648   DCI.AddToWorklist(V.getNode());
8649   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8650                                Vec, V, N->getOperand(2));
8651   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8652 }
8653
8654 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8655 /// ISD::VECTOR_SHUFFLE.
8656 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8657   // The LLVM shufflevector instruction does not require the shuffle mask
8658   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8659   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8660   // operands do not match the mask length, they are extended by concatenating
8661   // them with undef vectors.  That is probably the right thing for other
8662   // targets, but for NEON it is better to concatenate two double-register
8663   // size vector operands into a single quad-register size vector.  Do that
8664   // transformation here:
8665   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8666   //   shuffle(concat(v1, v2), undef)
8667   SDValue Op0 = N->getOperand(0);
8668   SDValue Op1 = N->getOperand(1);
8669   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8670       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8671       Op0.getNumOperands() != 2 ||
8672       Op1.getNumOperands() != 2)
8673     return SDValue();
8674   SDValue Concat0Op1 = Op0.getOperand(1);
8675   SDValue Concat1Op1 = Op1.getOperand(1);
8676   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8677       Concat1Op1.getOpcode() != ISD::UNDEF)
8678     return SDValue();
8679   // Skip the transformation if any of the types are illegal.
8680   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8681   EVT VT = N->getValueType(0);
8682   if (!TLI.isTypeLegal(VT) ||
8683       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8684       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8685     return SDValue();
8686
8687   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8688                                   Op0.getOperand(0), Op1.getOperand(0));
8689   // Translate the shuffle mask.
8690   SmallVector<int, 16> NewMask;
8691   unsigned NumElts = VT.getVectorNumElements();
8692   unsigned HalfElts = NumElts/2;
8693   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8694   for (unsigned n = 0; n < NumElts; ++n) {
8695     int MaskElt = SVN->getMaskElt(n);
8696     int NewElt = -1;
8697     if (MaskElt < (int)HalfElts)
8698       NewElt = MaskElt;
8699     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8700       NewElt = HalfElts + MaskElt - NumElts;
8701     NewMask.push_back(NewElt);
8702   }
8703   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8704                               DAG.getUNDEF(VT), NewMask.data());
8705 }
8706
8707 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8708 /// NEON load/store intrinsics to merge base address updates.
8709 static SDValue CombineBaseUpdate(SDNode *N,
8710                                  TargetLowering::DAGCombinerInfo &DCI) {
8711   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8712     return SDValue();
8713
8714   SelectionDAG &DAG = DCI.DAG;
8715   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8716                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8717   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8718   SDValue Addr = N->getOperand(AddrOpIdx);
8719
8720   // Search for a use of the address operand that is an increment.
8721   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8722          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8723     SDNode *User = *UI;
8724     if (User->getOpcode() != ISD::ADD ||
8725         UI.getUse().getResNo() != Addr.getResNo())
8726       continue;
8727
8728     // Check that the add is independent of the load/store.  Otherwise, folding
8729     // it would create a cycle.
8730     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8731       continue;
8732
8733     // Find the new opcode for the updating load/store.
8734     bool isLoad = true;
8735     bool isLaneOp = false;
8736     unsigned NewOpc = 0;
8737     unsigned NumVecs = 0;
8738     if (isIntrinsic) {
8739       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8740       switch (IntNo) {
8741       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8742       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8743         NumVecs = 1; break;
8744       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8745         NumVecs = 2; break;
8746       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8747         NumVecs = 3; break;
8748       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8749         NumVecs = 4; break;
8750       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8751         NumVecs = 2; isLaneOp = true; break;
8752       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8753         NumVecs = 3; isLaneOp = true; break;
8754       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8755         NumVecs = 4; isLaneOp = true; break;
8756       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8757         NumVecs = 1; isLoad = false; break;
8758       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8759         NumVecs = 2; isLoad = false; break;
8760       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8761         NumVecs = 3; isLoad = false; break;
8762       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8763         NumVecs = 4; isLoad = false; break;
8764       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8765         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8766       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8767         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8768       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8769         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8770       }
8771     } else {
8772       isLaneOp = true;
8773       switch (N->getOpcode()) {
8774       default: llvm_unreachable("unexpected opcode for Neon base update");
8775       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8776       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8777       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8778       }
8779     }
8780
8781     // Find the size of memory referenced by the load/store.
8782     EVT VecTy;
8783     if (isLoad)
8784       VecTy = N->getValueType(0);
8785     else
8786       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8787     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8788     if (isLaneOp)
8789       NumBytes /= VecTy.getVectorNumElements();
8790
8791     // If the increment is a constant, it must match the memory ref size.
8792     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8793     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8794       uint64_t IncVal = CInc->getZExtValue();
8795       if (IncVal != NumBytes)
8796         continue;
8797     } else if (NumBytes >= 3 * 16) {
8798       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8799       // separate instructions that make it harder to use a non-constant update.
8800       continue;
8801     }
8802
8803     // Create the new updating load/store node.
8804     EVT Tys[6];
8805     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8806     unsigned n;
8807     for (n = 0; n < NumResultVecs; ++n)
8808       Tys[n] = VecTy;
8809     Tys[n++] = MVT::i32;
8810     Tys[n] = MVT::Other;
8811     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8812     SmallVector<SDValue, 8> Ops;
8813     Ops.push_back(N->getOperand(0)); // incoming chain
8814     Ops.push_back(N->getOperand(AddrOpIdx));
8815     Ops.push_back(Inc);
8816     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8817       Ops.push_back(N->getOperand(i));
8818     }
8819     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8820     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8821                                            Ops, MemInt->getMemoryVT(),
8822                                            MemInt->getMemOperand());
8823
8824     // Update the uses.
8825     std::vector<SDValue> NewResults;
8826     for (unsigned i = 0; i < NumResultVecs; ++i) {
8827       NewResults.push_back(SDValue(UpdN.getNode(), i));
8828     }
8829     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8830     DCI.CombineTo(N, NewResults);
8831     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8832
8833     break;
8834   }
8835   return SDValue();
8836 }
8837
8838 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8839 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8840 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8841 /// return true.
8842 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8843   SelectionDAG &DAG = DCI.DAG;
8844   EVT VT = N->getValueType(0);
8845   // vldN-dup instructions only support 64-bit vectors for N > 1.
8846   if (!VT.is64BitVector())
8847     return false;
8848
8849   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8850   SDNode *VLD = N->getOperand(0).getNode();
8851   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8852     return false;
8853   unsigned NumVecs = 0;
8854   unsigned NewOpc = 0;
8855   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8856   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8857     NumVecs = 2;
8858     NewOpc = ARMISD::VLD2DUP;
8859   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8860     NumVecs = 3;
8861     NewOpc = ARMISD::VLD3DUP;
8862   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8863     NumVecs = 4;
8864     NewOpc = ARMISD::VLD4DUP;
8865   } else {
8866     return false;
8867   }
8868
8869   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8870   // numbers match the load.
8871   unsigned VLDLaneNo =
8872     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8873   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8874        UI != UE; ++UI) {
8875     // Ignore uses of the chain result.
8876     if (UI.getUse().getResNo() == NumVecs)
8877       continue;
8878     SDNode *User = *UI;
8879     if (User->getOpcode() != ARMISD::VDUPLANE ||
8880         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8881       return false;
8882   }
8883
8884   // Create the vldN-dup node.
8885   EVT Tys[5];
8886   unsigned n;
8887   for (n = 0; n < NumVecs; ++n)
8888     Tys[n] = VT;
8889   Tys[n] = MVT::Other;
8890   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8891   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8892   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8893   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8894                                            Ops, VLDMemInt->getMemoryVT(),
8895                                            VLDMemInt->getMemOperand());
8896
8897   // Update the uses.
8898   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8899        UI != UE; ++UI) {
8900     unsigned ResNo = UI.getUse().getResNo();
8901     // Ignore uses of the chain result.
8902     if (ResNo == NumVecs)
8903       continue;
8904     SDNode *User = *UI;
8905     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8906   }
8907
8908   // Now the vldN-lane intrinsic is dead except for its chain result.
8909   // Update uses of the chain.
8910   std::vector<SDValue> VLDDupResults;
8911   for (unsigned n = 0; n < NumVecs; ++n)
8912     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8913   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8914   DCI.CombineTo(VLD, VLDDupResults);
8915
8916   return true;
8917 }
8918
8919 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8920 /// ARMISD::VDUPLANE.
8921 static SDValue PerformVDUPLANECombine(SDNode *N,
8922                                       TargetLowering::DAGCombinerInfo &DCI) {
8923   SDValue Op = N->getOperand(0);
8924
8925   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8926   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8927   if (CombineVLDDUP(N, DCI))
8928     return SDValue(N, 0);
8929
8930   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8931   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8932   while (Op.getOpcode() == ISD::BITCAST)
8933     Op = Op.getOperand(0);
8934   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8935     return SDValue();
8936
8937   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8938   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8939   // The canonical VMOV for a zero vector uses a 32-bit element size.
8940   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8941   unsigned EltBits;
8942   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8943     EltSize = 8;
8944   EVT VT = N->getValueType(0);
8945   if (EltSize > VT.getVectorElementType().getSizeInBits())
8946     return SDValue();
8947
8948   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8949 }
8950
8951 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8952 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8953 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8954 {
8955   integerPart cN;
8956   integerPart c0 = 0;
8957   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8958        I != E; I++) {
8959     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8960     if (!C)
8961       return false;
8962
8963     bool isExact;
8964     APFloat APF = C->getValueAPF();
8965     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8966         != APFloat::opOK || !isExact)
8967       return false;
8968
8969     c0 = (I == 0) ? cN : c0;
8970     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8971       return false;
8972   }
8973   C = c0;
8974   return true;
8975 }
8976
8977 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8978 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8979 /// when the VMUL has a constant operand that is a power of 2.
8980 ///
8981 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8982 ///  vmul.f32        d16, d17, d16
8983 ///  vcvt.s32.f32    d16, d16
8984 /// becomes:
8985 ///  vcvt.s32.f32    d16, d16, #3
8986 static SDValue PerformVCVTCombine(SDNode *N,
8987                                   TargetLowering::DAGCombinerInfo &DCI,
8988                                   const ARMSubtarget *Subtarget) {
8989   SelectionDAG &DAG = DCI.DAG;
8990   SDValue Op = N->getOperand(0);
8991
8992   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8993       Op.getOpcode() != ISD::FMUL)
8994     return SDValue();
8995
8996   uint64_t C;
8997   SDValue N0 = Op->getOperand(0);
8998   SDValue ConstVec = Op->getOperand(1);
8999   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9000
9001   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9002       !isConstVecPow2(ConstVec, isSigned, C))
9003     return SDValue();
9004
9005   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9006   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9007   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9008     // These instructions only exist converting from f32 to i32. We can handle
9009     // smaller integers by generating an extra truncate, but larger ones would
9010     // be lossy.
9011     return SDValue();
9012   }
9013
9014   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9015     Intrinsic::arm_neon_vcvtfp2fxu;
9016   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9017   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9018                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9019                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9020                                  DAG.getConstant(Log2_64(C), MVT::i32));
9021
9022   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9023     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9024
9025   return FixConv;
9026 }
9027
9028 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9029 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9030 /// when the VDIV has a constant operand that is a power of 2.
9031 ///
9032 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9033 ///  vcvt.f32.s32    d16, d16
9034 ///  vdiv.f32        d16, d17, d16
9035 /// becomes:
9036 ///  vcvt.f32.s32    d16, d16, #3
9037 static SDValue PerformVDIVCombine(SDNode *N,
9038                                   TargetLowering::DAGCombinerInfo &DCI,
9039                                   const ARMSubtarget *Subtarget) {
9040   SelectionDAG &DAG = DCI.DAG;
9041   SDValue Op = N->getOperand(0);
9042   unsigned OpOpcode = Op.getNode()->getOpcode();
9043
9044   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9045       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9046     return SDValue();
9047
9048   uint64_t C;
9049   SDValue ConstVec = N->getOperand(1);
9050   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9051
9052   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9053       !isConstVecPow2(ConstVec, isSigned, C))
9054     return SDValue();
9055
9056   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9057   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9058   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9059     // These instructions only exist converting from i32 to f32. We can handle
9060     // smaller integers by generating an extra extend, but larger ones would
9061     // be lossy.
9062     return SDValue();
9063   }
9064
9065   SDValue ConvInput = Op.getOperand(0);
9066   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9067   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9068     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9069                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9070                             ConvInput);
9071
9072   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9073     Intrinsic::arm_neon_vcvtfxu2fp;
9074   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9075                      Op.getValueType(),
9076                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9077                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9078 }
9079
9080 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9081 /// operand of a vector shift operation, where all the elements of the
9082 /// build_vector must have the same constant integer value.
9083 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9084   // Ignore bit_converts.
9085   while (Op.getOpcode() == ISD::BITCAST)
9086     Op = Op.getOperand(0);
9087   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9088   APInt SplatBits, SplatUndef;
9089   unsigned SplatBitSize;
9090   bool HasAnyUndefs;
9091   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9092                                       HasAnyUndefs, ElementBits) ||
9093       SplatBitSize > ElementBits)
9094     return false;
9095   Cnt = SplatBits.getSExtValue();
9096   return true;
9097 }
9098
9099 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9100 /// operand of a vector shift left operation.  That value must be in the range:
9101 ///   0 <= Value < ElementBits for a left shift; or
9102 ///   0 <= Value <= ElementBits for a long left shift.
9103 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9104   assert(VT.isVector() && "vector shift count is not a vector type");
9105   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9106   if (! getVShiftImm(Op, ElementBits, Cnt))
9107     return false;
9108   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9109 }
9110
9111 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9112 /// operand of a vector shift right operation.  For a shift opcode, the value
9113 /// is positive, but for an intrinsic the value count must be negative. The
9114 /// absolute value must be in the range:
9115 ///   1 <= |Value| <= ElementBits for a right shift; or
9116 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9117 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9118                          int64_t &Cnt) {
9119   assert(VT.isVector() && "vector shift count is not a vector type");
9120   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9121   if (! getVShiftImm(Op, ElementBits, Cnt))
9122     return false;
9123   if (isIntrinsic)
9124     Cnt = -Cnt;
9125   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9126 }
9127
9128 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9129 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9130   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9131   switch (IntNo) {
9132   default:
9133     // Don't do anything for most intrinsics.
9134     break;
9135
9136   // Vector shifts: check for immediate versions and lower them.
9137   // Note: This is done during DAG combining instead of DAG legalizing because
9138   // the build_vectors for 64-bit vector element shift counts are generally
9139   // not legal, and it is hard to see their values after they get legalized to
9140   // loads from a constant pool.
9141   case Intrinsic::arm_neon_vshifts:
9142   case Intrinsic::arm_neon_vshiftu:
9143   case Intrinsic::arm_neon_vrshifts:
9144   case Intrinsic::arm_neon_vrshiftu:
9145   case Intrinsic::arm_neon_vrshiftn:
9146   case Intrinsic::arm_neon_vqshifts:
9147   case Intrinsic::arm_neon_vqshiftu:
9148   case Intrinsic::arm_neon_vqshiftsu:
9149   case Intrinsic::arm_neon_vqshiftns:
9150   case Intrinsic::arm_neon_vqshiftnu:
9151   case Intrinsic::arm_neon_vqshiftnsu:
9152   case Intrinsic::arm_neon_vqrshiftns:
9153   case Intrinsic::arm_neon_vqrshiftnu:
9154   case Intrinsic::arm_neon_vqrshiftnsu: {
9155     EVT VT = N->getOperand(1).getValueType();
9156     int64_t Cnt;
9157     unsigned VShiftOpc = 0;
9158
9159     switch (IntNo) {
9160     case Intrinsic::arm_neon_vshifts:
9161     case Intrinsic::arm_neon_vshiftu:
9162       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9163         VShiftOpc = ARMISD::VSHL;
9164         break;
9165       }
9166       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9167         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9168                      ARMISD::VSHRs : ARMISD::VSHRu);
9169         break;
9170       }
9171       return SDValue();
9172
9173     case Intrinsic::arm_neon_vrshifts:
9174     case Intrinsic::arm_neon_vrshiftu:
9175       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9176         break;
9177       return SDValue();
9178
9179     case Intrinsic::arm_neon_vqshifts:
9180     case Intrinsic::arm_neon_vqshiftu:
9181       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9182         break;
9183       return SDValue();
9184
9185     case Intrinsic::arm_neon_vqshiftsu:
9186       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9187         break;
9188       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9189
9190     case Intrinsic::arm_neon_vrshiftn:
9191     case Intrinsic::arm_neon_vqshiftns:
9192     case Intrinsic::arm_neon_vqshiftnu:
9193     case Intrinsic::arm_neon_vqshiftnsu:
9194     case Intrinsic::arm_neon_vqrshiftns:
9195     case Intrinsic::arm_neon_vqrshiftnu:
9196     case Intrinsic::arm_neon_vqrshiftnsu:
9197       // Narrowing shifts require an immediate right shift.
9198       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9199         break;
9200       llvm_unreachable("invalid shift count for narrowing vector shift "
9201                        "intrinsic");
9202
9203     default:
9204       llvm_unreachable("unhandled vector shift");
9205     }
9206
9207     switch (IntNo) {
9208     case Intrinsic::arm_neon_vshifts:
9209     case Intrinsic::arm_neon_vshiftu:
9210       // Opcode already set above.
9211       break;
9212     case Intrinsic::arm_neon_vrshifts:
9213       VShiftOpc = ARMISD::VRSHRs; break;
9214     case Intrinsic::arm_neon_vrshiftu:
9215       VShiftOpc = ARMISD::VRSHRu; break;
9216     case Intrinsic::arm_neon_vrshiftn:
9217       VShiftOpc = ARMISD::VRSHRN; break;
9218     case Intrinsic::arm_neon_vqshifts:
9219       VShiftOpc = ARMISD::VQSHLs; break;
9220     case Intrinsic::arm_neon_vqshiftu:
9221       VShiftOpc = ARMISD::VQSHLu; break;
9222     case Intrinsic::arm_neon_vqshiftsu:
9223       VShiftOpc = ARMISD::VQSHLsu; break;
9224     case Intrinsic::arm_neon_vqshiftns:
9225       VShiftOpc = ARMISD::VQSHRNs; break;
9226     case Intrinsic::arm_neon_vqshiftnu:
9227       VShiftOpc = ARMISD::VQSHRNu; break;
9228     case Intrinsic::arm_neon_vqshiftnsu:
9229       VShiftOpc = ARMISD::VQSHRNsu; break;
9230     case Intrinsic::arm_neon_vqrshiftns:
9231       VShiftOpc = ARMISD::VQRSHRNs; break;
9232     case Intrinsic::arm_neon_vqrshiftnu:
9233       VShiftOpc = ARMISD::VQRSHRNu; break;
9234     case Intrinsic::arm_neon_vqrshiftnsu:
9235       VShiftOpc = ARMISD::VQRSHRNsu; break;
9236     }
9237
9238     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9239                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9240   }
9241
9242   case Intrinsic::arm_neon_vshiftins: {
9243     EVT VT = N->getOperand(1).getValueType();
9244     int64_t Cnt;
9245     unsigned VShiftOpc = 0;
9246
9247     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9248       VShiftOpc = ARMISD::VSLI;
9249     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9250       VShiftOpc = ARMISD::VSRI;
9251     else {
9252       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9253     }
9254
9255     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9256                        N->getOperand(1), N->getOperand(2),
9257                        DAG.getConstant(Cnt, MVT::i32));
9258   }
9259
9260   case Intrinsic::arm_neon_vqrshifts:
9261   case Intrinsic::arm_neon_vqrshiftu:
9262     // No immediate versions of these to check for.
9263     break;
9264   }
9265
9266   return SDValue();
9267 }
9268
9269 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9270 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9271 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9272 /// vector element shift counts are generally not legal, and it is hard to see
9273 /// their values after they get legalized to loads from a constant pool.
9274 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9275                                    const ARMSubtarget *ST) {
9276   EVT VT = N->getValueType(0);
9277   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9278     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9279     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9280     SDValue N1 = N->getOperand(1);
9281     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9282       SDValue N0 = N->getOperand(0);
9283       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9284           DAG.MaskedValueIsZero(N0.getOperand(0),
9285                                 APInt::getHighBitsSet(32, 16)))
9286         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9287     }
9288   }
9289
9290   // Nothing to be done for scalar shifts.
9291   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9292   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9293     return SDValue();
9294
9295   assert(ST->hasNEON() && "unexpected vector shift");
9296   int64_t Cnt;
9297
9298   switch (N->getOpcode()) {
9299   default: llvm_unreachable("unexpected shift opcode");
9300
9301   case ISD::SHL:
9302     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9303       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9304                          DAG.getConstant(Cnt, MVT::i32));
9305     break;
9306
9307   case ISD::SRA:
9308   case ISD::SRL:
9309     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9310       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9311                             ARMISD::VSHRs : ARMISD::VSHRu);
9312       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9313                          DAG.getConstant(Cnt, MVT::i32));
9314     }
9315   }
9316   return SDValue();
9317 }
9318
9319 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9320 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9321 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9322                                     const ARMSubtarget *ST) {
9323   SDValue N0 = N->getOperand(0);
9324
9325   // Check for sign- and zero-extensions of vector extract operations of 8-
9326   // and 16-bit vector elements.  NEON supports these directly.  They are
9327   // handled during DAG combining because type legalization will promote them
9328   // to 32-bit types and it is messy to recognize the operations after that.
9329   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9330     SDValue Vec = N0.getOperand(0);
9331     SDValue Lane = N0.getOperand(1);
9332     EVT VT = N->getValueType(0);
9333     EVT EltVT = N0.getValueType();
9334     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9335
9336     if (VT == MVT::i32 &&
9337         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9338         TLI.isTypeLegal(Vec.getValueType()) &&
9339         isa<ConstantSDNode>(Lane)) {
9340
9341       unsigned Opc = 0;
9342       switch (N->getOpcode()) {
9343       default: llvm_unreachable("unexpected opcode");
9344       case ISD::SIGN_EXTEND:
9345         Opc = ARMISD::VGETLANEs;
9346         break;
9347       case ISD::ZERO_EXTEND:
9348       case ISD::ANY_EXTEND:
9349         Opc = ARMISD::VGETLANEu;
9350         break;
9351       }
9352       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9353     }
9354   }
9355
9356   return SDValue();
9357 }
9358
9359 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9360 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9361 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9362                                        const ARMSubtarget *ST) {
9363   // If the target supports NEON, try to use vmax/vmin instructions for f32
9364   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9365   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9366   // a NaN; only do the transformation when it matches that behavior.
9367
9368   // For now only do this when using NEON for FP operations; if using VFP, it
9369   // is not obvious that the benefit outweighs the cost of switching to the
9370   // NEON pipeline.
9371   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9372       N->getValueType(0) != MVT::f32)
9373     return SDValue();
9374
9375   SDValue CondLHS = N->getOperand(0);
9376   SDValue CondRHS = N->getOperand(1);
9377   SDValue LHS = N->getOperand(2);
9378   SDValue RHS = N->getOperand(3);
9379   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9380
9381   unsigned Opcode = 0;
9382   bool IsReversed;
9383   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9384     IsReversed = false; // x CC y ? x : y
9385   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9386     IsReversed = true ; // x CC y ? y : x
9387   } else {
9388     return SDValue();
9389   }
9390
9391   bool IsUnordered;
9392   switch (CC) {
9393   default: break;
9394   case ISD::SETOLT:
9395   case ISD::SETOLE:
9396   case ISD::SETLT:
9397   case ISD::SETLE:
9398   case ISD::SETULT:
9399   case ISD::SETULE:
9400     // If LHS is NaN, an ordered comparison will be false and the result will
9401     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9402     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9403     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9404     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9405       break;
9406     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9407     // will return -0, so vmin can only be used for unsafe math or if one of
9408     // the operands is known to be nonzero.
9409     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9410         !DAG.getTarget().Options.UnsafeFPMath &&
9411         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9412       break;
9413     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9414     break;
9415
9416   case ISD::SETOGT:
9417   case ISD::SETOGE:
9418   case ISD::SETGT:
9419   case ISD::SETGE:
9420   case ISD::SETUGT:
9421   case ISD::SETUGE:
9422     // If LHS is NaN, an ordered comparison will be false and the result will
9423     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9424     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9425     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9426     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9427       break;
9428     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9429     // will return +0, so vmax can only be used for unsafe math or if one of
9430     // the operands is known to be nonzero.
9431     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9432         !DAG.getTarget().Options.UnsafeFPMath &&
9433         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9434       break;
9435     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9436     break;
9437   }
9438
9439   if (!Opcode)
9440     return SDValue();
9441   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9442 }
9443
9444 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9445 SDValue
9446 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9447   SDValue Cmp = N->getOperand(4);
9448   if (Cmp.getOpcode() != ARMISD::CMPZ)
9449     // Only looking at EQ and NE cases.
9450     return SDValue();
9451
9452   EVT VT = N->getValueType(0);
9453   SDLoc dl(N);
9454   SDValue LHS = Cmp.getOperand(0);
9455   SDValue RHS = Cmp.getOperand(1);
9456   SDValue FalseVal = N->getOperand(0);
9457   SDValue TrueVal = N->getOperand(1);
9458   SDValue ARMcc = N->getOperand(2);
9459   ARMCC::CondCodes CC =
9460     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9461
9462   // Simplify
9463   //   mov     r1, r0
9464   //   cmp     r1, x
9465   //   mov     r0, y
9466   //   moveq   r0, x
9467   // to
9468   //   cmp     r0, x
9469   //   movne   r0, y
9470   //
9471   //   mov     r1, r0
9472   //   cmp     r1, x
9473   //   mov     r0, x
9474   //   movne   r0, y
9475   // to
9476   //   cmp     r0, x
9477   //   movne   r0, y
9478   /// FIXME: Turn this into a target neutral optimization?
9479   SDValue Res;
9480   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9481     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9482                       N->getOperand(3), Cmp);
9483   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9484     SDValue ARMcc;
9485     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9486     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9487                       N->getOperand(3), NewCmp);
9488   }
9489
9490   if (Res.getNode()) {
9491     APInt KnownZero, KnownOne;
9492     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9493     // Capture demanded bits information that would be otherwise lost.
9494     if (KnownZero == 0xfffffffe)
9495       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9496                         DAG.getValueType(MVT::i1));
9497     else if (KnownZero == 0xffffff00)
9498       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9499                         DAG.getValueType(MVT::i8));
9500     else if (KnownZero == 0xffff0000)
9501       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9502                         DAG.getValueType(MVT::i16));
9503   }
9504
9505   return Res;
9506 }
9507
9508 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9509                                              DAGCombinerInfo &DCI) const {
9510   switch (N->getOpcode()) {
9511   default: break;
9512   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9513   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9514   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9515   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9516   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9517   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9518   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9519   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9520   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9521   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9522   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9523   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9524   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9525   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9526   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9527   case ISD::FP_TO_SINT:
9528   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9529   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9530   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9531   case ISD::SHL:
9532   case ISD::SRA:
9533   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9534   case ISD::SIGN_EXTEND:
9535   case ISD::ZERO_EXTEND:
9536   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9537   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9538   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9539   case ARMISD::VLD2DUP:
9540   case ARMISD::VLD3DUP:
9541   case ARMISD::VLD4DUP:
9542     return CombineBaseUpdate(N, DCI);
9543   case ARMISD::BUILD_VECTOR:
9544     return PerformARMBUILD_VECTORCombine(N, DCI);
9545   case ISD::INTRINSIC_VOID:
9546   case ISD::INTRINSIC_W_CHAIN:
9547     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9548     case Intrinsic::arm_neon_vld1:
9549     case Intrinsic::arm_neon_vld2:
9550     case Intrinsic::arm_neon_vld3:
9551     case Intrinsic::arm_neon_vld4:
9552     case Intrinsic::arm_neon_vld2lane:
9553     case Intrinsic::arm_neon_vld3lane:
9554     case Intrinsic::arm_neon_vld4lane:
9555     case Intrinsic::arm_neon_vst1:
9556     case Intrinsic::arm_neon_vst2:
9557     case Intrinsic::arm_neon_vst3:
9558     case Intrinsic::arm_neon_vst4:
9559     case Intrinsic::arm_neon_vst2lane:
9560     case Intrinsic::arm_neon_vst3lane:
9561     case Intrinsic::arm_neon_vst4lane:
9562       return CombineBaseUpdate(N, DCI);
9563     default: break;
9564     }
9565     break;
9566   }
9567   return SDValue();
9568 }
9569
9570 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9571                                                           EVT VT) const {
9572   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9573 }
9574
9575 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9576                                                       bool *Fast) const {
9577   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9578   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9579
9580   switch (VT.getSimpleVT().SimpleTy) {
9581   default:
9582     return false;
9583   case MVT::i8:
9584   case MVT::i16:
9585   case MVT::i32: {
9586     // Unaligned access can use (for example) LRDB, LRDH, LDR
9587     if (AllowsUnaligned) {
9588       if (Fast)
9589         *Fast = Subtarget->hasV7Ops();
9590       return true;
9591     }
9592     return false;
9593   }
9594   case MVT::f64:
9595   case MVT::v2f64: {
9596     // For any little-endian targets with neon, we can support unaligned ld/st
9597     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9598     // A big-endian target may also explicitly support unaligned accesses
9599     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9600       if (Fast)
9601         *Fast = true;
9602       return true;
9603     }
9604     return false;
9605   }
9606   }
9607 }
9608
9609 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9610                        unsigned AlignCheck) {
9611   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9612           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9613 }
9614
9615 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9616                                            unsigned DstAlign, unsigned SrcAlign,
9617                                            bool IsMemset, bool ZeroMemset,
9618                                            bool MemcpyStrSrc,
9619                                            MachineFunction &MF) const {
9620   const Function *F = MF.getFunction();
9621
9622   // See if we can use NEON instructions for this...
9623   if ((!IsMemset || ZeroMemset) &&
9624       Subtarget->hasNEON() &&
9625       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9626                                        Attribute::NoImplicitFloat)) {
9627     bool Fast;
9628     if (Size >= 16 &&
9629         (memOpAlign(SrcAlign, DstAlign, 16) ||
9630          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9631       return MVT::v2f64;
9632     } else if (Size >= 8 &&
9633                (memOpAlign(SrcAlign, DstAlign, 8) ||
9634                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9635       return MVT::f64;
9636     }
9637   }
9638
9639   // Lowering to i32/i16 if the size permits.
9640   if (Size >= 4)
9641     return MVT::i32;
9642   else if (Size >= 2)
9643     return MVT::i16;
9644
9645   // Let the target-independent logic figure it out.
9646   return MVT::Other;
9647 }
9648
9649 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9650   if (Val.getOpcode() != ISD::LOAD)
9651     return false;
9652
9653   EVT VT1 = Val.getValueType();
9654   if (!VT1.isSimple() || !VT1.isInteger() ||
9655       !VT2.isSimple() || !VT2.isInteger())
9656     return false;
9657
9658   switch (VT1.getSimpleVT().SimpleTy) {
9659   default: break;
9660   case MVT::i1:
9661   case MVT::i8:
9662   case MVT::i16:
9663     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9664     return true;
9665   }
9666
9667   return false;
9668 }
9669
9670 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9671   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9672     return false;
9673
9674   if (!isTypeLegal(EVT::getEVT(Ty1)))
9675     return false;
9676
9677   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9678
9679   // Assuming the caller doesn't have a zeroext or signext return parameter,
9680   // truncation all the way down to i1 is valid.
9681   return true;
9682 }
9683
9684
9685 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9686   if (V < 0)
9687     return false;
9688
9689   unsigned Scale = 1;
9690   switch (VT.getSimpleVT().SimpleTy) {
9691   default: return false;
9692   case MVT::i1:
9693   case MVT::i8:
9694     // Scale == 1;
9695     break;
9696   case MVT::i16:
9697     // Scale == 2;
9698     Scale = 2;
9699     break;
9700   case MVT::i32:
9701     // Scale == 4;
9702     Scale = 4;
9703     break;
9704   }
9705
9706   if ((V & (Scale - 1)) != 0)
9707     return false;
9708   V /= Scale;
9709   return V == (V & ((1LL << 5) - 1));
9710 }
9711
9712 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9713                                       const ARMSubtarget *Subtarget) {
9714   bool isNeg = false;
9715   if (V < 0) {
9716     isNeg = true;
9717     V = - V;
9718   }
9719
9720   switch (VT.getSimpleVT().SimpleTy) {
9721   default: return false;
9722   case MVT::i1:
9723   case MVT::i8:
9724   case MVT::i16:
9725   case MVT::i32:
9726     // + imm12 or - imm8
9727     if (isNeg)
9728       return V == (V & ((1LL << 8) - 1));
9729     return V == (V & ((1LL << 12) - 1));
9730   case MVT::f32:
9731   case MVT::f64:
9732     // Same as ARM mode. FIXME: NEON?
9733     if (!Subtarget->hasVFP2())
9734       return false;
9735     if ((V & 3) != 0)
9736       return false;
9737     V >>= 2;
9738     return V == (V & ((1LL << 8) - 1));
9739   }
9740 }
9741
9742 /// isLegalAddressImmediate - Return true if the integer value can be used
9743 /// as the offset of the target addressing mode for load / store of the
9744 /// given type.
9745 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9746                                     const ARMSubtarget *Subtarget) {
9747   if (V == 0)
9748     return true;
9749
9750   if (!VT.isSimple())
9751     return false;
9752
9753   if (Subtarget->isThumb1Only())
9754     return isLegalT1AddressImmediate(V, VT);
9755   else if (Subtarget->isThumb2())
9756     return isLegalT2AddressImmediate(V, VT, Subtarget);
9757
9758   // ARM mode.
9759   if (V < 0)
9760     V = - V;
9761   switch (VT.getSimpleVT().SimpleTy) {
9762   default: return false;
9763   case MVT::i1:
9764   case MVT::i8:
9765   case MVT::i32:
9766     // +- imm12
9767     return V == (V & ((1LL << 12) - 1));
9768   case MVT::i16:
9769     // +- imm8
9770     return V == (V & ((1LL << 8) - 1));
9771   case MVT::f32:
9772   case MVT::f64:
9773     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9774       return false;
9775     if ((V & 3) != 0)
9776       return false;
9777     V >>= 2;
9778     return V == (V & ((1LL << 8) - 1));
9779   }
9780 }
9781
9782 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9783                                                       EVT VT) const {
9784   int Scale = AM.Scale;
9785   if (Scale < 0)
9786     return false;
9787
9788   switch (VT.getSimpleVT().SimpleTy) {
9789   default: return false;
9790   case MVT::i1:
9791   case MVT::i8:
9792   case MVT::i16:
9793   case MVT::i32:
9794     if (Scale == 1)
9795       return true;
9796     // r + r << imm
9797     Scale = Scale & ~1;
9798     return Scale == 2 || Scale == 4 || Scale == 8;
9799   case MVT::i64:
9800     // r + r
9801     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9802       return true;
9803     return false;
9804   case MVT::isVoid:
9805     // Note, we allow "void" uses (basically, uses that aren't loads or
9806     // stores), because arm allows folding a scale into many arithmetic
9807     // operations.  This should be made more precise and revisited later.
9808
9809     // Allow r << imm, but the imm has to be a multiple of two.
9810     if (Scale & 1) return false;
9811     return isPowerOf2_32(Scale);
9812   }
9813 }
9814
9815 /// isLegalAddressingMode - Return true if the addressing mode represented
9816 /// by AM is legal for this target, for a load/store of the specified type.
9817 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9818                                               Type *Ty) const {
9819   EVT VT = getValueType(Ty, true);
9820   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9821     return false;
9822
9823   // Can never fold addr of global into load/store.
9824   if (AM.BaseGV)
9825     return false;
9826
9827   switch (AM.Scale) {
9828   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9829     break;
9830   case 1:
9831     if (Subtarget->isThumb1Only())
9832       return false;
9833     // FALL THROUGH.
9834   default:
9835     // ARM doesn't support any R+R*scale+imm addr modes.
9836     if (AM.BaseOffs)
9837       return false;
9838
9839     if (!VT.isSimple())
9840       return false;
9841
9842     if (Subtarget->isThumb2())
9843       return isLegalT2ScaledAddressingMode(AM, VT);
9844
9845     int Scale = AM.Scale;
9846     switch (VT.getSimpleVT().SimpleTy) {
9847     default: return false;
9848     case MVT::i1:
9849     case MVT::i8:
9850     case MVT::i32:
9851       if (Scale < 0) Scale = -Scale;
9852       if (Scale == 1)
9853         return true;
9854       // r + r << imm
9855       return isPowerOf2_32(Scale & ~1);
9856     case MVT::i16:
9857     case MVT::i64:
9858       // r + r
9859       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9860         return true;
9861       return false;
9862
9863     case MVT::isVoid:
9864       // Note, we allow "void" uses (basically, uses that aren't loads or
9865       // stores), because arm allows folding a scale into many arithmetic
9866       // operations.  This should be made more precise and revisited later.
9867
9868       // Allow r << imm, but the imm has to be a multiple of two.
9869       if (Scale & 1) return false;
9870       return isPowerOf2_32(Scale);
9871     }
9872   }
9873   return true;
9874 }
9875
9876 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9877 /// icmp immediate, that is the target has icmp instructions which can compare
9878 /// a register against the immediate without having to materialize the
9879 /// immediate into a register.
9880 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9881   // Thumb2 and ARM modes can use cmn for negative immediates.
9882   if (!Subtarget->isThumb())
9883     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9884   if (Subtarget->isThumb2())
9885     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9886   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9887   return Imm >= 0 && Imm <= 255;
9888 }
9889
9890 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9891 /// *or sub* immediate, that is the target has add or sub instructions which can
9892 /// add a register with the immediate without having to materialize the
9893 /// immediate into a register.
9894 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9895   // Same encoding for add/sub, just flip the sign.
9896   int64_t AbsImm = llvm::abs64(Imm);
9897   if (!Subtarget->isThumb())
9898     return ARM_AM::getSOImmVal(AbsImm) != -1;
9899   if (Subtarget->isThumb2())
9900     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9901   // Thumb1 only has 8-bit unsigned immediate.
9902   return AbsImm >= 0 && AbsImm <= 255;
9903 }
9904
9905 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9906                                       bool isSEXTLoad, SDValue &Base,
9907                                       SDValue &Offset, bool &isInc,
9908                                       SelectionDAG &DAG) {
9909   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9910     return false;
9911
9912   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9913     // AddressingMode 3
9914     Base = Ptr->getOperand(0);
9915     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9916       int RHSC = (int)RHS->getZExtValue();
9917       if (RHSC < 0 && RHSC > -256) {
9918         assert(Ptr->getOpcode() == ISD::ADD);
9919         isInc = false;
9920         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9921         return true;
9922       }
9923     }
9924     isInc = (Ptr->getOpcode() == ISD::ADD);
9925     Offset = Ptr->getOperand(1);
9926     return true;
9927   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9928     // AddressingMode 2
9929     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9930       int RHSC = (int)RHS->getZExtValue();
9931       if (RHSC < 0 && RHSC > -0x1000) {
9932         assert(Ptr->getOpcode() == ISD::ADD);
9933         isInc = false;
9934         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9935         Base = Ptr->getOperand(0);
9936         return true;
9937       }
9938     }
9939
9940     if (Ptr->getOpcode() == ISD::ADD) {
9941       isInc = true;
9942       ARM_AM::ShiftOpc ShOpcVal=
9943         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9944       if (ShOpcVal != ARM_AM::no_shift) {
9945         Base = Ptr->getOperand(1);
9946         Offset = Ptr->getOperand(0);
9947       } else {
9948         Base = Ptr->getOperand(0);
9949         Offset = Ptr->getOperand(1);
9950       }
9951       return true;
9952     }
9953
9954     isInc = (Ptr->getOpcode() == ISD::ADD);
9955     Base = Ptr->getOperand(0);
9956     Offset = Ptr->getOperand(1);
9957     return true;
9958   }
9959
9960   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9961   return false;
9962 }
9963
9964 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9965                                      bool isSEXTLoad, SDValue &Base,
9966                                      SDValue &Offset, bool &isInc,
9967                                      SelectionDAG &DAG) {
9968   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9969     return false;
9970
9971   Base = Ptr->getOperand(0);
9972   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9973     int RHSC = (int)RHS->getZExtValue();
9974     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9975       assert(Ptr->getOpcode() == ISD::ADD);
9976       isInc = false;
9977       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9978       return true;
9979     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9980       isInc = Ptr->getOpcode() == ISD::ADD;
9981       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9982       return true;
9983     }
9984   }
9985
9986   return false;
9987 }
9988
9989 /// getPreIndexedAddressParts - returns true by value, base pointer and
9990 /// offset pointer and addressing mode by reference if the node's address
9991 /// can be legally represented as pre-indexed load / store address.
9992 bool
9993 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9994                                              SDValue &Offset,
9995                                              ISD::MemIndexedMode &AM,
9996                                              SelectionDAG &DAG) const {
9997   if (Subtarget->isThumb1Only())
9998     return false;
9999
10000   EVT VT;
10001   SDValue Ptr;
10002   bool isSEXTLoad = false;
10003   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10004     Ptr = LD->getBasePtr();
10005     VT  = LD->getMemoryVT();
10006     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10007   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10008     Ptr = ST->getBasePtr();
10009     VT  = ST->getMemoryVT();
10010   } else
10011     return false;
10012
10013   bool isInc;
10014   bool isLegal = false;
10015   if (Subtarget->isThumb2())
10016     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10017                                        Offset, isInc, DAG);
10018   else
10019     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10020                                         Offset, isInc, DAG);
10021   if (!isLegal)
10022     return false;
10023
10024   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10025   return true;
10026 }
10027
10028 /// getPostIndexedAddressParts - returns true by value, base pointer and
10029 /// offset pointer and addressing mode by reference if this node can be
10030 /// combined with a load / store to form a post-indexed load / store.
10031 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10032                                                    SDValue &Base,
10033                                                    SDValue &Offset,
10034                                                    ISD::MemIndexedMode &AM,
10035                                                    SelectionDAG &DAG) const {
10036   if (Subtarget->isThumb1Only())
10037     return false;
10038
10039   EVT VT;
10040   SDValue Ptr;
10041   bool isSEXTLoad = false;
10042   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10043     VT  = LD->getMemoryVT();
10044     Ptr = LD->getBasePtr();
10045     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10046   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10047     VT  = ST->getMemoryVT();
10048     Ptr = ST->getBasePtr();
10049   } else
10050     return false;
10051
10052   bool isInc;
10053   bool isLegal = false;
10054   if (Subtarget->isThumb2())
10055     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10056                                        isInc, DAG);
10057   else
10058     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10059                                         isInc, DAG);
10060   if (!isLegal)
10061     return false;
10062
10063   if (Ptr != Base) {
10064     // Swap base ptr and offset to catch more post-index load / store when
10065     // it's legal. In Thumb2 mode, offset must be an immediate.
10066     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10067         !Subtarget->isThumb2())
10068       std::swap(Base, Offset);
10069
10070     // Post-indexed load / store update the base pointer.
10071     if (Ptr != Base)
10072       return false;
10073   }
10074
10075   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10076   return true;
10077 }
10078
10079 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10080                                                       APInt &KnownZero,
10081                                                       APInt &KnownOne,
10082                                                       const SelectionDAG &DAG,
10083                                                       unsigned Depth) const {
10084   unsigned BitWidth = KnownOne.getBitWidth();
10085   KnownZero = KnownOne = APInt(BitWidth, 0);
10086   switch (Op.getOpcode()) {
10087   default: break;
10088   case ARMISD::ADDC:
10089   case ARMISD::ADDE:
10090   case ARMISD::SUBC:
10091   case ARMISD::SUBE:
10092     // These nodes' second result is a boolean
10093     if (Op.getResNo() == 0)
10094       break;
10095     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10096     break;
10097   case ARMISD::CMOV: {
10098     // Bits are known zero/one if known on the LHS and RHS.
10099     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10100     if (KnownZero == 0 && KnownOne == 0) return;
10101
10102     APInt KnownZeroRHS, KnownOneRHS;
10103     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10104     KnownZero &= KnownZeroRHS;
10105     KnownOne  &= KnownOneRHS;
10106     return;
10107   }
10108   case ISD::INTRINSIC_W_CHAIN: {
10109     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10110     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10111     switch (IntID) {
10112     default: return;
10113     case Intrinsic::arm_ldaex:
10114     case Intrinsic::arm_ldrex: {
10115       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10116       unsigned MemBits = VT.getScalarType().getSizeInBits();
10117       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10118       return;
10119     }
10120     }
10121   }
10122   }
10123 }
10124
10125 //===----------------------------------------------------------------------===//
10126 //                           ARM Inline Assembly Support
10127 //===----------------------------------------------------------------------===//
10128
10129 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10130   // Looking for "rev" which is V6+.
10131   if (!Subtarget->hasV6Ops())
10132     return false;
10133
10134   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10135   std::string AsmStr = IA->getAsmString();
10136   SmallVector<StringRef, 4> AsmPieces;
10137   SplitString(AsmStr, AsmPieces, ";\n");
10138
10139   switch (AsmPieces.size()) {
10140   default: return false;
10141   case 1:
10142     AsmStr = AsmPieces[0];
10143     AsmPieces.clear();
10144     SplitString(AsmStr, AsmPieces, " \t,");
10145
10146     // rev $0, $1
10147     if (AsmPieces.size() == 3 &&
10148         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10149         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10150       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10151       if (Ty && Ty->getBitWidth() == 32)
10152         return IntrinsicLowering::LowerToByteSwap(CI);
10153     }
10154     break;
10155   }
10156
10157   return false;
10158 }
10159
10160 /// getConstraintType - Given a constraint letter, return the type of
10161 /// constraint it is for this target.
10162 ARMTargetLowering::ConstraintType
10163 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10164   if (Constraint.size() == 1) {
10165     switch (Constraint[0]) {
10166     default:  break;
10167     case 'l': return C_RegisterClass;
10168     case 'w': return C_RegisterClass;
10169     case 'h': return C_RegisterClass;
10170     case 'x': return C_RegisterClass;
10171     case 't': return C_RegisterClass;
10172     case 'j': return C_Other; // Constant for movw.
10173       // An address with a single base register. Due to the way we
10174       // currently handle addresses it is the same as an 'r' memory constraint.
10175     case 'Q': return C_Memory;
10176     }
10177   } else if (Constraint.size() == 2) {
10178     switch (Constraint[0]) {
10179     default: break;
10180     // All 'U+' constraints are addresses.
10181     case 'U': return C_Memory;
10182     }
10183   }
10184   return TargetLowering::getConstraintType(Constraint);
10185 }
10186
10187 /// Examine constraint type and operand type and determine a weight value.
10188 /// This object must already have been set up with the operand type
10189 /// and the current alternative constraint selected.
10190 TargetLowering::ConstraintWeight
10191 ARMTargetLowering::getSingleConstraintMatchWeight(
10192     AsmOperandInfo &info, const char *constraint) const {
10193   ConstraintWeight weight = CW_Invalid;
10194   Value *CallOperandVal = info.CallOperandVal;
10195     // If we don't have a value, we can't do a match,
10196     // but allow it at the lowest weight.
10197   if (!CallOperandVal)
10198     return CW_Default;
10199   Type *type = CallOperandVal->getType();
10200   // Look at the constraint type.
10201   switch (*constraint) {
10202   default:
10203     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10204     break;
10205   case 'l':
10206     if (type->isIntegerTy()) {
10207       if (Subtarget->isThumb())
10208         weight = CW_SpecificReg;
10209       else
10210         weight = CW_Register;
10211     }
10212     break;
10213   case 'w':
10214     if (type->isFloatingPointTy())
10215       weight = CW_Register;
10216     break;
10217   }
10218   return weight;
10219 }
10220
10221 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10222 RCPair
10223 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10224                                                 MVT VT) const {
10225   if (Constraint.size() == 1) {
10226     // GCC ARM Constraint Letters
10227     switch (Constraint[0]) {
10228     case 'l': // Low regs or general regs.
10229       if (Subtarget->isThumb())
10230         return RCPair(0U, &ARM::tGPRRegClass);
10231       return RCPair(0U, &ARM::GPRRegClass);
10232     case 'h': // High regs or no regs.
10233       if (Subtarget->isThumb())
10234         return RCPair(0U, &ARM::hGPRRegClass);
10235       break;
10236     case 'r':
10237       return RCPair(0U, &ARM::GPRRegClass);
10238     case 'w':
10239       if (VT == MVT::Other)
10240         break;
10241       if (VT == MVT::f32)
10242         return RCPair(0U, &ARM::SPRRegClass);
10243       if (VT.getSizeInBits() == 64)
10244         return RCPair(0U, &ARM::DPRRegClass);
10245       if (VT.getSizeInBits() == 128)
10246         return RCPair(0U, &ARM::QPRRegClass);
10247       break;
10248     case 'x':
10249       if (VT == MVT::Other)
10250         break;
10251       if (VT == MVT::f32)
10252         return RCPair(0U, &ARM::SPR_8RegClass);
10253       if (VT.getSizeInBits() == 64)
10254         return RCPair(0U, &ARM::DPR_8RegClass);
10255       if (VT.getSizeInBits() == 128)
10256         return RCPair(0U, &ARM::QPR_8RegClass);
10257       break;
10258     case 't':
10259       if (VT == MVT::f32)
10260         return RCPair(0U, &ARM::SPRRegClass);
10261       break;
10262     }
10263   }
10264   if (StringRef("{cc}").equals_lower(Constraint))
10265     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10266
10267   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10268 }
10269
10270 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10271 /// vector.  If it is invalid, don't add anything to Ops.
10272 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10273                                                      std::string &Constraint,
10274                                                      std::vector<SDValue>&Ops,
10275                                                      SelectionDAG &DAG) const {
10276   SDValue Result;
10277
10278   // Currently only support length 1 constraints.
10279   if (Constraint.length() != 1) return;
10280
10281   char ConstraintLetter = Constraint[0];
10282   switch (ConstraintLetter) {
10283   default: break;
10284   case 'j':
10285   case 'I': case 'J': case 'K': case 'L':
10286   case 'M': case 'N': case 'O':
10287     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10288     if (!C)
10289       return;
10290
10291     int64_t CVal64 = C->getSExtValue();
10292     int CVal = (int) CVal64;
10293     // None of these constraints allow values larger than 32 bits.  Check
10294     // that the value fits in an int.
10295     if (CVal != CVal64)
10296       return;
10297
10298     switch (ConstraintLetter) {
10299       case 'j':
10300         // Constant suitable for movw, must be between 0 and
10301         // 65535.
10302         if (Subtarget->hasV6T2Ops())
10303           if (CVal >= 0 && CVal <= 65535)
10304             break;
10305         return;
10306       case 'I':
10307         if (Subtarget->isThumb1Only()) {
10308           // This must be a constant between 0 and 255, for ADD
10309           // immediates.
10310           if (CVal >= 0 && CVal <= 255)
10311             break;
10312         } else if (Subtarget->isThumb2()) {
10313           // A constant that can be used as an immediate value in a
10314           // data-processing instruction.
10315           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10316             break;
10317         } else {
10318           // A constant that can be used as an immediate value in a
10319           // data-processing instruction.
10320           if (ARM_AM::getSOImmVal(CVal) != -1)
10321             break;
10322         }
10323         return;
10324
10325       case 'J':
10326         if (Subtarget->isThumb()) {  // FIXME thumb2
10327           // This must be a constant between -255 and -1, for negated ADD
10328           // immediates. This can be used in GCC with an "n" modifier that
10329           // prints the negated value, for use with SUB instructions. It is
10330           // not useful otherwise but is implemented for compatibility.
10331           if (CVal >= -255 && CVal <= -1)
10332             break;
10333         } else {
10334           // This must be a constant between -4095 and 4095. It is not clear
10335           // what this constraint is intended for. Implemented for
10336           // compatibility with GCC.
10337           if (CVal >= -4095 && CVal <= 4095)
10338             break;
10339         }
10340         return;
10341
10342       case 'K':
10343         if (Subtarget->isThumb1Only()) {
10344           // A 32-bit value where only one byte has a nonzero value. Exclude
10345           // zero to match GCC. This constraint is used by GCC internally for
10346           // constants that can be loaded with a move/shift combination.
10347           // It is not useful otherwise but is implemented for compatibility.
10348           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10349             break;
10350         } else if (Subtarget->isThumb2()) {
10351           // A constant whose bitwise inverse can be used as an immediate
10352           // value in a data-processing instruction. This can be used in GCC
10353           // with a "B" modifier that prints the inverted value, for use with
10354           // BIC and MVN instructions. It is not useful otherwise but is
10355           // implemented for compatibility.
10356           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10357             break;
10358         } else {
10359           // A constant whose bitwise inverse can be used as an immediate
10360           // value in a data-processing instruction. This can be used in GCC
10361           // with a "B" modifier that prints the inverted value, for use with
10362           // BIC and MVN instructions. It is not useful otherwise but is
10363           // implemented for compatibility.
10364           if (ARM_AM::getSOImmVal(~CVal) != -1)
10365             break;
10366         }
10367         return;
10368
10369       case 'L':
10370         if (Subtarget->isThumb1Only()) {
10371           // This must be a constant between -7 and 7,
10372           // for 3-operand ADD/SUB immediate instructions.
10373           if (CVal >= -7 && CVal < 7)
10374             break;
10375         } else if (Subtarget->isThumb2()) {
10376           // A constant whose negation can be used as an immediate value in a
10377           // data-processing instruction. This can be used in GCC with an "n"
10378           // modifier that prints the negated value, for use with SUB
10379           // instructions. It is not useful otherwise but is implemented for
10380           // compatibility.
10381           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10382             break;
10383         } else {
10384           // A constant whose negation can be used as an immediate value in a
10385           // data-processing instruction. This can be used in GCC with an "n"
10386           // modifier that prints the negated value, for use with SUB
10387           // instructions. It is not useful otherwise but is implemented for
10388           // compatibility.
10389           if (ARM_AM::getSOImmVal(-CVal) != -1)
10390             break;
10391         }
10392         return;
10393
10394       case 'M':
10395         if (Subtarget->isThumb()) { // FIXME thumb2
10396           // This must be a multiple of 4 between 0 and 1020, for
10397           // ADD sp + immediate.
10398           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10399             break;
10400         } else {
10401           // A power of two or a constant between 0 and 32.  This is used in
10402           // GCC for the shift amount on shifted register operands, but it is
10403           // useful in general for any shift amounts.
10404           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10405             break;
10406         }
10407         return;
10408
10409       case 'N':
10410         if (Subtarget->isThumb()) {  // FIXME thumb2
10411           // This must be a constant between 0 and 31, for shift amounts.
10412           if (CVal >= 0 && CVal <= 31)
10413             break;
10414         }
10415         return;
10416
10417       case 'O':
10418         if (Subtarget->isThumb()) {  // FIXME thumb2
10419           // This must be a multiple of 4 between -508 and 508, for
10420           // ADD/SUB sp = sp + immediate.
10421           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10422             break;
10423         }
10424         return;
10425     }
10426     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10427     break;
10428   }
10429
10430   if (Result.getNode()) {
10431     Ops.push_back(Result);
10432     return;
10433   }
10434   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10435 }
10436
10437 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10438   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10439   unsigned Opcode = Op->getOpcode();
10440   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10441       "Invalid opcode for Div/Rem lowering");
10442   bool isSigned = (Opcode == ISD::SDIVREM);
10443   EVT VT = Op->getValueType(0);
10444   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10445
10446   RTLIB::Libcall LC;
10447   switch (VT.getSimpleVT().SimpleTy) {
10448   default: llvm_unreachable("Unexpected request for libcall!");
10449   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10450   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10451   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10452   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10453   }
10454
10455   SDValue InChain = DAG.getEntryNode();
10456
10457   TargetLowering::ArgListTy Args;
10458   TargetLowering::ArgListEntry Entry;
10459   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10460     EVT ArgVT = Op->getOperand(i).getValueType();
10461     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10462     Entry.Node = Op->getOperand(i);
10463     Entry.Ty = ArgTy;
10464     Entry.isSExt = isSigned;
10465     Entry.isZExt = !isSigned;
10466     Args.push_back(Entry);
10467   }
10468
10469   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10470                                          getPointerTy());
10471
10472   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10473
10474   SDLoc dl(Op);
10475   TargetLowering::CallLoweringInfo CLI(DAG);
10476   CLI.setDebugLoc(dl).setChain(InChain)
10477     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
10478     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10479
10480   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10481   return CallInfo.first;
10482 }
10483
10484 bool
10485 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10486   // The ARM target isn't yet aware of offsets.
10487   return false;
10488 }
10489
10490 bool ARM::isBitFieldInvertedMask(unsigned v) {
10491   if (v == 0xffffffff)
10492     return false;
10493
10494   // there can be 1's on either or both "outsides", all the "inside"
10495   // bits must be 0's
10496   unsigned TO = CountTrailingOnes_32(v);
10497   unsigned LO = CountLeadingOnes_32(v);
10498   v = (v >> TO) << TO;
10499   v = (v << LO) >> LO;
10500   return v == 0;
10501 }
10502
10503 /// isFPImmLegal - Returns true if the target can instruction select the
10504 /// specified FP immediate natively. If false, the legalizer will
10505 /// materialize the FP immediate as a load from a constant pool.
10506 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10507   if (!Subtarget->hasVFP3())
10508     return false;
10509   if (VT == MVT::f32)
10510     return ARM_AM::getFP32Imm(Imm) != -1;
10511   if (VT == MVT::f64)
10512     return ARM_AM::getFP64Imm(Imm) != -1;
10513   return false;
10514 }
10515
10516 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10517 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10518 /// specified in the intrinsic calls.
10519 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10520                                            const CallInst &I,
10521                                            unsigned Intrinsic) const {
10522   switch (Intrinsic) {
10523   case Intrinsic::arm_neon_vld1:
10524   case Intrinsic::arm_neon_vld2:
10525   case Intrinsic::arm_neon_vld3:
10526   case Intrinsic::arm_neon_vld4:
10527   case Intrinsic::arm_neon_vld2lane:
10528   case Intrinsic::arm_neon_vld3lane:
10529   case Intrinsic::arm_neon_vld4lane: {
10530     Info.opc = ISD::INTRINSIC_W_CHAIN;
10531     // Conservatively set memVT to the entire set of vectors loaded.
10532     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10533     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10534     Info.ptrVal = I.getArgOperand(0);
10535     Info.offset = 0;
10536     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10537     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10538     Info.vol = false; // volatile loads with NEON intrinsics not supported
10539     Info.readMem = true;
10540     Info.writeMem = false;
10541     return true;
10542   }
10543   case Intrinsic::arm_neon_vst1:
10544   case Intrinsic::arm_neon_vst2:
10545   case Intrinsic::arm_neon_vst3:
10546   case Intrinsic::arm_neon_vst4:
10547   case Intrinsic::arm_neon_vst2lane:
10548   case Intrinsic::arm_neon_vst3lane:
10549   case Intrinsic::arm_neon_vst4lane: {
10550     Info.opc = ISD::INTRINSIC_VOID;
10551     // Conservatively set memVT to the entire set of vectors stored.
10552     unsigned NumElts = 0;
10553     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10554       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10555       if (!ArgTy->isVectorTy())
10556         break;
10557       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10558     }
10559     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10560     Info.ptrVal = I.getArgOperand(0);
10561     Info.offset = 0;
10562     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10563     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10564     Info.vol = false; // volatile stores with NEON intrinsics not supported
10565     Info.readMem = false;
10566     Info.writeMem = true;
10567     return true;
10568   }
10569   case Intrinsic::arm_ldaex:
10570   case Intrinsic::arm_ldrex: {
10571     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10572     Info.opc = ISD::INTRINSIC_W_CHAIN;
10573     Info.memVT = MVT::getVT(PtrTy->getElementType());
10574     Info.ptrVal = I.getArgOperand(0);
10575     Info.offset = 0;
10576     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10577     Info.vol = true;
10578     Info.readMem = true;
10579     Info.writeMem = false;
10580     return true;
10581   }
10582   case Intrinsic::arm_stlex:
10583   case Intrinsic::arm_strex: {
10584     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10585     Info.opc = ISD::INTRINSIC_W_CHAIN;
10586     Info.memVT = MVT::getVT(PtrTy->getElementType());
10587     Info.ptrVal = I.getArgOperand(1);
10588     Info.offset = 0;
10589     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10590     Info.vol = true;
10591     Info.readMem = false;
10592     Info.writeMem = true;
10593     return true;
10594   }
10595   case Intrinsic::arm_stlexd:
10596   case Intrinsic::arm_strexd: {
10597     Info.opc = ISD::INTRINSIC_W_CHAIN;
10598     Info.memVT = MVT::i64;
10599     Info.ptrVal = I.getArgOperand(2);
10600     Info.offset = 0;
10601     Info.align = 8;
10602     Info.vol = true;
10603     Info.readMem = false;
10604     Info.writeMem = true;
10605     return true;
10606   }
10607   case Intrinsic::arm_ldaexd:
10608   case Intrinsic::arm_ldrexd: {
10609     Info.opc = ISD::INTRINSIC_W_CHAIN;
10610     Info.memVT = MVT::i64;
10611     Info.ptrVal = I.getArgOperand(0);
10612     Info.offset = 0;
10613     Info.align = 8;
10614     Info.vol = true;
10615     Info.readMem = true;
10616     Info.writeMem = false;
10617     return true;
10618   }
10619   default:
10620     break;
10621   }
10622
10623   return false;
10624 }
10625
10626 /// \brief Returns true if it is beneficial to convert a load of a constant
10627 /// to just the constant itself.
10628 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10629                                                           Type *Ty) const {
10630   assert(Ty->isIntegerTy());
10631
10632   unsigned Bits = Ty->getPrimitiveSizeInBits();
10633   if (Bits == 0 || Bits > 32)
10634     return false;
10635   return true;
10636 }
10637
10638 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10639   // Loads and stores less than 64-bits are already atomic; ones above that
10640   // are doomed anyway, so defer to the default libcall and blame the OS when
10641   // things go wrong:
10642   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10643     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10644   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10645     return LI->getType()->getPrimitiveSizeInBits() == 64;
10646
10647   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10648   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10649 }
10650
10651 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10652                                          AtomicOrdering Ord) const {
10653   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10654   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10655   bool IsAcquire =
10656       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10657
10658   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10659   // intrinsic must return {i32, i32} and we have to recombine them into a
10660   // single i64 here.
10661   if (ValTy->getPrimitiveSizeInBits() == 64) {
10662     Intrinsic::ID Int =
10663         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10664     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10665
10666     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10667     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10668
10669     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10670     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10671     if (!Subtarget->isLittle())
10672       std::swap (Lo, Hi);
10673     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10674     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10675     return Builder.CreateOr(
10676         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10677   }
10678
10679   Type *Tys[] = { Addr->getType() };
10680   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10681   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10682
10683   return Builder.CreateTruncOrBitCast(
10684       Builder.CreateCall(Ldrex, Addr),
10685       cast<PointerType>(Addr->getType())->getElementType());
10686 }
10687
10688 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10689                                                Value *Addr,
10690                                                AtomicOrdering Ord) const {
10691   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10692   bool IsRelease =
10693       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10694
10695   // Since the intrinsics must have legal type, the i64 intrinsics take two
10696   // parameters: "i32, i32". We must marshal Val into the appropriate form
10697   // before the call.
10698   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10699     Intrinsic::ID Int =
10700         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10701     Function *Strex = Intrinsic::getDeclaration(M, Int);
10702     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10703
10704     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10705     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10706     if (!Subtarget->isLittle())
10707       std::swap (Lo, Hi);
10708     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10709     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10710   }
10711
10712   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10713   Type *Tys[] = { Addr->getType() };
10714   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10715
10716   return Builder.CreateCall2(
10717       Strex, Builder.CreateZExtOrBitCast(
10718                  Val, Strex->getFunctionType()->getParamType(0)),
10719       Addr);
10720 }
10721
10722 enum HABaseType {
10723   HA_UNKNOWN = 0,
10724   HA_FLOAT,
10725   HA_DOUBLE,
10726   HA_VECT64,
10727   HA_VECT128
10728 };
10729
10730 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10731                                    uint64_t &Members) {
10732   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10733     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10734       uint64_t SubMembers = 0;
10735       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10736         return false;
10737       Members += SubMembers;
10738     }
10739   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10740     uint64_t SubMembers = 0;
10741     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10742       return false;
10743     Members += SubMembers * AT->getNumElements();
10744   } else if (Ty->isFloatTy()) {
10745     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10746       return false;
10747     Members = 1;
10748     Base = HA_FLOAT;
10749   } else if (Ty->isDoubleTy()) {
10750     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10751       return false;
10752     Members = 1;
10753     Base = HA_DOUBLE;
10754   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10755     Members = 1;
10756     switch (Base) {
10757     case HA_FLOAT:
10758     case HA_DOUBLE:
10759       return false;
10760     case HA_VECT64:
10761       return VT->getBitWidth() == 64;
10762     case HA_VECT128:
10763       return VT->getBitWidth() == 128;
10764     case HA_UNKNOWN:
10765       switch (VT->getBitWidth()) {
10766       case 64:
10767         Base = HA_VECT64;
10768         return true;
10769       case 128:
10770         Base = HA_VECT128;
10771         return true;
10772       default:
10773         return false;
10774       }
10775     }
10776   }
10777
10778   return (Members > 0 && Members <= 4);
10779 }
10780
10781 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10782 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10783     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10784   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10785       CallingConv::ARM_AAPCS_VFP)
10786     return false;
10787
10788   HABaseType Base = HA_UNKNOWN;
10789   uint64_t Members = 0;
10790   bool result = isHomogeneousAggregate(Ty, Base, Members);
10791   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10792   return result;
10793 }