Also combine zext/sext into selects for ARM.
[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 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
126   if (VT.isInteger()) {
127     setOperationAction(ISD::SHL, VT, Custom);
128     setOperationAction(ISD::SRA, VT, Custom);
129     setOperationAction(ISD::SRL, VT, Custom);
130   }
131
132   // Promote all bit-wise operations.
133   if (VT.isInteger() && VT != PromotedBitwiseVT) {
134     setOperationAction(ISD::AND, VT, Promote);
135     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136     setOperationAction(ISD::OR,  VT, Promote);
137     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
138     setOperationAction(ISD::XOR, VT, Promote);
139     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140   }
141
142   // Neon does not support vector divide/remainder operations.
143   setOperationAction(ISD::SDIV, VT, Expand);
144   setOperationAction(ISD::UDIV, VT, Expand);
145   setOperationAction(ISD::FDIV, VT, Expand);
146   setOperationAction(ISD::SREM, VT, Expand);
147   setOperationAction(ISD::UREM, VT, Expand);
148   setOperationAction(ISD::FREM, VT, Expand);
149 }
150
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152   addRegisterClass(VT, &ARM::DPRRegClass);
153   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 }
155
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157   addRegisterClass(VT, &ARM::QPRRegClass);
158   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 }
160
161 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
162   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
163     return new TargetLoweringObjectFileMachO();
164
165   return new ARMElfTargetObjectFile();
166 }
167
168 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
169     : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<ARMSubtarget>();
171   RegInfo = TM.getRegisterInfo();
172   Itins = TM.getInstrItineraryData();
173
174   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175
176   if (Subtarget->isTargetDarwin()) {
177     // Uses VFP for Thumb libfuncs if available.
178     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
179       // Single-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184
185       // Double-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190
191       // Single-precision comparisons.
192       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
199       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
200
201       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
208       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
209
210       // Double-precision comparisons.
211       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
218       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
219
220       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
227       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
228
229       // Floating-point to integer conversions.
230       // i64 conversions are done via library routines even when generating VFP
231       // instructions, so use the same ones.
232       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236
237       // Conversions between floating types.
238       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
240
241       // Integer to floating-point conversions.
242       // i64 conversions are done via library routines even when generating VFP
243       // instructions, so use the same ones.
244       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245       // e.g., __floatunsidf vs. __floatunssidfvfp.
246       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250     }
251   }
252
253   // These libcalls are not available in 32-bit.
254   setLibcallName(RTLIB::SHL_I128, 0);
255   setLibcallName(RTLIB::SRL_I128, 0);
256   setLibcallName(RTLIB::SRA_I128, 0);
257
258   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
259     // Double-precision floating-point arithmetic helper functions
260     // RTABI chapter 4.1.2, Table 2
261     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
269
270     // Double-precision floating-point comparison helper functions
271     // RTABI chapter 4.1.2, Table 3
272     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
286     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
287     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
288     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
296
297     // Single-precision floating-point arithmetic helper functions
298     // RTABI chapter 4.1.2, Table 4
299     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
307
308     // Single-precision floating-point comparison helper functions
309     // RTABI chapter 4.1.2, Table 5
310     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
324     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
325     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
326     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
334
335     // Floating-point to integer conversions.
336     // RTABI chapter 4.1.2, Table 6
337     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
353
354     // Conversions between floating types.
355     // RTABI chapter 4.1.2, Table 7
356     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
358     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
360
361     // Integer to floating-point conversions.
362     // RTABI chapter 4.1.2, Table 8
363     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379
380     // Long long helper functions
381     // RTABI chapter 4.2, Table 9
382     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
383     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
392
393     // Integer division functions
394     // RTABI chapter 4.3.1
395     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
411
412     // Memory operations
413     // RTABI chapter 4.3.4
414     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
415     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
417     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
420   }
421
422   // Use divmod compiler-rt calls for iOS 5.0 and later.
423   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
424       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
425     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
426     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
427   }
428
429   if (Subtarget->isThumb1Only())
430     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
431   else
432     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
433   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
434       !Subtarget->isThumb1Only()) {
435     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
436     if (!Subtarget->isFPOnlySP())
437       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
438
439     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440   }
441
442   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
444     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
445          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
446       setTruncStoreAction((MVT::SimpleValueType)VT,
447                           (MVT::SimpleValueType)InnerVT, Expand);
448     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
449     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
451   }
452
453   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
454
455   if (Subtarget->hasNEON()) {
456     addDRTypeForNEON(MVT::v2f32);
457     addDRTypeForNEON(MVT::v8i8);
458     addDRTypeForNEON(MVT::v4i16);
459     addDRTypeForNEON(MVT::v2i32);
460     addDRTypeForNEON(MVT::v1i64);
461
462     addQRTypeForNEON(MVT::v4f32);
463     addQRTypeForNEON(MVT::v2f64);
464     addQRTypeForNEON(MVT::v16i8);
465     addQRTypeForNEON(MVT::v8i16);
466     addQRTypeForNEON(MVT::v4i32);
467     addQRTypeForNEON(MVT::v2i64);
468
469     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
470     // neither Neon nor VFP support any arithmetic operations on it.
471     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
472     // supported for v4f32.
473     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
474     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
476     // FIXME: Code duplication: FDIV and FREM are expanded always, see
477     // ARMTargetLowering::addTypeForNEON method for details.
478     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
479     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
480     // FIXME: Create unittest.
481     // In another words, find a way when "copysign" appears in DAG with vector
482     // operands.
483     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
484     // FIXME: Code duplication: SETCC has custom operation action, see
485     // ARMTargetLowering::addTypeForNEON method for details.
486     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
487     // FIXME: Create unittest for FNEG and for FABS.
488     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
489     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
490     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
492     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
493     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
495     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
498     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
500     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
501     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
502     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
503     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
504     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
506
507     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
517
518     // Neon does not support some operations on v1i64 and v2i64 types.
519     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520     // Custom handling for some quad-vector types to detect VMULL.
521     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524     // Custom handling for some vector types to avoid expensive expansions
525     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532     // a destination type that is wider than the source, and nor does
533     // it have a FP_TO_[SU]INT instruction with a narrower destination than
534     // source.
535     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
539
540     setTargetDAGCombine(ISD::INTRINSIC_VOID);
541     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
542     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
543     setTargetDAGCombine(ISD::SHL);
544     setTargetDAGCombine(ISD::SRL);
545     setTargetDAGCombine(ISD::SRA);
546     setTargetDAGCombine(ISD::SIGN_EXTEND);
547     setTargetDAGCombine(ISD::ZERO_EXTEND);
548     setTargetDAGCombine(ISD::ANY_EXTEND);
549     setTargetDAGCombine(ISD::SELECT_CC);
550     setTargetDAGCombine(ISD::BUILD_VECTOR);
551     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
552     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
553     setTargetDAGCombine(ISD::STORE);
554     setTargetDAGCombine(ISD::FP_TO_SINT);
555     setTargetDAGCombine(ISD::FP_TO_UINT);
556     setTargetDAGCombine(ISD::FDIV);
557
558     // It is legal to extload from v4i8 to v4i16 or v4i32.
559     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
560                   MVT::v4i16, MVT::v2i16,
561                   MVT::v2i32};
562     for (unsigned i = 0; i < 6; ++i) {
563       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
564       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
565       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
566     }
567   }
568
569   computeRegisterProperties();
570
571   // ARM does not have f32 extending load.
572   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
573
574   // ARM does not have i1 sign extending load.
575   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
576
577   // ARM supports all 4 flavors of integer indexed load / store.
578   if (!Subtarget->isThumb1Only()) {
579     for (unsigned im = (unsigned)ISD::PRE_INC;
580          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
581       setIndexedLoadAction(im,  MVT::i1,  Legal);
582       setIndexedLoadAction(im,  MVT::i8,  Legal);
583       setIndexedLoadAction(im,  MVT::i16, Legal);
584       setIndexedLoadAction(im,  MVT::i32, Legal);
585       setIndexedStoreAction(im, MVT::i1,  Legal);
586       setIndexedStoreAction(im, MVT::i8,  Legal);
587       setIndexedStoreAction(im, MVT::i16, Legal);
588       setIndexedStoreAction(im, MVT::i32, Legal);
589     }
590   }
591
592   // i64 operation support.
593   setOperationAction(ISD::MUL,     MVT::i64, Expand);
594   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
595   if (Subtarget->isThumb1Only()) {
596     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
597     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
598   }
599   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
600       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
601     setOperationAction(ISD::MULHS, MVT::i32, Expand);
602
603   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
604   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
605   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
606   setOperationAction(ISD::SRL,       MVT::i64, Custom);
607   setOperationAction(ISD::SRA,       MVT::i64, Custom);
608
609   if (!Subtarget->isThumb1Only()) {
610     // FIXME: We should do this for Thumb1 as well.
611     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
612     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
613     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
614     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
615   }
616
617   // ARM does not have ROTL.
618   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
619   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
620   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
621   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
622     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
623
624   // These just redirect to CTTZ and CTLZ on ARM.
625   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
626   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
627
628   // Only ARMv6 has BSWAP.
629   if (!Subtarget->hasV6Ops())
630     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
631
632   // These are expanded into libcalls.
633   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
634     // v7M has a hardware divider
635     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
636     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
637   }
638   setOperationAction(ISD::SREM,  MVT::i32, Expand);
639   setOperationAction(ISD::UREM,  MVT::i32, Expand);
640   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
641   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
642
643   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
644   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
645   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
646   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
647   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
648
649   setOperationAction(ISD::TRAP, MVT::Other, Legal);
650
651   // Use the default implementation.
652   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
653   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
654   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
655   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
656   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
657   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
658
659   if (!Subtarget->isTargetDarwin()) {
660     // Non-Darwin platforms may return values in these registers via the
661     // personality function.
662     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
663     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
664     setExceptionPointerRegister(ARM::R0);
665     setExceptionSelectorRegister(ARM::R1);
666   }
667
668   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
669   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
670   // the default expansion.
671   // FIXME: This should be checking for v6k, not just v6.
672   if (Subtarget->hasDataBarrier() ||
673       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
674     // membarrier needs custom lowering; the rest are legal and handled
675     // normally.
676     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
677     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
678     // Custom lowering for 64-bit ops
679     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
680     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
681     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
682     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
683     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
684     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
685     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
686     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
687     setInsertFencesForAtomic(true);
688   } else {
689     // Set them all for expansion, which will force libcalls.
690     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
691     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
692     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
693     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
694     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
695     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
696     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
697     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
698     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
704     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
705     // Unordered/Monotonic case.
706     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
707     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
708     // Since the libcalls include locking, fold in the fences
709     setShouldFoldAtomicFences(true);
710   }
711
712   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
713
714   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
715   if (!Subtarget->hasV6Ops()) {
716     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
717     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
718   }
719   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
720
721   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
722       !Subtarget->isThumb1Only()) {
723     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
724     // iff target supports vfp2.
725     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
726     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
727   }
728
729   // We want to custom lower some of our intrinsics.
730   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
731   if (Subtarget->isTargetDarwin()) {
732     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
733     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
734     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
735   }
736
737   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
738   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
739   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
740   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
741   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
742   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
743   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
744   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
745   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
746
747   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
748   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
749   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
750   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
751   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
752
753   // We don't support sin/cos/fmod/copysign/pow
754   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
755   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
756   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
757   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
758   setOperationAction(ISD::FREM,      MVT::f64, Expand);
759   setOperationAction(ISD::FREM,      MVT::f32, Expand);
760   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
761       !Subtarget->isThumb1Only()) {
762     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
763     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
764   }
765   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
766   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
767
768   if (!Subtarget->hasVFP4()) {
769     setOperationAction(ISD::FMA, MVT::f64, Expand);
770     setOperationAction(ISD::FMA, MVT::f32, Expand);
771   }
772
773   // Various VFP goodness
774   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
775     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
776     if (Subtarget->hasVFP2()) {
777       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
778       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
779       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
780       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
781     }
782     // Special handling for half-precision FP.
783     if (!Subtarget->hasFP16()) {
784       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
785       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
786     }
787   }
788
789   // We have target-specific dag combine patterns for the following nodes:
790   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
791   setTargetDAGCombine(ISD::ADD);
792   setTargetDAGCombine(ISD::SUB);
793   setTargetDAGCombine(ISD::MUL);
794
795   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
796     setTargetDAGCombine(ISD::AND);
797     setTargetDAGCombine(ISD::OR);
798     setTargetDAGCombine(ISD::XOR);
799   }
800
801   if (Subtarget->hasV6Ops())
802     setTargetDAGCombine(ISD::SRL);
803
804   setStackPointerRegisterToSaveRestore(ARM::SP);
805
806   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
807       !Subtarget->hasVFP2())
808     setSchedulingPreference(Sched::RegPressure);
809   else
810     setSchedulingPreference(Sched::Hybrid);
811
812   //// temporary - rewrite interface to use type
813   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
814   maxStoresPerMemset = 16;
815   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
816
817   // On ARM arguments smaller than 4 bytes are extended, so all arguments
818   // are at least 4 bytes aligned.
819   setMinStackArgumentAlignment(4);
820
821   benefitFromCodePlacementOpt = true;
822
823   // Prefer likely predicted branches to selects on out-of-order cores.
824   predictableSelectIsExpensive = Subtarget->isCortexA9();
825
826   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
827 }
828
829 // FIXME: It might make sense to define the representative register class as the
830 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
831 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
832 // SPR's representative would be DPR_VFP2. This should work well if register
833 // pressure tracking were modified such that a register use would increment the
834 // pressure of the register class's representative and all of it's super
835 // classes' representatives transitively. We have not implemented this because
836 // of the difficulty prior to coalescing of modeling operand register classes
837 // due to the common occurrence of cross class copies and subregister insertions
838 // and extractions.
839 std::pair<const TargetRegisterClass*, uint8_t>
840 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
841   const TargetRegisterClass *RRC = 0;
842   uint8_t Cost = 1;
843   switch (VT.getSimpleVT().SimpleTy) {
844   default:
845     return TargetLowering::findRepresentativeClass(VT);
846   // Use DPR as representative register class for all floating point
847   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
848   // the cost is 1 for both f32 and f64.
849   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
850   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
851     RRC = &ARM::DPRRegClass;
852     // When NEON is used for SP, only half of the register file is available
853     // because operations that define both SP and DP results will be constrained
854     // to the VFP2 class (D0-D15). We currently model this constraint prior to
855     // coalescing by double-counting the SP regs. See the FIXME above.
856     if (Subtarget->useNEONForSinglePrecisionFP())
857       Cost = 2;
858     break;
859   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
860   case MVT::v4f32: case MVT::v2f64:
861     RRC = &ARM::DPRRegClass;
862     Cost = 2;
863     break;
864   case MVT::v4i64:
865     RRC = &ARM::DPRRegClass;
866     Cost = 4;
867     break;
868   case MVT::v8i64:
869     RRC = &ARM::DPRRegClass;
870     Cost = 8;
871     break;
872   }
873   return std::make_pair(RRC, Cost);
874 }
875
876 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
877   switch (Opcode) {
878   default: return 0;
879   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
880   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
881   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
882   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
883   case ARMISD::CALL:          return "ARMISD::CALL";
884   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
885   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
886   case ARMISD::tCALL:         return "ARMISD::tCALL";
887   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
888   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
889   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
890   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
891   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
892   case ARMISD::CMP:           return "ARMISD::CMP";
893   case ARMISD::CMN:           return "ARMISD::CMN";
894   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
895   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
896   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
897   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
898   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
899
900   case ARMISD::CMOV:          return "ARMISD::CMOV";
901   case ARMISD::CAND:          return "ARMISD::CAND";
902   case ARMISD::COR:           return "ARMISD::COR";
903   case ARMISD::CXOR:          return "ARMISD::CXOR";
904
905   case ARMISD::RBIT:          return "ARMISD::RBIT";
906
907   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
908   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
909   case ARMISD::SITOF:         return "ARMISD::SITOF";
910   case ARMISD::UITOF:         return "ARMISD::UITOF";
911
912   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
913   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
914   case ARMISD::RRX:           return "ARMISD::RRX";
915
916   case ARMISD::ADDC:          return "ARMISD::ADDC";
917   case ARMISD::ADDE:          return "ARMISD::ADDE";
918   case ARMISD::SUBC:          return "ARMISD::SUBC";
919   case ARMISD::SUBE:          return "ARMISD::SUBE";
920
921   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
922   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
923
924   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
925   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
926
927   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
928
929   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
930
931   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
932
933   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
934   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
935
936   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
937
938   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
939   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
940   case ARMISD::VCGE:          return "ARMISD::VCGE";
941   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
942   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
943   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
944   case ARMISD::VCGT:          return "ARMISD::VCGT";
945   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
946   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
947   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
948   case ARMISD::VTST:          return "ARMISD::VTST";
949
950   case ARMISD::VSHL:          return "ARMISD::VSHL";
951   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
952   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
953   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
954   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
955   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
956   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
957   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
958   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
959   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
960   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
961   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
962   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
963   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
964   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
965   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
966   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
967   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
968   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
969   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
970   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
971   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
972   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
973   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
974   case ARMISD::VDUP:          return "ARMISD::VDUP";
975   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
976   case ARMISD::VEXT:          return "ARMISD::VEXT";
977   case ARMISD::VREV64:        return "ARMISD::VREV64";
978   case ARMISD::VREV32:        return "ARMISD::VREV32";
979   case ARMISD::VREV16:        return "ARMISD::VREV16";
980   case ARMISD::VZIP:          return "ARMISD::VZIP";
981   case ARMISD::VUZP:          return "ARMISD::VUZP";
982   case ARMISD::VTRN:          return "ARMISD::VTRN";
983   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
984   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
985   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
986   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
987   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
988   case ARMISD::FMAX:          return "ARMISD::FMAX";
989   case ARMISD::FMIN:          return "ARMISD::FMIN";
990   case ARMISD::BFI:           return "ARMISD::BFI";
991   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
992   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
993   case ARMISD::VBSL:          return "ARMISD::VBSL";
994   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
995   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
996   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
997   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
998   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
999   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1000   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1001   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1002   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1003   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1004   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1005   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1006   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1007   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1008   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1009   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1010   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1011   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1012   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1013   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1014   }
1015 }
1016
1017 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1018   if (!VT.isVector()) return getPointerTy();
1019   return VT.changeVectorElementTypeToInteger();
1020 }
1021
1022 /// getRegClassFor - Return the register class that should be used for the
1023 /// specified value type.
1024 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1025   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1026   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1027   // load / store 4 to 8 consecutive D registers.
1028   if (Subtarget->hasNEON()) {
1029     if (VT == MVT::v4i64)
1030       return &ARM::QQPRRegClass;
1031     if (VT == MVT::v8i64)
1032       return &ARM::QQQQPRRegClass;
1033   }
1034   return TargetLowering::getRegClassFor(VT);
1035 }
1036
1037 // Create a fast isel object.
1038 FastISel *
1039 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1040                                   const TargetLibraryInfo *libInfo) const {
1041   return ARM::createFastISel(funcInfo, libInfo);
1042 }
1043
1044 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1045 /// be used for loads / stores from the global.
1046 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1047   return (Subtarget->isThumb1Only() ? 127 : 4095);
1048 }
1049
1050 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1051   unsigned NumVals = N->getNumValues();
1052   if (!NumVals)
1053     return Sched::RegPressure;
1054
1055   for (unsigned i = 0; i != NumVals; ++i) {
1056     EVT VT = N->getValueType(i);
1057     if (VT == MVT::Glue || VT == MVT::Other)
1058       continue;
1059     if (VT.isFloatingPoint() || VT.isVector())
1060       return Sched::ILP;
1061   }
1062
1063   if (!N->isMachineOpcode())
1064     return Sched::RegPressure;
1065
1066   // Load are scheduled for latency even if there instruction itinerary
1067   // is not available.
1068   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1069   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1070
1071   if (MCID.getNumDefs() == 0)
1072     return Sched::RegPressure;
1073   if (!Itins->isEmpty() &&
1074       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1075     return Sched::ILP;
1076
1077   return Sched::RegPressure;
1078 }
1079
1080 //===----------------------------------------------------------------------===//
1081 // Lowering Code
1082 //===----------------------------------------------------------------------===//
1083
1084 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1085 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1086   switch (CC) {
1087   default: llvm_unreachable("Unknown condition code!");
1088   case ISD::SETNE:  return ARMCC::NE;
1089   case ISD::SETEQ:  return ARMCC::EQ;
1090   case ISD::SETGT:  return ARMCC::GT;
1091   case ISD::SETGE:  return ARMCC::GE;
1092   case ISD::SETLT:  return ARMCC::LT;
1093   case ISD::SETLE:  return ARMCC::LE;
1094   case ISD::SETUGT: return ARMCC::HI;
1095   case ISD::SETUGE: return ARMCC::HS;
1096   case ISD::SETULT: return ARMCC::LO;
1097   case ISD::SETULE: return ARMCC::LS;
1098   }
1099 }
1100
1101 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1102 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1103                         ARMCC::CondCodes &CondCode2) {
1104   CondCode2 = ARMCC::AL;
1105   switch (CC) {
1106   default: llvm_unreachable("Unknown FP condition!");
1107   case ISD::SETEQ:
1108   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1109   case ISD::SETGT:
1110   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1111   case ISD::SETGE:
1112   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1113   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1114   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1115   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1116   case ISD::SETO:   CondCode = ARMCC::VC; break;
1117   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1118   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1119   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1120   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1121   case ISD::SETLT:
1122   case ISD::SETULT: CondCode = ARMCC::LT; break;
1123   case ISD::SETLE:
1124   case ISD::SETULE: CondCode = ARMCC::LE; break;
1125   case ISD::SETNE:
1126   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1127   }
1128 }
1129
1130 //===----------------------------------------------------------------------===//
1131 //                      Calling Convention Implementation
1132 //===----------------------------------------------------------------------===//
1133
1134 #include "ARMGenCallingConv.inc"
1135
1136 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1137 /// given CallingConvention value.
1138 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1139                                                  bool Return,
1140                                                  bool isVarArg) const {
1141   switch (CC) {
1142   default:
1143     llvm_unreachable("Unsupported calling convention");
1144   case CallingConv::Fast:
1145     if (Subtarget->hasVFP2() && !isVarArg) {
1146       if (!Subtarget->isAAPCS_ABI())
1147         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1148       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1149       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1150     }
1151     // Fallthrough
1152   case CallingConv::C: {
1153     // Use target triple & subtarget features to do actual dispatch.
1154     if (!Subtarget->isAAPCS_ABI())
1155       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1156     else if (Subtarget->hasVFP2() &&
1157              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1158              !isVarArg)
1159       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1160     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1161   }
1162   case CallingConv::ARM_AAPCS_VFP:
1163     if (!isVarArg)
1164       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1165     // Fallthrough
1166   case CallingConv::ARM_AAPCS:
1167     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1168   case CallingConv::ARM_APCS:
1169     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1170   case CallingConv::GHC:
1171     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1172   }
1173 }
1174
1175 /// LowerCallResult - Lower the result values of a call into the
1176 /// appropriate copies out of appropriate physical registers.
1177 SDValue
1178 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1179                                    CallingConv::ID CallConv, bool isVarArg,
1180                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1181                                    DebugLoc dl, SelectionDAG &DAG,
1182                                    SmallVectorImpl<SDValue> &InVals) const {
1183
1184   // Assign locations to each value returned by this call.
1185   SmallVector<CCValAssign, 16> RVLocs;
1186   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1187                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1188   CCInfo.AnalyzeCallResult(Ins,
1189                            CCAssignFnForNode(CallConv, /* Return*/ true,
1190                                              isVarArg));
1191
1192   // Copy all of the result registers out of their specified physreg.
1193   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1194     CCValAssign VA = RVLocs[i];
1195
1196     SDValue Val;
1197     if (VA.needsCustom()) {
1198       // Handle f64 or half of a v2f64.
1199       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1200                                       InFlag);
1201       Chain = Lo.getValue(1);
1202       InFlag = Lo.getValue(2);
1203       VA = RVLocs[++i]; // skip ahead to next loc
1204       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1205                                       InFlag);
1206       Chain = Hi.getValue(1);
1207       InFlag = Hi.getValue(2);
1208       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1209
1210       if (VA.getLocVT() == MVT::v2f64) {
1211         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1212         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1213                           DAG.getConstant(0, MVT::i32));
1214
1215         VA = RVLocs[++i]; // skip ahead to next loc
1216         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1217         Chain = Lo.getValue(1);
1218         InFlag = Lo.getValue(2);
1219         VA = RVLocs[++i]; // skip ahead to next loc
1220         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1221         Chain = Hi.getValue(1);
1222         InFlag = Hi.getValue(2);
1223         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1224         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1225                           DAG.getConstant(1, MVT::i32));
1226       }
1227     } else {
1228       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1229                                InFlag);
1230       Chain = Val.getValue(1);
1231       InFlag = Val.getValue(2);
1232     }
1233
1234     switch (VA.getLocInfo()) {
1235     default: llvm_unreachable("Unknown loc info!");
1236     case CCValAssign::Full: break;
1237     case CCValAssign::BCvt:
1238       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1239       break;
1240     }
1241
1242     InVals.push_back(Val);
1243   }
1244
1245   return Chain;
1246 }
1247
1248 /// LowerMemOpCallTo - Store the argument to the stack.
1249 SDValue
1250 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1251                                     SDValue StackPtr, SDValue Arg,
1252                                     DebugLoc dl, SelectionDAG &DAG,
1253                                     const CCValAssign &VA,
1254                                     ISD::ArgFlagsTy Flags) const {
1255   unsigned LocMemOffset = VA.getLocMemOffset();
1256   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1257   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1258   return DAG.getStore(Chain, dl, Arg, PtrOff,
1259                       MachinePointerInfo::getStack(LocMemOffset),
1260                       false, false, 0);
1261 }
1262
1263 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1264                                          SDValue Chain, SDValue &Arg,
1265                                          RegsToPassVector &RegsToPass,
1266                                          CCValAssign &VA, CCValAssign &NextVA,
1267                                          SDValue &StackPtr,
1268                                          SmallVector<SDValue, 8> &MemOpChains,
1269                                          ISD::ArgFlagsTy Flags) const {
1270
1271   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1272                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1273   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1274
1275   if (NextVA.isRegLoc())
1276     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1277   else {
1278     assert(NextVA.isMemLoc());
1279     if (StackPtr.getNode() == 0)
1280       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1281
1282     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1283                                            dl, DAG, NextVA,
1284                                            Flags));
1285   }
1286 }
1287
1288 /// LowerCall - Lowering a call into a callseq_start <-
1289 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1290 /// nodes.
1291 SDValue
1292 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1293                              SmallVectorImpl<SDValue> &InVals) const {
1294   SelectionDAG &DAG                     = CLI.DAG;
1295   DebugLoc &dl                          = CLI.DL;
1296   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1297   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1298   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1299   SDValue Chain                         = CLI.Chain;
1300   SDValue Callee                        = CLI.Callee;
1301   bool &isTailCall                      = CLI.IsTailCall;
1302   CallingConv::ID CallConv              = CLI.CallConv;
1303   bool doesNotRet                       = CLI.DoesNotReturn;
1304   bool isVarArg                         = CLI.IsVarArg;
1305
1306   MachineFunction &MF = DAG.getMachineFunction();
1307   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1308   bool IsSibCall = false;
1309   // Disable tail calls if they're not supported.
1310   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1311     isTailCall = false;
1312   if (isTailCall) {
1313     // Check if it's really possible to do a tail call.
1314     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1315                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1316                                                    Outs, OutVals, Ins, DAG);
1317     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1318     // detected sibcalls.
1319     if (isTailCall) {
1320       ++NumTailCalls;
1321       IsSibCall = true;
1322     }
1323   }
1324
1325   // Analyze operands of the call, assigning locations to each operand.
1326   SmallVector<CCValAssign, 16> ArgLocs;
1327   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1328                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1329   CCInfo.AnalyzeCallOperands(Outs,
1330                              CCAssignFnForNode(CallConv, /* Return*/ false,
1331                                                isVarArg));
1332
1333   // Get a count of how many bytes are to be pushed on the stack.
1334   unsigned NumBytes = CCInfo.getNextStackOffset();
1335
1336   // For tail calls, memory operands are available in our caller's stack.
1337   if (IsSibCall)
1338     NumBytes = 0;
1339
1340   // Adjust the stack pointer for the new arguments...
1341   // These operations are automatically eliminated by the prolog/epilog pass
1342   if (!IsSibCall)
1343     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1344
1345   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1346
1347   RegsToPassVector RegsToPass;
1348   SmallVector<SDValue, 8> MemOpChains;
1349
1350   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1351   // of tail call optimization, arguments are handled later.
1352   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1353        i != e;
1354        ++i, ++realArgIdx) {
1355     CCValAssign &VA = ArgLocs[i];
1356     SDValue Arg = OutVals[realArgIdx];
1357     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1358     bool isByVal = Flags.isByVal();
1359
1360     // Promote the value if needed.
1361     switch (VA.getLocInfo()) {
1362     default: llvm_unreachable("Unknown loc info!");
1363     case CCValAssign::Full: break;
1364     case CCValAssign::SExt:
1365       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1366       break;
1367     case CCValAssign::ZExt:
1368       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1369       break;
1370     case CCValAssign::AExt:
1371       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1372       break;
1373     case CCValAssign::BCvt:
1374       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1375       break;
1376     }
1377
1378     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1379     if (VA.needsCustom()) {
1380       if (VA.getLocVT() == MVT::v2f64) {
1381         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1382                                   DAG.getConstant(0, MVT::i32));
1383         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1384                                   DAG.getConstant(1, MVT::i32));
1385
1386         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1387                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1388
1389         VA = ArgLocs[++i]; // skip ahead to next loc
1390         if (VA.isRegLoc()) {
1391           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1392                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1393         } else {
1394           assert(VA.isMemLoc());
1395
1396           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1397                                                  dl, DAG, VA, Flags));
1398         }
1399       } else {
1400         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1401                          StackPtr, MemOpChains, Flags);
1402       }
1403     } else if (VA.isRegLoc()) {
1404       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1405     } else if (isByVal) {
1406       assert(VA.isMemLoc());
1407       unsigned offset = 0;
1408
1409       // True if this byval aggregate will be split between registers
1410       // and memory.
1411       if (CCInfo.isFirstByValRegValid()) {
1412         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1413         unsigned int i, j;
1414         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1415           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1416           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1417           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1418                                      MachinePointerInfo(),
1419                                      false, false, false, 0);
1420           MemOpChains.push_back(Load.getValue(1));
1421           RegsToPass.push_back(std::make_pair(j, Load));
1422         }
1423         offset = ARM::R4 - CCInfo.getFirstByValReg();
1424         CCInfo.clearFirstByValReg();
1425       }
1426
1427       if (Flags.getByValSize() - 4*offset > 0) {
1428         unsigned LocMemOffset = VA.getLocMemOffset();
1429         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1430         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1431                                   StkPtrOff);
1432         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1433         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1434         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1435                                            MVT::i32);
1436         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1437
1438         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1439         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1440         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1441                                           Ops, array_lengthof(Ops)));
1442       }
1443     } else if (!IsSibCall) {
1444       assert(VA.isMemLoc());
1445
1446       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1447                                              dl, DAG, VA, Flags));
1448     }
1449   }
1450
1451   if (!MemOpChains.empty())
1452     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1453                         &MemOpChains[0], MemOpChains.size());
1454
1455   // Build a sequence of copy-to-reg nodes chained together with token chain
1456   // and flag operands which copy the outgoing args into the appropriate regs.
1457   SDValue InFlag;
1458   // Tail call byval lowering might overwrite argument registers so in case of
1459   // tail call optimization the copies to registers are lowered later.
1460   if (!isTailCall)
1461     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1462       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1463                                RegsToPass[i].second, InFlag);
1464       InFlag = Chain.getValue(1);
1465     }
1466
1467   // For tail calls lower the arguments to the 'real' stack slot.
1468   if (isTailCall) {
1469     // Force all the incoming stack arguments to be loaded from the stack
1470     // before any new outgoing arguments are stored to the stack, because the
1471     // outgoing stack slots may alias the incoming argument stack slots, and
1472     // the alias isn't otherwise explicit. This is slightly more conservative
1473     // than necessary, because it means that each store effectively depends
1474     // on every argument instead of just those arguments it would clobber.
1475
1476     // Do not flag preceding copytoreg stuff together with the following stuff.
1477     InFlag = SDValue();
1478     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1479       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1480                                RegsToPass[i].second, InFlag);
1481       InFlag = Chain.getValue(1);
1482     }
1483     InFlag =SDValue();
1484   }
1485
1486   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1487   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1488   // node so that legalize doesn't hack it.
1489   bool isDirect = false;
1490   bool isARMFunc = false;
1491   bool isLocalARMFunc = false;
1492   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1493
1494   if (EnableARMLongCalls) {
1495     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1496             && "long-calls with non-static relocation model!");
1497     // Handle a global address or an external symbol. If it's not one of
1498     // those, the target's already in a register, so we don't need to do
1499     // anything extra.
1500     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1501       const GlobalValue *GV = G->getGlobal();
1502       // Create a constant pool entry for the callee address
1503       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1504       ARMConstantPoolValue *CPV =
1505         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1506
1507       // Get the address of the callee into a register
1508       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1509       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1510       Callee = DAG.getLoad(getPointerTy(), dl,
1511                            DAG.getEntryNode(), CPAddr,
1512                            MachinePointerInfo::getConstantPool(),
1513                            false, false, false, 0);
1514     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1515       const char *Sym = S->getSymbol();
1516
1517       // Create a constant pool entry for the callee address
1518       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1519       ARMConstantPoolValue *CPV =
1520         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1521                                       ARMPCLabelIndex, 0);
1522       // Get the address of the callee into a register
1523       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1524       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1525       Callee = DAG.getLoad(getPointerTy(), dl,
1526                            DAG.getEntryNode(), CPAddr,
1527                            MachinePointerInfo::getConstantPool(),
1528                            false, false, false, 0);
1529     }
1530   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1531     const GlobalValue *GV = G->getGlobal();
1532     isDirect = true;
1533     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1534     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1535                    getTargetMachine().getRelocationModel() != Reloc::Static;
1536     isARMFunc = !Subtarget->isThumb() || isStub;
1537     // ARM call to a local ARM function is predicable.
1538     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1539     // tBX takes a register source operand.
1540     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1541       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1542       ARMConstantPoolValue *CPV =
1543         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1544       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1545       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1546       Callee = DAG.getLoad(getPointerTy(), dl,
1547                            DAG.getEntryNode(), CPAddr,
1548                            MachinePointerInfo::getConstantPool(),
1549                            false, false, false, 0);
1550       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1551       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1552                            getPointerTy(), Callee, PICLabel);
1553     } else {
1554       // On ELF targets for PIC code, direct calls should go through the PLT
1555       unsigned OpFlags = 0;
1556       if (Subtarget->isTargetELF() &&
1557                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1558         OpFlags = ARMII::MO_PLT;
1559       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1560     }
1561   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1562     isDirect = true;
1563     bool isStub = Subtarget->isTargetDarwin() &&
1564                   getTargetMachine().getRelocationModel() != Reloc::Static;
1565     isARMFunc = !Subtarget->isThumb() || isStub;
1566     // tBX takes a register source operand.
1567     const char *Sym = S->getSymbol();
1568     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1569       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1570       ARMConstantPoolValue *CPV =
1571         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1572                                       ARMPCLabelIndex, 4);
1573       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1574       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1575       Callee = DAG.getLoad(getPointerTy(), dl,
1576                            DAG.getEntryNode(), CPAddr,
1577                            MachinePointerInfo::getConstantPool(),
1578                            false, false, false, 0);
1579       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1580       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1581                            getPointerTy(), Callee, PICLabel);
1582     } else {
1583       unsigned OpFlags = 0;
1584       // On ELF targets for PIC code, direct calls should go through the PLT
1585       if (Subtarget->isTargetELF() &&
1586                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1587         OpFlags = ARMII::MO_PLT;
1588       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1589     }
1590   }
1591
1592   // FIXME: handle tail calls differently.
1593   unsigned CallOpc;
1594   if (Subtarget->isThumb()) {
1595     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1596       CallOpc = ARMISD::CALL_NOLINK;
1597     else if (doesNotRet && isDirect && !isARMFunc &&
1598              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1599       // "mov lr, pc; b _foo" to avoid confusing the RSP
1600       CallOpc = ARMISD::CALL_NOLINK;
1601     else
1602       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1603   } else {
1604     if (!isDirect && !Subtarget->hasV5TOps()) {
1605       CallOpc = ARMISD::CALL_NOLINK;
1606     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1607       // "mov lr, pc; b _foo" to avoid confusing the RSP
1608       CallOpc = ARMISD::CALL_NOLINK;
1609     else
1610       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1611   }
1612
1613   std::vector<SDValue> Ops;
1614   Ops.push_back(Chain);
1615   Ops.push_back(Callee);
1616
1617   // Add argument registers to the end of the list so that they are known live
1618   // into the call.
1619   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1620     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1621                                   RegsToPass[i].second.getValueType()));
1622
1623   // Add a register mask operand representing the call-preserved registers.
1624   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1625   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1626   assert(Mask && "Missing call preserved mask for calling convention");
1627   Ops.push_back(DAG.getRegisterMask(Mask));
1628
1629   if (InFlag.getNode())
1630     Ops.push_back(InFlag);
1631
1632   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1633   if (isTailCall)
1634     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1635
1636   // Returns a chain and a flag for retval copy to use.
1637   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1638   InFlag = Chain.getValue(1);
1639
1640   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1641                              DAG.getIntPtrConstant(0, true), InFlag);
1642   if (!Ins.empty())
1643     InFlag = Chain.getValue(1);
1644
1645   // Handle result values, copying them out of physregs into vregs that we
1646   // return.
1647   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1648                          dl, DAG, InVals);
1649 }
1650
1651 /// HandleByVal - Every parameter *after* a byval parameter is passed
1652 /// on the stack.  Remember the next parameter register to allocate,
1653 /// and then confiscate the rest of the parameter registers to insure
1654 /// this.
1655 void
1656 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1657   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1658   assert((State->getCallOrPrologue() == Prologue ||
1659           State->getCallOrPrologue() == Call) &&
1660          "unhandled ParmContext");
1661   if ((!State->isFirstByValRegValid()) &&
1662       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1663     State->setFirstByValReg(reg);
1664     // At a call site, a byval parameter that is split between
1665     // registers and memory needs its size truncated here.  In a
1666     // function prologue, such byval parameters are reassembled in
1667     // memory, and are not truncated.
1668     if (State->getCallOrPrologue() == Call) {
1669       unsigned excess = 4 * (ARM::R4 - reg);
1670       assert(size >= excess && "expected larger existing stack allocation");
1671       size -= excess;
1672     }
1673   }
1674   // Confiscate any remaining parameter registers to preclude their
1675   // assignment to subsequent parameters.
1676   while (State->AllocateReg(GPRArgRegs, 4))
1677     ;
1678 }
1679
1680 /// MatchingStackOffset - Return true if the given stack call argument is
1681 /// already available in the same position (relatively) of the caller's
1682 /// incoming argument stack.
1683 static
1684 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1685                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1686                          const TargetInstrInfo *TII) {
1687   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1688   int FI = INT_MAX;
1689   if (Arg.getOpcode() == ISD::CopyFromReg) {
1690     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1691     if (!TargetRegisterInfo::isVirtualRegister(VR))
1692       return false;
1693     MachineInstr *Def = MRI->getVRegDef(VR);
1694     if (!Def)
1695       return false;
1696     if (!Flags.isByVal()) {
1697       if (!TII->isLoadFromStackSlot(Def, FI))
1698         return false;
1699     } else {
1700       return false;
1701     }
1702   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1703     if (Flags.isByVal())
1704       // ByVal argument is passed in as a pointer but it's now being
1705       // dereferenced. e.g.
1706       // define @foo(%struct.X* %A) {
1707       //   tail call @bar(%struct.X* byval %A)
1708       // }
1709       return false;
1710     SDValue Ptr = Ld->getBasePtr();
1711     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1712     if (!FINode)
1713       return false;
1714     FI = FINode->getIndex();
1715   } else
1716     return false;
1717
1718   assert(FI != INT_MAX);
1719   if (!MFI->isFixedObjectIndex(FI))
1720     return false;
1721   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1722 }
1723
1724 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1725 /// for tail call optimization. Targets which want to do tail call
1726 /// optimization should implement this function.
1727 bool
1728 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1729                                                      CallingConv::ID CalleeCC,
1730                                                      bool isVarArg,
1731                                                      bool isCalleeStructRet,
1732                                                      bool isCallerStructRet,
1733                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1734                                     const SmallVectorImpl<SDValue> &OutVals,
1735                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1736                                                      SelectionDAG& DAG) const {
1737   const Function *CallerF = DAG.getMachineFunction().getFunction();
1738   CallingConv::ID CallerCC = CallerF->getCallingConv();
1739   bool CCMatch = CallerCC == CalleeCC;
1740
1741   // Look for obvious safe cases to perform tail call optimization that do not
1742   // require ABI changes. This is what gcc calls sibcall.
1743
1744   // Do not sibcall optimize vararg calls unless the call site is not passing
1745   // any arguments.
1746   if (isVarArg && !Outs.empty())
1747     return false;
1748
1749   // Also avoid sibcall optimization if either caller or callee uses struct
1750   // return semantics.
1751   if (isCalleeStructRet || isCallerStructRet)
1752     return false;
1753
1754   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1755   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1756   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1757   // support in the assembler and linker to be used. This would need to be
1758   // fixed to fully support tail calls in Thumb1.
1759   //
1760   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1761   // LR.  This means if we need to reload LR, it takes an extra instructions,
1762   // which outweighs the value of the tail call; but here we don't know yet
1763   // whether LR is going to be used.  Probably the right approach is to
1764   // generate the tail call here and turn it back into CALL/RET in
1765   // emitEpilogue if LR is used.
1766
1767   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1768   // but we need to make sure there are enough registers; the only valid
1769   // registers are the 4 used for parameters.  We don't currently do this
1770   // case.
1771   if (Subtarget->isThumb1Only())
1772     return false;
1773
1774   // If the calling conventions do not match, then we'd better make sure the
1775   // results are returned in the same way as what the caller expects.
1776   if (!CCMatch) {
1777     SmallVector<CCValAssign, 16> RVLocs1;
1778     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1779                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1780     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1781
1782     SmallVector<CCValAssign, 16> RVLocs2;
1783     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1784                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1785     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1786
1787     if (RVLocs1.size() != RVLocs2.size())
1788       return false;
1789     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1790       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1791         return false;
1792       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1793         return false;
1794       if (RVLocs1[i].isRegLoc()) {
1795         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1796           return false;
1797       } else {
1798         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1799           return false;
1800       }
1801     }
1802   }
1803
1804   // If the callee takes no arguments then go on to check the results of the
1805   // call.
1806   if (!Outs.empty()) {
1807     // Check if stack adjustment is needed. For now, do not do this if any
1808     // argument is passed on the stack.
1809     SmallVector<CCValAssign, 16> ArgLocs;
1810     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1811                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1812     CCInfo.AnalyzeCallOperands(Outs,
1813                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1814     if (CCInfo.getNextStackOffset()) {
1815       MachineFunction &MF = DAG.getMachineFunction();
1816
1817       // Check if the arguments are already laid out in the right way as
1818       // the caller's fixed stack objects.
1819       MachineFrameInfo *MFI = MF.getFrameInfo();
1820       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1821       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1822       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1823            i != e;
1824            ++i, ++realArgIdx) {
1825         CCValAssign &VA = ArgLocs[i];
1826         EVT RegVT = VA.getLocVT();
1827         SDValue Arg = OutVals[realArgIdx];
1828         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1829         if (VA.getLocInfo() == CCValAssign::Indirect)
1830           return false;
1831         if (VA.needsCustom()) {
1832           // f64 and vector types are split into multiple registers or
1833           // register/stack-slot combinations.  The types will not match
1834           // the registers; give up on memory f64 refs until we figure
1835           // out what to do about this.
1836           if (!VA.isRegLoc())
1837             return false;
1838           if (!ArgLocs[++i].isRegLoc())
1839             return false;
1840           if (RegVT == MVT::v2f64) {
1841             if (!ArgLocs[++i].isRegLoc())
1842               return false;
1843             if (!ArgLocs[++i].isRegLoc())
1844               return false;
1845           }
1846         } else if (!VA.isRegLoc()) {
1847           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1848                                    MFI, MRI, TII))
1849             return false;
1850         }
1851       }
1852     }
1853   }
1854
1855   return true;
1856 }
1857
1858 SDValue
1859 ARMTargetLowering::LowerReturn(SDValue Chain,
1860                                CallingConv::ID CallConv, bool isVarArg,
1861                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1862                                const SmallVectorImpl<SDValue> &OutVals,
1863                                DebugLoc dl, SelectionDAG &DAG) const {
1864
1865   // CCValAssign - represent the assignment of the return value to a location.
1866   SmallVector<CCValAssign, 16> RVLocs;
1867
1868   // CCState - Info about the registers and stack slots.
1869   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1870                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1871
1872   // Analyze outgoing return values.
1873   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1874                                                isVarArg));
1875
1876   // If this is the first return lowered for this function, add
1877   // the regs to the liveout set for the function.
1878   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1879     for (unsigned i = 0; i != RVLocs.size(); ++i)
1880       if (RVLocs[i].isRegLoc())
1881         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1882   }
1883
1884   SDValue Flag;
1885
1886   // Copy the result values into the output registers.
1887   for (unsigned i = 0, realRVLocIdx = 0;
1888        i != RVLocs.size();
1889        ++i, ++realRVLocIdx) {
1890     CCValAssign &VA = RVLocs[i];
1891     assert(VA.isRegLoc() && "Can only return in registers!");
1892
1893     SDValue Arg = OutVals[realRVLocIdx];
1894
1895     switch (VA.getLocInfo()) {
1896     default: llvm_unreachable("Unknown loc info!");
1897     case CCValAssign::Full: break;
1898     case CCValAssign::BCvt:
1899       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1900       break;
1901     }
1902
1903     if (VA.needsCustom()) {
1904       if (VA.getLocVT() == MVT::v2f64) {
1905         // Extract the first half and return it in two registers.
1906         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1907                                    DAG.getConstant(0, MVT::i32));
1908         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1909                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1910
1911         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1912         Flag = Chain.getValue(1);
1913         VA = RVLocs[++i]; // skip ahead to next loc
1914         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1915                                  HalfGPRs.getValue(1), Flag);
1916         Flag = Chain.getValue(1);
1917         VA = RVLocs[++i]; // skip ahead to next loc
1918
1919         // Extract the 2nd half and fall through to handle it as an f64 value.
1920         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1921                           DAG.getConstant(1, MVT::i32));
1922       }
1923       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1924       // available.
1925       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1926                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1927       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1928       Flag = Chain.getValue(1);
1929       VA = RVLocs[++i]; // skip ahead to next loc
1930       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1931                                Flag);
1932     } else
1933       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1934
1935     // Guarantee that all emitted copies are
1936     // stuck together, avoiding something bad.
1937     Flag = Chain.getValue(1);
1938   }
1939
1940   SDValue result;
1941   if (Flag.getNode())
1942     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1943   else // Return Void
1944     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1945
1946   return result;
1947 }
1948
1949 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1950   if (N->getNumValues() != 1)
1951     return false;
1952   if (!N->hasNUsesOfValue(1, 0))
1953     return false;
1954
1955   SDValue TCChain = Chain;
1956   SDNode *Copy = *N->use_begin();
1957   if (Copy->getOpcode() == ISD::CopyToReg) {
1958     // If the copy has a glue operand, we conservatively assume it isn't safe to
1959     // perform a tail call.
1960     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1961       return false;
1962     TCChain = Copy->getOperand(0);
1963   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1964     SDNode *VMov = Copy;
1965     // f64 returned in a pair of GPRs.
1966     SmallPtrSet<SDNode*, 2> Copies;
1967     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1968          UI != UE; ++UI) {
1969       if (UI->getOpcode() != ISD::CopyToReg)
1970         return false;
1971       Copies.insert(*UI);
1972     }
1973     if (Copies.size() > 2)
1974       return false;
1975
1976     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1977          UI != UE; ++UI) {
1978       SDValue UseChain = UI->getOperand(0);
1979       if (Copies.count(UseChain.getNode()))
1980         // Second CopyToReg
1981         Copy = *UI;
1982       else
1983         // First CopyToReg
1984         TCChain = UseChain;
1985     }
1986   } else if (Copy->getOpcode() == ISD::BITCAST) {
1987     // f32 returned in a single GPR.
1988     if (!Copy->hasOneUse())
1989       return false;
1990     Copy = *Copy->use_begin();
1991     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1992       return false;
1993     Chain = Copy->getOperand(0);
1994   } else {
1995     return false;
1996   }
1997
1998   bool HasRet = false;
1999   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2000        UI != UE; ++UI) {
2001     if (UI->getOpcode() != ARMISD::RET_FLAG)
2002       return false;
2003     HasRet = true;
2004   }
2005
2006   if (!HasRet)
2007     return false;
2008
2009   Chain = TCChain;
2010   return true;
2011 }
2012
2013 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2014   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2015     return false;
2016
2017   if (!CI->isTailCall())
2018     return false;
2019
2020   return !Subtarget->isThumb1Only();
2021 }
2022
2023 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2024 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2025 // one of the above mentioned nodes. It has to be wrapped because otherwise
2026 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2027 // be used to form addressing mode. These wrapped nodes will be selected
2028 // into MOVi.
2029 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2030   EVT PtrVT = Op.getValueType();
2031   // FIXME there is no actual debug info here
2032   DebugLoc dl = Op.getDebugLoc();
2033   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2034   SDValue Res;
2035   if (CP->isMachineConstantPoolEntry())
2036     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2037                                     CP->getAlignment());
2038   else
2039     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2040                                     CP->getAlignment());
2041   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2042 }
2043
2044 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2045   return MachineJumpTableInfo::EK_Inline;
2046 }
2047
2048 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2049                                              SelectionDAG &DAG) const {
2050   MachineFunction &MF = DAG.getMachineFunction();
2051   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2052   unsigned ARMPCLabelIndex = 0;
2053   DebugLoc DL = Op.getDebugLoc();
2054   EVT PtrVT = getPointerTy();
2055   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2056   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2057   SDValue CPAddr;
2058   if (RelocM == Reloc::Static) {
2059     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2060   } else {
2061     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2062     ARMPCLabelIndex = AFI->createPICLabelUId();
2063     ARMConstantPoolValue *CPV =
2064       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2065                                       ARMCP::CPBlockAddress, PCAdj);
2066     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2067   }
2068   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2069   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2070                                MachinePointerInfo::getConstantPool(),
2071                                false, false, false, 0);
2072   if (RelocM == Reloc::Static)
2073     return Result;
2074   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2075   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2076 }
2077
2078 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2079 SDValue
2080 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2081                                                  SelectionDAG &DAG) const {
2082   DebugLoc dl = GA->getDebugLoc();
2083   EVT PtrVT = getPointerTy();
2084   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2085   MachineFunction &MF = DAG.getMachineFunction();
2086   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2087   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2088   ARMConstantPoolValue *CPV =
2089     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2090                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2091   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2092   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2093   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2094                          MachinePointerInfo::getConstantPool(),
2095                          false, false, false, 0);
2096   SDValue Chain = Argument.getValue(1);
2097
2098   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2099   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2100
2101   // call __tls_get_addr.
2102   ArgListTy Args;
2103   ArgListEntry Entry;
2104   Entry.Node = Argument;
2105   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2106   Args.push_back(Entry);
2107   // FIXME: is there useful debug info available here?
2108   TargetLowering::CallLoweringInfo CLI(Chain,
2109                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2110                 false, false, false, false,
2111                 0, CallingConv::C, /*isTailCall=*/false,
2112                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2113                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2114   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2115   return CallResult.first;
2116 }
2117
2118 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2119 // "local exec" model.
2120 SDValue
2121 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2122                                         SelectionDAG &DAG,
2123                                         TLSModel::Model model) const {
2124   const GlobalValue *GV = GA->getGlobal();
2125   DebugLoc dl = GA->getDebugLoc();
2126   SDValue Offset;
2127   SDValue Chain = DAG.getEntryNode();
2128   EVT PtrVT = getPointerTy();
2129   // Get the Thread Pointer
2130   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2131
2132   if (model == TLSModel::InitialExec) {
2133     MachineFunction &MF = DAG.getMachineFunction();
2134     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2135     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2136     // Initial exec model.
2137     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2138     ARMConstantPoolValue *CPV =
2139       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2140                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2141                                       true);
2142     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2143     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2144     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2145                          MachinePointerInfo::getConstantPool(),
2146                          false, false, false, 0);
2147     Chain = Offset.getValue(1);
2148
2149     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2150     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2151
2152     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2153                          MachinePointerInfo::getConstantPool(),
2154                          false, false, false, 0);
2155   } else {
2156     // local exec model
2157     assert(model == TLSModel::LocalExec);
2158     ARMConstantPoolValue *CPV =
2159       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2160     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2161     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2162     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2163                          MachinePointerInfo::getConstantPool(),
2164                          false, false, false, 0);
2165   }
2166
2167   // The address of the thread local variable is the add of the thread
2168   // pointer with the offset of the variable.
2169   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2170 }
2171
2172 SDValue
2173 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2174   // TODO: implement the "local dynamic" model
2175   assert(Subtarget->isTargetELF() &&
2176          "TLS not implemented for non-ELF targets");
2177   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2178
2179   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2180
2181   switch (model) {
2182     case TLSModel::GeneralDynamic:
2183     case TLSModel::LocalDynamic:
2184       return LowerToTLSGeneralDynamicModel(GA, DAG);
2185     case TLSModel::InitialExec:
2186     case TLSModel::LocalExec:
2187       return LowerToTLSExecModels(GA, DAG, model);
2188   }
2189   llvm_unreachable("bogus TLS model");
2190 }
2191
2192 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2193                                                  SelectionDAG &DAG) const {
2194   EVT PtrVT = getPointerTy();
2195   DebugLoc dl = Op.getDebugLoc();
2196   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2197   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2198   if (RelocM == Reloc::PIC_) {
2199     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2200     ARMConstantPoolValue *CPV =
2201       ARMConstantPoolConstant::Create(GV,
2202                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2203     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2204     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2205     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2206                                  CPAddr,
2207                                  MachinePointerInfo::getConstantPool(),
2208                                  false, false, false, 0);
2209     SDValue Chain = Result.getValue(1);
2210     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2211     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2212     if (!UseGOTOFF)
2213       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2214                            MachinePointerInfo::getGOT(),
2215                            false, false, false, 0);
2216     return Result;
2217   }
2218
2219   // If we have T2 ops, we can materialize the address directly via movt/movw
2220   // pair. This is always cheaper.
2221   if (Subtarget->useMovt()) {
2222     ++NumMovwMovt;
2223     // FIXME: Once remat is capable of dealing with instructions with register
2224     // operands, expand this into two nodes.
2225     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2226                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2227   } else {
2228     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2229     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2230     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2231                        MachinePointerInfo::getConstantPool(),
2232                        false, false, false, 0);
2233   }
2234 }
2235
2236 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2237                                                     SelectionDAG &DAG) const {
2238   EVT PtrVT = getPointerTy();
2239   DebugLoc dl = Op.getDebugLoc();
2240   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2241   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2242   MachineFunction &MF = DAG.getMachineFunction();
2243   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2244
2245   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2246   // update ARMFastISel::ARMMaterializeGV.
2247   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2248     ++NumMovwMovt;
2249     // FIXME: Once remat is capable of dealing with instructions with register
2250     // operands, expand this into two nodes.
2251     if (RelocM == Reloc::Static)
2252       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2253                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2254
2255     unsigned Wrapper = (RelocM == Reloc::PIC_)
2256       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2257     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2258                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2259     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2260       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2261                            MachinePointerInfo::getGOT(),
2262                            false, false, false, 0);
2263     return Result;
2264   }
2265
2266   unsigned ARMPCLabelIndex = 0;
2267   SDValue CPAddr;
2268   if (RelocM == Reloc::Static) {
2269     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2270   } else {
2271     ARMPCLabelIndex = AFI->createPICLabelUId();
2272     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2273     ARMConstantPoolValue *CPV =
2274       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2275                                       PCAdj);
2276     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2277   }
2278   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2279
2280   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2281                                MachinePointerInfo::getConstantPool(),
2282                                false, false, false, 0);
2283   SDValue Chain = Result.getValue(1);
2284
2285   if (RelocM == Reloc::PIC_) {
2286     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2287     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2288   }
2289
2290   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2291     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2292                          false, false, false, 0);
2293
2294   return Result;
2295 }
2296
2297 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2298                                                     SelectionDAG &DAG) const {
2299   assert(Subtarget->isTargetELF() &&
2300          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2301   MachineFunction &MF = DAG.getMachineFunction();
2302   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2303   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2304   EVT PtrVT = getPointerTy();
2305   DebugLoc dl = Op.getDebugLoc();
2306   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2307   ARMConstantPoolValue *CPV =
2308     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2309                                   ARMPCLabelIndex, PCAdj);
2310   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2311   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2312   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2313                                MachinePointerInfo::getConstantPool(),
2314                                false, false, false, 0);
2315   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2316   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2317 }
2318
2319 SDValue
2320 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2321   DebugLoc dl = Op.getDebugLoc();
2322   SDValue Val = DAG.getConstant(0, MVT::i32);
2323   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2324                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2325                      Op.getOperand(1), Val);
2326 }
2327
2328 SDValue
2329 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2330   DebugLoc dl = Op.getDebugLoc();
2331   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2332                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2333 }
2334
2335 SDValue
2336 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2337                                           const ARMSubtarget *Subtarget) const {
2338   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2339   DebugLoc dl = Op.getDebugLoc();
2340   switch (IntNo) {
2341   default: return SDValue();    // Don't custom lower most intrinsics.
2342   case Intrinsic::arm_thread_pointer: {
2343     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2344     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2345   }
2346   case Intrinsic::eh_sjlj_lsda: {
2347     MachineFunction &MF = DAG.getMachineFunction();
2348     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2349     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2350     EVT PtrVT = getPointerTy();
2351     DebugLoc dl = Op.getDebugLoc();
2352     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2353     SDValue CPAddr;
2354     unsigned PCAdj = (RelocM != Reloc::PIC_)
2355       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2356     ARMConstantPoolValue *CPV =
2357       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2358                                       ARMCP::CPLSDA, PCAdj);
2359     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2361     SDValue Result =
2362       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2363                   MachinePointerInfo::getConstantPool(),
2364                   false, false, false, 0);
2365
2366     if (RelocM == Reloc::PIC_) {
2367       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2368       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2369     }
2370     return Result;
2371   }
2372   case Intrinsic::arm_neon_vmulls:
2373   case Intrinsic::arm_neon_vmullu: {
2374     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2375       ? ARMISD::VMULLs : ARMISD::VMULLu;
2376     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2377                        Op.getOperand(1), Op.getOperand(2));
2378   }
2379   }
2380 }
2381
2382 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2383                                const ARMSubtarget *Subtarget) {
2384   DebugLoc dl = Op.getDebugLoc();
2385   if (!Subtarget->hasDataBarrier()) {
2386     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2387     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2388     // here.
2389     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2390            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2391     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2392                        DAG.getConstant(0, MVT::i32));
2393   }
2394
2395   SDValue Op5 = Op.getOperand(5);
2396   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2397   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2398   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2399   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2400
2401   ARM_MB::MemBOpt DMBOpt;
2402   if (isDeviceBarrier)
2403     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2404   else
2405     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2406   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2407                      DAG.getConstant(DMBOpt, MVT::i32));
2408 }
2409
2410
2411 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2412                                  const ARMSubtarget *Subtarget) {
2413   // FIXME: handle "fence singlethread" more efficiently.
2414   DebugLoc dl = Op.getDebugLoc();
2415   if (!Subtarget->hasDataBarrier()) {
2416     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2417     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2418     // here.
2419     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2420            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2421     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2422                        DAG.getConstant(0, MVT::i32));
2423   }
2424
2425   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2426                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2427 }
2428
2429 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2430                              const ARMSubtarget *Subtarget) {
2431   // ARM pre v5TE and Thumb1 does not have preload instructions.
2432   if (!(Subtarget->isThumb2() ||
2433         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2434     // Just preserve the chain.
2435     return Op.getOperand(0);
2436
2437   DebugLoc dl = Op.getDebugLoc();
2438   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2439   if (!isRead &&
2440       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2441     // ARMv7 with MP extension has PLDW.
2442     return Op.getOperand(0);
2443
2444   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2445   if (Subtarget->isThumb()) {
2446     // Invert the bits.
2447     isRead = ~isRead & 1;
2448     isData = ~isData & 1;
2449   }
2450
2451   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2452                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2453                      DAG.getConstant(isData, MVT::i32));
2454 }
2455
2456 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2457   MachineFunction &MF = DAG.getMachineFunction();
2458   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2459
2460   // vastart just stores the address of the VarArgsFrameIndex slot into the
2461   // memory location argument.
2462   DebugLoc dl = Op.getDebugLoc();
2463   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2464   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2465   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2466   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2467                       MachinePointerInfo(SV), false, false, 0);
2468 }
2469
2470 SDValue
2471 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2472                                         SDValue &Root, SelectionDAG &DAG,
2473                                         DebugLoc dl) const {
2474   MachineFunction &MF = DAG.getMachineFunction();
2475   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2476
2477   const TargetRegisterClass *RC;
2478   if (AFI->isThumb1OnlyFunction())
2479     RC = &ARM::tGPRRegClass;
2480   else
2481     RC = &ARM::GPRRegClass;
2482
2483   // Transform the arguments stored in physical registers into virtual ones.
2484   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2485   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2486
2487   SDValue ArgValue2;
2488   if (NextVA.isMemLoc()) {
2489     MachineFrameInfo *MFI = MF.getFrameInfo();
2490     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2491
2492     // Create load node to retrieve arguments from the stack.
2493     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2494     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2495                             MachinePointerInfo::getFixedStack(FI),
2496                             false, false, false, 0);
2497   } else {
2498     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2499     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2500   }
2501
2502   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2503 }
2504
2505 void
2506 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2507                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2508   const {
2509   unsigned NumGPRs;
2510   if (CCInfo.isFirstByValRegValid())
2511     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2512   else {
2513     unsigned int firstUnalloced;
2514     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2515                                                 sizeof(GPRArgRegs) /
2516                                                 sizeof(GPRArgRegs[0]));
2517     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2518   }
2519
2520   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2521   VARegSize = NumGPRs * 4;
2522   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2523 }
2524
2525 // The remaining GPRs hold either the beginning of variable-argument
2526 // data, or the beginning of an aggregate passed by value (usuall
2527 // byval).  Either way, we allocate stack slots adjacent to the data
2528 // provided by our caller, and store the unallocated registers there.
2529 // If this is a variadic function, the va_list pointer will begin with
2530 // these values; otherwise, this reassembles a (byval) structure that
2531 // was split between registers and memory.
2532 void
2533 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2534                                         DebugLoc dl, SDValue &Chain,
2535                                         unsigned ArgOffset) const {
2536   MachineFunction &MF = DAG.getMachineFunction();
2537   MachineFrameInfo *MFI = MF.getFrameInfo();
2538   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2539   unsigned firstRegToSaveIndex;
2540   if (CCInfo.isFirstByValRegValid())
2541     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2542   else {
2543     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2544       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2545   }
2546
2547   unsigned VARegSize, VARegSaveSize;
2548   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2549   if (VARegSaveSize) {
2550     // If this function is vararg, store any remaining integer argument regs
2551     // to their spots on the stack so that they may be loaded by deferencing
2552     // the result of va_next.
2553     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2554     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2555                                                      ArgOffset + VARegSaveSize
2556                                                      - VARegSize,
2557                                                      false));
2558     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2559                                     getPointerTy());
2560
2561     SmallVector<SDValue, 4> MemOps;
2562     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2563       const TargetRegisterClass *RC;
2564       if (AFI->isThumb1OnlyFunction())
2565         RC = &ARM::tGPRRegClass;
2566       else
2567         RC = &ARM::GPRRegClass;
2568
2569       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2570       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2571       SDValue Store =
2572         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2573                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2574                      false, false, 0);
2575       MemOps.push_back(Store);
2576       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2577                         DAG.getConstant(4, getPointerTy()));
2578     }
2579     if (!MemOps.empty())
2580       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2581                           &MemOps[0], MemOps.size());
2582   } else
2583     // This will point to the next argument passed via stack.
2584     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2585 }
2586
2587 SDValue
2588 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2589                                         CallingConv::ID CallConv, bool isVarArg,
2590                                         const SmallVectorImpl<ISD::InputArg>
2591                                           &Ins,
2592                                         DebugLoc dl, SelectionDAG &DAG,
2593                                         SmallVectorImpl<SDValue> &InVals)
2594                                           const {
2595   MachineFunction &MF = DAG.getMachineFunction();
2596   MachineFrameInfo *MFI = MF.getFrameInfo();
2597
2598   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2599
2600   // Assign locations to all of the incoming arguments.
2601   SmallVector<CCValAssign, 16> ArgLocs;
2602   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2603                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2604   CCInfo.AnalyzeFormalArguments(Ins,
2605                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2606                                                   isVarArg));
2607
2608   SmallVector<SDValue, 16> ArgValues;
2609   int lastInsIndex = -1;
2610
2611   SDValue ArgValue;
2612   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2613     CCValAssign &VA = ArgLocs[i];
2614
2615     // Arguments stored in registers.
2616     if (VA.isRegLoc()) {
2617       EVT RegVT = VA.getLocVT();
2618
2619       if (VA.needsCustom()) {
2620         // f64 and vector types are split up into multiple registers or
2621         // combinations of registers and stack slots.
2622         if (VA.getLocVT() == MVT::v2f64) {
2623           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2624                                                    Chain, DAG, dl);
2625           VA = ArgLocs[++i]; // skip ahead to next loc
2626           SDValue ArgValue2;
2627           if (VA.isMemLoc()) {
2628             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2629             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2630             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2631                                     MachinePointerInfo::getFixedStack(FI),
2632                                     false, false, false, 0);
2633           } else {
2634             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2635                                              Chain, DAG, dl);
2636           }
2637           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2638           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2639                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2640           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2641                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2642         } else
2643           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2644
2645       } else {
2646         const TargetRegisterClass *RC;
2647
2648         if (RegVT == MVT::f32)
2649           RC = &ARM::SPRRegClass;
2650         else if (RegVT == MVT::f64)
2651           RC = &ARM::DPRRegClass;
2652         else if (RegVT == MVT::v2f64)
2653           RC = &ARM::QPRRegClass;
2654         else if (RegVT == MVT::i32)
2655           RC = AFI->isThumb1OnlyFunction() ?
2656             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2657             (const TargetRegisterClass*)&ARM::GPRRegClass;
2658         else
2659           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2660
2661         // Transform the arguments in physical registers into virtual ones.
2662         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2663         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2664       }
2665
2666       // If this is an 8 or 16-bit value, it is really passed promoted
2667       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2668       // truncate to the right size.
2669       switch (VA.getLocInfo()) {
2670       default: llvm_unreachable("Unknown loc info!");
2671       case CCValAssign::Full: break;
2672       case CCValAssign::BCvt:
2673         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2674         break;
2675       case CCValAssign::SExt:
2676         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2677                                DAG.getValueType(VA.getValVT()));
2678         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2679         break;
2680       case CCValAssign::ZExt:
2681         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2682                                DAG.getValueType(VA.getValVT()));
2683         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2684         break;
2685       }
2686
2687       InVals.push_back(ArgValue);
2688
2689     } else { // VA.isRegLoc()
2690
2691       // sanity check
2692       assert(VA.isMemLoc());
2693       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2694
2695       int index = ArgLocs[i].getValNo();
2696
2697       // Some Ins[] entries become multiple ArgLoc[] entries.
2698       // Process them only once.
2699       if (index != lastInsIndex)
2700         {
2701           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2702           // FIXME: For now, all byval parameter objects are marked mutable.
2703           // This can be changed with more analysis.
2704           // In case of tail call optimization mark all arguments mutable.
2705           // Since they could be overwritten by lowering of arguments in case of
2706           // a tail call.
2707           if (Flags.isByVal()) {
2708             unsigned VARegSize, VARegSaveSize;
2709             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2710             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2711             unsigned Bytes = Flags.getByValSize() - VARegSize;
2712             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2713             int FI = MFI->CreateFixedObject(Bytes,
2714                                             VA.getLocMemOffset(), false);
2715             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2716           } else {
2717             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2718                                             VA.getLocMemOffset(), true);
2719
2720             // Create load nodes to retrieve arguments from the stack.
2721             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2722             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2723                                          MachinePointerInfo::getFixedStack(FI),
2724                                          false, false, false, 0));
2725           }
2726           lastInsIndex = index;
2727         }
2728     }
2729   }
2730
2731   // varargs
2732   if (isVarArg)
2733     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2734
2735   return Chain;
2736 }
2737
2738 /// isFloatingPointZero - Return true if this is +0.0.
2739 static bool isFloatingPointZero(SDValue Op) {
2740   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2741     return CFP->getValueAPF().isPosZero();
2742   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2743     // Maybe this has already been legalized into the constant pool?
2744     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2745       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2746       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2747         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2748           return CFP->getValueAPF().isPosZero();
2749     }
2750   }
2751   return false;
2752 }
2753
2754 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2755 /// the given operands.
2756 SDValue
2757 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2758                              SDValue &ARMcc, SelectionDAG &DAG,
2759                              DebugLoc dl) const {
2760   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2761     unsigned C = RHSC->getZExtValue();
2762     if (!isLegalICmpImmediate(C)) {
2763       // Constant does not fit, try adjusting it by one?
2764       switch (CC) {
2765       default: break;
2766       case ISD::SETLT:
2767       case ISD::SETGE:
2768         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2769           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2770           RHS = DAG.getConstant(C-1, MVT::i32);
2771         }
2772         break;
2773       case ISD::SETULT:
2774       case ISD::SETUGE:
2775         if (C != 0 && isLegalICmpImmediate(C-1)) {
2776           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2777           RHS = DAG.getConstant(C-1, MVT::i32);
2778         }
2779         break;
2780       case ISD::SETLE:
2781       case ISD::SETGT:
2782         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2783           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2784           RHS = DAG.getConstant(C+1, MVT::i32);
2785         }
2786         break;
2787       case ISD::SETULE:
2788       case ISD::SETUGT:
2789         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2790           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2791           RHS = DAG.getConstant(C+1, MVT::i32);
2792         }
2793         break;
2794       }
2795     }
2796   }
2797
2798   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2799   ARMISD::NodeType CompareType;
2800   switch (CondCode) {
2801   default:
2802     CompareType = ARMISD::CMP;
2803     break;
2804   case ARMCC::EQ:
2805   case ARMCC::NE:
2806     // Uses only Z Flag
2807     CompareType = ARMISD::CMPZ;
2808     break;
2809   }
2810   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2811   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2812 }
2813
2814 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2815 SDValue
2816 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2817                              DebugLoc dl) const {
2818   SDValue Cmp;
2819   if (!isFloatingPointZero(RHS))
2820     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2821   else
2822     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2823   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2824 }
2825
2826 /// duplicateCmp - Glue values can have only one use, so this function
2827 /// duplicates a comparison node.
2828 SDValue
2829 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2830   unsigned Opc = Cmp.getOpcode();
2831   DebugLoc DL = Cmp.getDebugLoc();
2832   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2833     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2834
2835   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2836   Cmp = Cmp.getOperand(0);
2837   Opc = Cmp.getOpcode();
2838   if (Opc == ARMISD::CMPFP)
2839     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2840   else {
2841     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2842     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2843   }
2844   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2845 }
2846
2847 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2848   SDValue Cond = Op.getOperand(0);
2849   SDValue SelectTrue = Op.getOperand(1);
2850   SDValue SelectFalse = Op.getOperand(2);
2851   DebugLoc dl = Op.getDebugLoc();
2852
2853   // Convert:
2854   //
2855   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2856   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2857   //
2858   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2859     const ConstantSDNode *CMOVTrue =
2860       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2861     const ConstantSDNode *CMOVFalse =
2862       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2863
2864     if (CMOVTrue && CMOVFalse) {
2865       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2866       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2867
2868       SDValue True;
2869       SDValue False;
2870       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2871         True = SelectTrue;
2872         False = SelectFalse;
2873       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2874         True = SelectFalse;
2875         False = SelectTrue;
2876       }
2877
2878       if (True.getNode() && False.getNode()) {
2879         EVT VT = Op.getValueType();
2880         SDValue ARMcc = Cond.getOperand(2);
2881         SDValue CCR = Cond.getOperand(3);
2882         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2883         assert(True.getValueType() == VT);
2884         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2885       }
2886     }
2887   }
2888
2889   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2890   // undefined bits before doing a full-word comparison with zero.
2891   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2892                      DAG.getConstant(1, Cond.getValueType()));
2893
2894   return DAG.getSelectCC(dl, Cond,
2895                          DAG.getConstant(0, Cond.getValueType()),
2896                          SelectTrue, SelectFalse, ISD::SETNE);
2897 }
2898
2899 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2900   EVT VT = Op.getValueType();
2901   SDValue LHS = Op.getOperand(0);
2902   SDValue RHS = Op.getOperand(1);
2903   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2904   SDValue TrueVal = Op.getOperand(2);
2905   SDValue FalseVal = Op.getOperand(3);
2906   DebugLoc dl = Op.getDebugLoc();
2907
2908   if (LHS.getValueType() == MVT::i32) {
2909     SDValue ARMcc;
2910     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2911     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2912     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2913   }
2914
2915   ARMCC::CondCodes CondCode, CondCode2;
2916   FPCCToARMCC(CC, CondCode, CondCode2);
2917
2918   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2919   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2920   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2921   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2922                                ARMcc, CCR, Cmp);
2923   if (CondCode2 != ARMCC::AL) {
2924     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2925     // FIXME: Needs another CMP because flag can have but one use.
2926     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2927     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2928                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2929   }
2930   return Result;
2931 }
2932
2933 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2934 /// to morph to an integer compare sequence.
2935 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2936                            const ARMSubtarget *Subtarget) {
2937   SDNode *N = Op.getNode();
2938   if (!N->hasOneUse())
2939     // Otherwise it requires moving the value from fp to integer registers.
2940     return false;
2941   if (!N->getNumValues())
2942     return false;
2943   EVT VT = Op.getValueType();
2944   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2945     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2946     // vmrs are very slow, e.g. cortex-a8.
2947     return false;
2948
2949   if (isFloatingPointZero(Op)) {
2950     SeenZero = true;
2951     return true;
2952   }
2953   return ISD::isNormalLoad(N);
2954 }
2955
2956 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2957   if (isFloatingPointZero(Op))
2958     return DAG.getConstant(0, MVT::i32);
2959
2960   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2961     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2962                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2963                        Ld->isVolatile(), Ld->isNonTemporal(),
2964                        Ld->isInvariant(), Ld->getAlignment());
2965
2966   llvm_unreachable("Unknown VFP cmp argument!");
2967 }
2968
2969 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2970                            SDValue &RetVal1, SDValue &RetVal2) {
2971   if (isFloatingPointZero(Op)) {
2972     RetVal1 = DAG.getConstant(0, MVT::i32);
2973     RetVal2 = DAG.getConstant(0, MVT::i32);
2974     return;
2975   }
2976
2977   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2978     SDValue Ptr = Ld->getBasePtr();
2979     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2980                           Ld->getChain(), Ptr,
2981                           Ld->getPointerInfo(),
2982                           Ld->isVolatile(), Ld->isNonTemporal(),
2983                           Ld->isInvariant(), Ld->getAlignment());
2984
2985     EVT PtrType = Ptr.getValueType();
2986     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2987     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2988                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2989     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2990                           Ld->getChain(), NewPtr,
2991                           Ld->getPointerInfo().getWithOffset(4),
2992                           Ld->isVolatile(), Ld->isNonTemporal(),
2993                           Ld->isInvariant(), NewAlign);
2994     return;
2995   }
2996
2997   llvm_unreachable("Unknown VFP cmp argument!");
2998 }
2999
3000 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3001 /// f32 and even f64 comparisons to integer ones.
3002 SDValue
3003 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3004   SDValue Chain = Op.getOperand(0);
3005   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3006   SDValue LHS = Op.getOperand(2);
3007   SDValue RHS = Op.getOperand(3);
3008   SDValue Dest = Op.getOperand(4);
3009   DebugLoc dl = Op.getDebugLoc();
3010
3011   bool LHSSeenZero = false;
3012   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3013   bool RHSSeenZero = false;
3014   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3015   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3016     // If unsafe fp math optimization is enabled and there are no other uses of
3017     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3018     // to an integer comparison.
3019     if (CC == ISD::SETOEQ)
3020       CC = ISD::SETEQ;
3021     else if (CC == ISD::SETUNE)
3022       CC = ISD::SETNE;
3023
3024     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3025     SDValue ARMcc;
3026     if (LHS.getValueType() == MVT::f32) {
3027       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3028                         bitcastf32Toi32(LHS, DAG), Mask);
3029       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3030                         bitcastf32Toi32(RHS, DAG), Mask);
3031       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3032       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3033       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3034                          Chain, Dest, ARMcc, CCR, Cmp);
3035     }
3036
3037     SDValue LHS1, LHS2;
3038     SDValue RHS1, RHS2;
3039     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3040     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3041     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3042     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3043     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3044     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3045     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3046     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3047     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3048   }
3049
3050   return SDValue();
3051 }
3052
3053 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3054   SDValue Chain = Op.getOperand(0);
3055   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3056   SDValue LHS = Op.getOperand(2);
3057   SDValue RHS = Op.getOperand(3);
3058   SDValue Dest = Op.getOperand(4);
3059   DebugLoc dl = Op.getDebugLoc();
3060
3061   if (LHS.getValueType() == MVT::i32) {
3062     SDValue ARMcc;
3063     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3064     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3065     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3066                        Chain, Dest, ARMcc, CCR, Cmp);
3067   }
3068
3069   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3070
3071   if (getTargetMachine().Options.UnsafeFPMath &&
3072       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3073        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3074     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3075     if (Result.getNode())
3076       return Result;
3077   }
3078
3079   ARMCC::CondCodes CondCode, CondCode2;
3080   FPCCToARMCC(CC, CondCode, CondCode2);
3081
3082   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3083   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3084   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3085   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3086   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3087   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3088   if (CondCode2 != ARMCC::AL) {
3089     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3090     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3091     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3092   }
3093   return Res;
3094 }
3095
3096 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3097   SDValue Chain = Op.getOperand(0);
3098   SDValue Table = Op.getOperand(1);
3099   SDValue Index = Op.getOperand(2);
3100   DebugLoc dl = Op.getDebugLoc();
3101
3102   EVT PTy = getPointerTy();
3103   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3104   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3105   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3106   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3107   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3108   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3109   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3110   if (Subtarget->isThumb2()) {
3111     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3112     // which does another jump to the destination. This also makes it easier
3113     // to translate it to TBB / TBH later.
3114     // FIXME: This might not work if the function is extremely large.
3115     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3116                        Addr, Op.getOperand(2), JTI, UId);
3117   }
3118   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3119     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3120                        MachinePointerInfo::getJumpTable(),
3121                        false, false, false, 0);
3122     Chain = Addr.getValue(1);
3123     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3124     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3125   } else {
3126     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3127                        MachinePointerInfo::getJumpTable(),
3128                        false, false, false, 0);
3129     Chain = Addr.getValue(1);
3130     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3131   }
3132 }
3133
3134 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3135   EVT VT = Op.getValueType();
3136   DebugLoc dl = Op.getDebugLoc();
3137
3138   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3139     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3140       return Op;
3141     return DAG.UnrollVectorOp(Op.getNode());
3142   }
3143
3144   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3145          "Invalid type for custom lowering!");
3146   if (VT != MVT::v4i16)
3147     return DAG.UnrollVectorOp(Op.getNode());
3148
3149   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3150   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3151 }
3152
3153 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3154   EVT VT = Op.getValueType();
3155   if (VT.isVector())
3156     return LowerVectorFP_TO_INT(Op, DAG);
3157
3158   DebugLoc dl = Op.getDebugLoc();
3159   unsigned Opc;
3160
3161   switch (Op.getOpcode()) {
3162   default: llvm_unreachable("Invalid opcode!");
3163   case ISD::FP_TO_SINT:
3164     Opc = ARMISD::FTOSI;
3165     break;
3166   case ISD::FP_TO_UINT:
3167     Opc = ARMISD::FTOUI;
3168     break;
3169   }
3170   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3171   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3172 }
3173
3174 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3175   EVT VT = Op.getValueType();
3176   DebugLoc dl = Op.getDebugLoc();
3177
3178   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3179     if (VT.getVectorElementType() == MVT::f32)
3180       return Op;
3181     return DAG.UnrollVectorOp(Op.getNode());
3182   }
3183
3184   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3185          "Invalid type for custom lowering!");
3186   if (VT != MVT::v4f32)
3187     return DAG.UnrollVectorOp(Op.getNode());
3188
3189   unsigned CastOpc;
3190   unsigned Opc;
3191   switch (Op.getOpcode()) {
3192   default: llvm_unreachable("Invalid opcode!");
3193   case ISD::SINT_TO_FP:
3194     CastOpc = ISD::SIGN_EXTEND;
3195     Opc = ISD::SINT_TO_FP;
3196     break;
3197   case ISD::UINT_TO_FP:
3198     CastOpc = ISD::ZERO_EXTEND;
3199     Opc = ISD::UINT_TO_FP;
3200     break;
3201   }
3202
3203   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3204   return DAG.getNode(Opc, dl, VT, Op);
3205 }
3206
3207 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3208   EVT VT = Op.getValueType();
3209   if (VT.isVector())
3210     return LowerVectorINT_TO_FP(Op, DAG);
3211
3212   DebugLoc dl = Op.getDebugLoc();
3213   unsigned Opc;
3214
3215   switch (Op.getOpcode()) {
3216   default: llvm_unreachable("Invalid opcode!");
3217   case ISD::SINT_TO_FP:
3218     Opc = ARMISD::SITOF;
3219     break;
3220   case ISD::UINT_TO_FP:
3221     Opc = ARMISD::UITOF;
3222     break;
3223   }
3224
3225   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3226   return DAG.getNode(Opc, dl, VT, Op);
3227 }
3228
3229 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3230   // Implement fcopysign with a fabs and a conditional fneg.
3231   SDValue Tmp0 = Op.getOperand(0);
3232   SDValue Tmp1 = Op.getOperand(1);
3233   DebugLoc dl = Op.getDebugLoc();
3234   EVT VT = Op.getValueType();
3235   EVT SrcVT = Tmp1.getValueType();
3236   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3237     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3238   bool UseNEON = !InGPR && Subtarget->hasNEON();
3239
3240   if (UseNEON) {
3241     // Use VBSL to copy the sign bit.
3242     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3243     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3244                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3245     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3246     if (VT == MVT::f64)
3247       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3248                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3249                          DAG.getConstant(32, MVT::i32));
3250     else /*if (VT == MVT::f32)*/
3251       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3252     if (SrcVT == MVT::f32) {
3253       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3254       if (VT == MVT::f64)
3255         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3256                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3257                            DAG.getConstant(32, MVT::i32));
3258     } else if (VT == MVT::f32)
3259       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3260                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3261                          DAG.getConstant(32, MVT::i32));
3262     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3263     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3264
3265     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3266                                             MVT::i32);
3267     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3268     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3269                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3270
3271     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3272                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3273                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3274     if (VT == MVT::f32) {
3275       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3276       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3277                         DAG.getConstant(0, MVT::i32));
3278     } else {
3279       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3280     }
3281
3282     return Res;
3283   }
3284
3285   // Bitcast operand 1 to i32.
3286   if (SrcVT == MVT::f64)
3287     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3288                        &Tmp1, 1).getValue(1);
3289   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3290
3291   // Or in the signbit with integer operations.
3292   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3293   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3294   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3295   if (VT == MVT::f32) {
3296     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3297                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3298     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3299                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3300   }
3301
3302   // f64: Or the high part with signbit and then combine two parts.
3303   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3304                      &Tmp0, 1);
3305   SDValue Lo = Tmp0.getValue(0);
3306   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3307   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3308   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3309 }
3310
3311 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3312   MachineFunction &MF = DAG.getMachineFunction();
3313   MachineFrameInfo *MFI = MF.getFrameInfo();
3314   MFI->setReturnAddressIsTaken(true);
3315
3316   EVT VT = Op.getValueType();
3317   DebugLoc dl = Op.getDebugLoc();
3318   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3319   if (Depth) {
3320     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3321     SDValue Offset = DAG.getConstant(4, MVT::i32);
3322     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3323                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3324                        MachinePointerInfo(), false, false, false, 0);
3325   }
3326
3327   // Return LR, which contains the return address. Mark it an implicit live-in.
3328   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3329   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3330 }
3331
3332 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3333   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3334   MFI->setFrameAddressIsTaken(true);
3335
3336   EVT VT = Op.getValueType();
3337   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3338   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3339   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3340     ? ARM::R7 : ARM::R11;
3341   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3342   while (Depth--)
3343     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3344                             MachinePointerInfo(),
3345                             false, false, false, 0);
3346   return FrameAddr;
3347 }
3348
3349 /// ExpandBITCAST - If the target supports VFP, this function is called to
3350 /// expand a bit convert where either the source or destination type is i64 to
3351 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3352 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3353 /// vectors), since the legalizer won't know what to do with that.
3354 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3356   DebugLoc dl = N->getDebugLoc();
3357   SDValue Op = N->getOperand(0);
3358
3359   // This function is only supposed to be called for i64 types, either as the
3360   // source or destination of the bit convert.
3361   EVT SrcVT = Op.getValueType();
3362   EVT DstVT = N->getValueType(0);
3363   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3364          "ExpandBITCAST called for non-i64 type");
3365
3366   // Turn i64->f64 into VMOVDRR.
3367   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3368     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3369                              DAG.getConstant(0, MVT::i32));
3370     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3371                              DAG.getConstant(1, MVT::i32));
3372     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3373                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3374   }
3375
3376   // Turn f64->i64 into VMOVRRD.
3377   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3378     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3379                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3380     // Merge the pieces into a single i64 value.
3381     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3382   }
3383
3384   return SDValue();
3385 }
3386
3387 /// getZeroVector - Returns a vector of specified type with all zero elements.
3388 /// Zero vectors are used to represent vector negation and in those cases
3389 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3390 /// not support i64 elements, so sometimes the zero vectors will need to be
3391 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3392 /// zero vector.
3393 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3394   assert(VT.isVector() && "Expected a vector type");
3395   // The canonical modified immediate encoding of a zero vector is....0!
3396   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3397   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3398   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3399   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3400 }
3401
3402 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3403 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3404 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3405                                                 SelectionDAG &DAG) const {
3406   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3407   EVT VT = Op.getValueType();
3408   unsigned VTBits = VT.getSizeInBits();
3409   DebugLoc dl = Op.getDebugLoc();
3410   SDValue ShOpLo = Op.getOperand(0);
3411   SDValue ShOpHi = Op.getOperand(1);
3412   SDValue ShAmt  = Op.getOperand(2);
3413   SDValue ARMcc;
3414   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3415
3416   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3417
3418   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3419                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3420   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3421   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3422                                    DAG.getConstant(VTBits, MVT::i32));
3423   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3424   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3425   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3426
3427   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3428   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3429                           ARMcc, DAG, dl);
3430   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3431   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3432                            CCR, Cmp);
3433
3434   SDValue Ops[2] = { Lo, Hi };
3435   return DAG.getMergeValues(Ops, 2, dl);
3436 }
3437
3438 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3439 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3440 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3441                                                SelectionDAG &DAG) const {
3442   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3443   EVT VT = Op.getValueType();
3444   unsigned VTBits = VT.getSizeInBits();
3445   DebugLoc dl = Op.getDebugLoc();
3446   SDValue ShOpLo = Op.getOperand(0);
3447   SDValue ShOpHi = Op.getOperand(1);
3448   SDValue ShAmt  = Op.getOperand(2);
3449   SDValue ARMcc;
3450
3451   assert(Op.getOpcode() == ISD::SHL_PARTS);
3452   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3453                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3454   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3455   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3456                                    DAG.getConstant(VTBits, MVT::i32));
3457   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3458   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3459
3460   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3461   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3462   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3463                           ARMcc, DAG, dl);
3464   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3465   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3466                            CCR, Cmp);
3467
3468   SDValue Ops[2] = { Lo, Hi };
3469   return DAG.getMergeValues(Ops, 2, dl);
3470 }
3471
3472 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3473                                             SelectionDAG &DAG) const {
3474   // The rounding mode is in bits 23:22 of the FPSCR.
3475   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3476   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3477   // so that the shift + and get folded into a bitfield extract.
3478   DebugLoc dl = Op.getDebugLoc();
3479   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3480                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3481                                               MVT::i32));
3482   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3483                                   DAG.getConstant(1U << 22, MVT::i32));
3484   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3485                               DAG.getConstant(22, MVT::i32));
3486   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3487                      DAG.getConstant(3, MVT::i32));
3488 }
3489
3490 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3491                          const ARMSubtarget *ST) {
3492   EVT VT = N->getValueType(0);
3493   DebugLoc dl = N->getDebugLoc();
3494
3495   if (!ST->hasV6T2Ops())
3496     return SDValue();
3497
3498   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3499   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3500 }
3501
3502 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3503                           const ARMSubtarget *ST) {
3504   EVT VT = N->getValueType(0);
3505   DebugLoc dl = N->getDebugLoc();
3506
3507   if (!VT.isVector())
3508     return SDValue();
3509
3510   // Lower vector shifts on NEON to use VSHL.
3511   assert(ST->hasNEON() && "unexpected vector shift");
3512
3513   // Left shifts translate directly to the vshiftu intrinsic.
3514   if (N->getOpcode() == ISD::SHL)
3515     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3516                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3517                        N->getOperand(0), N->getOperand(1));
3518
3519   assert((N->getOpcode() == ISD::SRA ||
3520           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3521
3522   // NEON uses the same intrinsics for both left and right shifts.  For
3523   // right shifts, the shift amounts are negative, so negate the vector of
3524   // shift amounts.
3525   EVT ShiftVT = N->getOperand(1).getValueType();
3526   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3527                                      getZeroVector(ShiftVT, DAG, dl),
3528                                      N->getOperand(1));
3529   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3530                              Intrinsic::arm_neon_vshifts :
3531                              Intrinsic::arm_neon_vshiftu);
3532   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3533                      DAG.getConstant(vshiftInt, MVT::i32),
3534                      N->getOperand(0), NegatedCount);
3535 }
3536
3537 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3538                                 const ARMSubtarget *ST) {
3539   EVT VT = N->getValueType(0);
3540   DebugLoc dl = N->getDebugLoc();
3541
3542   // We can get here for a node like i32 = ISD::SHL i32, i64
3543   if (VT != MVT::i64)
3544     return SDValue();
3545
3546   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3547          "Unknown shift to lower!");
3548
3549   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3550   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3551       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3552     return SDValue();
3553
3554   // If we are in thumb mode, we don't have RRX.
3555   if (ST->isThumb1Only()) return SDValue();
3556
3557   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3558   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3559                            DAG.getConstant(0, MVT::i32));
3560   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3561                            DAG.getConstant(1, MVT::i32));
3562
3563   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3564   // captures the result into a carry flag.
3565   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3566   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3567
3568   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3569   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3570
3571   // Merge the pieces into a single i64 value.
3572  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3573 }
3574
3575 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3576   SDValue TmpOp0, TmpOp1;
3577   bool Invert = false;
3578   bool Swap = false;
3579   unsigned Opc = 0;
3580
3581   SDValue Op0 = Op.getOperand(0);
3582   SDValue Op1 = Op.getOperand(1);
3583   SDValue CC = Op.getOperand(2);
3584   EVT VT = Op.getValueType();
3585   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3586   DebugLoc dl = Op.getDebugLoc();
3587
3588   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3589     switch (SetCCOpcode) {
3590     default: llvm_unreachable("Illegal FP comparison");
3591     case ISD::SETUNE:
3592     case ISD::SETNE:  Invert = true; // Fallthrough
3593     case ISD::SETOEQ:
3594     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3595     case ISD::SETOLT:
3596     case ISD::SETLT: Swap = true; // Fallthrough
3597     case ISD::SETOGT:
3598     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3599     case ISD::SETOLE:
3600     case ISD::SETLE:  Swap = true; // Fallthrough
3601     case ISD::SETOGE:
3602     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3603     case ISD::SETUGE: Swap = true; // Fallthrough
3604     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3605     case ISD::SETUGT: Swap = true; // Fallthrough
3606     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3607     case ISD::SETUEQ: Invert = true; // Fallthrough
3608     case ISD::SETONE:
3609       // Expand this to (OLT | OGT).
3610       TmpOp0 = Op0;
3611       TmpOp1 = Op1;
3612       Opc = ISD::OR;
3613       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3614       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3615       break;
3616     case ISD::SETUO: Invert = true; // Fallthrough
3617     case ISD::SETO:
3618       // Expand this to (OLT | OGE).
3619       TmpOp0 = Op0;
3620       TmpOp1 = Op1;
3621       Opc = ISD::OR;
3622       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3623       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3624       break;
3625     }
3626   } else {
3627     // Integer comparisons.
3628     switch (SetCCOpcode) {
3629     default: llvm_unreachable("Illegal integer comparison");
3630     case ISD::SETNE:  Invert = true;
3631     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3632     case ISD::SETLT:  Swap = true;
3633     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3634     case ISD::SETLE:  Swap = true;
3635     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3636     case ISD::SETULT: Swap = true;
3637     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3638     case ISD::SETULE: Swap = true;
3639     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3640     }
3641
3642     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3643     if (Opc == ARMISD::VCEQ) {
3644
3645       SDValue AndOp;
3646       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3647         AndOp = Op0;
3648       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3649         AndOp = Op1;
3650
3651       // Ignore bitconvert.
3652       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3653         AndOp = AndOp.getOperand(0);
3654
3655       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3656         Opc = ARMISD::VTST;
3657         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3658         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3659         Invert = !Invert;
3660       }
3661     }
3662   }
3663
3664   if (Swap)
3665     std::swap(Op0, Op1);
3666
3667   // If one of the operands is a constant vector zero, attempt to fold the
3668   // comparison to a specialized compare-against-zero form.
3669   SDValue SingleOp;
3670   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3671     SingleOp = Op0;
3672   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3673     if (Opc == ARMISD::VCGE)
3674       Opc = ARMISD::VCLEZ;
3675     else if (Opc == ARMISD::VCGT)
3676       Opc = ARMISD::VCLTZ;
3677     SingleOp = Op1;
3678   }
3679
3680   SDValue Result;
3681   if (SingleOp.getNode()) {
3682     switch (Opc) {
3683     case ARMISD::VCEQ:
3684       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3685     case ARMISD::VCGE:
3686       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3687     case ARMISD::VCLEZ:
3688       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3689     case ARMISD::VCGT:
3690       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3691     case ARMISD::VCLTZ:
3692       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3693     default:
3694       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3695     }
3696   } else {
3697      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3698   }
3699
3700   if (Invert)
3701     Result = DAG.getNOT(dl, Result, VT);
3702
3703   return Result;
3704 }
3705
3706 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3707 /// valid vector constant for a NEON instruction with a "modified immediate"
3708 /// operand (e.g., VMOV).  If so, return the encoded value.
3709 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3710                                  unsigned SplatBitSize, SelectionDAG &DAG,
3711                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3712   unsigned OpCmode, Imm;
3713
3714   // SplatBitSize is set to the smallest size that splats the vector, so a
3715   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3716   // immediate instructions others than VMOV do not support the 8-bit encoding
3717   // of a zero vector, and the default encoding of zero is supposed to be the
3718   // 32-bit version.
3719   if (SplatBits == 0)
3720     SplatBitSize = 32;
3721
3722   switch (SplatBitSize) {
3723   case 8:
3724     if (type != VMOVModImm)
3725       return SDValue();
3726     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3727     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3728     OpCmode = 0xe;
3729     Imm = SplatBits;
3730     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3731     break;
3732
3733   case 16:
3734     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3735     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3736     if ((SplatBits & ~0xff) == 0) {
3737       // Value = 0x00nn: Op=x, Cmode=100x.
3738       OpCmode = 0x8;
3739       Imm = SplatBits;
3740       break;
3741     }
3742     if ((SplatBits & ~0xff00) == 0) {
3743       // Value = 0xnn00: Op=x, Cmode=101x.
3744       OpCmode = 0xa;
3745       Imm = SplatBits >> 8;
3746       break;
3747     }
3748     return SDValue();
3749
3750   case 32:
3751     // NEON's 32-bit VMOV supports splat values where:
3752     // * only one byte is nonzero, or
3753     // * the least significant byte is 0xff and the second byte is nonzero, or
3754     // * the least significant 2 bytes are 0xff and the third is nonzero.
3755     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3756     if ((SplatBits & ~0xff) == 0) {
3757       // Value = 0x000000nn: Op=x, Cmode=000x.
3758       OpCmode = 0;
3759       Imm = SplatBits;
3760       break;
3761     }
3762     if ((SplatBits & ~0xff00) == 0) {
3763       // Value = 0x0000nn00: Op=x, Cmode=001x.
3764       OpCmode = 0x2;
3765       Imm = SplatBits >> 8;
3766       break;
3767     }
3768     if ((SplatBits & ~0xff0000) == 0) {
3769       // Value = 0x00nn0000: Op=x, Cmode=010x.
3770       OpCmode = 0x4;
3771       Imm = SplatBits >> 16;
3772       break;
3773     }
3774     if ((SplatBits & ~0xff000000) == 0) {
3775       // Value = 0xnn000000: Op=x, Cmode=011x.
3776       OpCmode = 0x6;
3777       Imm = SplatBits >> 24;
3778       break;
3779     }
3780
3781     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3782     if (type == OtherModImm) return SDValue();
3783
3784     if ((SplatBits & ~0xffff) == 0 &&
3785         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3786       // Value = 0x0000nnff: Op=x, Cmode=1100.
3787       OpCmode = 0xc;
3788       Imm = SplatBits >> 8;
3789       SplatBits |= 0xff;
3790       break;
3791     }
3792
3793     if ((SplatBits & ~0xffffff) == 0 &&
3794         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3795       // Value = 0x00nnffff: Op=x, Cmode=1101.
3796       OpCmode = 0xd;
3797       Imm = SplatBits >> 16;
3798       SplatBits |= 0xffff;
3799       break;
3800     }
3801
3802     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3803     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3804     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3805     // and fall through here to test for a valid 64-bit splat.  But, then the
3806     // caller would also need to check and handle the change in size.
3807     return SDValue();
3808
3809   case 64: {
3810     if (type != VMOVModImm)
3811       return SDValue();
3812     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3813     uint64_t BitMask = 0xff;
3814     uint64_t Val = 0;
3815     unsigned ImmMask = 1;
3816     Imm = 0;
3817     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3818       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3819         Val |= BitMask;
3820         Imm |= ImmMask;
3821       } else if ((SplatBits & BitMask) != 0) {
3822         return SDValue();
3823       }
3824       BitMask <<= 8;
3825       ImmMask <<= 1;
3826     }
3827     // Op=1, Cmode=1110.
3828     OpCmode = 0x1e;
3829     SplatBits = Val;
3830     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3831     break;
3832   }
3833
3834   default:
3835     llvm_unreachable("unexpected size for isNEONModifiedImm");
3836   }
3837
3838   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3839   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3840 }
3841
3842 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3843                                            const ARMSubtarget *ST) const {
3844   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3845     return SDValue();
3846
3847   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3848   assert(Op.getValueType() == MVT::f32 &&
3849          "ConstantFP custom lowering should only occur for f32.");
3850
3851   // Try splatting with a VMOV.f32...
3852   APFloat FPVal = CFP->getValueAPF();
3853   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3854   if (ImmVal != -1) {
3855     DebugLoc DL = Op.getDebugLoc();
3856     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3857     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3858                                       NewVal);
3859     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3860                        DAG.getConstant(0, MVT::i32));
3861   }
3862
3863   // If that fails, try a VMOV.i32
3864   EVT VMovVT;
3865   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3866   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3867                                      VMOVModImm);
3868   if (NewVal != SDValue()) {
3869     DebugLoc DL = Op.getDebugLoc();
3870     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3871                                       NewVal);
3872     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3873                                        VecConstant);
3874     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3875                        DAG.getConstant(0, MVT::i32));
3876   }
3877
3878   // Finally, try a VMVN.i32
3879   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3880                              VMVNModImm);
3881   if (NewVal != SDValue()) {
3882     DebugLoc DL = Op.getDebugLoc();
3883     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3884     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3885                                        VecConstant);
3886     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3887                        DAG.getConstant(0, MVT::i32));
3888   }
3889
3890   return SDValue();
3891 }
3892
3893
3894 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3895                        bool &ReverseVEXT, unsigned &Imm) {
3896   unsigned NumElts = VT.getVectorNumElements();
3897   ReverseVEXT = false;
3898
3899   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3900   if (M[0] < 0)
3901     return false;
3902
3903   Imm = M[0];
3904
3905   // If this is a VEXT shuffle, the immediate value is the index of the first
3906   // element.  The other shuffle indices must be the successive elements after
3907   // the first one.
3908   unsigned ExpectedElt = Imm;
3909   for (unsigned i = 1; i < NumElts; ++i) {
3910     // Increment the expected index.  If it wraps around, it may still be
3911     // a VEXT but the source vectors must be swapped.
3912     ExpectedElt += 1;
3913     if (ExpectedElt == NumElts * 2) {
3914       ExpectedElt = 0;
3915       ReverseVEXT = true;
3916     }
3917
3918     if (M[i] < 0) continue; // ignore UNDEF indices
3919     if (ExpectedElt != static_cast<unsigned>(M[i]))
3920       return false;
3921   }
3922
3923   // Adjust the index value if the source operands will be swapped.
3924   if (ReverseVEXT)
3925     Imm -= NumElts;
3926
3927   return true;
3928 }
3929
3930 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3931 /// instruction with the specified blocksize.  (The order of the elements
3932 /// within each block of the vector is reversed.)
3933 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3934   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3935          "Only possible block sizes for VREV are: 16, 32, 64");
3936
3937   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3938   if (EltSz == 64)
3939     return false;
3940
3941   unsigned NumElts = VT.getVectorNumElements();
3942   unsigned BlockElts = M[0] + 1;
3943   // If the first shuffle index is UNDEF, be optimistic.
3944   if (M[0] < 0)
3945     BlockElts = BlockSize / EltSz;
3946
3947   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3948     return false;
3949
3950   for (unsigned i = 0; i < NumElts; ++i) {
3951     if (M[i] < 0) continue; // ignore UNDEF indices
3952     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3953       return false;
3954   }
3955
3956   return true;
3957 }
3958
3959 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3960   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3961   // range, then 0 is placed into the resulting vector. So pretty much any mask
3962   // of 8 elements can work here.
3963   return VT == MVT::v8i8 && M.size() == 8;
3964 }
3965
3966 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3967   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3968   if (EltSz == 64)
3969     return false;
3970
3971   unsigned NumElts = VT.getVectorNumElements();
3972   WhichResult = (M[0] == 0 ? 0 : 1);
3973   for (unsigned i = 0; i < NumElts; i += 2) {
3974     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3975         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3976       return false;
3977   }
3978   return true;
3979 }
3980
3981 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3982 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3983 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3984 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3985   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3986   if (EltSz == 64)
3987     return false;
3988
3989   unsigned NumElts = VT.getVectorNumElements();
3990   WhichResult = (M[0] == 0 ? 0 : 1);
3991   for (unsigned i = 0; i < NumElts; i += 2) {
3992     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3993         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3994       return false;
3995   }
3996   return true;
3997 }
3998
3999 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4000   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4001   if (EltSz == 64)
4002     return false;
4003
4004   unsigned NumElts = VT.getVectorNumElements();
4005   WhichResult = (M[0] == 0 ? 0 : 1);
4006   for (unsigned i = 0; i != NumElts; ++i) {
4007     if (M[i] < 0) continue; // ignore UNDEF indices
4008     if ((unsigned) M[i] != 2 * i + WhichResult)
4009       return false;
4010   }
4011
4012   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4013   if (VT.is64BitVector() && EltSz == 32)
4014     return false;
4015
4016   return true;
4017 }
4018
4019 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4020 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4021 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4022 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4023   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4024   if (EltSz == 64)
4025     return false;
4026
4027   unsigned Half = VT.getVectorNumElements() / 2;
4028   WhichResult = (M[0] == 0 ? 0 : 1);
4029   for (unsigned j = 0; j != 2; ++j) {
4030     unsigned Idx = WhichResult;
4031     for (unsigned i = 0; i != Half; ++i) {
4032       int MIdx = M[i + j * Half];
4033       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4034         return false;
4035       Idx += 2;
4036     }
4037   }
4038
4039   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4040   if (VT.is64BitVector() && EltSz == 32)
4041     return false;
4042
4043   return true;
4044 }
4045
4046 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4047   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4048   if (EltSz == 64)
4049     return false;
4050
4051   unsigned NumElts = VT.getVectorNumElements();
4052   WhichResult = (M[0] == 0 ? 0 : 1);
4053   unsigned Idx = WhichResult * NumElts / 2;
4054   for (unsigned i = 0; i != NumElts; i += 2) {
4055     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4056         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4057       return false;
4058     Idx += 1;
4059   }
4060
4061   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4062   if (VT.is64BitVector() && EltSz == 32)
4063     return false;
4064
4065   return true;
4066 }
4067
4068 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4069 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4070 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4071 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4072   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4073   if (EltSz == 64)
4074     return false;
4075
4076   unsigned NumElts = VT.getVectorNumElements();
4077   WhichResult = (M[0] == 0 ? 0 : 1);
4078   unsigned Idx = WhichResult * NumElts / 2;
4079   for (unsigned i = 0; i != NumElts; i += 2) {
4080     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4081         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4082       return false;
4083     Idx += 1;
4084   }
4085
4086   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4087   if (VT.is64BitVector() && EltSz == 32)
4088     return false;
4089
4090   return true;
4091 }
4092
4093 // If N is an integer constant that can be moved into a register in one
4094 // instruction, return an SDValue of such a constant (will become a MOV
4095 // instruction).  Otherwise return null.
4096 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4097                                      const ARMSubtarget *ST, DebugLoc dl) {
4098   uint64_t Val;
4099   if (!isa<ConstantSDNode>(N))
4100     return SDValue();
4101   Val = cast<ConstantSDNode>(N)->getZExtValue();
4102
4103   if (ST->isThumb1Only()) {
4104     if (Val <= 255 || ~Val <= 255)
4105       return DAG.getConstant(Val, MVT::i32);
4106   } else {
4107     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4108       return DAG.getConstant(Val, MVT::i32);
4109   }
4110   return SDValue();
4111 }
4112
4113 // If this is a case we can't handle, return null and let the default
4114 // expansion code take care of it.
4115 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4116                                              const ARMSubtarget *ST) const {
4117   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4118   DebugLoc dl = Op.getDebugLoc();
4119   EVT VT = Op.getValueType();
4120
4121   APInt SplatBits, SplatUndef;
4122   unsigned SplatBitSize;
4123   bool HasAnyUndefs;
4124   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4125     if (SplatBitSize <= 64) {
4126       // Check if an immediate VMOV works.
4127       EVT VmovVT;
4128       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4129                                       SplatUndef.getZExtValue(), SplatBitSize,
4130                                       DAG, VmovVT, VT.is128BitVector(),
4131                                       VMOVModImm);
4132       if (Val.getNode()) {
4133         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4134         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4135       }
4136
4137       // Try an immediate VMVN.
4138       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4139       Val = isNEONModifiedImm(NegatedImm,
4140                                       SplatUndef.getZExtValue(), SplatBitSize,
4141                                       DAG, VmovVT, VT.is128BitVector(),
4142                                       VMVNModImm);
4143       if (Val.getNode()) {
4144         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4145         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4146       }
4147
4148       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4149       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4150         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4151         if (ImmVal != -1) {
4152           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4153           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4154         }
4155       }
4156     }
4157   }
4158
4159   // Scan through the operands to see if only one value is used.
4160   unsigned NumElts = VT.getVectorNumElements();
4161   bool isOnlyLowElement = true;
4162   bool usesOnlyOneValue = true;
4163   bool isConstant = true;
4164   SDValue Value;
4165   for (unsigned i = 0; i < NumElts; ++i) {
4166     SDValue V = Op.getOperand(i);
4167     if (V.getOpcode() == ISD::UNDEF)
4168       continue;
4169     if (i > 0)
4170       isOnlyLowElement = false;
4171     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4172       isConstant = false;
4173
4174     if (!Value.getNode())
4175       Value = V;
4176     else if (V != Value)
4177       usesOnlyOneValue = false;
4178   }
4179
4180   if (!Value.getNode())
4181     return DAG.getUNDEF(VT);
4182
4183   if (isOnlyLowElement)
4184     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4185
4186   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4187
4188   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4189   // i32 and try again.
4190   if (usesOnlyOneValue && EltSize <= 32) {
4191     if (!isConstant)
4192       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4193     if (VT.getVectorElementType().isFloatingPoint()) {
4194       SmallVector<SDValue, 8> Ops;
4195       for (unsigned i = 0; i < NumElts; ++i)
4196         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4197                                   Op.getOperand(i)));
4198       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4199       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4200       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4201       if (Val.getNode())
4202         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4203     }
4204     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4205     if (Val.getNode())
4206       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4207   }
4208
4209   // If all elements are constants and the case above didn't get hit, fall back
4210   // to the default expansion, which will generate a load from the constant
4211   // pool.
4212   if (isConstant)
4213     return SDValue();
4214
4215   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4216   if (NumElts >= 4) {
4217     SDValue shuffle = ReconstructShuffle(Op, DAG);
4218     if (shuffle != SDValue())
4219       return shuffle;
4220   }
4221
4222   // Vectors with 32- or 64-bit elements can be built by directly assigning
4223   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4224   // will be legalized.
4225   if (EltSize >= 32) {
4226     // Do the expansion with floating-point types, since that is what the VFP
4227     // registers are defined to use, and since i64 is not legal.
4228     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4229     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4230     SmallVector<SDValue, 8> Ops;
4231     for (unsigned i = 0; i < NumElts; ++i)
4232       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4233     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4234     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4235   }
4236
4237   return SDValue();
4238 }
4239
4240 // Gather data to see if the operation can be modelled as a
4241 // shuffle in combination with VEXTs.
4242 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4243                                               SelectionDAG &DAG) const {
4244   DebugLoc dl = Op.getDebugLoc();
4245   EVT VT = Op.getValueType();
4246   unsigned NumElts = VT.getVectorNumElements();
4247
4248   SmallVector<SDValue, 2> SourceVecs;
4249   SmallVector<unsigned, 2> MinElts;
4250   SmallVector<unsigned, 2> MaxElts;
4251
4252   for (unsigned i = 0; i < NumElts; ++i) {
4253     SDValue V = Op.getOperand(i);
4254     if (V.getOpcode() == ISD::UNDEF)
4255       continue;
4256     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4257       // A shuffle can only come from building a vector from various
4258       // elements of other vectors.
4259       return SDValue();
4260     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4261                VT.getVectorElementType()) {
4262       // This code doesn't know how to handle shuffles where the vector
4263       // element types do not match (this happens because type legalization
4264       // promotes the return type of EXTRACT_VECTOR_ELT).
4265       // FIXME: It might be appropriate to extend this code to handle
4266       // mismatched types.
4267       return SDValue();
4268     }
4269
4270     // Record this extraction against the appropriate vector if possible...
4271     SDValue SourceVec = V.getOperand(0);
4272     // If the element number isn't a constant, we can't effectively
4273     // analyze what's going on.
4274     if (!isa<ConstantSDNode>(V.getOperand(1)))
4275       return SDValue();
4276     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4277     bool FoundSource = false;
4278     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4279       if (SourceVecs[j] == SourceVec) {
4280         if (MinElts[j] > EltNo)
4281           MinElts[j] = EltNo;
4282         if (MaxElts[j] < EltNo)
4283           MaxElts[j] = EltNo;
4284         FoundSource = true;
4285         break;
4286       }
4287     }
4288
4289     // Or record a new source if not...
4290     if (!FoundSource) {
4291       SourceVecs.push_back(SourceVec);
4292       MinElts.push_back(EltNo);
4293       MaxElts.push_back(EltNo);
4294     }
4295   }
4296
4297   // Currently only do something sane when at most two source vectors
4298   // involved.
4299   if (SourceVecs.size() > 2)
4300     return SDValue();
4301
4302   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4303   int VEXTOffsets[2] = {0, 0};
4304
4305   // This loop extracts the usage patterns of the source vectors
4306   // and prepares appropriate SDValues for a shuffle if possible.
4307   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4308     if (SourceVecs[i].getValueType() == VT) {
4309       // No VEXT necessary
4310       ShuffleSrcs[i] = SourceVecs[i];
4311       VEXTOffsets[i] = 0;
4312       continue;
4313     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4314       // It probably isn't worth padding out a smaller vector just to
4315       // break it down again in a shuffle.
4316       return SDValue();
4317     }
4318
4319     // Since only 64-bit and 128-bit vectors are legal on ARM and
4320     // we've eliminated the other cases...
4321     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4322            "unexpected vector sizes in ReconstructShuffle");
4323
4324     if (MaxElts[i] - MinElts[i] >= NumElts) {
4325       // Span too large for a VEXT to cope
4326       return SDValue();
4327     }
4328
4329     if (MinElts[i] >= NumElts) {
4330       // The extraction can just take the second half
4331       VEXTOffsets[i] = NumElts;
4332       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4333                                    SourceVecs[i],
4334                                    DAG.getIntPtrConstant(NumElts));
4335     } else if (MaxElts[i] < NumElts) {
4336       // The extraction can just take the first half
4337       VEXTOffsets[i] = 0;
4338       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4339                                    SourceVecs[i],
4340                                    DAG.getIntPtrConstant(0));
4341     } else {
4342       // An actual VEXT is needed
4343       VEXTOffsets[i] = MinElts[i];
4344       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4345                                      SourceVecs[i],
4346                                      DAG.getIntPtrConstant(0));
4347       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4348                                      SourceVecs[i],
4349                                      DAG.getIntPtrConstant(NumElts));
4350       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4351                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4352     }
4353   }
4354
4355   SmallVector<int, 8> Mask;
4356
4357   for (unsigned i = 0; i < NumElts; ++i) {
4358     SDValue Entry = Op.getOperand(i);
4359     if (Entry.getOpcode() == ISD::UNDEF) {
4360       Mask.push_back(-1);
4361       continue;
4362     }
4363
4364     SDValue ExtractVec = Entry.getOperand(0);
4365     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4366                                           .getOperand(1))->getSExtValue();
4367     if (ExtractVec == SourceVecs[0]) {
4368       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4369     } else {
4370       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4371     }
4372   }
4373
4374   // Final check before we try to produce nonsense...
4375   if (isShuffleMaskLegal(Mask, VT))
4376     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4377                                 &Mask[0]);
4378
4379   return SDValue();
4380 }
4381
4382 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4383 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4384 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4385 /// are assumed to be legal.
4386 bool
4387 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4388                                       EVT VT) const {
4389   if (VT.getVectorNumElements() == 4 &&
4390       (VT.is128BitVector() || VT.is64BitVector())) {
4391     unsigned PFIndexes[4];
4392     for (unsigned i = 0; i != 4; ++i) {
4393       if (M[i] < 0)
4394         PFIndexes[i] = 8;
4395       else
4396         PFIndexes[i] = M[i];
4397     }
4398
4399     // Compute the index in the perfect shuffle table.
4400     unsigned PFTableIndex =
4401       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4402     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4403     unsigned Cost = (PFEntry >> 30);
4404
4405     if (Cost <= 4)
4406       return true;
4407   }
4408
4409   bool ReverseVEXT;
4410   unsigned Imm, WhichResult;
4411
4412   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4413   return (EltSize >= 32 ||
4414           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4415           isVREVMask(M, VT, 64) ||
4416           isVREVMask(M, VT, 32) ||
4417           isVREVMask(M, VT, 16) ||
4418           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4419           isVTBLMask(M, VT) ||
4420           isVTRNMask(M, VT, WhichResult) ||
4421           isVUZPMask(M, VT, WhichResult) ||
4422           isVZIPMask(M, VT, WhichResult) ||
4423           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4424           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4425           isVZIP_v_undef_Mask(M, VT, WhichResult));
4426 }
4427
4428 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4429 /// the specified operations to build the shuffle.
4430 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4431                                       SDValue RHS, SelectionDAG &DAG,
4432                                       DebugLoc dl) {
4433   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4434   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4435   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4436
4437   enum {
4438     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4439     OP_VREV,
4440     OP_VDUP0,
4441     OP_VDUP1,
4442     OP_VDUP2,
4443     OP_VDUP3,
4444     OP_VEXT1,
4445     OP_VEXT2,
4446     OP_VEXT3,
4447     OP_VUZPL, // VUZP, left result
4448     OP_VUZPR, // VUZP, right result
4449     OP_VZIPL, // VZIP, left result
4450     OP_VZIPR, // VZIP, right result
4451     OP_VTRNL, // VTRN, left result
4452     OP_VTRNR  // VTRN, right result
4453   };
4454
4455   if (OpNum == OP_COPY) {
4456     if (LHSID == (1*9+2)*9+3) return LHS;
4457     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4458     return RHS;
4459   }
4460
4461   SDValue OpLHS, OpRHS;
4462   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4463   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4464   EVT VT = OpLHS.getValueType();
4465
4466   switch (OpNum) {
4467   default: llvm_unreachable("Unknown shuffle opcode!");
4468   case OP_VREV:
4469     // VREV divides the vector in half and swaps within the half.
4470     if (VT.getVectorElementType() == MVT::i32 ||
4471         VT.getVectorElementType() == MVT::f32)
4472       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4473     // vrev <4 x i16> -> VREV32
4474     if (VT.getVectorElementType() == MVT::i16)
4475       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4476     // vrev <4 x i8> -> VREV16
4477     assert(VT.getVectorElementType() == MVT::i8);
4478     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4479   case OP_VDUP0:
4480   case OP_VDUP1:
4481   case OP_VDUP2:
4482   case OP_VDUP3:
4483     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4484                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4485   case OP_VEXT1:
4486   case OP_VEXT2:
4487   case OP_VEXT3:
4488     return DAG.getNode(ARMISD::VEXT, dl, VT,
4489                        OpLHS, OpRHS,
4490                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4491   case OP_VUZPL:
4492   case OP_VUZPR:
4493     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4494                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4495   case OP_VZIPL:
4496   case OP_VZIPR:
4497     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4498                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4499   case OP_VTRNL:
4500   case OP_VTRNR:
4501     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4502                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4503   }
4504 }
4505
4506 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4507                                        ArrayRef<int> ShuffleMask,
4508                                        SelectionDAG &DAG) {
4509   // Check to see if we can use the VTBL instruction.
4510   SDValue V1 = Op.getOperand(0);
4511   SDValue V2 = Op.getOperand(1);
4512   DebugLoc DL = Op.getDebugLoc();
4513
4514   SmallVector<SDValue, 8> VTBLMask;
4515   for (ArrayRef<int>::iterator
4516          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4517     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4518
4519   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4520     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4521                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4522                                    &VTBLMask[0], 8));
4523
4524   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4525                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4526                                  &VTBLMask[0], 8));
4527 }
4528
4529 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4530   SDValue V1 = Op.getOperand(0);
4531   SDValue V2 = Op.getOperand(1);
4532   DebugLoc dl = Op.getDebugLoc();
4533   EVT VT = Op.getValueType();
4534   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4535
4536   // Convert shuffles that are directly supported on NEON to target-specific
4537   // DAG nodes, instead of keeping them as shuffles and matching them again
4538   // during code selection.  This is more efficient and avoids the possibility
4539   // of inconsistencies between legalization and selection.
4540   // FIXME: floating-point vectors should be canonicalized to integer vectors
4541   // of the same time so that they get CSEd properly.
4542   ArrayRef<int> ShuffleMask = SVN->getMask();
4543
4544   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4545   if (EltSize <= 32) {
4546     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4547       int Lane = SVN->getSplatIndex();
4548       // If this is undef splat, generate it via "just" vdup, if possible.
4549       if (Lane == -1) Lane = 0;
4550
4551       // Test if V1 is a SCALAR_TO_VECTOR.
4552       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4553         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4554       }
4555       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4556       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4557       // reaches it).
4558       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4559           !isa<ConstantSDNode>(V1.getOperand(0))) {
4560         bool IsScalarToVector = true;
4561         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4562           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4563             IsScalarToVector = false;
4564             break;
4565           }
4566         if (IsScalarToVector)
4567           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4568       }
4569       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4570                          DAG.getConstant(Lane, MVT::i32));
4571     }
4572
4573     bool ReverseVEXT;
4574     unsigned Imm;
4575     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4576       if (ReverseVEXT)
4577         std::swap(V1, V2);
4578       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4579                          DAG.getConstant(Imm, MVT::i32));
4580     }
4581
4582     if (isVREVMask(ShuffleMask, VT, 64))
4583       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4584     if (isVREVMask(ShuffleMask, VT, 32))
4585       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4586     if (isVREVMask(ShuffleMask, VT, 16))
4587       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4588
4589     // Check for Neon shuffles that modify both input vectors in place.
4590     // If both results are used, i.e., if there are two shuffles with the same
4591     // source operands and with masks corresponding to both results of one of
4592     // these operations, DAG memoization will ensure that a single node is
4593     // used for both shuffles.
4594     unsigned WhichResult;
4595     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4596       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4597                          V1, V2).getValue(WhichResult);
4598     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4599       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4600                          V1, V2).getValue(WhichResult);
4601     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4602       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4603                          V1, V2).getValue(WhichResult);
4604
4605     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4606       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4607                          V1, V1).getValue(WhichResult);
4608     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4609       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4610                          V1, V1).getValue(WhichResult);
4611     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4612       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4613                          V1, V1).getValue(WhichResult);
4614   }
4615
4616   // If the shuffle is not directly supported and it has 4 elements, use
4617   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4618   unsigned NumElts = VT.getVectorNumElements();
4619   if (NumElts == 4) {
4620     unsigned PFIndexes[4];
4621     for (unsigned i = 0; i != 4; ++i) {
4622       if (ShuffleMask[i] < 0)
4623         PFIndexes[i] = 8;
4624       else
4625         PFIndexes[i] = ShuffleMask[i];
4626     }
4627
4628     // Compute the index in the perfect shuffle table.
4629     unsigned PFTableIndex =
4630       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4631     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4632     unsigned Cost = (PFEntry >> 30);
4633
4634     if (Cost <= 4)
4635       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4636   }
4637
4638   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4639   if (EltSize >= 32) {
4640     // Do the expansion with floating-point types, since that is what the VFP
4641     // registers are defined to use, and since i64 is not legal.
4642     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4643     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4644     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4645     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4646     SmallVector<SDValue, 8> Ops;
4647     for (unsigned i = 0; i < NumElts; ++i) {
4648       if (ShuffleMask[i] < 0)
4649         Ops.push_back(DAG.getUNDEF(EltVT));
4650       else
4651         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4652                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4653                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4654                                                   MVT::i32)));
4655     }
4656     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4657     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4658   }
4659
4660   if (VT == MVT::v8i8) {
4661     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4662     if (NewOp.getNode())
4663       return NewOp;
4664   }
4665
4666   return SDValue();
4667 }
4668
4669 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4670   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4671   SDValue Lane = Op.getOperand(2);
4672   if (!isa<ConstantSDNode>(Lane))
4673     return SDValue();
4674
4675   return Op;
4676 }
4677
4678 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4679   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4680   SDValue Lane = Op.getOperand(1);
4681   if (!isa<ConstantSDNode>(Lane))
4682     return SDValue();
4683
4684   SDValue Vec = Op.getOperand(0);
4685   if (Op.getValueType() == MVT::i32 &&
4686       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4687     DebugLoc dl = Op.getDebugLoc();
4688     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4689   }
4690
4691   return Op;
4692 }
4693
4694 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4695   // The only time a CONCAT_VECTORS operation can have legal types is when
4696   // two 64-bit vectors are concatenated to a 128-bit vector.
4697   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4698          "unexpected CONCAT_VECTORS");
4699   DebugLoc dl = Op.getDebugLoc();
4700   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4701   SDValue Op0 = Op.getOperand(0);
4702   SDValue Op1 = Op.getOperand(1);
4703   if (Op0.getOpcode() != ISD::UNDEF)
4704     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4705                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4706                       DAG.getIntPtrConstant(0));
4707   if (Op1.getOpcode() != ISD::UNDEF)
4708     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4709                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4710                       DAG.getIntPtrConstant(1));
4711   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4712 }
4713
4714 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4715 /// element has been zero/sign-extended, depending on the isSigned parameter,
4716 /// from an integer type half its size.
4717 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4718                                    bool isSigned) {
4719   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4720   EVT VT = N->getValueType(0);
4721   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4722     SDNode *BVN = N->getOperand(0).getNode();
4723     if (BVN->getValueType(0) != MVT::v4i32 ||
4724         BVN->getOpcode() != ISD::BUILD_VECTOR)
4725       return false;
4726     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4727     unsigned HiElt = 1 - LoElt;
4728     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4729     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4730     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4731     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4732     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4733       return false;
4734     if (isSigned) {
4735       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4736           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4737         return true;
4738     } else {
4739       if (Hi0->isNullValue() && Hi1->isNullValue())
4740         return true;
4741     }
4742     return false;
4743   }
4744
4745   if (N->getOpcode() != ISD::BUILD_VECTOR)
4746     return false;
4747
4748   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4749     SDNode *Elt = N->getOperand(i).getNode();
4750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4751       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4752       unsigned HalfSize = EltSize / 2;
4753       if (isSigned) {
4754         if (!isIntN(HalfSize, C->getSExtValue()))
4755           return false;
4756       } else {
4757         if (!isUIntN(HalfSize, C->getZExtValue()))
4758           return false;
4759       }
4760       continue;
4761     }
4762     return false;
4763   }
4764
4765   return true;
4766 }
4767
4768 /// isSignExtended - Check if a node is a vector value that is sign-extended
4769 /// or a constant BUILD_VECTOR with sign-extended elements.
4770 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4771   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4772     return true;
4773   if (isExtendedBUILD_VECTOR(N, DAG, true))
4774     return true;
4775   return false;
4776 }
4777
4778 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4779 /// or a constant BUILD_VECTOR with zero-extended elements.
4780 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4781   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4782     return true;
4783   if (isExtendedBUILD_VECTOR(N, DAG, false))
4784     return true;
4785   return false;
4786 }
4787
4788 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4789 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4790 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4791   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4792     return N->getOperand(0);
4793   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4794     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4795                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4796                        LD->isNonTemporal(), LD->isInvariant(),
4797                        LD->getAlignment());
4798   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4799   // have been legalized as a BITCAST from v4i32.
4800   if (N->getOpcode() == ISD::BITCAST) {
4801     SDNode *BVN = N->getOperand(0).getNode();
4802     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4803            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4804     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4805     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4806                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4807   }
4808   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4809   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4810   EVT VT = N->getValueType(0);
4811   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4812   unsigned NumElts = VT.getVectorNumElements();
4813   MVT TruncVT = MVT::getIntegerVT(EltSize);
4814   SmallVector<SDValue, 8> Ops;
4815   for (unsigned i = 0; i != NumElts; ++i) {
4816     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4817     const APInt &CInt = C->getAPIntValue();
4818     // Element types smaller than 32 bits are not legal, so use i32 elements.
4819     // The values are implicitly truncated so sext vs. zext doesn't matter.
4820     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4821   }
4822   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4823                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4824 }
4825
4826 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4827   unsigned Opcode = N->getOpcode();
4828   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4829     SDNode *N0 = N->getOperand(0).getNode();
4830     SDNode *N1 = N->getOperand(1).getNode();
4831     return N0->hasOneUse() && N1->hasOneUse() &&
4832       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4833   }
4834   return false;
4835 }
4836
4837 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4838   unsigned Opcode = N->getOpcode();
4839   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4840     SDNode *N0 = N->getOperand(0).getNode();
4841     SDNode *N1 = N->getOperand(1).getNode();
4842     return N0->hasOneUse() && N1->hasOneUse() &&
4843       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4844   }
4845   return false;
4846 }
4847
4848 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4849   // Multiplications are only custom-lowered for 128-bit vectors so that
4850   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4851   EVT VT = Op.getValueType();
4852   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4853   SDNode *N0 = Op.getOperand(0).getNode();
4854   SDNode *N1 = Op.getOperand(1).getNode();
4855   unsigned NewOpc = 0;
4856   bool isMLA = false;
4857   bool isN0SExt = isSignExtended(N0, DAG);
4858   bool isN1SExt = isSignExtended(N1, DAG);
4859   if (isN0SExt && isN1SExt)
4860     NewOpc = ARMISD::VMULLs;
4861   else {
4862     bool isN0ZExt = isZeroExtended(N0, DAG);
4863     bool isN1ZExt = isZeroExtended(N1, DAG);
4864     if (isN0ZExt && isN1ZExt)
4865       NewOpc = ARMISD::VMULLu;
4866     else if (isN1SExt || isN1ZExt) {
4867       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4868       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4869       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4870         NewOpc = ARMISD::VMULLs;
4871         isMLA = true;
4872       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4873         NewOpc = ARMISD::VMULLu;
4874         isMLA = true;
4875       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4876         std::swap(N0, N1);
4877         NewOpc = ARMISD::VMULLu;
4878         isMLA = true;
4879       }
4880     }
4881
4882     if (!NewOpc) {
4883       if (VT == MVT::v2i64)
4884         // Fall through to expand this.  It is not legal.
4885         return SDValue();
4886       else
4887         // Other vector multiplications are legal.
4888         return Op;
4889     }
4890   }
4891
4892   // Legalize to a VMULL instruction.
4893   DebugLoc DL = Op.getDebugLoc();
4894   SDValue Op0;
4895   SDValue Op1 = SkipExtension(N1, DAG);
4896   if (!isMLA) {
4897     Op0 = SkipExtension(N0, DAG);
4898     assert(Op0.getValueType().is64BitVector() &&
4899            Op1.getValueType().is64BitVector() &&
4900            "unexpected types for extended operands to VMULL");
4901     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4902   }
4903
4904   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4905   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4906   //   vmull q0, d4, d6
4907   //   vmlal q0, d5, d6
4908   // is faster than
4909   //   vaddl q0, d4, d5
4910   //   vmovl q1, d6
4911   //   vmul  q0, q0, q1
4912   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4913   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4914   EVT Op1VT = Op1.getValueType();
4915   return DAG.getNode(N0->getOpcode(), DL, VT,
4916                      DAG.getNode(NewOpc, DL, VT,
4917                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4918                      DAG.getNode(NewOpc, DL, VT,
4919                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4920 }
4921
4922 static SDValue
4923 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4924   // Convert to float
4925   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4926   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4927   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4928   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4929   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4930   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4931   // Get reciprocal estimate.
4932   // float4 recip = vrecpeq_f32(yf);
4933   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4934                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4935   // Because char has a smaller range than uchar, we can actually get away
4936   // without any newton steps.  This requires that we use a weird bias
4937   // of 0xb000, however (again, this has been exhaustively tested).
4938   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4939   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4940   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4941   Y = DAG.getConstant(0xb000, MVT::i32);
4942   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4943   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4944   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4945   // Convert back to short.
4946   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4947   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4948   return X;
4949 }
4950
4951 static SDValue
4952 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4953   SDValue N2;
4954   // Convert to float.
4955   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4956   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4957   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4958   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4959   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4960   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4961
4962   // Use reciprocal estimate and one refinement step.
4963   // float4 recip = vrecpeq_f32(yf);
4964   // recip *= vrecpsq_f32(yf, recip);
4965   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4966                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4967   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4968                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4969                    N1, N2);
4970   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4971   // Because short has a smaller range than ushort, we can actually get away
4972   // with only a single newton step.  This requires that we use a weird bias
4973   // of 89, however (again, this has been exhaustively tested).
4974   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4975   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4976   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4977   N1 = DAG.getConstant(0x89, MVT::i32);
4978   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4979   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4980   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4981   // Convert back to integer and return.
4982   // return vmovn_s32(vcvt_s32_f32(result));
4983   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4984   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4985   return N0;
4986 }
4987
4988 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4989   EVT VT = Op.getValueType();
4990   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4991          "unexpected type for custom-lowering ISD::SDIV");
4992
4993   DebugLoc dl = Op.getDebugLoc();
4994   SDValue N0 = Op.getOperand(0);
4995   SDValue N1 = Op.getOperand(1);
4996   SDValue N2, N3;
4997
4998   if (VT == MVT::v8i8) {
4999     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5000     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5001
5002     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5003                      DAG.getIntPtrConstant(4));
5004     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5005                      DAG.getIntPtrConstant(4));
5006     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5007                      DAG.getIntPtrConstant(0));
5008     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5009                      DAG.getIntPtrConstant(0));
5010
5011     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5012     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5013
5014     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5015     N0 = LowerCONCAT_VECTORS(N0, DAG);
5016
5017     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5018     return N0;
5019   }
5020   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5021 }
5022
5023 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5024   EVT VT = Op.getValueType();
5025   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5026          "unexpected type for custom-lowering ISD::UDIV");
5027
5028   DebugLoc dl = Op.getDebugLoc();
5029   SDValue N0 = Op.getOperand(0);
5030   SDValue N1 = Op.getOperand(1);
5031   SDValue N2, N3;
5032
5033   if (VT == MVT::v8i8) {
5034     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5035     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5036
5037     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5038                      DAG.getIntPtrConstant(4));
5039     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5040                      DAG.getIntPtrConstant(4));
5041     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5042                      DAG.getIntPtrConstant(0));
5043     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5044                      DAG.getIntPtrConstant(0));
5045
5046     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5047     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5048
5049     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5050     N0 = LowerCONCAT_VECTORS(N0, DAG);
5051
5052     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5053                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5054                      N0);
5055     return N0;
5056   }
5057
5058   // v4i16 sdiv ... Convert to float.
5059   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5060   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5061   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5062   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5063   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5064   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5065
5066   // Use reciprocal estimate and two refinement steps.
5067   // float4 recip = vrecpeq_f32(yf);
5068   // recip *= vrecpsq_f32(yf, recip);
5069   // recip *= vrecpsq_f32(yf, recip);
5070   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5071                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5072   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5073                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5074                    BN1, N2);
5075   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5076   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5077                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5078                    BN1, N2);
5079   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5080   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5081   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5082   // and that it will never cause us to return an answer too large).
5083   // float4 result = as_float4(as_int4(xf*recip) + 2);
5084   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5085   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5086   N1 = DAG.getConstant(2, MVT::i32);
5087   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5088   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5089   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5090   // Convert back to integer and return.
5091   // return vmovn_u32(vcvt_s32_f32(result));
5092   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5093   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5094   return N0;
5095 }
5096
5097 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5098   EVT VT = Op.getNode()->getValueType(0);
5099   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5100
5101   unsigned Opc;
5102   bool ExtraOp = false;
5103   switch (Op.getOpcode()) {
5104   default: llvm_unreachable("Invalid code");
5105   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5106   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5107   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5108   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5109   }
5110
5111   if (!ExtraOp)
5112     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5113                        Op.getOperand(1));
5114   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5115                      Op.getOperand(1), Op.getOperand(2));
5116 }
5117
5118 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5119   // Monotonic load/store is legal for all targets
5120   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5121     return Op;
5122
5123   // Aquire/Release load/store is not legal for targets without a
5124   // dmb or equivalent available.
5125   return SDValue();
5126 }
5127
5128
5129 static void
5130 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5131                     SelectionDAG &DAG, unsigned NewOp) {
5132   DebugLoc dl = Node->getDebugLoc();
5133   assert (Node->getValueType(0) == MVT::i64 &&
5134           "Only know how to expand i64 atomics");
5135
5136   SmallVector<SDValue, 6> Ops;
5137   Ops.push_back(Node->getOperand(0)); // Chain
5138   Ops.push_back(Node->getOperand(1)); // Ptr
5139   // Low part of Val1
5140   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5141                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5142   // High part of Val1
5143   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5144                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5145   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5146     // High part of Val1
5147     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5148                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5149     // High part of Val2
5150     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5151                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5152   }
5153   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5154   SDValue Result =
5155     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5156                             cast<MemSDNode>(Node)->getMemOperand());
5157   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5158   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5159   Results.push_back(Result.getValue(2));
5160 }
5161
5162 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5163   switch (Op.getOpcode()) {
5164   default: llvm_unreachable("Don't know how to custom lower this!");
5165   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5166   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5167   case ISD::GlobalAddress:
5168     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5169       LowerGlobalAddressELF(Op, DAG);
5170   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5171   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5172   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5173   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5174   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5175   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5176   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5177   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5178   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5179   case ISD::SINT_TO_FP:
5180   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5181   case ISD::FP_TO_SINT:
5182   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5183   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5184   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5185   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5186   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5187   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5188   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5189   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5190                                                                Subtarget);
5191   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5192   case ISD::SHL:
5193   case ISD::SRL:
5194   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5195   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5196   case ISD::SRL_PARTS:
5197   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5198   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5199   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5200   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5201   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5202   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5203   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5204   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5205   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5206   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5207   case ISD::MUL:           return LowerMUL(Op, DAG);
5208   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5209   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5210   case ISD::ADDC:
5211   case ISD::ADDE:
5212   case ISD::SUBC:
5213   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5214   case ISD::ATOMIC_LOAD:
5215   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5216   }
5217 }
5218
5219 /// ReplaceNodeResults - Replace the results of node with an illegal result
5220 /// type with new values built out of custom code.
5221 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5222                                            SmallVectorImpl<SDValue>&Results,
5223                                            SelectionDAG &DAG) const {
5224   SDValue Res;
5225   switch (N->getOpcode()) {
5226   default:
5227     llvm_unreachable("Don't know how to custom expand this!");
5228   case ISD::BITCAST:
5229     Res = ExpandBITCAST(N, DAG);
5230     break;
5231   case ISD::SRL:
5232   case ISD::SRA:
5233     Res = Expand64BitShift(N, DAG, Subtarget);
5234     break;
5235   case ISD::ATOMIC_LOAD_ADD:
5236     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5237     return;
5238   case ISD::ATOMIC_LOAD_AND:
5239     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5240     return;
5241   case ISD::ATOMIC_LOAD_NAND:
5242     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5243     return;
5244   case ISD::ATOMIC_LOAD_OR:
5245     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5246     return;
5247   case ISD::ATOMIC_LOAD_SUB:
5248     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5249     return;
5250   case ISD::ATOMIC_LOAD_XOR:
5251     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5252     return;
5253   case ISD::ATOMIC_SWAP:
5254     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5255     return;
5256   case ISD::ATOMIC_CMP_SWAP:
5257     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5258     return;
5259   }
5260   if (Res.getNode())
5261     Results.push_back(Res);
5262 }
5263
5264 //===----------------------------------------------------------------------===//
5265 //                           ARM Scheduler Hooks
5266 //===----------------------------------------------------------------------===//
5267
5268 MachineBasicBlock *
5269 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5270                                      MachineBasicBlock *BB,
5271                                      unsigned Size) const {
5272   unsigned dest    = MI->getOperand(0).getReg();
5273   unsigned ptr     = MI->getOperand(1).getReg();
5274   unsigned oldval  = MI->getOperand(2).getReg();
5275   unsigned newval  = MI->getOperand(3).getReg();
5276   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5277   DebugLoc dl = MI->getDebugLoc();
5278   bool isThumb2 = Subtarget->isThumb2();
5279
5280   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5281   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5282     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5283     (const TargetRegisterClass*)&ARM::GPRRegClass);
5284
5285   if (isThumb2) {
5286     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5287     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5288     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5289   }
5290
5291   unsigned ldrOpc, strOpc;
5292   switch (Size) {
5293   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5294   case 1:
5295     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5296     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5297     break;
5298   case 2:
5299     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5300     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5301     break;
5302   case 4:
5303     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5304     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5305     break;
5306   }
5307
5308   MachineFunction *MF = BB->getParent();
5309   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5310   MachineFunction::iterator It = BB;
5311   ++It; // insert the new blocks after the current block
5312
5313   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5314   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5315   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5316   MF->insert(It, loop1MBB);
5317   MF->insert(It, loop2MBB);
5318   MF->insert(It, exitMBB);
5319
5320   // Transfer the remainder of BB and its successor edges to exitMBB.
5321   exitMBB->splice(exitMBB->begin(), BB,
5322                   llvm::next(MachineBasicBlock::iterator(MI)),
5323                   BB->end());
5324   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5325
5326   //  thisMBB:
5327   //   ...
5328   //   fallthrough --> loop1MBB
5329   BB->addSuccessor(loop1MBB);
5330
5331   // loop1MBB:
5332   //   ldrex dest, [ptr]
5333   //   cmp dest, oldval
5334   //   bne exitMBB
5335   BB = loop1MBB;
5336   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5337   if (ldrOpc == ARM::t2LDREX)
5338     MIB.addImm(0);
5339   AddDefaultPred(MIB);
5340   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5341                  .addReg(dest).addReg(oldval));
5342   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5343     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5344   BB->addSuccessor(loop2MBB);
5345   BB->addSuccessor(exitMBB);
5346
5347   // loop2MBB:
5348   //   strex scratch, newval, [ptr]
5349   //   cmp scratch, #0
5350   //   bne loop1MBB
5351   BB = loop2MBB;
5352   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5353   if (strOpc == ARM::t2STREX)
5354     MIB.addImm(0);
5355   AddDefaultPred(MIB);
5356   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5357                  .addReg(scratch).addImm(0));
5358   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5359     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5360   BB->addSuccessor(loop1MBB);
5361   BB->addSuccessor(exitMBB);
5362
5363   //  exitMBB:
5364   //   ...
5365   BB = exitMBB;
5366
5367   MI->eraseFromParent();   // The instruction is gone now.
5368
5369   return BB;
5370 }
5371
5372 MachineBasicBlock *
5373 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5374                                     unsigned Size, unsigned BinOpcode) const {
5375   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5376   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5377
5378   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5379   MachineFunction *MF = BB->getParent();
5380   MachineFunction::iterator It = BB;
5381   ++It;
5382
5383   unsigned dest = MI->getOperand(0).getReg();
5384   unsigned ptr = MI->getOperand(1).getReg();
5385   unsigned incr = MI->getOperand(2).getReg();
5386   DebugLoc dl = MI->getDebugLoc();
5387   bool isThumb2 = Subtarget->isThumb2();
5388
5389   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5390   if (isThumb2) {
5391     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5392     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5393   }
5394
5395   unsigned ldrOpc, strOpc;
5396   switch (Size) {
5397   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5398   case 1:
5399     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5400     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5401     break;
5402   case 2:
5403     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5404     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5405     break;
5406   case 4:
5407     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5408     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5409     break;
5410   }
5411
5412   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5413   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5414   MF->insert(It, loopMBB);
5415   MF->insert(It, exitMBB);
5416
5417   // Transfer the remainder of BB and its successor edges to exitMBB.
5418   exitMBB->splice(exitMBB->begin(), BB,
5419                   llvm::next(MachineBasicBlock::iterator(MI)),
5420                   BB->end());
5421   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5422
5423   const TargetRegisterClass *TRC = isThumb2 ?
5424     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5425     (const TargetRegisterClass*)&ARM::GPRRegClass;
5426   unsigned scratch = MRI.createVirtualRegister(TRC);
5427   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5428
5429   //  thisMBB:
5430   //   ...
5431   //   fallthrough --> loopMBB
5432   BB->addSuccessor(loopMBB);
5433
5434   //  loopMBB:
5435   //   ldrex dest, ptr
5436   //   <binop> scratch2, dest, incr
5437   //   strex scratch, scratch2, ptr
5438   //   cmp scratch, #0
5439   //   bne- loopMBB
5440   //   fallthrough --> exitMBB
5441   BB = loopMBB;
5442   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5443   if (ldrOpc == ARM::t2LDREX)
5444     MIB.addImm(0);
5445   AddDefaultPred(MIB);
5446   if (BinOpcode) {
5447     // operand order needs to go the other way for NAND
5448     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5449       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5450                      addReg(incr).addReg(dest)).addReg(0);
5451     else
5452       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5453                      addReg(dest).addReg(incr)).addReg(0);
5454   }
5455
5456   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5457   if (strOpc == ARM::t2STREX)
5458     MIB.addImm(0);
5459   AddDefaultPred(MIB);
5460   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5461                  .addReg(scratch).addImm(0));
5462   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5463     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5464
5465   BB->addSuccessor(loopMBB);
5466   BB->addSuccessor(exitMBB);
5467
5468   //  exitMBB:
5469   //   ...
5470   BB = exitMBB;
5471
5472   MI->eraseFromParent();   // The instruction is gone now.
5473
5474   return BB;
5475 }
5476
5477 MachineBasicBlock *
5478 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5479                                           MachineBasicBlock *BB,
5480                                           unsigned Size,
5481                                           bool signExtend,
5482                                           ARMCC::CondCodes Cond) const {
5483   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5484
5485   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5486   MachineFunction *MF = BB->getParent();
5487   MachineFunction::iterator It = BB;
5488   ++It;
5489
5490   unsigned dest = MI->getOperand(0).getReg();
5491   unsigned ptr = MI->getOperand(1).getReg();
5492   unsigned incr = MI->getOperand(2).getReg();
5493   unsigned oldval = dest;
5494   DebugLoc dl = MI->getDebugLoc();
5495   bool isThumb2 = Subtarget->isThumb2();
5496
5497   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5498   if (isThumb2) {
5499     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5500     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5501   }
5502
5503   unsigned ldrOpc, strOpc, extendOpc;
5504   switch (Size) {
5505   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5506   case 1:
5507     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5508     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5509     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5510     break;
5511   case 2:
5512     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5513     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5514     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5515     break;
5516   case 4:
5517     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5518     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5519     extendOpc = 0;
5520     break;
5521   }
5522
5523   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5524   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5525   MF->insert(It, loopMBB);
5526   MF->insert(It, exitMBB);
5527
5528   // Transfer the remainder of BB and its successor edges to exitMBB.
5529   exitMBB->splice(exitMBB->begin(), BB,
5530                   llvm::next(MachineBasicBlock::iterator(MI)),
5531                   BB->end());
5532   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5533
5534   const TargetRegisterClass *TRC = isThumb2 ?
5535     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5536     (const TargetRegisterClass*)&ARM::GPRRegClass;
5537   unsigned scratch = MRI.createVirtualRegister(TRC);
5538   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5539
5540   //  thisMBB:
5541   //   ...
5542   //   fallthrough --> loopMBB
5543   BB->addSuccessor(loopMBB);
5544
5545   //  loopMBB:
5546   //   ldrex dest, ptr
5547   //   (sign extend dest, if required)
5548   //   cmp dest, incr
5549   //   cmov.cond scratch2, dest, incr
5550   //   strex scratch, scratch2, ptr
5551   //   cmp scratch, #0
5552   //   bne- loopMBB
5553   //   fallthrough --> exitMBB
5554   BB = loopMBB;
5555   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5556   if (ldrOpc == ARM::t2LDREX)
5557     MIB.addImm(0);
5558   AddDefaultPred(MIB);
5559
5560   // Sign extend the value, if necessary.
5561   if (signExtend && extendOpc) {
5562     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5563     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5564                      .addReg(dest)
5565                      .addImm(0));
5566   }
5567
5568   // Build compare and cmov instructions.
5569   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5570                  .addReg(oldval).addReg(incr));
5571   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5572          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5573
5574   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5575   if (strOpc == ARM::t2STREX)
5576     MIB.addImm(0);
5577   AddDefaultPred(MIB);
5578   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5579                  .addReg(scratch).addImm(0));
5580   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5581     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5582
5583   BB->addSuccessor(loopMBB);
5584   BB->addSuccessor(exitMBB);
5585
5586   //  exitMBB:
5587   //   ...
5588   BB = exitMBB;
5589
5590   MI->eraseFromParent();   // The instruction is gone now.
5591
5592   return BB;
5593 }
5594
5595 MachineBasicBlock *
5596 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5597                                       unsigned Op1, unsigned Op2,
5598                                       bool NeedsCarry, bool IsCmpxchg) const {
5599   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5600   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5601
5602   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5603   MachineFunction *MF = BB->getParent();
5604   MachineFunction::iterator It = BB;
5605   ++It;
5606
5607   unsigned destlo = MI->getOperand(0).getReg();
5608   unsigned desthi = MI->getOperand(1).getReg();
5609   unsigned ptr = MI->getOperand(2).getReg();
5610   unsigned vallo = MI->getOperand(3).getReg();
5611   unsigned valhi = MI->getOperand(4).getReg();
5612   DebugLoc dl = MI->getDebugLoc();
5613   bool isThumb2 = Subtarget->isThumb2();
5614
5615   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5616   if (isThumb2) {
5617     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5618     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5619     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5620   }
5621
5622   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5623   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5624
5625   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5626   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5627   if (IsCmpxchg) {
5628     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5629     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5630   }
5631   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5632   MF->insert(It, loopMBB);
5633   if (IsCmpxchg) {
5634     MF->insert(It, contBB);
5635     MF->insert(It, cont2BB);
5636   }
5637   MF->insert(It, exitMBB);
5638
5639   // Transfer the remainder of BB and its successor edges to exitMBB.
5640   exitMBB->splice(exitMBB->begin(), BB,
5641                   llvm::next(MachineBasicBlock::iterator(MI)),
5642                   BB->end());
5643   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5644
5645   const TargetRegisterClass *TRC = isThumb2 ?
5646     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5647     (const TargetRegisterClass*)&ARM::GPRRegClass;
5648   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5649
5650   //  thisMBB:
5651   //   ...
5652   //   fallthrough --> loopMBB
5653   BB->addSuccessor(loopMBB);
5654
5655   //  loopMBB:
5656   //   ldrexd r2, r3, ptr
5657   //   <binopa> r0, r2, incr
5658   //   <binopb> r1, r3, incr
5659   //   strexd storesuccess, r0, r1, ptr
5660   //   cmp storesuccess, #0
5661   //   bne- loopMBB
5662   //   fallthrough --> exitMBB
5663   //
5664   // Note that the registers are explicitly specified because there is not any
5665   // way to force the register allocator to allocate a register pair.
5666   //
5667   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5668   // need to properly enforce the restriction that the two output registers
5669   // for ldrexd must be different.
5670   BB = loopMBB;
5671   // Load
5672   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5673                  .addReg(ARM::R2, RegState::Define)
5674                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5675   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5676   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5677   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5678
5679   if (IsCmpxchg) {
5680     // Add early exit
5681     for (unsigned i = 0; i < 2; i++) {
5682       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5683                                                          ARM::CMPrr))
5684                      .addReg(i == 0 ? destlo : desthi)
5685                      .addReg(i == 0 ? vallo : valhi));
5686       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5687         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5688       BB->addSuccessor(exitMBB);
5689       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5690       BB = (i == 0 ? contBB : cont2BB);
5691     }
5692
5693     // Copy to physregs for strexd
5694     unsigned setlo = MI->getOperand(5).getReg();
5695     unsigned sethi = MI->getOperand(6).getReg();
5696     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5697     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5698   } else if (Op1) {
5699     // Perform binary operation
5700     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5701                    .addReg(destlo).addReg(vallo))
5702         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5703     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5704                    .addReg(desthi).addReg(valhi)).addReg(0);
5705   } else {
5706     // Copy to physregs for strexd
5707     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5708     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5709   }
5710
5711   // Store
5712   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5713                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5714   // Cmp+jump
5715   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5716                  .addReg(storesuccess).addImm(0));
5717   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5718     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5719
5720   BB->addSuccessor(loopMBB);
5721   BB->addSuccessor(exitMBB);
5722
5723   //  exitMBB:
5724   //   ...
5725   BB = exitMBB;
5726
5727   MI->eraseFromParent();   // The instruction is gone now.
5728
5729   return BB;
5730 }
5731
5732 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5733 /// registers the function context.
5734 void ARMTargetLowering::
5735 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5736                        MachineBasicBlock *DispatchBB, int FI) const {
5737   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5738   DebugLoc dl = MI->getDebugLoc();
5739   MachineFunction *MF = MBB->getParent();
5740   MachineRegisterInfo *MRI = &MF->getRegInfo();
5741   MachineConstantPool *MCP = MF->getConstantPool();
5742   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5743   const Function *F = MF->getFunction();
5744
5745   bool isThumb = Subtarget->isThumb();
5746   bool isThumb2 = Subtarget->isThumb2();
5747
5748   unsigned PCLabelId = AFI->createPICLabelUId();
5749   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5750   ARMConstantPoolValue *CPV =
5751     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5752   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5753
5754   const TargetRegisterClass *TRC = isThumb ?
5755     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5756     (const TargetRegisterClass*)&ARM::GPRRegClass;
5757
5758   // Grab constant pool and fixed stack memory operands.
5759   MachineMemOperand *CPMMO =
5760     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5761                              MachineMemOperand::MOLoad, 4, 4);
5762
5763   MachineMemOperand *FIMMOSt =
5764     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5765                              MachineMemOperand::MOStore, 4, 4);
5766
5767   // Load the address of the dispatch MBB into the jump buffer.
5768   if (isThumb2) {
5769     // Incoming value: jbuf
5770     //   ldr.n  r5, LCPI1_1
5771     //   orr    r5, r5, #1
5772     //   add    r5, pc
5773     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5774     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5775     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5776                    .addConstantPoolIndex(CPI)
5777                    .addMemOperand(CPMMO));
5778     // Set the low bit because of thumb mode.
5779     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5780     AddDefaultCC(
5781       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5782                      .addReg(NewVReg1, RegState::Kill)
5783                      .addImm(0x01)));
5784     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5785     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5786       .addReg(NewVReg2, RegState::Kill)
5787       .addImm(PCLabelId);
5788     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5789                    .addReg(NewVReg3, RegState::Kill)
5790                    .addFrameIndex(FI)
5791                    .addImm(36)  // &jbuf[1] :: pc
5792                    .addMemOperand(FIMMOSt));
5793   } else if (isThumb) {
5794     // Incoming value: jbuf
5795     //   ldr.n  r1, LCPI1_4
5796     //   add    r1, pc
5797     //   mov    r2, #1
5798     //   orrs   r1, r2
5799     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5800     //   str    r1, [r2]
5801     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5802     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5803                    .addConstantPoolIndex(CPI)
5804                    .addMemOperand(CPMMO));
5805     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5806     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5807       .addReg(NewVReg1, RegState::Kill)
5808       .addImm(PCLabelId);
5809     // Set the low bit because of thumb mode.
5810     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5811     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5812                    .addReg(ARM::CPSR, RegState::Define)
5813                    .addImm(1));
5814     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5815     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5816                    .addReg(ARM::CPSR, RegState::Define)
5817                    .addReg(NewVReg2, RegState::Kill)
5818                    .addReg(NewVReg3, RegState::Kill));
5819     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5820     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5821                    .addFrameIndex(FI)
5822                    .addImm(36)); // &jbuf[1] :: pc
5823     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5824                    .addReg(NewVReg4, RegState::Kill)
5825                    .addReg(NewVReg5, RegState::Kill)
5826                    .addImm(0)
5827                    .addMemOperand(FIMMOSt));
5828   } else {
5829     // Incoming value: jbuf
5830     //   ldr  r1, LCPI1_1
5831     //   add  r1, pc, r1
5832     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5833     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5834     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5835                    .addConstantPoolIndex(CPI)
5836                    .addImm(0)
5837                    .addMemOperand(CPMMO));
5838     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5839     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5840                    .addReg(NewVReg1, RegState::Kill)
5841                    .addImm(PCLabelId));
5842     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5843                    .addReg(NewVReg2, RegState::Kill)
5844                    .addFrameIndex(FI)
5845                    .addImm(36)  // &jbuf[1] :: pc
5846                    .addMemOperand(FIMMOSt));
5847   }
5848 }
5849
5850 MachineBasicBlock *ARMTargetLowering::
5851 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5853   DebugLoc dl = MI->getDebugLoc();
5854   MachineFunction *MF = MBB->getParent();
5855   MachineRegisterInfo *MRI = &MF->getRegInfo();
5856   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5857   MachineFrameInfo *MFI = MF->getFrameInfo();
5858   int FI = MFI->getFunctionContextIndex();
5859
5860   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5861     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5862     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5863
5864   // Get a mapping of the call site numbers to all of the landing pads they're
5865   // associated with.
5866   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5867   unsigned MaxCSNum = 0;
5868   MachineModuleInfo &MMI = MF->getMMI();
5869   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5870        ++BB) {
5871     if (!BB->isLandingPad()) continue;
5872
5873     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5874     // pad.
5875     for (MachineBasicBlock::iterator
5876            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5877       if (!II->isEHLabel()) continue;
5878
5879       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5880       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5881
5882       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5883       for (SmallVectorImpl<unsigned>::iterator
5884              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5885            CSI != CSE; ++CSI) {
5886         CallSiteNumToLPad[*CSI].push_back(BB);
5887         MaxCSNum = std::max(MaxCSNum, *CSI);
5888       }
5889       break;
5890     }
5891   }
5892
5893   // Get an ordered list of the machine basic blocks for the jump table.
5894   std::vector<MachineBasicBlock*> LPadList;
5895   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5896   LPadList.reserve(CallSiteNumToLPad.size());
5897   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5898     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5899     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5900            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5901       LPadList.push_back(*II);
5902       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5903     }
5904   }
5905
5906   assert(!LPadList.empty() &&
5907          "No landing pad destinations for the dispatch jump table!");
5908
5909   // Create the jump table and associated information.
5910   MachineJumpTableInfo *JTI =
5911     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5912   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5913   unsigned UId = AFI->createJumpTableUId();
5914
5915   // Create the MBBs for the dispatch code.
5916
5917   // Shove the dispatch's address into the return slot in the function context.
5918   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5919   DispatchBB->setIsLandingPad();
5920
5921   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5922   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5923   DispatchBB->addSuccessor(TrapBB);
5924
5925   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5926   DispatchBB->addSuccessor(DispContBB);
5927
5928   // Insert and MBBs.
5929   MF->insert(MF->end(), DispatchBB);
5930   MF->insert(MF->end(), DispContBB);
5931   MF->insert(MF->end(), TrapBB);
5932
5933   // Insert code into the entry block that creates and registers the function
5934   // context.
5935   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5936
5937   MachineMemOperand *FIMMOLd =
5938     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5939                              MachineMemOperand::MOLoad |
5940                              MachineMemOperand::MOVolatile, 4, 4);
5941
5942   if (AFI->isThumb1OnlyFunction())
5943     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5944   else if (!Subtarget->hasVFP2())
5945     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5946   else
5947     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5948
5949   unsigned NumLPads = LPadList.size();
5950   if (Subtarget->isThumb2()) {
5951     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5952     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5953                    .addFrameIndex(FI)
5954                    .addImm(4)
5955                    .addMemOperand(FIMMOLd));
5956
5957     if (NumLPads < 256) {
5958       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5959                      .addReg(NewVReg1)
5960                      .addImm(LPadList.size()));
5961     } else {
5962       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5963       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5964                      .addImm(NumLPads & 0xFFFF));
5965
5966       unsigned VReg2 = VReg1;
5967       if ((NumLPads & 0xFFFF0000) != 0) {
5968         VReg2 = MRI->createVirtualRegister(TRC);
5969         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5970                        .addReg(VReg1)
5971                        .addImm(NumLPads >> 16));
5972       }
5973
5974       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5975                      .addReg(NewVReg1)
5976                      .addReg(VReg2));
5977     }
5978
5979     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5980       .addMBB(TrapBB)
5981       .addImm(ARMCC::HI)
5982       .addReg(ARM::CPSR);
5983
5984     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5985     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5986                    .addJumpTableIndex(MJTI)
5987                    .addImm(UId));
5988
5989     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5990     AddDefaultCC(
5991       AddDefaultPred(
5992         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5993         .addReg(NewVReg3, RegState::Kill)
5994         .addReg(NewVReg1)
5995         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5996
5997     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5998       .addReg(NewVReg4, RegState::Kill)
5999       .addReg(NewVReg1)
6000       .addJumpTableIndex(MJTI)
6001       .addImm(UId);
6002   } else if (Subtarget->isThumb()) {
6003     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6004     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6005                    .addFrameIndex(FI)
6006                    .addImm(1)
6007                    .addMemOperand(FIMMOLd));
6008
6009     if (NumLPads < 256) {
6010       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6011                      .addReg(NewVReg1)
6012                      .addImm(NumLPads));
6013     } else {
6014       MachineConstantPool *ConstantPool = MF->getConstantPool();
6015       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6016       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6017
6018       // MachineConstantPool wants an explicit alignment.
6019       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6020       if (Align == 0)
6021         Align = getTargetData()->getTypeAllocSize(C->getType());
6022       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6023
6024       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6025       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6026                      .addReg(VReg1, RegState::Define)
6027                      .addConstantPoolIndex(Idx));
6028       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6029                      .addReg(NewVReg1)
6030                      .addReg(VReg1));
6031     }
6032
6033     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6034       .addMBB(TrapBB)
6035       .addImm(ARMCC::HI)
6036       .addReg(ARM::CPSR);
6037
6038     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6039     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6040                    .addReg(ARM::CPSR, RegState::Define)
6041                    .addReg(NewVReg1)
6042                    .addImm(2));
6043
6044     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6045     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6046                    .addJumpTableIndex(MJTI)
6047                    .addImm(UId));
6048
6049     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6050     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6051                    .addReg(ARM::CPSR, RegState::Define)
6052                    .addReg(NewVReg2, RegState::Kill)
6053                    .addReg(NewVReg3));
6054
6055     MachineMemOperand *JTMMOLd =
6056       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6057                                MachineMemOperand::MOLoad, 4, 4);
6058
6059     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6060     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6061                    .addReg(NewVReg4, RegState::Kill)
6062                    .addImm(0)
6063                    .addMemOperand(JTMMOLd));
6064
6065     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6066     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6067                    .addReg(ARM::CPSR, RegState::Define)
6068                    .addReg(NewVReg5, RegState::Kill)
6069                    .addReg(NewVReg3));
6070
6071     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6072       .addReg(NewVReg6, RegState::Kill)
6073       .addJumpTableIndex(MJTI)
6074       .addImm(UId);
6075   } else {
6076     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6077     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6078                    .addFrameIndex(FI)
6079                    .addImm(4)
6080                    .addMemOperand(FIMMOLd));
6081
6082     if (NumLPads < 256) {
6083       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6084                      .addReg(NewVReg1)
6085                      .addImm(NumLPads));
6086     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6087       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6088       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6089                      .addImm(NumLPads & 0xFFFF));
6090
6091       unsigned VReg2 = VReg1;
6092       if ((NumLPads & 0xFFFF0000) != 0) {
6093         VReg2 = MRI->createVirtualRegister(TRC);
6094         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6095                        .addReg(VReg1)
6096                        .addImm(NumLPads >> 16));
6097       }
6098
6099       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6100                      .addReg(NewVReg1)
6101                      .addReg(VReg2));
6102     } else {
6103       MachineConstantPool *ConstantPool = MF->getConstantPool();
6104       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6105       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6106
6107       // MachineConstantPool wants an explicit alignment.
6108       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6109       if (Align == 0)
6110         Align = getTargetData()->getTypeAllocSize(C->getType());
6111       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6112
6113       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6114       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6115                      .addReg(VReg1, RegState::Define)
6116                      .addConstantPoolIndex(Idx)
6117                      .addImm(0));
6118       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6119                      .addReg(NewVReg1)
6120                      .addReg(VReg1, RegState::Kill));
6121     }
6122
6123     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6124       .addMBB(TrapBB)
6125       .addImm(ARMCC::HI)
6126       .addReg(ARM::CPSR);
6127
6128     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6129     AddDefaultCC(
6130       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6131                      .addReg(NewVReg1)
6132                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6133     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6134     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6135                    .addJumpTableIndex(MJTI)
6136                    .addImm(UId));
6137
6138     MachineMemOperand *JTMMOLd =
6139       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6140                                MachineMemOperand::MOLoad, 4, 4);
6141     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6142     AddDefaultPred(
6143       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6144       .addReg(NewVReg3, RegState::Kill)
6145       .addReg(NewVReg4)
6146       .addImm(0)
6147       .addMemOperand(JTMMOLd));
6148
6149     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6150       .addReg(NewVReg5, RegState::Kill)
6151       .addReg(NewVReg4)
6152       .addJumpTableIndex(MJTI)
6153       .addImm(UId);
6154   }
6155
6156   // Add the jump table entries as successors to the MBB.
6157   MachineBasicBlock *PrevMBB = 0;
6158   for (std::vector<MachineBasicBlock*>::iterator
6159          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6160     MachineBasicBlock *CurMBB = *I;
6161     if (PrevMBB != CurMBB)
6162       DispContBB->addSuccessor(CurMBB);
6163     PrevMBB = CurMBB;
6164   }
6165
6166   // N.B. the order the invoke BBs are processed in doesn't matter here.
6167   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6168   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6169   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6170   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6171   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6172          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6173     MachineBasicBlock *BB = *I;
6174
6175     // Remove the landing pad successor from the invoke block and replace it
6176     // with the new dispatch block.
6177     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6178                                                   BB->succ_end());
6179     while (!Successors.empty()) {
6180       MachineBasicBlock *SMBB = Successors.pop_back_val();
6181       if (SMBB->isLandingPad()) {
6182         BB->removeSuccessor(SMBB);
6183         MBBLPads.push_back(SMBB);
6184       }
6185     }
6186
6187     BB->addSuccessor(DispatchBB);
6188
6189     // Find the invoke call and mark all of the callee-saved registers as
6190     // 'implicit defined' so that they're spilled. This prevents code from
6191     // moving instructions to before the EH block, where they will never be
6192     // executed.
6193     for (MachineBasicBlock::reverse_iterator
6194            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6195       if (!II->isCall()) continue;
6196
6197       DenseMap<unsigned, bool> DefRegs;
6198       for (MachineInstr::mop_iterator
6199              OI = II->operands_begin(), OE = II->operands_end();
6200            OI != OE; ++OI) {
6201         if (!OI->isReg()) continue;
6202         DefRegs[OI->getReg()] = true;
6203       }
6204
6205       MachineInstrBuilder MIB(&*II);
6206
6207       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6208         unsigned Reg = SavedRegs[i];
6209         if (Subtarget->isThumb2() &&
6210             !ARM::tGPRRegClass.contains(Reg) &&
6211             !ARM::hGPRRegClass.contains(Reg))
6212           continue;
6213         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6214           continue;
6215         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6216           continue;
6217         if (!DefRegs[Reg])
6218           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6219       }
6220
6221       break;
6222     }
6223   }
6224
6225   // Mark all former landing pads as non-landing pads. The dispatch is the only
6226   // landing pad now.
6227   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6228          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6229     (*I)->setIsLandingPad(false);
6230
6231   // The instruction is gone now.
6232   MI->eraseFromParent();
6233
6234   return MBB;
6235 }
6236
6237 static
6238 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6239   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6240        E = MBB->succ_end(); I != E; ++I)
6241     if (*I != Succ)
6242       return *I;
6243   llvm_unreachable("Expecting a BB with two successors!");
6244 }
6245
6246 MachineBasicBlock *ARMTargetLowering::
6247 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6248   // This pseudo instruction has 3 operands: dst, src, size
6249   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6250   // Otherwise, we will generate unrolled scalar copies.
6251   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6252   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6253   MachineFunction::iterator It = BB;
6254   ++It;
6255
6256   unsigned dest = MI->getOperand(0).getReg();
6257   unsigned src = MI->getOperand(1).getReg();
6258   unsigned SizeVal = MI->getOperand(2).getImm();
6259   unsigned Align = MI->getOperand(3).getImm();
6260   DebugLoc dl = MI->getDebugLoc();
6261
6262   bool isThumb2 = Subtarget->isThumb2();
6263   MachineFunction *MF = BB->getParent();
6264   MachineRegisterInfo &MRI = MF->getRegInfo();
6265   unsigned ldrOpc, strOpc, UnitSize = 0;
6266
6267   const TargetRegisterClass *TRC = isThumb2 ?
6268     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6269     (const TargetRegisterClass*)&ARM::GPRRegClass;
6270   const TargetRegisterClass *TRC_Vec = 0;
6271
6272   if (Align & 1) {
6273     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6274     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6275     UnitSize = 1;
6276   } else if (Align & 2) {
6277     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6278     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6279     UnitSize = 2;
6280   } else {
6281     // Check whether we can use NEON instructions.
6282     if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6283         Subtarget->hasNEON()) {
6284       if ((Align % 16 == 0) && SizeVal >= 16) {
6285         ldrOpc = ARM::VLD1q32wb_fixed;
6286         strOpc = ARM::VST1q32wb_fixed;
6287         UnitSize = 16;
6288         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6289       }
6290       else if ((Align % 8 == 0) && SizeVal >= 8) {
6291         ldrOpc = ARM::VLD1d32wb_fixed;
6292         strOpc = ARM::VST1d32wb_fixed;
6293         UnitSize = 8;
6294         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6295       }
6296     }
6297     // Can't use NEON instructions.
6298     if (UnitSize == 0) {
6299       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6300       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6301       UnitSize = 4;
6302     }
6303   }
6304
6305   unsigned BytesLeft = SizeVal % UnitSize;
6306   unsigned LoopSize = SizeVal - BytesLeft;
6307
6308   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6309     // Use LDR and STR to copy.
6310     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6311     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6312     unsigned srcIn = src;
6313     unsigned destIn = dest;
6314     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6315       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6316       unsigned srcOut = MRI.createVirtualRegister(TRC);
6317       unsigned destOut = MRI.createVirtualRegister(TRC);
6318       if (UnitSize >= 8) {
6319         AddDefaultPred(BuildMI(*BB, MI, dl,
6320           TII->get(ldrOpc), scratch)
6321           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6322
6323         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6324           .addReg(destIn).addImm(0).addReg(scratch));
6325       } else if (isThumb2) {
6326         AddDefaultPred(BuildMI(*BB, MI, dl,
6327           TII->get(ldrOpc), scratch)
6328           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6329
6330         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6331           .addReg(scratch).addReg(destIn)
6332           .addImm(UnitSize));
6333       } else {
6334         AddDefaultPred(BuildMI(*BB, MI, dl,
6335           TII->get(ldrOpc), scratch)
6336           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6337           .addImm(UnitSize));
6338
6339         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6340           .addReg(scratch).addReg(destIn)
6341           .addReg(0).addImm(UnitSize));
6342       }
6343       srcIn = srcOut;
6344       destIn = destOut;
6345     }
6346
6347     // Handle the leftover bytes with LDRB and STRB.
6348     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6349     // [destOut] = STRB_POST(scratch, destIn, 1)
6350     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6351     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6352     for (unsigned i = 0; i < BytesLeft; i++) {
6353       unsigned scratch = MRI.createVirtualRegister(TRC);
6354       unsigned srcOut = MRI.createVirtualRegister(TRC);
6355       unsigned destOut = MRI.createVirtualRegister(TRC);
6356       if (isThumb2) {
6357         AddDefaultPred(BuildMI(*BB, MI, dl,
6358           TII->get(ldrOpc),scratch)
6359           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6360
6361         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6362           .addReg(scratch).addReg(destIn)
6363           .addReg(0).addImm(1));
6364       } else {
6365         AddDefaultPred(BuildMI(*BB, MI, dl,
6366           TII->get(ldrOpc),scratch)
6367           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6368
6369         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6370           .addReg(scratch).addReg(destIn)
6371           .addReg(0).addImm(1));
6372       }
6373       srcIn = srcOut;
6374       destIn = destOut;
6375     }
6376     MI->eraseFromParent();   // The instruction is gone now.
6377     return BB;
6378   }
6379
6380   // Expand the pseudo op to a loop.
6381   // thisMBB:
6382   //   ...
6383   //   movw varEnd, # --> with thumb2
6384   //   movt varEnd, #
6385   //   ldrcp varEnd, idx --> without thumb2
6386   //   fallthrough --> loopMBB
6387   // loopMBB:
6388   //   PHI varPhi, varEnd, varLoop
6389   //   PHI srcPhi, src, srcLoop
6390   //   PHI destPhi, dst, destLoop
6391   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6392   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6393   //   subs varLoop, varPhi, #UnitSize
6394   //   bne loopMBB
6395   //   fallthrough --> exitMBB
6396   // exitMBB:
6397   //   epilogue to handle left-over bytes
6398   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6399   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6400   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6401   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6402   MF->insert(It, loopMBB);
6403   MF->insert(It, exitMBB);
6404
6405   // Transfer the remainder of BB and its successor edges to exitMBB.
6406   exitMBB->splice(exitMBB->begin(), BB,
6407                   llvm::next(MachineBasicBlock::iterator(MI)),
6408                   BB->end());
6409   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6410
6411   // Load an immediate to varEnd.
6412   unsigned varEnd = MRI.createVirtualRegister(TRC);
6413   if (isThumb2) {
6414     unsigned VReg1 = varEnd;
6415     if ((LoopSize & 0xFFFF0000) != 0)
6416       VReg1 = MRI.createVirtualRegister(TRC);
6417     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6418                    .addImm(LoopSize & 0xFFFF));
6419
6420     if ((LoopSize & 0xFFFF0000) != 0)
6421       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6422                      .addReg(VReg1)
6423                      .addImm(LoopSize >> 16));
6424   } else {
6425     MachineConstantPool *ConstantPool = MF->getConstantPool();
6426     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6427     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6428
6429     // MachineConstantPool wants an explicit alignment.
6430     unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6431     if (Align == 0)
6432       Align = getTargetData()->getTypeAllocSize(C->getType());
6433     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6434
6435     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6436                    .addReg(varEnd, RegState::Define)
6437                    .addConstantPoolIndex(Idx)
6438                    .addImm(0));
6439   }
6440   BB->addSuccessor(loopMBB);
6441
6442   // Generate the loop body:
6443   //   varPhi = PHI(varLoop, varEnd)
6444   //   srcPhi = PHI(srcLoop, src)
6445   //   destPhi = PHI(destLoop, dst)
6446   MachineBasicBlock *entryBB = BB;
6447   BB = loopMBB;
6448   unsigned varLoop = MRI.createVirtualRegister(TRC);
6449   unsigned varPhi = MRI.createVirtualRegister(TRC);
6450   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6451   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6452   unsigned destLoop = MRI.createVirtualRegister(TRC);
6453   unsigned destPhi = MRI.createVirtualRegister(TRC);
6454
6455   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6456     .addReg(varLoop).addMBB(loopMBB)
6457     .addReg(varEnd).addMBB(entryBB);
6458   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6459     .addReg(srcLoop).addMBB(loopMBB)
6460     .addReg(src).addMBB(entryBB);
6461   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6462     .addReg(destLoop).addMBB(loopMBB)
6463     .addReg(dest).addMBB(entryBB);
6464
6465   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6466   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6467   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6468   if (UnitSize >= 8) {
6469     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6470       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6471
6472     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6473       .addReg(destPhi).addImm(0).addReg(scratch));
6474   } else if (isThumb2) {
6475     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6476       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6477
6478     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6479       .addReg(scratch).addReg(destPhi)
6480       .addImm(UnitSize));
6481   } else {
6482     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6483       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6484       .addImm(UnitSize));
6485
6486     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6487       .addReg(scratch).addReg(destPhi)
6488       .addReg(0).addImm(UnitSize));
6489   }
6490
6491   // Decrement loop variable by UnitSize.
6492   MachineInstrBuilder MIB = BuildMI(BB, dl,
6493     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6494   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6495   MIB->getOperand(5).setReg(ARM::CPSR);
6496   MIB->getOperand(5).setIsDef(true);
6497
6498   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6499     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6500
6501   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6502   BB->addSuccessor(loopMBB);
6503   BB->addSuccessor(exitMBB);
6504
6505   // Add epilogue to handle BytesLeft.
6506   BB = exitMBB;
6507   MachineInstr *StartOfExit = exitMBB->begin();
6508   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6509   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6510
6511   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6512   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6513   unsigned srcIn = srcLoop;
6514   unsigned destIn = destLoop;
6515   for (unsigned i = 0; i < BytesLeft; i++) {
6516     unsigned scratch = MRI.createVirtualRegister(TRC);
6517     unsigned srcOut = MRI.createVirtualRegister(TRC);
6518     unsigned destOut = MRI.createVirtualRegister(TRC);
6519     if (isThumb2) {
6520       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6521         TII->get(ldrOpc),scratch)
6522         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6523
6524       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6525         .addReg(scratch).addReg(destIn)
6526         .addImm(1));
6527     } else {
6528       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6529         TII->get(ldrOpc),scratch)
6530         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6531
6532       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6533         .addReg(scratch).addReg(destIn)
6534         .addReg(0).addImm(1));
6535     }
6536     srcIn = srcOut;
6537     destIn = destOut;
6538   }
6539
6540   MI->eraseFromParent();   // The instruction is gone now.
6541   return BB;
6542 }
6543
6544 MachineBasicBlock *
6545 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6546                                                MachineBasicBlock *BB) const {
6547   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6548   DebugLoc dl = MI->getDebugLoc();
6549   bool isThumb2 = Subtarget->isThumb2();
6550   switch (MI->getOpcode()) {
6551   default: {
6552     MI->dump();
6553     llvm_unreachable("Unexpected instr type to insert");
6554   }
6555   // The Thumb2 pre-indexed stores have the same MI operands, they just
6556   // define them differently in the .td files from the isel patterns, so
6557   // they need pseudos.
6558   case ARM::t2STR_preidx:
6559     MI->setDesc(TII->get(ARM::t2STR_PRE));
6560     return BB;
6561   case ARM::t2STRB_preidx:
6562     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6563     return BB;
6564   case ARM::t2STRH_preidx:
6565     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6566     return BB;
6567
6568   case ARM::STRi_preidx:
6569   case ARM::STRBi_preidx: {
6570     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6571       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6572     // Decode the offset.
6573     unsigned Offset = MI->getOperand(4).getImm();
6574     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6575     Offset = ARM_AM::getAM2Offset(Offset);
6576     if (isSub)
6577       Offset = -Offset;
6578
6579     MachineMemOperand *MMO = *MI->memoperands_begin();
6580     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6581       .addOperand(MI->getOperand(0))  // Rn_wb
6582       .addOperand(MI->getOperand(1))  // Rt
6583       .addOperand(MI->getOperand(2))  // Rn
6584       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6585       .addOperand(MI->getOperand(5))  // pred
6586       .addOperand(MI->getOperand(6))
6587       .addMemOperand(MMO);
6588     MI->eraseFromParent();
6589     return BB;
6590   }
6591   case ARM::STRr_preidx:
6592   case ARM::STRBr_preidx:
6593   case ARM::STRH_preidx: {
6594     unsigned NewOpc;
6595     switch (MI->getOpcode()) {
6596     default: llvm_unreachable("unexpected opcode!");
6597     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6598     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6599     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6600     }
6601     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6602     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6603       MIB.addOperand(MI->getOperand(i));
6604     MI->eraseFromParent();
6605     return BB;
6606   }
6607   case ARM::ATOMIC_LOAD_ADD_I8:
6608      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6609   case ARM::ATOMIC_LOAD_ADD_I16:
6610      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6611   case ARM::ATOMIC_LOAD_ADD_I32:
6612      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6613
6614   case ARM::ATOMIC_LOAD_AND_I8:
6615      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6616   case ARM::ATOMIC_LOAD_AND_I16:
6617      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6618   case ARM::ATOMIC_LOAD_AND_I32:
6619      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6620
6621   case ARM::ATOMIC_LOAD_OR_I8:
6622      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6623   case ARM::ATOMIC_LOAD_OR_I16:
6624      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6625   case ARM::ATOMIC_LOAD_OR_I32:
6626      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6627
6628   case ARM::ATOMIC_LOAD_XOR_I8:
6629      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6630   case ARM::ATOMIC_LOAD_XOR_I16:
6631      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6632   case ARM::ATOMIC_LOAD_XOR_I32:
6633      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6634
6635   case ARM::ATOMIC_LOAD_NAND_I8:
6636      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6637   case ARM::ATOMIC_LOAD_NAND_I16:
6638      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6639   case ARM::ATOMIC_LOAD_NAND_I32:
6640      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6641
6642   case ARM::ATOMIC_LOAD_SUB_I8:
6643      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6644   case ARM::ATOMIC_LOAD_SUB_I16:
6645      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6646   case ARM::ATOMIC_LOAD_SUB_I32:
6647      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6648
6649   case ARM::ATOMIC_LOAD_MIN_I8:
6650      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6651   case ARM::ATOMIC_LOAD_MIN_I16:
6652      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6653   case ARM::ATOMIC_LOAD_MIN_I32:
6654      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6655
6656   case ARM::ATOMIC_LOAD_MAX_I8:
6657      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6658   case ARM::ATOMIC_LOAD_MAX_I16:
6659      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6660   case ARM::ATOMIC_LOAD_MAX_I32:
6661      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6662
6663   case ARM::ATOMIC_LOAD_UMIN_I8:
6664      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6665   case ARM::ATOMIC_LOAD_UMIN_I16:
6666      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6667   case ARM::ATOMIC_LOAD_UMIN_I32:
6668      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6669
6670   case ARM::ATOMIC_LOAD_UMAX_I8:
6671      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6672   case ARM::ATOMIC_LOAD_UMAX_I16:
6673      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6674   case ARM::ATOMIC_LOAD_UMAX_I32:
6675      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6676
6677   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6678   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6679   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6680
6681   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6682   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6683   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6684
6685
6686   case ARM::ATOMADD6432:
6687     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6688                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6689                               /*NeedsCarry*/ true);
6690   case ARM::ATOMSUB6432:
6691     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6692                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6693                               /*NeedsCarry*/ true);
6694   case ARM::ATOMOR6432:
6695     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6696                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6697   case ARM::ATOMXOR6432:
6698     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6699                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6700   case ARM::ATOMAND6432:
6701     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6702                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6703   case ARM::ATOMSWAP6432:
6704     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6705   case ARM::ATOMCMPXCHG6432:
6706     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6707                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6708                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6709
6710   case ARM::tMOVCCr_pseudo: {
6711     // To "insert" a SELECT_CC instruction, we actually have to insert the
6712     // diamond control-flow pattern.  The incoming instruction knows the
6713     // destination vreg to set, the condition code register to branch on, the
6714     // true/false values to select between, and a branch opcode to use.
6715     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6716     MachineFunction::iterator It = BB;
6717     ++It;
6718
6719     //  thisMBB:
6720     //  ...
6721     //   TrueVal = ...
6722     //   cmpTY ccX, r1, r2
6723     //   bCC copy1MBB
6724     //   fallthrough --> copy0MBB
6725     MachineBasicBlock *thisMBB  = BB;
6726     MachineFunction *F = BB->getParent();
6727     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6728     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6729     F->insert(It, copy0MBB);
6730     F->insert(It, sinkMBB);
6731
6732     // Transfer the remainder of BB and its successor edges to sinkMBB.
6733     sinkMBB->splice(sinkMBB->begin(), BB,
6734                     llvm::next(MachineBasicBlock::iterator(MI)),
6735                     BB->end());
6736     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6737
6738     BB->addSuccessor(copy0MBB);
6739     BB->addSuccessor(sinkMBB);
6740
6741     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6742       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6743
6744     //  copy0MBB:
6745     //   %FalseValue = ...
6746     //   # fallthrough to sinkMBB
6747     BB = copy0MBB;
6748
6749     // Update machine-CFG edges
6750     BB->addSuccessor(sinkMBB);
6751
6752     //  sinkMBB:
6753     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6754     //  ...
6755     BB = sinkMBB;
6756     BuildMI(*BB, BB->begin(), dl,
6757             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6758       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6759       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6760
6761     MI->eraseFromParent();   // The pseudo instruction is gone now.
6762     return BB;
6763   }
6764
6765   case ARM::BCCi64:
6766   case ARM::BCCZi64: {
6767     // If there is an unconditional branch to the other successor, remove it.
6768     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6769
6770     // Compare both parts that make up the double comparison separately for
6771     // equality.
6772     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6773
6774     unsigned LHS1 = MI->getOperand(1).getReg();
6775     unsigned LHS2 = MI->getOperand(2).getReg();
6776     if (RHSisZero) {
6777       AddDefaultPred(BuildMI(BB, dl,
6778                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6779                      .addReg(LHS1).addImm(0));
6780       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6781         .addReg(LHS2).addImm(0)
6782         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6783     } else {
6784       unsigned RHS1 = MI->getOperand(3).getReg();
6785       unsigned RHS2 = MI->getOperand(4).getReg();
6786       AddDefaultPred(BuildMI(BB, dl,
6787                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6788                      .addReg(LHS1).addReg(RHS1));
6789       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6790         .addReg(LHS2).addReg(RHS2)
6791         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6792     }
6793
6794     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6795     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6796     if (MI->getOperand(0).getImm() == ARMCC::NE)
6797       std::swap(destMBB, exitMBB);
6798
6799     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6800       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6801     if (isThumb2)
6802       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6803     else
6804       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6805
6806     MI->eraseFromParent();   // The pseudo instruction is gone now.
6807     return BB;
6808   }
6809
6810   case ARM::Int_eh_sjlj_setjmp:
6811   case ARM::Int_eh_sjlj_setjmp_nofp:
6812   case ARM::tInt_eh_sjlj_setjmp:
6813   case ARM::t2Int_eh_sjlj_setjmp:
6814   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6815     EmitSjLjDispatchBlock(MI, BB);
6816     return BB;
6817
6818   case ARM::ABS:
6819   case ARM::t2ABS: {
6820     // To insert an ABS instruction, we have to insert the
6821     // diamond control-flow pattern.  The incoming instruction knows the
6822     // source vreg to test against 0, the destination vreg to set,
6823     // the condition code register to branch on, the
6824     // true/false values to select between, and a branch opcode to use.
6825     // It transforms
6826     //     V1 = ABS V0
6827     // into
6828     //     V2 = MOVS V0
6829     //     BCC                      (branch to SinkBB if V0 >= 0)
6830     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6831     //     SinkBB: V1 = PHI(V2, V3)
6832     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6833     MachineFunction::iterator BBI = BB;
6834     ++BBI;
6835     MachineFunction *Fn = BB->getParent();
6836     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6837     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6838     Fn->insert(BBI, RSBBB);
6839     Fn->insert(BBI, SinkBB);
6840
6841     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6842     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6843     bool isThumb2 = Subtarget->isThumb2();
6844     MachineRegisterInfo &MRI = Fn->getRegInfo();
6845     // In Thumb mode S must not be specified if source register is the SP or
6846     // PC and if destination register is the SP, so restrict register class
6847     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6848       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6849       (const TargetRegisterClass*)&ARM::GPRRegClass);
6850
6851     // Transfer the remainder of BB and its successor edges to sinkMBB.
6852     SinkBB->splice(SinkBB->begin(), BB,
6853       llvm::next(MachineBasicBlock::iterator(MI)),
6854       BB->end());
6855     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6856
6857     BB->addSuccessor(RSBBB);
6858     BB->addSuccessor(SinkBB);
6859
6860     // fall through to SinkMBB
6861     RSBBB->addSuccessor(SinkBB);
6862
6863     // insert a cmp at the end of BB
6864     AddDefaultPred(BuildMI(BB, dl,
6865                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6866                    .addReg(ABSSrcReg).addImm(0));
6867
6868     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6869     BuildMI(BB, dl,
6870       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6871       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6872
6873     // insert rsbri in RSBBB
6874     // Note: BCC and rsbri will be converted into predicated rsbmi
6875     // by if-conversion pass
6876     BuildMI(*RSBBB, RSBBB->begin(), dl,
6877       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6878       .addReg(ABSSrcReg, RegState::Kill)
6879       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6880
6881     // insert PHI in SinkBB,
6882     // reuse ABSDstReg to not change uses of ABS instruction
6883     BuildMI(*SinkBB, SinkBB->begin(), dl,
6884       TII->get(ARM::PHI), ABSDstReg)
6885       .addReg(NewRsbDstReg).addMBB(RSBBB)
6886       .addReg(ABSSrcReg).addMBB(BB);
6887
6888     // remove ABS instruction
6889     MI->eraseFromParent();
6890
6891     // return last added BB
6892     return SinkBB;
6893   }
6894   case ARM::COPY_STRUCT_BYVAL_I32:
6895     ++NumLoopByVals;
6896     return EmitStructByval(MI, BB);
6897   }
6898 }
6899
6900 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6901                                                       SDNode *Node) const {
6902   if (!MI->hasPostISelHook()) {
6903     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6904            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6905     return;
6906   }
6907
6908   const MCInstrDesc *MCID = &MI->getDesc();
6909   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6910   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6911   // operand is still set to noreg. If needed, set the optional operand's
6912   // register to CPSR, and remove the redundant implicit def.
6913   //
6914   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6915
6916   // Rename pseudo opcodes.
6917   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6918   if (NewOpc) {
6919     const ARMBaseInstrInfo *TII =
6920       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6921     MCID = &TII->get(NewOpc);
6922
6923     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6924            "converted opcode should be the same except for cc_out");
6925
6926     MI->setDesc(*MCID);
6927
6928     // Add the optional cc_out operand
6929     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6930   }
6931   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6932
6933   // Any ARM instruction that sets the 's' bit should specify an optional
6934   // "cc_out" operand in the last operand position.
6935   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6936     assert(!NewOpc && "Optional cc_out operand required");
6937     return;
6938   }
6939   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6940   // since we already have an optional CPSR def.
6941   bool definesCPSR = false;
6942   bool deadCPSR = false;
6943   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6944        i != e; ++i) {
6945     const MachineOperand &MO = MI->getOperand(i);
6946     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6947       definesCPSR = true;
6948       if (MO.isDead())
6949         deadCPSR = true;
6950       MI->RemoveOperand(i);
6951       break;
6952     }
6953   }
6954   if (!definesCPSR) {
6955     assert(!NewOpc && "Optional cc_out operand required");
6956     return;
6957   }
6958   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6959   if (deadCPSR) {
6960     assert(!MI->getOperand(ccOutIdx).getReg() &&
6961            "expect uninitialized optional cc_out operand");
6962     return;
6963   }
6964
6965   // If this instruction was defined with an optional CPSR def and its dag node
6966   // had a live implicit CPSR def, then activate the optional CPSR def.
6967   MachineOperand &MO = MI->getOperand(ccOutIdx);
6968   MO.setReg(ARM::CPSR);
6969   MO.setIsDef(true);
6970 }
6971
6972 //===----------------------------------------------------------------------===//
6973 //                           ARM Optimization Hooks
6974 //===----------------------------------------------------------------------===//
6975
6976 // Helper function that checks if N is a null or all ones constant.
6977 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
6978   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
6979   if (!C)
6980     return false;
6981   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
6982 }
6983
6984 // Return true if N is conditionally 0 or all ones.
6985 // Detects these expressions where cc is an i1 value:
6986 //
6987 //   (select cc 0, y)   [AllOnes=0]
6988 //   (select cc y, 0)   [AllOnes=0]
6989 //   (zext cc)          [AllOnes=0]
6990 //   (sext cc)          [AllOnes=0/1]
6991 //   (select cc -1, y)  [AllOnes=1]
6992 //   (select cc y, -1)  [AllOnes=1]
6993 //
6994 // Invert is set when N is the null/all ones constant when CC is false.
6995 // OtherOp is set to the alternative value of N.
6996 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
6997                                        SDValue &CC, bool &Invert,
6998                                        SDValue &OtherOp,
6999                                        SelectionDAG &DAG) {
7000   switch (N->getOpcode()) {
7001   default: return false;
7002   case ISD::SELECT: {
7003     CC = N->getOperand(0);
7004     SDValue N1 = N->getOperand(1);
7005     SDValue N2 = N->getOperand(2);
7006     if (isZeroOrAllOnes(N1, AllOnes)) {
7007       Invert = false;
7008       OtherOp = N2;
7009       return true;
7010     }
7011     if (isZeroOrAllOnes(N2, AllOnes)) {
7012       Invert = true;
7013       OtherOp = N1;
7014       return true;
7015     }
7016     return false;
7017   }
7018   case ISD::ZERO_EXTEND:
7019     // (zext cc) can never be the all ones value.
7020     if (AllOnes)
7021       return false;
7022     // Fall through.
7023   case ISD::SIGN_EXTEND: {
7024     EVT VT = N->getValueType(0);
7025     CC = N->getOperand(0);
7026     if (CC.getValueType() != MVT::i1)
7027       return false;
7028     Invert = !AllOnes;
7029     if (AllOnes)
7030       // When looking for an AllOnes constant, N is an sext, and the 'other'
7031       // value is 0.
7032       OtherOp = DAG.getConstant(0, VT);
7033     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7034       // When looking for a 0 constant, N can be zext or sext.
7035       OtherOp = DAG.getConstant(1, VT);
7036     else
7037       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7038     return true;
7039   }
7040   }
7041 }
7042
7043 // Combine a constant select operand into its use:
7044 //
7045 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7046 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7047 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7048 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7049 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7050 //
7051 // The transform is rejected if the select doesn't have a constant operand that
7052 // is null, or all ones when AllOnes is set.
7053 //
7054 // Also recognize sext/zext from i1:
7055 //
7056 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7057 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7058 //
7059 // These transformations eventually create predicated instructions.
7060 //
7061 // @param N       The node to transform.
7062 // @param Slct    The N operand that is a select.
7063 // @param OtherOp The other N operand (x above).
7064 // @param DCI     Context.
7065 // @param AllOnes Require the select constant to be all ones instead of null.
7066 // @returns The new node, or SDValue() on failure.
7067 static
7068 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7069                             TargetLowering::DAGCombinerInfo &DCI,
7070                             bool AllOnes = false) {
7071   SelectionDAG &DAG = DCI.DAG;
7072   EVT VT = N->getValueType(0);
7073   SDValue NonConstantVal;
7074   SDValue CCOp;
7075   bool SwapSelectOps;
7076   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7077                                   NonConstantVal, DAG))
7078     return SDValue();
7079
7080   // Slct is now know to be the desired identity constant when CC is true.
7081   SDValue TrueVal = OtherOp;
7082   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7083                                  OtherOp, NonConstantVal);
7084   // Unless SwapSelectOps says CC should be false.
7085   if (SwapSelectOps)
7086     std::swap(TrueVal, FalseVal);
7087
7088   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7089                      CCOp, TrueVal, FalseVal);
7090 }
7091
7092 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7093 static
7094 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7095                                        TargetLowering::DAGCombinerInfo &DCI) {
7096   SDValue N0 = N->getOperand(0);
7097   SDValue N1 = N->getOperand(1);
7098   if (N0.getNode()->hasOneUse()) {
7099     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7100     if (Result.getNode())
7101       return Result;
7102   }
7103   if (N1.getNode()->hasOneUse()) {
7104     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7105     if (Result.getNode())
7106       return Result;
7107   }
7108   return SDValue();
7109 }
7110
7111 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7112 // (only after legalization).
7113 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7114                                  TargetLowering::DAGCombinerInfo &DCI,
7115                                  const ARMSubtarget *Subtarget) {
7116
7117   // Only perform optimization if after legalize, and if NEON is available. We
7118   // also expected both operands to be BUILD_VECTORs.
7119   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7120       || N0.getOpcode() != ISD::BUILD_VECTOR
7121       || N1.getOpcode() != ISD::BUILD_VECTOR)
7122     return SDValue();
7123
7124   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7125   EVT VT = N->getValueType(0);
7126   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7127     return SDValue();
7128
7129   // Check that the vector operands are of the right form.
7130   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7131   // operands, where N is the size of the formed vector.
7132   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7133   // index such that we have a pair wise add pattern.
7134
7135   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7136   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7137     return SDValue();
7138   SDValue Vec = N0->getOperand(0)->getOperand(0);
7139   SDNode *V = Vec.getNode();
7140   unsigned nextIndex = 0;
7141
7142   // For each operands to the ADD which are BUILD_VECTORs,
7143   // check to see if each of their operands are an EXTRACT_VECTOR with
7144   // the same vector and appropriate index.
7145   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7146     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7147         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7148
7149       SDValue ExtVec0 = N0->getOperand(i);
7150       SDValue ExtVec1 = N1->getOperand(i);
7151
7152       // First operand is the vector, verify its the same.
7153       if (V != ExtVec0->getOperand(0).getNode() ||
7154           V != ExtVec1->getOperand(0).getNode())
7155         return SDValue();
7156
7157       // Second is the constant, verify its correct.
7158       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7159       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7160
7161       // For the constant, we want to see all the even or all the odd.
7162       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7163           || C1->getZExtValue() != nextIndex+1)
7164         return SDValue();
7165
7166       // Increment index.
7167       nextIndex+=2;
7168     } else
7169       return SDValue();
7170   }
7171
7172   // Create VPADDL node.
7173   SelectionDAG &DAG = DCI.DAG;
7174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7175
7176   // Build operand list.
7177   SmallVector<SDValue, 8> Ops;
7178   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7179                                 TLI.getPointerTy()));
7180
7181   // Input is the vector.
7182   Ops.push_back(Vec);
7183
7184   // Get widened type and narrowed type.
7185   MVT widenType;
7186   unsigned numElem = VT.getVectorNumElements();
7187   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7188     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7189     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7190     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7191     default:
7192       llvm_unreachable("Invalid vector element type for padd optimization.");
7193   }
7194
7195   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7196                             widenType, &Ops[0], Ops.size());
7197   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7198 }
7199
7200 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7201 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7202 /// called with the default operands, and if that fails, with commuted
7203 /// operands.
7204 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7205                                           TargetLowering::DAGCombinerInfo &DCI,
7206                                           const ARMSubtarget *Subtarget){
7207
7208   // Attempt to create vpaddl for this add.
7209   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7210   if (Result.getNode())
7211     return Result;
7212
7213   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7214   if (N0.getNode()->hasOneUse()) {
7215     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7216     if (Result.getNode()) return Result;
7217   }
7218   return SDValue();
7219 }
7220
7221 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7222 ///
7223 static SDValue PerformADDCombine(SDNode *N,
7224                                  TargetLowering::DAGCombinerInfo &DCI,
7225                                  const ARMSubtarget *Subtarget) {
7226   SDValue N0 = N->getOperand(0);
7227   SDValue N1 = N->getOperand(1);
7228
7229   // First try with the default operand order.
7230   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7231   if (Result.getNode())
7232     return Result;
7233
7234   // If that didn't work, try again with the operands commuted.
7235   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7236 }
7237
7238 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7239 ///
7240 static SDValue PerformSUBCombine(SDNode *N,
7241                                  TargetLowering::DAGCombinerInfo &DCI) {
7242   SDValue N0 = N->getOperand(0);
7243   SDValue N1 = N->getOperand(1);
7244
7245   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7246   if (N1.getNode()->hasOneUse()) {
7247     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7248     if (Result.getNode()) return Result;
7249   }
7250
7251   return SDValue();
7252 }
7253
7254 /// PerformVMULCombine
7255 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7256 /// special multiplier accumulator forwarding.
7257 ///   vmul d3, d0, d2
7258 ///   vmla d3, d1, d2
7259 /// is faster than
7260 ///   vadd d3, d0, d1
7261 ///   vmul d3, d3, d2
7262 static SDValue PerformVMULCombine(SDNode *N,
7263                                   TargetLowering::DAGCombinerInfo &DCI,
7264                                   const ARMSubtarget *Subtarget) {
7265   if (!Subtarget->hasVMLxForwarding())
7266     return SDValue();
7267
7268   SelectionDAG &DAG = DCI.DAG;
7269   SDValue N0 = N->getOperand(0);
7270   SDValue N1 = N->getOperand(1);
7271   unsigned Opcode = N0.getOpcode();
7272   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7273       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7274     Opcode = N1.getOpcode();
7275     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7276         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7277       return SDValue();
7278     std::swap(N0, N1);
7279   }
7280
7281   EVT VT = N->getValueType(0);
7282   DebugLoc DL = N->getDebugLoc();
7283   SDValue N00 = N0->getOperand(0);
7284   SDValue N01 = N0->getOperand(1);
7285   return DAG.getNode(Opcode, DL, VT,
7286                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7287                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7288 }
7289
7290 static SDValue PerformMULCombine(SDNode *N,
7291                                  TargetLowering::DAGCombinerInfo &DCI,
7292                                  const ARMSubtarget *Subtarget) {
7293   SelectionDAG &DAG = DCI.DAG;
7294
7295   if (Subtarget->isThumb1Only())
7296     return SDValue();
7297
7298   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7299     return SDValue();
7300
7301   EVT VT = N->getValueType(0);
7302   if (VT.is64BitVector() || VT.is128BitVector())
7303     return PerformVMULCombine(N, DCI, Subtarget);
7304   if (VT != MVT::i32)
7305     return SDValue();
7306
7307   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7308   if (!C)
7309     return SDValue();
7310
7311   int64_t MulAmt = C->getSExtValue();
7312   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7313
7314   ShiftAmt = ShiftAmt & (32 - 1);
7315   SDValue V = N->getOperand(0);
7316   DebugLoc DL = N->getDebugLoc();
7317
7318   SDValue Res;
7319   MulAmt >>= ShiftAmt;
7320
7321   if (MulAmt >= 0) {
7322     if (isPowerOf2_32(MulAmt - 1)) {
7323       // (mul x, 2^N + 1) => (add (shl x, N), x)
7324       Res = DAG.getNode(ISD::ADD, DL, VT,
7325                         V,
7326                         DAG.getNode(ISD::SHL, DL, VT,
7327                                     V,
7328                                     DAG.getConstant(Log2_32(MulAmt - 1),
7329                                                     MVT::i32)));
7330     } else if (isPowerOf2_32(MulAmt + 1)) {
7331       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7332       Res = DAG.getNode(ISD::SUB, DL, VT,
7333                         DAG.getNode(ISD::SHL, DL, VT,
7334                                     V,
7335                                     DAG.getConstant(Log2_32(MulAmt + 1),
7336                                                     MVT::i32)),
7337                         V);
7338     } else
7339       return SDValue();
7340   } else {
7341     uint64_t MulAmtAbs = -MulAmt;
7342     if (isPowerOf2_32(MulAmtAbs + 1)) {
7343       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7344       Res = DAG.getNode(ISD::SUB, DL, VT,
7345                         V,
7346                         DAG.getNode(ISD::SHL, DL, VT,
7347                                     V,
7348                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7349                                                     MVT::i32)));
7350     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7351       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7352       Res = DAG.getNode(ISD::ADD, DL, VT,
7353                         V,
7354                         DAG.getNode(ISD::SHL, DL, VT,
7355                                     V,
7356                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7357                                                     MVT::i32)));
7358       Res = DAG.getNode(ISD::SUB, DL, VT,
7359                         DAG.getConstant(0, MVT::i32),Res);
7360
7361     } else
7362       return SDValue();
7363   }
7364
7365   if (ShiftAmt != 0)
7366     Res = DAG.getNode(ISD::SHL, DL, VT,
7367                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7368
7369   // Do not add new nodes to DAG combiner worklist.
7370   DCI.CombineTo(N, Res, false);
7371   return SDValue();
7372 }
7373
7374 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
7375   return N.getOpcode() == ARMISD::CMOV && N.getNode()->hasOneUse() &&
7376     isZeroOrAllOnes(N.getOperand(0), AllOnes);
7377 }
7378
7379 /// formConditionalOp - Combine an operation with a conditional move operand
7380 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7381 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7382 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7383                                  bool Commutable) {
7384   SDValue N0 = N->getOperand(0);
7385   SDValue N1 = N->getOperand(1);
7386
7387   bool isAND = N->getOpcode() == ISD::AND;
7388   bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7389   if (!isCand && Commutable) {
7390     isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7391     if (isCand)
7392       std::swap(N0, N1);
7393   }
7394   if (!isCand)
7395     return SDValue();
7396
7397   unsigned Opc = 0;
7398   switch (N->getOpcode()) {
7399   default: llvm_unreachable("Unexpected node");
7400   case ISD::AND: Opc = ARMISD::CAND; break;
7401   case ISD::OR:  Opc = ARMISD::COR; break;
7402   case ISD::XOR: Opc = ARMISD::CXOR; break;
7403   }
7404   return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7405                      N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7406                      N1.getOperand(4));
7407 }
7408
7409 static SDValue PerformANDCombine(SDNode *N,
7410                                  TargetLowering::DAGCombinerInfo &DCI,
7411                                  const ARMSubtarget *Subtarget) {
7412
7413   // Attempt to use immediate-form VBIC
7414   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7415   DebugLoc dl = N->getDebugLoc();
7416   EVT VT = N->getValueType(0);
7417   SelectionDAG &DAG = DCI.DAG;
7418
7419   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7420     return SDValue();
7421
7422   APInt SplatBits, SplatUndef;
7423   unsigned SplatBitSize;
7424   bool HasAnyUndefs;
7425   if (BVN &&
7426       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7427     if (SplatBitSize <= 64) {
7428       EVT VbicVT;
7429       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7430                                       SplatUndef.getZExtValue(), SplatBitSize,
7431                                       DAG, VbicVT, VT.is128BitVector(),
7432                                       OtherModImm);
7433       if (Val.getNode()) {
7434         SDValue Input =
7435           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7436         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7437         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7438       }
7439     }
7440   }
7441
7442   if (!Subtarget->isThumb1Only()) {
7443     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7444     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7445     if (Result.getNode())
7446       return Result;
7447     // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7448     SDValue CAND = formConditionalOp(N, DAG, true);
7449     if (CAND.getNode())
7450       return CAND;
7451   }
7452
7453   return SDValue();
7454 }
7455
7456 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7457 static SDValue PerformORCombine(SDNode *N,
7458                                 TargetLowering::DAGCombinerInfo &DCI,
7459                                 const ARMSubtarget *Subtarget) {
7460   // Attempt to use immediate-form VORR
7461   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7462   DebugLoc dl = N->getDebugLoc();
7463   EVT VT = N->getValueType(0);
7464   SelectionDAG &DAG = DCI.DAG;
7465
7466   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7467     return SDValue();
7468
7469   APInt SplatBits, SplatUndef;
7470   unsigned SplatBitSize;
7471   bool HasAnyUndefs;
7472   if (BVN && Subtarget->hasNEON() &&
7473       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7474     if (SplatBitSize <= 64) {
7475       EVT VorrVT;
7476       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7477                                       SplatUndef.getZExtValue(), SplatBitSize,
7478                                       DAG, VorrVT, VT.is128BitVector(),
7479                                       OtherModImm);
7480       if (Val.getNode()) {
7481         SDValue Input =
7482           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7483         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7484         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7485       }
7486     }
7487   }
7488
7489   if (!Subtarget->isThumb1Only()) {
7490     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7491     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7492     if (Result.getNode())
7493       return Result;
7494     // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7495     SDValue COR = formConditionalOp(N, DAG, true);
7496     if (COR.getNode())
7497       return COR;
7498   }
7499
7500
7501   // The code below optimizes (or (and X, Y), Z).
7502   // The AND operand needs to have a single user to make these optimizations
7503   // profitable.
7504   SDValue N0 = N->getOperand(0);
7505   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7506     return SDValue();
7507   SDValue N1 = N->getOperand(1);
7508
7509   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7510   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7511       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7512     APInt SplatUndef;
7513     unsigned SplatBitSize;
7514     bool HasAnyUndefs;
7515
7516     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7517     APInt SplatBits0;
7518     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7519                                   HasAnyUndefs) && !HasAnyUndefs) {
7520       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7521       APInt SplatBits1;
7522       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7523                                     HasAnyUndefs) && !HasAnyUndefs &&
7524           SplatBits0 == ~SplatBits1) {
7525         // Canonicalize the vector type to make instruction selection simpler.
7526         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7527         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7528                                      N0->getOperand(1), N0->getOperand(0),
7529                                      N1->getOperand(0));
7530         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7531       }
7532     }
7533   }
7534
7535   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7536   // reasonable.
7537
7538   // BFI is only available on V6T2+
7539   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7540     return SDValue();
7541
7542   DebugLoc DL = N->getDebugLoc();
7543   // 1) or (and A, mask), val => ARMbfi A, val, mask
7544   //      iff (val & mask) == val
7545   //
7546   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7547   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7548   //          && mask == ~mask2
7549   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7550   //          && ~mask == mask2
7551   //  (i.e., copy a bitfield value into another bitfield of the same width)
7552
7553   if (VT != MVT::i32)
7554     return SDValue();
7555
7556   SDValue N00 = N0.getOperand(0);
7557
7558   // The value and the mask need to be constants so we can verify this is
7559   // actually a bitfield set. If the mask is 0xffff, we can do better
7560   // via a movt instruction, so don't use BFI in that case.
7561   SDValue MaskOp = N0.getOperand(1);
7562   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7563   if (!MaskC)
7564     return SDValue();
7565   unsigned Mask = MaskC->getZExtValue();
7566   if (Mask == 0xffff)
7567     return SDValue();
7568   SDValue Res;
7569   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7570   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7571   if (N1C) {
7572     unsigned Val = N1C->getZExtValue();
7573     if ((Val & ~Mask) != Val)
7574       return SDValue();
7575
7576     if (ARM::isBitFieldInvertedMask(Mask)) {
7577       Val >>= CountTrailingZeros_32(~Mask);
7578
7579       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7580                         DAG.getConstant(Val, MVT::i32),
7581                         DAG.getConstant(Mask, MVT::i32));
7582
7583       // Do not add new nodes to DAG combiner worklist.
7584       DCI.CombineTo(N, Res, false);
7585       return SDValue();
7586     }
7587   } else if (N1.getOpcode() == ISD::AND) {
7588     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7589     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7590     if (!N11C)
7591       return SDValue();
7592     unsigned Mask2 = N11C->getZExtValue();
7593
7594     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7595     // as is to match.
7596     if (ARM::isBitFieldInvertedMask(Mask) &&
7597         (Mask == ~Mask2)) {
7598       // The pack halfword instruction works better for masks that fit it,
7599       // so use that when it's available.
7600       if (Subtarget->hasT2ExtractPack() &&
7601           (Mask == 0xffff || Mask == 0xffff0000))
7602         return SDValue();
7603       // 2a
7604       unsigned amt = CountTrailingZeros_32(Mask2);
7605       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7606                         DAG.getConstant(amt, MVT::i32));
7607       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7608                         DAG.getConstant(Mask, MVT::i32));
7609       // Do not add new nodes to DAG combiner worklist.
7610       DCI.CombineTo(N, Res, false);
7611       return SDValue();
7612     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7613                (~Mask == Mask2)) {
7614       // The pack halfword instruction works better for masks that fit it,
7615       // so use that when it's available.
7616       if (Subtarget->hasT2ExtractPack() &&
7617           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7618         return SDValue();
7619       // 2b
7620       unsigned lsb = CountTrailingZeros_32(Mask);
7621       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7622                         DAG.getConstant(lsb, MVT::i32));
7623       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7624                         DAG.getConstant(Mask2, MVT::i32));
7625       // Do not add new nodes to DAG combiner worklist.
7626       DCI.CombineTo(N, Res, false);
7627       return SDValue();
7628     }
7629   }
7630
7631   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7632       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7633       ARM::isBitFieldInvertedMask(~Mask)) {
7634     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7635     // where lsb(mask) == #shamt and masked bits of B are known zero.
7636     SDValue ShAmt = N00.getOperand(1);
7637     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7638     unsigned LSB = CountTrailingZeros_32(Mask);
7639     if (ShAmtC != LSB)
7640       return SDValue();
7641
7642     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7643                       DAG.getConstant(~Mask, MVT::i32));
7644
7645     // Do not add new nodes to DAG combiner worklist.
7646     DCI.CombineTo(N, Res, false);
7647   }
7648
7649   return SDValue();
7650 }
7651
7652 static SDValue PerformXORCombine(SDNode *N,
7653                                  TargetLowering::DAGCombinerInfo &DCI,
7654                                  const ARMSubtarget *Subtarget) {
7655   EVT VT = N->getValueType(0);
7656   SelectionDAG &DAG = DCI.DAG;
7657
7658   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7659     return SDValue();
7660
7661   if (!Subtarget->isThumb1Only()) {
7662     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7663     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7664     if (Result.getNode())
7665       return Result;
7666     // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7667     SDValue CXOR = formConditionalOp(N, DAG, true);
7668     if (CXOR.getNode())
7669       return CXOR;
7670   }
7671
7672   return SDValue();
7673 }
7674
7675 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7676 /// the bits being cleared by the AND are not demanded by the BFI.
7677 static SDValue PerformBFICombine(SDNode *N,
7678                                  TargetLowering::DAGCombinerInfo &DCI) {
7679   SDValue N1 = N->getOperand(1);
7680   if (N1.getOpcode() == ISD::AND) {
7681     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7682     if (!N11C)
7683       return SDValue();
7684     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7685     unsigned LSB = CountTrailingZeros_32(~InvMask);
7686     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7687     unsigned Mask = (1 << Width)-1;
7688     unsigned Mask2 = N11C->getZExtValue();
7689     if ((Mask & (~Mask2)) == 0)
7690       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7691                              N->getOperand(0), N1.getOperand(0),
7692                              N->getOperand(2));
7693   }
7694   return SDValue();
7695 }
7696
7697 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7698 /// ARMISD::VMOVRRD.
7699 static SDValue PerformVMOVRRDCombine(SDNode *N,
7700                                      TargetLowering::DAGCombinerInfo &DCI) {
7701   // vmovrrd(vmovdrr x, y) -> x,y
7702   SDValue InDouble = N->getOperand(0);
7703   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7704     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7705
7706   // vmovrrd(load f64) -> (load i32), (load i32)
7707   SDNode *InNode = InDouble.getNode();
7708   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7709       InNode->getValueType(0) == MVT::f64 &&
7710       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7711       !cast<LoadSDNode>(InNode)->isVolatile()) {
7712     // TODO: Should this be done for non-FrameIndex operands?
7713     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7714
7715     SelectionDAG &DAG = DCI.DAG;
7716     DebugLoc DL = LD->getDebugLoc();
7717     SDValue BasePtr = LD->getBasePtr();
7718     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7719                                  LD->getPointerInfo(), LD->isVolatile(),
7720                                  LD->isNonTemporal(), LD->isInvariant(),
7721                                  LD->getAlignment());
7722
7723     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7724                                     DAG.getConstant(4, MVT::i32));
7725     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7726                                  LD->getPointerInfo(), LD->isVolatile(),
7727                                  LD->isNonTemporal(), LD->isInvariant(),
7728                                  std::min(4U, LD->getAlignment() / 2));
7729
7730     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7731     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7732     DCI.RemoveFromWorklist(LD);
7733     DAG.DeleteNode(LD);
7734     return Result;
7735   }
7736
7737   return SDValue();
7738 }
7739
7740 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7741 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7742 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7743   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7744   SDValue Op0 = N->getOperand(0);
7745   SDValue Op1 = N->getOperand(1);
7746   if (Op0.getOpcode() == ISD::BITCAST)
7747     Op0 = Op0.getOperand(0);
7748   if (Op1.getOpcode() == ISD::BITCAST)
7749     Op1 = Op1.getOperand(0);
7750   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7751       Op0.getNode() == Op1.getNode() &&
7752       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7753     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7754                        N->getValueType(0), Op0.getOperand(0));
7755   return SDValue();
7756 }
7757
7758 /// PerformSTORECombine - Target-specific dag combine xforms for
7759 /// ISD::STORE.
7760 static SDValue PerformSTORECombine(SDNode *N,
7761                                    TargetLowering::DAGCombinerInfo &DCI) {
7762   StoreSDNode *St = cast<StoreSDNode>(N);
7763   if (St->isVolatile())
7764     return SDValue();
7765
7766   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
7767   // pack all of the elements in one place.  Next, store to memory in fewer
7768   // chunks.
7769   SDValue StVal = St->getValue();
7770   EVT VT = StVal.getValueType();
7771   if (St->isTruncatingStore() && VT.isVector()) {
7772     SelectionDAG &DAG = DCI.DAG;
7773     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7774     EVT StVT = St->getMemoryVT();
7775     unsigned NumElems = VT.getVectorNumElements();
7776     assert(StVT != VT && "Cannot truncate to the same type");
7777     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7778     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7779
7780     // From, To sizes and ElemCount must be pow of two
7781     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7782
7783     // We are going to use the original vector elt for storing.
7784     // Accumulated smaller vector elements must be a multiple of the store size.
7785     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7786
7787     unsigned SizeRatio  = FromEltSz / ToEltSz;
7788     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7789
7790     // Create a type on which we perform the shuffle.
7791     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7792                                      NumElems*SizeRatio);
7793     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7794
7795     DebugLoc DL = St->getDebugLoc();
7796     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7797     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7798     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7799
7800     // Can't shuffle using an illegal type.
7801     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7802
7803     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7804                                 DAG.getUNDEF(WideVec.getValueType()),
7805                                 ShuffleVec.data());
7806     // At this point all of the data is stored at the bottom of the
7807     // register. We now need to save it to mem.
7808
7809     // Find the largest store unit
7810     MVT StoreType = MVT::i8;
7811     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7812          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7813       MVT Tp = (MVT::SimpleValueType)tp;
7814       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7815         StoreType = Tp;
7816     }
7817     // Didn't find a legal store type.
7818     if (!TLI.isTypeLegal(StoreType))
7819       return SDValue();
7820
7821     // Bitcast the original vector into a vector of store-size units
7822     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7823             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7824     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7825     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7826     SmallVector<SDValue, 8> Chains;
7827     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7828                                         TLI.getPointerTy());
7829     SDValue BasePtr = St->getBasePtr();
7830
7831     // Perform one or more big stores into memory.
7832     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7833     for (unsigned I = 0; I < E; I++) {
7834       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7835                                    StoreType, ShuffWide,
7836                                    DAG.getIntPtrConstant(I));
7837       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7838                                 St->getPointerInfo(), St->isVolatile(),
7839                                 St->isNonTemporal(), St->getAlignment());
7840       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7841                             Increment);
7842       Chains.push_back(Ch);
7843     }
7844     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7845                        Chains.size());
7846   }
7847
7848   if (!ISD::isNormalStore(St))
7849     return SDValue();
7850
7851   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7852   // ARM stores of arguments in the same cache line.
7853   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7854       StVal.getNode()->hasOneUse()) {
7855     SelectionDAG  &DAG = DCI.DAG;
7856     DebugLoc DL = St->getDebugLoc();
7857     SDValue BasePtr = St->getBasePtr();
7858     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7859                                   StVal.getNode()->getOperand(0), BasePtr,
7860                                   St->getPointerInfo(), St->isVolatile(),
7861                                   St->isNonTemporal(), St->getAlignment());
7862
7863     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7864                                     DAG.getConstant(4, MVT::i32));
7865     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7866                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7867                         St->isNonTemporal(),
7868                         std::min(4U, St->getAlignment() / 2));
7869   }
7870
7871   if (StVal.getValueType() != MVT::i64 ||
7872       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7873     return SDValue();
7874
7875   // Bitcast an i64 store extracted from a vector to f64.
7876   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7877   SelectionDAG &DAG = DCI.DAG;
7878   DebugLoc dl = StVal.getDebugLoc();
7879   SDValue IntVec = StVal.getOperand(0);
7880   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7881                                  IntVec.getValueType().getVectorNumElements());
7882   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7883   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7884                                Vec, StVal.getOperand(1));
7885   dl = N->getDebugLoc();
7886   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7887   // Make the DAGCombiner fold the bitcasts.
7888   DCI.AddToWorklist(Vec.getNode());
7889   DCI.AddToWorklist(ExtElt.getNode());
7890   DCI.AddToWorklist(V.getNode());
7891   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7892                       St->getPointerInfo(), St->isVolatile(),
7893                       St->isNonTemporal(), St->getAlignment(),
7894                       St->getTBAAInfo());
7895 }
7896
7897 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7898 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7899 /// i64 vector to have f64 elements, since the value can then be loaded
7900 /// directly into a VFP register.
7901 static bool hasNormalLoadOperand(SDNode *N) {
7902   unsigned NumElts = N->getValueType(0).getVectorNumElements();
7903   for (unsigned i = 0; i < NumElts; ++i) {
7904     SDNode *Elt = N->getOperand(i).getNode();
7905     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7906       return true;
7907   }
7908   return false;
7909 }
7910
7911 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7912 /// ISD::BUILD_VECTOR.
7913 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7914                                           TargetLowering::DAGCombinerInfo &DCI){
7915   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7916   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7917   // into a pair of GPRs, which is fine when the value is used as a scalar,
7918   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7919   SelectionDAG &DAG = DCI.DAG;
7920   if (N->getNumOperands() == 2) {
7921     SDValue RV = PerformVMOVDRRCombine(N, DAG);
7922     if (RV.getNode())
7923       return RV;
7924   }
7925
7926   // Load i64 elements as f64 values so that type legalization does not split
7927   // them up into i32 values.
7928   EVT VT = N->getValueType(0);
7929   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7930     return SDValue();
7931   DebugLoc dl = N->getDebugLoc();
7932   SmallVector<SDValue, 8> Ops;
7933   unsigned NumElts = VT.getVectorNumElements();
7934   for (unsigned i = 0; i < NumElts; ++i) {
7935     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7936     Ops.push_back(V);
7937     // Make the DAGCombiner fold the bitcast.
7938     DCI.AddToWorklist(V.getNode());
7939   }
7940   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7941   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7942   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7943 }
7944
7945 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7946 /// ISD::INSERT_VECTOR_ELT.
7947 static SDValue PerformInsertEltCombine(SDNode *N,
7948                                        TargetLowering::DAGCombinerInfo &DCI) {
7949   // Bitcast an i64 load inserted into a vector to f64.
7950   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7951   EVT VT = N->getValueType(0);
7952   SDNode *Elt = N->getOperand(1).getNode();
7953   if (VT.getVectorElementType() != MVT::i64 ||
7954       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7955     return SDValue();
7956
7957   SelectionDAG &DAG = DCI.DAG;
7958   DebugLoc dl = N->getDebugLoc();
7959   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7960                                  VT.getVectorNumElements());
7961   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7962   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7963   // Make the DAGCombiner fold the bitcasts.
7964   DCI.AddToWorklist(Vec.getNode());
7965   DCI.AddToWorklist(V.getNode());
7966   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7967                                Vec, V, N->getOperand(2));
7968   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7969 }
7970
7971 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7972 /// ISD::VECTOR_SHUFFLE.
7973 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7974   // The LLVM shufflevector instruction does not require the shuffle mask
7975   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7976   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7977   // operands do not match the mask length, they are extended by concatenating
7978   // them with undef vectors.  That is probably the right thing for other
7979   // targets, but for NEON it is better to concatenate two double-register
7980   // size vector operands into a single quad-register size vector.  Do that
7981   // transformation here:
7982   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7983   //   shuffle(concat(v1, v2), undef)
7984   SDValue Op0 = N->getOperand(0);
7985   SDValue Op1 = N->getOperand(1);
7986   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7987       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7988       Op0.getNumOperands() != 2 ||
7989       Op1.getNumOperands() != 2)
7990     return SDValue();
7991   SDValue Concat0Op1 = Op0.getOperand(1);
7992   SDValue Concat1Op1 = Op1.getOperand(1);
7993   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7994       Concat1Op1.getOpcode() != ISD::UNDEF)
7995     return SDValue();
7996   // Skip the transformation if any of the types are illegal.
7997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7998   EVT VT = N->getValueType(0);
7999   if (!TLI.isTypeLegal(VT) ||
8000       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8001       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8002     return SDValue();
8003
8004   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8005                                   Op0.getOperand(0), Op1.getOperand(0));
8006   // Translate the shuffle mask.
8007   SmallVector<int, 16> NewMask;
8008   unsigned NumElts = VT.getVectorNumElements();
8009   unsigned HalfElts = NumElts/2;
8010   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8011   for (unsigned n = 0; n < NumElts; ++n) {
8012     int MaskElt = SVN->getMaskElt(n);
8013     int NewElt = -1;
8014     if (MaskElt < (int)HalfElts)
8015       NewElt = MaskElt;
8016     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8017       NewElt = HalfElts + MaskElt - NumElts;
8018     NewMask.push_back(NewElt);
8019   }
8020   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8021                               DAG.getUNDEF(VT), NewMask.data());
8022 }
8023
8024 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8025 /// NEON load/store intrinsics to merge base address updates.
8026 static SDValue CombineBaseUpdate(SDNode *N,
8027                                  TargetLowering::DAGCombinerInfo &DCI) {
8028   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8029     return SDValue();
8030
8031   SelectionDAG &DAG = DCI.DAG;
8032   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8033                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8034   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8035   SDValue Addr = N->getOperand(AddrOpIdx);
8036
8037   // Search for a use of the address operand that is an increment.
8038   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8039          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8040     SDNode *User = *UI;
8041     if (User->getOpcode() != ISD::ADD ||
8042         UI.getUse().getResNo() != Addr.getResNo())
8043       continue;
8044
8045     // Check that the add is independent of the load/store.  Otherwise, folding
8046     // it would create a cycle.
8047     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8048       continue;
8049
8050     // Find the new opcode for the updating load/store.
8051     bool isLoad = true;
8052     bool isLaneOp = false;
8053     unsigned NewOpc = 0;
8054     unsigned NumVecs = 0;
8055     if (isIntrinsic) {
8056       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8057       switch (IntNo) {
8058       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8059       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8060         NumVecs = 1; break;
8061       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8062         NumVecs = 2; break;
8063       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8064         NumVecs = 3; break;
8065       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8066         NumVecs = 4; break;
8067       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8068         NumVecs = 2; isLaneOp = true; break;
8069       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8070         NumVecs = 3; isLaneOp = true; break;
8071       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8072         NumVecs = 4; isLaneOp = true; break;
8073       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8074         NumVecs = 1; isLoad = false; break;
8075       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8076         NumVecs = 2; isLoad = false; break;
8077       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8078         NumVecs = 3; isLoad = false; break;
8079       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8080         NumVecs = 4; isLoad = false; break;
8081       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8082         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8083       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8084         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8085       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8086         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8087       }
8088     } else {
8089       isLaneOp = true;
8090       switch (N->getOpcode()) {
8091       default: llvm_unreachable("unexpected opcode for Neon base update");
8092       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8093       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8094       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8095       }
8096     }
8097
8098     // Find the size of memory referenced by the load/store.
8099     EVT VecTy;
8100     if (isLoad)
8101       VecTy = N->getValueType(0);
8102     else
8103       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8104     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8105     if (isLaneOp)
8106       NumBytes /= VecTy.getVectorNumElements();
8107
8108     // If the increment is a constant, it must match the memory ref size.
8109     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8110     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8111       uint64_t IncVal = CInc->getZExtValue();
8112       if (IncVal != NumBytes)
8113         continue;
8114     } else if (NumBytes >= 3 * 16) {
8115       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8116       // separate instructions that make it harder to use a non-constant update.
8117       continue;
8118     }
8119
8120     // Create the new updating load/store node.
8121     EVT Tys[6];
8122     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8123     unsigned n;
8124     for (n = 0; n < NumResultVecs; ++n)
8125       Tys[n] = VecTy;
8126     Tys[n++] = MVT::i32;
8127     Tys[n] = MVT::Other;
8128     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8129     SmallVector<SDValue, 8> Ops;
8130     Ops.push_back(N->getOperand(0)); // incoming chain
8131     Ops.push_back(N->getOperand(AddrOpIdx));
8132     Ops.push_back(Inc);
8133     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8134       Ops.push_back(N->getOperand(i));
8135     }
8136     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8137     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8138                                            Ops.data(), Ops.size(),
8139                                            MemInt->getMemoryVT(),
8140                                            MemInt->getMemOperand());
8141
8142     // Update the uses.
8143     std::vector<SDValue> NewResults;
8144     for (unsigned i = 0; i < NumResultVecs; ++i) {
8145       NewResults.push_back(SDValue(UpdN.getNode(), i));
8146     }
8147     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8148     DCI.CombineTo(N, NewResults);
8149     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8150
8151     break;
8152   }
8153   return SDValue();
8154 }
8155
8156 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8157 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8158 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8159 /// return true.
8160 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8161   SelectionDAG &DAG = DCI.DAG;
8162   EVT VT = N->getValueType(0);
8163   // vldN-dup instructions only support 64-bit vectors for N > 1.
8164   if (!VT.is64BitVector())
8165     return false;
8166
8167   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8168   SDNode *VLD = N->getOperand(0).getNode();
8169   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8170     return false;
8171   unsigned NumVecs = 0;
8172   unsigned NewOpc = 0;
8173   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8174   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8175     NumVecs = 2;
8176     NewOpc = ARMISD::VLD2DUP;
8177   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8178     NumVecs = 3;
8179     NewOpc = ARMISD::VLD3DUP;
8180   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8181     NumVecs = 4;
8182     NewOpc = ARMISD::VLD4DUP;
8183   } else {
8184     return false;
8185   }
8186
8187   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8188   // numbers match the load.
8189   unsigned VLDLaneNo =
8190     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8191   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8192        UI != UE; ++UI) {
8193     // Ignore uses of the chain result.
8194     if (UI.getUse().getResNo() == NumVecs)
8195       continue;
8196     SDNode *User = *UI;
8197     if (User->getOpcode() != ARMISD::VDUPLANE ||
8198         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8199       return false;
8200   }
8201
8202   // Create the vldN-dup node.
8203   EVT Tys[5];
8204   unsigned n;
8205   for (n = 0; n < NumVecs; ++n)
8206     Tys[n] = VT;
8207   Tys[n] = MVT::Other;
8208   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8209   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8210   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8211   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8212                                            Ops, 2, VLDMemInt->getMemoryVT(),
8213                                            VLDMemInt->getMemOperand());
8214
8215   // Update the uses.
8216   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8217        UI != UE; ++UI) {
8218     unsigned ResNo = UI.getUse().getResNo();
8219     // Ignore uses of the chain result.
8220     if (ResNo == NumVecs)
8221       continue;
8222     SDNode *User = *UI;
8223     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8224   }
8225
8226   // Now the vldN-lane intrinsic is dead except for its chain result.
8227   // Update uses of the chain.
8228   std::vector<SDValue> VLDDupResults;
8229   for (unsigned n = 0; n < NumVecs; ++n)
8230     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8231   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8232   DCI.CombineTo(VLD, VLDDupResults);
8233
8234   return true;
8235 }
8236
8237 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8238 /// ARMISD::VDUPLANE.
8239 static SDValue PerformVDUPLANECombine(SDNode *N,
8240                                       TargetLowering::DAGCombinerInfo &DCI) {
8241   SDValue Op = N->getOperand(0);
8242
8243   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8244   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8245   if (CombineVLDDUP(N, DCI))
8246     return SDValue(N, 0);
8247
8248   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8249   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8250   while (Op.getOpcode() == ISD::BITCAST)
8251     Op = Op.getOperand(0);
8252   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8253     return SDValue();
8254
8255   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8256   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8257   // The canonical VMOV for a zero vector uses a 32-bit element size.
8258   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8259   unsigned EltBits;
8260   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8261     EltSize = 8;
8262   EVT VT = N->getValueType(0);
8263   if (EltSize > VT.getVectorElementType().getSizeInBits())
8264     return SDValue();
8265
8266   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8267 }
8268
8269 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8270 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8271 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8272 {
8273   integerPart cN;
8274   integerPart c0 = 0;
8275   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8276        I != E; I++) {
8277     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8278     if (!C)
8279       return false;
8280
8281     bool isExact;
8282     APFloat APF = C->getValueAPF();
8283     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8284         != APFloat::opOK || !isExact)
8285       return false;
8286
8287     c0 = (I == 0) ? cN : c0;
8288     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8289       return false;
8290   }
8291   C = c0;
8292   return true;
8293 }
8294
8295 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8296 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8297 /// when the VMUL has a constant operand that is a power of 2.
8298 ///
8299 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8300 ///  vmul.f32        d16, d17, d16
8301 ///  vcvt.s32.f32    d16, d16
8302 /// becomes:
8303 ///  vcvt.s32.f32    d16, d16, #3
8304 static SDValue PerformVCVTCombine(SDNode *N,
8305                                   TargetLowering::DAGCombinerInfo &DCI,
8306                                   const ARMSubtarget *Subtarget) {
8307   SelectionDAG &DAG = DCI.DAG;
8308   SDValue Op = N->getOperand(0);
8309
8310   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8311       Op.getOpcode() != ISD::FMUL)
8312     return SDValue();
8313
8314   uint64_t C;
8315   SDValue N0 = Op->getOperand(0);
8316   SDValue ConstVec = Op->getOperand(1);
8317   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8318
8319   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8320       !isConstVecPow2(ConstVec, isSigned, C))
8321     return SDValue();
8322
8323   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8324     Intrinsic::arm_neon_vcvtfp2fxu;
8325   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8326                      N->getValueType(0),
8327                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8328                      DAG.getConstant(Log2_64(C), MVT::i32));
8329 }
8330
8331 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8332 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8333 /// when the VDIV has a constant operand that is a power of 2.
8334 ///
8335 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8336 ///  vcvt.f32.s32    d16, d16
8337 ///  vdiv.f32        d16, d17, d16
8338 /// becomes:
8339 ///  vcvt.f32.s32    d16, d16, #3
8340 static SDValue PerformVDIVCombine(SDNode *N,
8341                                   TargetLowering::DAGCombinerInfo &DCI,
8342                                   const ARMSubtarget *Subtarget) {
8343   SelectionDAG &DAG = DCI.DAG;
8344   SDValue Op = N->getOperand(0);
8345   unsigned OpOpcode = Op.getNode()->getOpcode();
8346
8347   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8348       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8349     return SDValue();
8350
8351   uint64_t C;
8352   SDValue ConstVec = N->getOperand(1);
8353   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8354
8355   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8356       !isConstVecPow2(ConstVec, isSigned, C))
8357     return SDValue();
8358
8359   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8360     Intrinsic::arm_neon_vcvtfxu2fp;
8361   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8362                      Op.getValueType(),
8363                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8364                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8365 }
8366
8367 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8368 /// operand of a vector shift operation, where all the elements of the
8369 /// build_vector must have the same constant integer value.
8370 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8371   // Ignore bit_converts.
8372   while (Op.getOpcode() == ISD::BITCAST)
8373     Op = Op.getOperand(0);
8374   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8375   APInt SplatBits, SplatUndef;
8376   unsigned SplatBitSize;
8377   bool HasAnyUndefs;
8378   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8379                                       HasAnyUndefs, ElementBits) ||
8380       SplatBitSize > ElementBits)
8381     return false;
8382   Cnt = SplatBits.getSExtValue();
8383   return true;
8384 }
8385
8386 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8387 /// operand of a vector shift left operation.  That value must be in the range:
8388 ///   0 <= Value < ElementBits for a left shift; or
8389 ///   0 <= Value <= ElementBits for a long left shift.
8390 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8391   assert(VT.isVector() && "vector shift count is not a vector type");
8392   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8393   if (! getVShiftImm(Op, ElementBits, Cnt))
8394     return false;
8395   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8396 }
8397
8398 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8399 /// operand of a vector shift right operation.  For a shift opcode, the value
8400 /// is positive, but for an intrinsic the value count must be negative. The
8401 /// absolute value must be in the range:
8402 ///   1 <= |Value| <= ElementBits for a right shift; or
8403 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8404 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8405                          int64_t &Cnt) {
8406   assert(VT.isVector() && "vector shift count is not a vector type");
8407   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8408   if (! getVShiftImm(Op, ElementBits, Cnt))
8409     return false;
8410   if (isIntrinsic)
8411     Cnt = -Cnt;
8412   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8413 }
8414
8415 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8416 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8417   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8418   switch (IntNo) {
8419   default:
8420     // Don't do anything for most intrinsics.
8421     break;
8422
8423   // Vector shifts: check for immediate versions and lower them.
8424   // Note: This is done during DAG combining instead of DAG legalizing because
8425   // the build_vectors for 64-bit vector element shift counts are generally
8426   // not legal, and it is hard to see their values after they get legalized to
8427   // loads from a constant pool.
8428   case Intrinsic::arm_neon_vshifts:
8429   case Intrinsic::arm_neon_vshiftu:
8430   case Intrinsic::arm_neon_vshiftls:
8431   case Intrinsic::arm_neon_vshiftlu:
8432   case Intrinsic::arm_neon_vshiftn:
8433   case Intrinsic::arm_neon_vrshifts:
8434   case Intrinsic::arm_neon_vrshiftu:
8435   case Intrinsic::arm_neon_vrshiftn:
8436   case Intrinsic::arm_neon_vqshifts:
8437   case Intrinsic::arm_neon_vqshiftu:
8438   case Intrinsic::arm_neon_vqshiftsu:
8439   case Intrinsic::arm_neon_vqshiftns:
8440   case Intrinsic::arm_neon_vqshiftnu:
8441   case Intrinsic::arm_neon_vqshiftnsu:
8442   case Intrinsic::arm_neon_vqrshiftns:
8443   case Intrinsic::arm_neon_vqrshiftnu:
8444   case Intrinsic::arm_neon_vqrshiftnsu: {
8445     EVT VT = N->getOperand(1).getValueType();
8446     int64_t Cnt;
8447     unsigned VShiftOpc = 0;
8448
8449     switch (IntNo) {
8450     case Intrinsic::arm_neon_vshifts:
8451     case Intrinsic::arm_neon_vshiftu:
8452       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8453         VShiftOpc = ARMISD::VSHL;
8454         break;
8455       }
8456       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8457         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8458                      ARMISD::VSHRs : ARMISD::VSHRu);
8459         break;
8460       }
8461       return SDValue();
8462
8463     case Intrinsic::arm_neon_vshiftls:
8464     case Intrinsic::arm_neon_vshiftlu:
8465       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8466         break;
8467       llvm_unreachable("invalid shift count for vshll intrinsic");
8468
8469     case Intrinsic::arm_neon_vrshifts:
8470     case Intrinsic::arm_neon_vrshiftu:
8471       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8472         break;
8473       return SDValue();
8474
8475     case Intrinsic::arm_neon_vqshifts:
8476     case Intrinsic::arm_neon_vqshiftu:
8477       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8478         break;
8479       return SDValue();
8480
8481     case Intrinsic::arm_neon_vqshiftsu:
8482       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8483         break;
8484       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8485
8486     case Intrinsic::arm_neon_vshiftn:
8487     case Intrinsic::arm_neon_vrshiftn:
8488     case Intrinsic::arm_neon_vqshiftns:
8489     case Intrinsic::arm_neon_vqshiftnu:
8490     case Intrinsic::arm_neon_vqshiftnsu:
8491     case Intrinsic::arm_neon_vqrshiftns:
8492     case Intrinsic::arm_neon_vqrshiftnu:
8493     case Intrinsic::arm_neon_vqrshiftnsu:
8494       // Narrowing shifts require an immediate right shift.
8495       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8496         break;
8497       llvm_unreachable("invalid shift count for narrowing vector shift "
8498                        "intrinsic");
8499
8500     default:
8501       llvm_unreachable("unhandled vector shift");
8502     }
8503
8504     switch (IntNo) {
8505     case Intrinsic::arm_neon_vshifts:
8506     case Intrinsic::arm_neon_vshiftu:
8507       // Opcode already set above.
8508       break;
8509     case Intrinsic::arm_neon_vshiftls:
8510     case Intrinsic::arm_neon_vshiftlu:
8511       if (Cnt == VT.getVectorElementType().getSizeInBits())
8512         VShiftOpc = ARMISD::VSHLLi;
8513       else
8514         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8515                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8516       break;
8517     case Intrinsic::arm_neon_vshiftn:
8518       VShiftOpc = ARMISD::VSHRN; break;
8519     case Intrinsic::arm_neon_vrshifts:
8520       VShiftOpc = ARMISD::VRSHRs; break;
8521     case Intrinsic::arm_neon_vrshiftu:
8522       VShiftOpc = ARMISD::VRSHRu; break;
8523     case Intrinsic::arm_neon_vrshiftn:
8524       VShiftOpc = ARMISD::VRSHRN; break;
8525     case Intrinsic::arm_neon_vqshifts:
8526       VShiftOpc = ARMISD::VQSHLs; break;
8527     case Intrinsic::arm_neon_vqshiftu:
8528       VShiftOpc = ARMISD::VQSHLu; break;
8529     case Intrinsic::arm_neon_vqshiftsu:
8530       VShiftOpc = ARMISD::VQSHLsu; break;
8531     case Intrinsic::arm_neon_vqshiftns:
8532       VShiftOpc = ARMISD::VQSHRNs; break;
8533     case Intrinsic::arm_neon_vqshiftnu:
8534       VShiftOpc = ARMISD::VQSHRNu; break;
8535     case Intrinsic::arm_neon_vqshiftnsu:
8536       VShiftOpc = ARMISD::VQSHRNsu; break;
8537     case Intrinsic::arm_neon_vqrshiftns:
8538       VShiftOpc = ARMISD::VQRSHRNs; break;
8539     case Intrinsic::arm_neon_vqrshiftnu:
8540       VShiftOpc = ARMISD::VQRSHRNu; break;
8541     case Intrinsic::arm_neon_vqrshiftnsu:
8542       VShiftOpc = ARMISD::VQRSHRNsu; break;
8543     }
8544
8545     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8546                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8547   }
8548
8549   case Intrinsic::arm_neon_vshiftins: {
8550     EVT VT = N->getOperand(1).getValueType();
8551     int64_t Cnt;
8552     unsigned VShiftOpc = 0;
8553
8554     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8555       VShiftOpc = ARMISD::VSLI;
8556     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8557       VShiftOpc = ARMISD::VSRI;
8558     else {
8559       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8560     }
8561
8562     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8563                        N->getOperand(1), N->getOperand(2),
8564                        DAG.getConstant(Cnt, MVT::i32));
8565   }
8566
8567   case Intrinsic::arm_neon_vqrshifts:
8568   case Intrinsic::arm_neon_vqrshiftu:
8569     // No immediate versions of these to check for.
8570     break;
8571   }
8572
8573   return SDValue();
8574 }
8575
8576 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8577 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8578 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8579 /// vector element shift counts are generally not legal, and it is hard to see
8580 /// their values after they get legalized to loads from a constant pool.
8581 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8582                                    const ARMSubtarget *ST) {
8583   EVT VT = N->getValueType(0);
8584   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8585     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8586     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8587     SDValue N1 = N->getOperand(1);
8588     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8589       SDValue N0 = N->getOperand(0);
8590       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8591           DAG.MaskedValueIsZero(N0.getOperand(0),
8592                                 APInt::getHighBitsSet(32, 16)))
8593         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8594     }
8595   }
8596
8597   // Nothing to be done for scalar shifts.
8598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8599   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8600     return SDValue();
8601
8602   assert(ST->hasNEON() && "unexpected vector shift");
8603   int64_t Cnt;
8604
8605   switch (N->getOpcode()) {
8606   default: llvm_unreachable("unexpected shift opcode");
8607
8608   case ISD::SHL:
8609     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8610       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8611                          DAG.getConstant(Cnt, MVT::i32));
8612     break;
8613
8614   case ISD::SRA:
8615   case ISD::SRL:
8616     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8617       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8618                             ARMISD::VSHRs : ARMISD::VSHRu);
8619       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8620                          DAG.getConstant(Cnt, MVT::i32));
8621     }
8622   }
8623   return SDValue();
8624 }
8625
8626 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8627 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8628 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8629                                     const ARMSubtarget *ST) {
8630   SDValue N0 = N->getOperand(0);
8631
8632   // Check for sign- and zero-extensions of vector extract operations of 8-
8633   // and 16-bit vector elements.  NEON supports these directly.  They are
8634   // handled during DAG combining because type legalization will promote them
8635   // to 32-bit types and it is messy to recognize the operations after that.
8636   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8637     SDValue Vec = N0.getOperand(0);
8638     SDValue Lane = N0.getOperand(1);
8639     EVT VT = N->getValueType(0);
8640     EVT EltVT = N0.getValueType();
8641     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8642
8643     if (VT == MVT::i32 &&
8644         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8645         TLI.isTypeLegal(Vec.getValueType()) &&
8646         isa<ConstantSDNode>(Lane)) {
8647
8648       unsigned Opc = 0;
8649       switch (N->getOpcode()) {
8650       default: llvm_unreachable("unexpected opcode");
8651       case ISD::SIGN_EXTEND:
8652         Opc = ARMISD::VGETLANEs;
8653         break;
8654       case ISD::ZERO_EXTEND:
8655       case ISD::ANY_EXTEND:
8656         Opc = ARMISD::VGETLANEu;
8657         break;
8658       }
8659       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8660     }
8661   }
8662
8663   return SDValue();
8664 }
8665
8666 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8667 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8668 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8669                                        const ARMSubtarget *ST) {
8670   // If the target supports NEON, try to use vmax/vmin instructions for f32
8671   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8672   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8673   // a NaN; only do the transformation when it matches that behavior.
8674
8675   // For now only do this when using NEON for FP operations; if using VFP, it
8676   // is not obvious that the benefit outweighs the cost of switching to the
8677   // NEON pipeline.
8678   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8679       N->getValueType(0) != MVT::f32)
8680     return SDValue();
8681
8682   SDValue CondLHS = N->getOperand(0);
8683   SDValue CondRHS = N->getOperand(1);
8684   SDValue LHS = N->getOperand(2);
8685   SDValue RHS = N->getOperand(3);
8686   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8687
8688   unsigned Opcode = 0;
8689   bool IsReversed;
8690   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8691     IsReversed = false; // x CC y ? x : y
8692   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8693     IsReversed = true ; // x CC y ? y : x
8694   } else {
8695     return SDValue();
8696   }
8697
8698   bool IsUnordered;
8699   switch (CC) {
8700   default: break;
8701   case ISD::SETOLT:
8702   case ISD::SETOLE:
8703   case ISD::SETLT:
8704   case ISD::SETLE:
8705   case ISD::SETULT:
8706   case ISD::SETULE:
8707     // If LHS is NaN, an ordered comparison will be false and the result will
8708     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8709     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8710     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8711     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8712       break;
8713     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8714     // will return -0, so vmin can only be used for unsafe math or if one of
8715     // the operands is known to be nonzero.
8716     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8717         !DAG.getTarget().Options.UnsafeFPMath &&
8718         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8719       break;
8720     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8721     break;
8722
8723   case ISD::SETOGT:
8724   case ISD::SETOGE:
8725   case ISD::SETGT:
8726   case ISD::SETGE:
8727   case ISD::SETUGT:
8728   case ISD::SETUGE:
8729     // If LHS is NaN, an ordered comparison will be false and the result will
8730     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8731     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8732     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8733     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8734       break;
8735     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8736     // will return +0, so vmax can only be used for unsafe math or if one of
8737     // the operands is known to be nonzero.
8738     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8739         !DAG.getTarget().Options.UnsafeFPMath &&
8740         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8741       break;
8742     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8743     break;
8744   }
8745
8746   if (!Opcode)
8747     return SDValue();
8748   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8749 }
8750
8751 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8752 SDValue
8753 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8754   SDValue Cmp = N->getOperand(4);
8755   if (Cmp.getOpcode() != ARMISD::CMPZ)
8756     // Only looking at EQ and NE cases.
8757     return SDValue();
8758
8759   EVT VT = N->getValueType(0);
8760   DebugLoc dl = N->getDebugLoc();
8761   SDValue LHS = Cmp.getOperand(0);
8762   SDValue RHS = Cmp.getOperand(1);
8763   SDValue FalseVal = N->getOperand(0);
8764   SDValue TrueVal = N->getOperand(1);
8765   SDValue ARMcc = N->getOperand(2);
8766   ARMCC::CondCodes CC =
8767     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8768
8769   // Simplify
8770   //   mov     r1, r0
8771   //   cmp     r1, x
8772   //   mov     r0, y
8773   //   moveq   r0, x
8774   // to
8775   //   cmp     r0, x
8776   //   movne   r0, y
8777   //
8778   //   mov     r1, r0
8779   //   cmp     r1, x
8780   //   mov     r0, x
8781   //   movne   r0, y
8782   // to
8783   //   cmp     r0, x
8784   //   movne   r0, y
8785   /// FIXME: Turn this into a target neutral optimization?
8786   SDValue Res;
8787   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8788     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8789                       N->getOperand(3), Cmp);
8790   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8791     SDValue ARMcc;
8792     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8793     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8794                       N->getOperand(3), NewCmp);
8795   }
8796
8797   if (Res.getNode()) {
8798     APInt KnownZero, KnownOne;
8799     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8800     // Capture demanded bits information that would be otherwise lost.
8801     if (KnownZero == 0xfffffffe)
8802       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8803                         DAG.getValueType(MVT::i1));
8804     else if (KnownZero == 0xffffff00)
8805       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8806                         DAG.getValueType(MVT::i8));
8807     else if (KnownZero == 0xffff0000)
8808       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8809                         DAG.getValueType(MVT::i16));
8810   }
8811
8812   return Res;
8813 }
8814
8815 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8816                                              DAGCombinerInfo &DCI) const {
8817   switch (N->getOpcode()) {
8818   default: break;
8819   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8820   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8821   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8822   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8823   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8824   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8825   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8826   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8827   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8828   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8829   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8830   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8831   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8832   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8833   case ISD::FP_TO_SINT:
8834   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8835   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8836   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8837   case ISD::SHL:
8838   case ISD::SRA:
8839   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8840   case ISD::SIGN_EXTEND:
8841   case ISD::ZERO_EXTEND:
8842   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8843   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8844   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8845   case ARMISD::VLD2DUP:
8846   case ARMISD::VLD3DUP:
8847   case ARMISD::VLD4DUP:
8848     return CombineBaseUpdate(N, DCI);
8849   case ISD::INTRINSIC_VOID:
8850   case ISD::INTRINSIC_W_CHAIN:
8851     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8852     case Intrinsic::arm_neon_vld1:
8853     case Intrinsic::arm_neon_vld2:
8854     case Intrinsic::arm_neon_vld3:
8855     case Intrinsic::arm_neon_vld4:
8856     case Intrinsic::arm_neon_vld2lane:
8857     case Intrinsic::arm_neon_vld3lane:
8858     case Intrinsic::arm_neon_vld4lane:
8859     case Intrinsic::arm_neon_vst1:
8860     case Intrinsic::arm_neon_vst2:
8861     case Intrinsic::arm_neon_vst3:
8862     case Intrinsic::arm_neon_vst4:
8863     case Intrinsic::arm_neon_vst2lane:
8864     case Intrinsic::arm_neon_vst3lane:
8865     case Intrinsic::arm_neon_vst4lane:
8866       return CombineBaseUpdate(N, DCI);
8867     default: break;
8868     }
8869     break;
8870   }
8871   return SDValue();
8872 }
8873
8874 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8875                                                           EVT VT) const {
8876   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8877 }
8878
8879 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8880   if (!Subtarget->allowsUnalignedMem())
8881     return false;
8882
8883   switch (VT.getSimpleVT().SimpleTy) {
8884   default:
8885     return false;
8886   case MVT::i8:
8887   case MVT::i16:
8888   case MVT::i32:
8889     return true;
8890   case MVT::f64:
8891     return Subtarget->hasNEON();
8892   // FIXME: VLD1 etc with standard alignment is legal.
8893   }
8894 }
8895
8896 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8897                        unsigned AlignCheck) {
8898   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8899           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8900 }
8901
8902 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8903                                            unsigned DstAlign, unsigned SrcAlign,
8904                                            bool IsZeroVal,
8905                                            bool MemcpyStrSrc,
8906                                            MachineFunction &MF) const {
8907   const Function *F = MF.getFunction();
8908
8909   // See if we can use NEON instructions for this...
8910   if (IsZeroVal &&
8911       !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8912       Subtarget->hasNEON()) {
8913     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8914       return MVT::v4i32;
8915     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8916       return MVT::v2i32;
8917     }
8918   }
8919
8920   // Lowering to i32/i16 if the size permits.
8921   if (Size >= 4) {
8922     return MVT::i32;
8923   } else if (Size >= 2) {
8924     return MVT::i16;
8925   }
8926
8927   // Let the target-independent logic figure it out.
8928   return MVT::Other;
8929 }
8930
8931 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8932   if (V < 0)
8933     return false;
8934
8935   unsigned Scale = 1;
8936   switch (VT.getSimpleVT().SimpleTy) {
8937   default: return false;
8938   case MVT::i1:
8939   case MVT::i8:
8940     // Scale == 1;
8941     break;
8942   case MVT::i16:
8943     // Scale == 2;
8944     Scale = 2;
8945     break;
8946   case MVT::i32:
8947     // Scale == 4;
8948     Scale = 4;
8949     break;
8950   }
8951
8952   if ((V & (Scale - 1)) != 0)
8953     return false;
8954   V /= Scale;
8955   return V == (V & ((1LL << 5) - 1));
8956 }
8957
8958 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8959                                       const ARMSubtarget *Subtarget) {
8960   bool isNeg = false;
8961   if (V < 0) {
8962     isNeg = true;
8963     V = - V;
8964   }
8965
8966   switch (VT.getSimpleVT().SimpleTy) {
8967   default: return false;
8968   case MVT::i1:
8969   case MVT::i8:
8970   case MVT::i16:
8971   case MVT::i32:
8972     // + imm12 or - imm8
8973     if (isNeg)
8974       return V == (V & ((1LL << 8) - 1));
8975     return V == (V & ((1LL << 12) - 1));
8976   case MVT::f32:
8977   case MVT::f64:
8978     // Same as ARM mode. FIXME: NEON?
8979     if (!Subtarget->hasVFP2())
8980       return false;
8981     if ((V & 3) != 0)
8982       return false;
8983     V >>= 2;
8984     return V == (V & ((1LL << 8) - 1));
8985   }
8986 }
8987
8988 /// isLegalAddressImmediate - Return true if the integer value can be used
8989 /// as the offset of the target addressing mode for load / store of the
8990 /// given type.
8991 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8992                                     const ARMSubtarget *Subtarget) {
8993   if (V == 0)
8994     return true;
8995
8996   if (!VT.isSimple())
8997     return false;
8998
8999   if (Subtarget->isThumb1Only())
9000     return isLegalT1AddressImmediate(V, VT);
9001   else if (Subtarget->isThumb2())
9002     return isLegalT2AddressImmediate(V, VT, Subtarget);
9003
9004   // ARM mode.
9005   if (V < 0)
9006     V = - V;
9007   switch (VT.getSimpleVT().SimpleTy) {
9008   default: return false;
9009   case MVT::i1:
9010   case MVT::i8:
9011   case MVT::i32:
9012     // +- imm12
9013     return V == (V & ((1LL << 12) - 1));
9014   case MVT::i16:
9015     // +- imm8
9016     return V == (V & ((1LL << 8) - 1));
9017   case MVT::f32:
9018   case MVT::f64:
9019     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9020       return false;
9021     if ((V & 3) != 0)
9022       return false;
9023     V >>= 2;
9024     return V == (V & ((1LL << 8) - 1));
9025   }
9026 }
9027
9028 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9029                                                       EVT VT) const {
9030   int Scale = AM.Scale;
9031   if (Scale < 0)
9032     return false;
9033
9034   switch (VT.getSimpleVT().SimpleTy) {
9035   default: return false;
9036   case MVT::i1:
9037   case MVT::i8:
9038   case MVT::i16:
9039   case MVT::i32:
9040     if (Scale == 1)
9041       return true;
9042     // r + r << imm
9043     Scale = Scale & ~1;
9044     return Scale == 2 || Scale == 4 || Scale == 8;
9045   case MVT::i64:
9046     // r + r
9047     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9048       return true;
9049     return false;
9050   case MVT::isVoid:
9051     // Note, we allow "void" uses (basically, uses that aren't loads or
9052     // stores), because arm allows folding a scale into many arithmetic
9053     // operations.  This should be made more precise and revisited later.
9054
9055     // Allow r << imm, but the imm has to be a multiple of two.
9056     if (Scale & 1) return false;
9057     return isPowerOf2_32(Scale);
9058   }
9059 }
9060
9061 /// isLegalAddressingMode - Return true if the addressing mode represented
9062 /// by AM is legal for this target, for a load/store of the specified type.
9063 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9064                                               Type *Ty) const {
9065   EVT VT = getValueType(Ty, true);
9066   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9067     return false;
9068
9069   // Can never fold addr of global into load/store.
9070   if (AM.BaseGV)
9071     return false;
9072
9073   switch (AM.Scale) {
9074   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9075     break;
9076   case 1:
9077     if (Subtarget->isThumb1Only())
9078       return false;
9079     // FALL THROUGH.
9080   default:
9081     // ARM doesn't support any R+R*scale+imm addr modes.
9082     if (AM.BaseOffs)
9083       return false;
9084
9085     if (!VT.isSimple())
9086       return false;
9087
9088     if (Subtarget->isThumb2())
9089       return isLegalT2ScaledAddressingMode(AM, VT);
9090
9091     int Scale = AM.Scale;
9092     switch (VT.getSimpleVT().SimpleTy) {
9093     default: return false;
9094     case MVT::i1:
9095     case MVT::i8:
9096     case MVT::i32:
9097       if (Scale < 0) Scale = -Scale;
9098       if (Scale == 1)
9099         return true;
9100       // r + r << imm
9101       return isPowerOf2_32(Scale & ~1);
9102     case MVT::i16:
9103     case MVT::i64:
9104       // r + r
9105       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9106         return true;
9107       return false;
9108
9109     case MVT::isVoid:
9110       // Note, we allow "void" uses (basically, uses that aren't loads or
9111       // stores), because arm allows folding a scale into many arithmetic
9112       // operations.  This should be made more precise and revisited later.
9113
9114       // Allow r << imm, but the imm has to be a multiple of two.
9115       if (Scale & 1) return false;
9116       return isPowerOf2_32(Scale);
9117     }
9118   }
9119   return true;
9120 }
9121
9122 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9123 /// icmp immediate, that is the target has icmp instructions which can compare
9124 /// a register against the immediate without having to materialize the
9125 /// immediate into a register.
9126 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9127   // Thumb2 and ARM modes can use cmn for negative immediates.
9128   if (!Subtarget->isThumb())
9129     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9130   if (Subtarget->isThumb2())
9131     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9132   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9133   return Imm >= 0 && Imm <= 255;
9134 }
9135
9136 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9137 /// *or sub* immediate, that is the target has add or sub instructions which can
9138 /// add a register with the immediate without having to materialize the
9139 /// immediate into a register.
9140 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9141   // Same encoding for add/sub, just flip the sign.
9142   int64_t AbsImm = llvm::abs64(Imm);
9143   if (!Subtarget->isThumb())
9144     return ARM_AM::getSOImmVal(AbsImm) != -1;
9145   if (Subtarget->isThumb2())
9146     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9147   // Thumb1 only has 8-bit unsigned immediate.
9148   return AbsImm >= 0 && AbsImm <= 255;
9149 }
9150
9151 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9152                                       bool isSEXTLoad, SDValue &Base,
9153                                       SDValue &Offset, bool &isInc,
9154                                       SelectionDAG &DAG) {
9155   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9156     return false;
9157
9158   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9159     // AddressingMode 3
9160     Base = Ptr->getOperand(0);
9161     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9162       int RHSC = (int)RHS->getZExtValue();
9163       if (RHSC < 0 && RHSC > -256) {
9164         assert(Ptr->getOpcode() == ISD::ADD);
9165         isInc = false;
9166         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9167         return true;
9168       }
9169     }
9170     isInc = (Ptr->getOpcode() == ISD::ADD);
9171     Offset = Ptr->getOperand(1);
9172     return true;
9173   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9174     // AddressingMode 2
9175     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9176       int RHSC = (int)RHS->getZExtValue();
9177       if (RHSC < 0 && RHSC > -0x1000) {
9178         assert(Ptr->getOpcode() == ISD::ADD);
9179         isInc = false;
9180         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9181         Base = Ptr->getOperand(0);
9182         return true;
9183       }
9184     }
9185
9186     if (Ptr->getOpcode() == ISD::ADD) {
9187       isInc = true;
9188       ARM_AM::ShiftOpc ShOpcVal=
9189         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9190       if (ShOpcVal != ARM_AM::no_shift) {
9191         Base = Ptr->getOperand(1);
9192         Offset = Ptr->getOperand(0);
9193       } else {
9194         Base = Ptr->getOperand(0);
9195         Offset = Ptr->getOperand(1);
9196       }
9197       return true;
9198     }
9199
9200     isInc = (Ptr->getOpcode() == ISD::ADD);
9201     Base = Ptr->getOperand(0);
9202     Offset = Ptr->getOperand(1);
9203     return true;
9204   }
9205
9206   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9207   return false;
9208 }
9209
9210 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9211                                      bool isSEXTLoad, SDValue &Base,
9212                                      SDValue &Offset, bool &isInc,
9213                                      SelectionDAG &DAG) {
9214   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9215     return false;
9216
9217   Base = Ptr->getOperand(0);
9218   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9219     int RHSC = (int)RHS->getZExtValue();
9220     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9221       assert(Ptr->getOpcode() == ISD::ADD);
9222       isInc = false;
9223       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9224       return true;
9225     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9226       isInc = Ptr->getOpcode() == ISD::ADD;
9227       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9228       return true;
9229     }
9230   }
9231
9232   return false;
9233 }
9234
9235 /// getPreIndexedAddressParts - returns true by value, base pointer and
9236 /// offset pointer and addressing mode by reference if the node's address
9237 /// can be legally represented as pre-indexed load / store address.
9238 bool
9239 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9240                                              SDValue &Offset,
9241                                              ISD::MemIndexedMode &AM,
9242                                              SelectionDAG &DAG) const {
9243   if (Subtarget->isThumb1Only())
9244     return false;
9245
9246   EVT VT;
9247   SDValue Ptr;
9248   bool isSEXTLoad = false;
9249   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9250     Ptr = LD->getBasePtr();
9251     VT  = LD->getMemoryVT();
9252     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9253   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9254     Ptr = ST->getBasePtr();
9255     VT  = ST->getMemoryVT();
9256   } else
9257     return false;
9258
9259   bool isInc;
9260   bool isLegal = false;
9261   if (Subtarget->isThumb2())
9262     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9263                                        Offset, isInc, DAG);
9264   else
9265     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9266                                         Offset, isInc, DAG);
9267   if (!isLegal)
9268     return false;
9269
9270   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9271   return true;
9272 }
9273
9274 /// getPostIndexedAddressParts - returns true by value, base pointer and
9275 /// offset pointer and addressing mode by reference if this node can be
9276 /// combined with a load / store to form a post-indexed load / store.
9277 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9278                                                    SDValue &Base,
9279                                                    SDValue &Offset,
9280                                                    ISD::MemIndexedMode &AM,
9281                                                    SelectionDAG &DAG) const {
9282   if (Subtarget->isThumb1Only())
9283     return false;
9284
9285   EVT VT;
9286   SDValue Ptr;
9287   bool isSEXTLoad = false;
9288   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9289     VT  = LD->getMemoryVT();
9290     Ptr = LD->getBasePtr();
9291     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9292   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9293     VT  = ST->getMemoryVT();
9294     Ptr = ST->getBasePtr();
9295   } else
9296     return false;
9297
9298   bool isInc;
9299   bool isLegal = false;
9300   if (Subtarget->isThumb2())
9301     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9302                                        isInc, DAG);
9303   else
9304     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9305                                         isInc, DAG);
9306   if (!isLegal)
9307     return false;
9308
9309   if (Ptr != Base) {
9310     // Swap base ptr and offset to catch more post-index load / store when
9311     // it's legal. In Thumb2 mode, offset must be an immediate.
9312     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9313         !Subtarget->isThumb2())
9314       std::swap(Base, Offset);
9315
9316     // Post-indexed load / store update the base pointer.
9317     if (Ptr != Base)
9318       return false;
9319   }
9320
9321   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9322   return true;
9323 }
9324
9325 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9326                                                        APInt &KnownZero,
9327                                                        APInt &KnownOne,
9328                                                        const SelectionDAG &DAG,
9329                                                        unsigned Depth) const {
9330   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9331   switch (Op.getOpcode()) {
9332   default: break;
9333   case ARMISD::CMOV: {
9334     // Bits are known zero/one if known on the LHS and RHS.
9335     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9336     if (KnownZero == 0 && KnownOne == 0) return;
9337
9338     APInt KnownZeroRHS, KnownOneRHS;
9339     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9340     KnownZero &= KnownZeroRHS;
9341     KnownOne  &= KnownOneRHS;
9342     return;
9343   }
9344   }
9345 }
9346
9347 //===----------------------------------------------------------------------===//
9348 //                           ARM Inline Assembly Support
9349 //===----------------------------------------------------------------------===//
9350
9351 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9352   // Looking for "rev" which is V6+.
9353   if (!Subtarget->hasV6Ops())
9354     return false;
9355
9356   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9357   std::string AsmStr = IA->getAsmString();
9358   SmallVector<StringRef, 4> AsmPieces;
9359   SplitString(AsmStr, AsmPieces, ";\n");
9360
9361   switch (AsmPieces.size()) {
9362   default: return false;
9363   case 1:
9364     AsmStr = AsmPieces[0];
9365     AsmPieces.clear();
9366     SplitString(AsmStr, AsmPieces, " \t,");
9367
9368     // rev $0, $1
9369     if (AsmPieces.size() == 3 &&
9370         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9371         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9372       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9373       if (Ty && Ty->getBitWidth() == 32)
9374         return IntrinsicLowering::LowerToByteSwap(CI);
9375     }
9376     break;
9377   }
9378
9379   return false;
9380 }
9381
9382 /// getConstraintType - Given a constraint letter, return the type of
9383 /// constraint it is for this target.
9384 ARMTargetLowering::ConstraintType
9385 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9386   if (Constraint.size() == 1) {
9387     switch (Constraint[0]) {
9388     default:  break;
9389     case 'l': return C_RegisterClass;
9390     case 'w': return C_RegisterClass;
9391     case 'h': return C_RegisterClass;
9392     case 'x': return C_RegisterClass;
9393     case 't': return C_RegisterClass;
9394     case 'j': return C_Other; // Constant for movw.
9395       // An address with a single base register. Due to the way we
9396       // currently handle addresses it is the same as an 'r' memory constraint.
9397     case 'Q': return C_Memory;
9398     }
9399   } else if (Constraint.size() == 2) {
9400     switch (Constraint[0]) {
9401     default: break;
9402     // All 'U+' constraints are addresses.
9403     case 'U': return C_Memory;
9404     }
9405   }
9406   return TargetLowering::getConstraintType(Constraint);
9407 }
9408
9409 /// Examine constraint type and operand type and determine a weight value.
9410 /// This object must already have been set up with the operand type
9411 /// and the current alternative constraint selected.
9412 TargetLowering::ConstraintWeight
9413 ARMTargetLowering::getSingleConstraintMatchWeight(
9414     AsmOperandInfo &info, const char *constraint) const {
9415   ConstraintWeight weight = CW_Invalid;
9416   Value *CallOperandVal = info.CallOperandVal;
9417     // If we don't have a value, we can't do a match,
9418     // but allow it at the lowest weight.
9419   if (CallOperandVal == NULL)
9420     return CW_Default;
9421   Type *type = CallOperandVal->getType();
9422   // Look at the constraint type.
9423   switch (*constraint) {
9424   default:
9425     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9426     break;
9427   case 'l':
9428     if (type->isIntegerTy()) {
9429       if (Subtarget->isThumb())
9430         weight = CW_SpecificReg;
9431       else
9432         weight = CW_Register;
9433     }
9434     break;
9435   case 'w':
9436     if (type->isFloatingPointTy())
9437       weight = CW_Register;
9438     break;
9439   }
9440   return weight;
9441 }
9442
9443 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9444 RCPair
9445 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9446                                                 EVT VT) const {
9447   if (Constraint.size() == 1) {
9448     // GCC ARM Constraint Letters
9449     switch (Constraint[0]) {
9450     case 'l': // Low regs or general regs.
9451       if (Subtarget->isThumb())
9452         return RCPair(0U, &ARM::tGPRRegClass);
9453       return RCPair(0U, &ARM::GPRRegClass);
9454     case 'h': // High regs or no regs.
9455       if (Subtarget->isThumb())
9456         return RCPair(0U, &ARM::hGPRRegClass);
9457       break;
9458     case 'r':
9459       return RCPair(0U, &ARM::GPRRegClass);
9460     case 'w':
9461       if (VT == MVT::f32)
9462         return RCPair(0U, &ARM::SPRRegClass);
9463       if (VT.getSizeInBits() == 64)
9464         return RCPair(0U, &ARM::DPRRegClass);
9465       if (VT.getSizeInBits() == 128)
9466         return RCPair(0U, &ARM::QPRRegClass);
9467       break;
9468     case 'x':
9469       if (VT == MVT::f32)
9470         return RCPair(0U, &ARM::SPR_8RegClass);
9471       if (VT.getSizeInBits() == 64)
9472         return RCPair(0U, &ARM::DPR_8RegClass);
9473       if (VT.getSizeInBits() == 128)
9474         return RCPair(0U, &ARM::QPR_8RegClass);
9475       break;
9476     case 't':
9477       if (VT == MVT::f32)
9478         return RCPair(0U, &ARM::SPRRegClass);
9479       break;
9480     }
9481   }
9482   if (StringRef("{cc}").equals_lower(Constraint))
9483     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9484
9485   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9486 }
9487
9488 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9489 /// vector.  If it is invalid, don't add anything to Ops.
9490 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9491                                                      std::string &Constraint,
9492                                                      std::vector<SDValue>&Ops,
9493                                                      SelectionDAG &DAG) const {
9494   SDValue Result(0, 0);
9495
9496   // Currently only support length 1 constraints.
9497   if (Constraint.length() != 1) return;
9498
9499   char ConstraintLetter = Constraint[0];
9500   switch (ConstraintLetter) {
9501   default: break;
9502   case 'j':
9503   case 'I': case 'J': case 'K': case 'L':
9504   case 'M': case 'N': case 'O':
9505     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9506     if (!C)
9507       return;
9508
9509     int64_t CVal64 = C->getSExtValue();
9510     int CVal = (int) CVal64;
9511     // None of these constraints allow values larger than 32 bits.  Check
9512     // that the value fits in an int.
9513     if (CVal != CVal64)
9514       return;
9515
9516     switch (ConstraintLetter) {
9517       case 'j':
9518         // Constant suitable for movw, must be between 0 and
9519         // 65535.
9520         if (Subtarget->hasV6T2Ops())
9521           if (CVal >= 0 && CVal <= 65535)
9522             break;
9523         return;
9524       case 'I':
9525         if (Subtarget->isThumb1Only()) {
9526           // This must be a constant between 0 and 255, for ADD
9527           // immediates.
9528           if (CVal >= 0 && CVal <= 255)
9529             break;
9530         } else if (Subtarget->isThumb2()) {
9531           // A constant that can be used as an immediate value in a
9532           // data-processing instruction.
9533           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9534             break;
9535         } else {
9536           // A constant that can be used as an immediate value in a
9537           // data-processing instruction.
9538           if (ARM_AM::getSOImmVal(CVal) != -1)
9539             break;
9540         }
9541         return;
9542
9543       case 'J':
9544         if (Subtarget->isThumb()) {  // FIXME thumb2
9545           // This must be a constant between -255 and -1, for negated ADD
9546           // immediates. This can be used in GCC with an "n" modifier that
9547           // prints the negated value, for use with SUB instructions. It is
9548           // not useful otherwise but is implemented for compatibility.
9549           if (CVal >= -255 && CVal <= -1)
9550             break;
9551         } else {
9552           // This must be a constant between -4095 and 4095. It is not clear
9553           // what this constraint is intended for. Implemented for
9554           // compatibility with GCC.
9555           if (CVal >= -4095 && CVal <= 4095)
9556             break;
9557         }
9558         return;
9559
9560       case 'K':
9561         if (Subtarget->isThumb1Only()) {
9562           // A 32-bit value where only one byte has a nonzero value. Exclude
9563           // zero to match GCC. This constraint is used by GCC internally for
9564           // constants that can be loaded with a move/shift combination.
9565           // It is not useful otherwise but is implemented for compatibility.
9566           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9567             break;
9568         } else if (Subtarget->isThumb2()) {
9569           // A constant whose bitwise inverse can be used as an immediate
9570           // value in a data-processing instruction. This can be used in GCC
9571           // with a "B" modifier that prints the inverted value, for use with
9572           // BIC and MVN instructions. It is not useful otherwise but is
9573           // implemented for compatibility.
9574           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9575             break;
9576         } else {
9577           // A constant whose bitwise inverse can be used as an immediate
9578           // value in a data-processing instruction. This can be used in GCC
9579           // with a "B" modifier that prints the inverted value, for use with
9580           // BIC and MVN instructions. It is not useful otherwise but is
9581           // implemented for compatibility.
9582           if (ARM_AM::getSOImmVal(~CVal) != -1)
9583             break;
9584         }
9585         return;
9586
9587       case 'L':
9588         if (Subtarget->isThumb1Only()) {
9589           // This must be a constant between -7 and 7,
9590           // for 3-operand ADD/SUB immediate instructions.
9591           if (CVal >= -7 && CVal < 7)
9592             break;
9593         } else if (Subtarget->isThumb2()) {
9594           // A constant whose negation can be used as an immediate value in a
9595           // data-processing instruction. This can be used in GCC with an "n"
9596           // modifier that prints the negated value, for use with SUB
9597           // instructions. It is not useful otherwise but is implemented for
9598           // compatibility.
9599           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9600             break;
9601         } else {
9602           // A constant whose negation can be used as an immediate value in a
9603           // data-processing instruction. This can be used in GCC with an "n"
9604           // modifier that prints the negated value, for use with SUB
9605           // instructions. It is not useful otherwise but is implemented for
9606           // compatibility.
9607           if (ARM_AM::getSOImmVal(-CVal) != -1)
9608             break;
9609         }
9610         return;
9611
9612       case 'M':
9613         if (Subtarget->isThumb()) { // FIXME thumb2
9614           // This must be a multiple of 4 between 0 and 1020, for
9615           // ADD sp + immediate.
9616           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9617             break;
9618         } else {
9619           // A power of two or a constant between 0 and 32.  This is used in
9620           // GCC for the shift amount on shifted register operands, but it is
9621           // useful in general for any shift amounts.
9622           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9623             break;
9624         }
9625         return;
9626
9627       case 'N':
9628         if (Subtarget->isThumb()) {  // FIXME thumb2
9629           // This must be a constant between 0 and 31, for shift amounts.
9630           if (CVal >= 0 && CVal <= 31)
9631             break;
9632         }
9633         return;
9634
9635       case 'O':
9636         if (Subtarget->isThumb()) {  // FIXME thumb2
9637           // This must be a multiple of 4 between -508 and 508, for
9638           // ADD/SUB sp = sp + immediate.
9639           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9640             break;
9641         }
9642         return;
9643     }
9644     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9645     break;
9646   }
9647
9648   if (Result.getNode()) {
9649     Ops.push_back(Result);
9650     return;
9651   }
9652   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9653 }
9654
9655 bool
9656 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9657   // The ARM target isn't yet aware of offsets.
9658   return false;
9659 }
9660
9661 bool ARM::isBitFieldInvertedMask(unsigned v) {
9662   if (v == 0xffffffff)
9663     return 0;
9664   // there can be 1's on either or both "outsides", all the "inside"
9665   // bits must be 0's
9666   unsigned int lsb = 0, msb = 31;
9667   while (v & (1 << msb)) --msb;
9668   while (v & (1 << lsb)) ++lsb;
9669   for (unsigned int i = lsb; i <= msb; ++i) {
9670     if (v & (1 << i))
9671       return 0;
9672   }
9673   return 1;
9674 }
9675
9676 /// isFPImmLegal - Returns true if the target can instruction select the
9677 /// specified FP immediate natively. If false, the legalizer will
9678 /// materialize the FP immediate as a load from a constant pool.
9679 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9680   if (!Subtarget->hasVFP3())
9681     return false;
9682   if (VT == MVT::f32)
9683     return ARM_AM::getFP32Imm(Imm) != -1;
9684   if (VT == MVT::f64)
9685     return ARM_AM::getFP64Imm(Imm) != -1;
9686   return false;
9687 }
9688
9689 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9690 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9691 /// specified in the intrinsic calls.
9692 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9693                                            const CallInst &I,
9694                                            unsigned Intrinsic) const {
9695   switch (Intrinsic) {
9696   case Intrinsic::arm_neon_vld1:
9697   case Intrinsic::arm_neon_vld2:
9698   case Intrinsic::arm_neon_vld3:
9699   case Intrinsic::arm_neon_vld4:
9700   case Intrinsic::arm_neon_vld2lane:
9701   case Intrinsic::arm_neon_vld3lane:
9702   case Intrinsic::arm_neon_vld4lane: {
9703     Info.opc = ISD::INTRINSIC_W_CHAIN;
9704     // Conservatively set memVT to the entire set of vectors loaded.
9705     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9706     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9707     Info.ptrVal = I.getArgOperand(0);
9708     Info.offset = 0;
9709     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9710     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9711     Info.vol = false; // volatile loads with NEON intrinsics not supported
9712     Info.readMem = true;
9713     Info.writeMem = false;
9714     return true;
9715   }
9716   case Intrinsic::arm_neon_vst1:
9717   case Intrinsic::arm_neon_vst2:
9718   case Intrinsic::arm_neon_vst3:
9719   case Intrinsic::arm_neon_vst4:
9720   case Intrinsic::arm_neon_vst2lane:
9721   case Intrinsic::arm_neon_vst3lane:
9722   case Intrinsic::arm_neon_vst4lane: {
9723     Info.opc = ISD::INTRINSIC_VOID;
9724     // Conservatively set memVT to the entire set of vectors stored.
9725     unsigned NumElts = 0;
9726     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9727       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9728       if (!ArgTy->isVectorTy())
9729         break;
9730       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9731     }
9732     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9733     Info.ptrVal = I.getArgOperand(0);
9734     Info.offset = 0;
9735     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9736     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9737     Info.vol = false; // volatile stores with NEON intrinsics not supported
9738     Info.readMem = false;
9739     Info.writeMem = true;
9740     return true;
9741   }
9742   case Intrinsic::arm_strexd: {
9743     Info.opc = ISD::INTRINSIC_W_CHAIN;
9744     Info.memVT = MVT::i64;
9745     Info.ptrVal = I.getArgOperand(2);
9746     Info.offset = 0;
9747     Info.align = 8;
9748     Info.vol = true;
9749     Info.readMem = false;
9750     Info.writeMem = true;
9751     return true;
9752   }
9753   case Intrinsic::arm_ldrexd: {
9754     Info.opc = ISD::INTRINSIC_W_CHAIN;
9755     Info.memVT = MVT::i64;
9756     Info.ptrVal = I.getArgOperand(0);
9757     Info.offset = 0;
9758     Info.align = 8;
9759     Info.vol = true;
9760     Info.readMem = true;
9761     Info.writeMem = false;
9762     return true;
9763   }
9764   default:
9765     break;
9766   }
9767
9768   return false;
9769 }