Expand some more vector operations not supported by Neon.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/Constants.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instruction.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/CodeGen/SelectionDAG.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/VectorExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MathExtras.h"
43 #include <sstream>
44 using namespace llvm;
45
46 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
47                                    CCValAssign::LocInfo &LocInfo,
48                                    ISD::ArgFlagsTy &ArgFlags,
49                                    CCState &State);
50 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
51                                     CCValAssign::LocInfo &LocInfo,
52                                     ISD::ArgFlagsTy &ArgFlags,
53                                     CCState &State);
54 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
55                                       CCValAssign::LocInfo &LocInfo,
56                                       ISD::ArgFlagsTy &ArgFlags,
57                                       CCState &State);
58 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
59                                        CCValAssign::LocInfo &LocInfo,
60                                        ISD::ArgFlagsTy &ArgFlags,
61                                        CCState &State);
62
63 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
64                                        EVT PromotedBitwiseVT) {
65   if (VT != PromotedLdStVT) {
66     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
67     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
68                        PromotedLdStVT.getSimpleVT());
69
70     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
71     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
72                        PromotedLdStVT.getSimpleVT());
73   }
74
75   EVT ElemTy = VT.getVectorElementType();
76   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
77     setOperationAction(ISD::VSETCC, VT.getSimpleVT(), Custom);
78   if (ElemTy == MVT::i8 || ElemTy == MVT::i16)
79     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
80   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
81   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
82   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Custom);
83   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Expand);
84   if (VT.isInteger()) {
85     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
86     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
87     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
88   }
89
90   // Promote all bit-wise operations.
91   if (VT.isInteger() && VT != PromotedBitwiseVT) {
92     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
93     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
94                        PromotedBitwiseVT.getSimpleVT());
95     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
96     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
97                        PromotedBitwiseVT.getSimpleVT());
98     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
99     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
100                        PromotedBitwiseVT.getSimpleVT());
101   }
102
103   // Neon does not support vector divide/remainder operations.
104   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
105   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
106   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
107   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
108   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
109   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
110 }
111
112 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
113   addRegisterClass(VT, ARM::DPRRegisterClass);
114   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
115 }
116
117 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
118   addRegisterClass(VT, ARM::QPRRegisterClass);
119   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
120 }
121
122 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
123   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
124     return new TargetLoweringObjectFileMachO();
125   return new ARMElfTargetObjectFile();
126 }
127
128 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
129     : TargetLowering(TM, createTLOF(TM)), ARMPCLabelIndex(0) {
130   Subtarget = &TM.getSubtarget<ARMSubtarget>();
131
132   if (Subtarget->isTargetDarwin()) {
133     // Uses VFP for Thumb libfuncs if available.
134     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
135       // Single-precision floating-point arithmetic.
136       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
137       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
138       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
139       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
140
141       // Double-precision floating-point arithmetic.
142       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
143       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
144       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
145       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
146
147       // Single-precision comparisons.
148       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
149       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
150       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
151       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
152       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
153       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
154       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
155       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
156
157       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
158       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
159       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
160       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
161       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
162       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
163       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
164       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
165
166       // Double-precision comparisons.
167       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
168       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
169       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
170       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
171       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
172       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
173       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
174       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
175
176       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
177       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
178       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
179       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
180       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
181       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
182       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
183       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
184
185       // Floating-point to integer conversions.
186       // i64 conversions are done via library routines even when generating VFP
187       // instructions, so use the same ones.
188       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
189       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
190       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
191       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
192
193       // Conversions between floating types.
194       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
195       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
196
197       // Integer to floating-point conversions.
198       // i64 conversions are done via library routines even when generating VFP
199       // instructions, so use the same ones.
200       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
201       // e.g., __floatunsidf vs. __floatunssidfvfp.
202       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
203       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
204       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
205       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
206     }
207   }
208
209   // These libcalls are not available in 32-bit.
210   setLibcallName(RTLIB::SHL_I128, 0);
211   setLibcallName(RTLIB::SRL_I128, 0);
212   setLibcallName(RTLIB::SRA_I128, 0);
213
214   // Libcalls should use the AAPCS base standard ABI, even if hard float
215   // is in effect, as per the ARM RTABI specification, section 4.1.2.
216   if (Subtarget->isAAPCS_ABI()) {
217     for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
218       setLibcallCallingConv(static_cast<RTLIB::Libcall>(i),
219                             CallingConv::ARM_AAPCS);
220     }
221   }
222
223   if (Subtarget->isThumb1Only())
224     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
225   else
226     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
227   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
228     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
229     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
230
231     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
232   }
233
234   if (Subtarget->hasNEON()) {
235     addDRTypeForNEON(MVT::v2f32);
236     addDRTypeForNEON(MVT::v8i8);
237     addDRTypeForNEON(MVT::v4i16);
238     addDRTypeForNEON(MVT::v2i32);
239     addDRTypeForNEON(MVT::v1i64);
240
241     addQRTypeForNEON(MVT::v4f32);
242     addQRTypeForNEON(MVT::v2f64);
243     addQRTypeForNEON(MVT::v16i8);
244     addQRTypeForNEON(MVT::v8i16);
245     addQRTypeForNEON(MVT::v4i32);
246     addQRTypeForNEON(MVT::v2i64);
247
248     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
249     // neither Neon nor VFP support any arithmetic operations on it.
250     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
251     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
252     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
253     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
254     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
255     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
256     setOperationAction(ISD::VSETCC, MVT::v2f64, Expand);
257     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
258     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
259     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
260     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
261     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
262     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
263     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
264     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
265     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
266     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
267     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
268     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
269     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
270     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
271     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
272     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
273     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
274
275     // Neon does not support some operations on v1i64 and v2i64 types.
276     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
277     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
278     setOperationAction(ISD::VSETCC, MVT::v1i64, Expand);
279     setOperationAction(ISD::VSETCC, MVT::v2i64, Expand);
280
281     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
282     setTargetDAGCombine(ISD::SHL);
283     setTargetDAGCombine(ISD::SRL);
284     setTargetDAGCombine(ISD::SRA);
285     setTargetDAGCombine(ISD::SIGN_EXTEND);
286     setTargetDAGCombine(ISD::ZERO_EXTEND);
287     setTargetDAGCombine(ISD::ANY_EXTEND);
288   }
289
290   computeRegisterProperties();
291
292   // ARM does not have f32 extending load.
293   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
294
295   // ARM does not have i1 sign extending load.
296   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297
298   // ARM supports all 4 flavors of integer indexed load / store.
299   if (!Subtarget->isThumb1Only()) {
300     for (unsigned im = (unsigned)ISD::PRE_INC;
301          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
302       setIndexedLoadAction(im,  MVT::i1,  Legal);
303       setIndexedLoadAction(im,  MVT::i8,  Legal);
304       setIndexedLoadAction(im,  MVT::i16, Legal);
305       setIndexedLoadAction(im,  MVT::i32, Legal);
306       setIndexedStoreAction(im, MVT::i1,  Legal);
307       setIndexedStoreAction(im, MVT::i8,  Legal);
308       setIndexedStoreAction(im, MVT::i16, Legal);
309       setIndexedStoreAction(im, MVT::i32, Legal);
310     }
311   }
312
313   // i64 operation support.
314   if (Subtarget->isThumb1Only()) {
315     setOperationAction(ISD::MUL,     MVT::i64, Expand);
316     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
317     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
318     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
319     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
320   } else {
321     setOperationAction(ISD::MUL,     MVT::i64, Expand);
322     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
323     if (!Subtarget->hasV6Ops())
324       setOperationAction(ISD::MULHS, MVT::i32, Expand);
325   }
326   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
327   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
328   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
329   setOperationAction(ISD::SRL,       MVT::i64, Custom);
330   setOperationAction(ISD::SRA,       MVT::i64, Custom);
331
332   // ARM does not have ROTL.
333   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
334   setOperationAction(ISD::CTTZ,  MVT::i32, Expand);
335   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
336   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
337     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
338
339   // Only ARMv6 has BSWAP.
340   if (!Subtarget->hasV6Ops())
341     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
342
343   // These are expanded into libcalls.
344   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
345   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
346   setOperationAction(ISD::SREM,  MVT::i32, Expand);
347   setOperationAction(ISD::UREM,  MVT::i32, Expand);
348   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
349   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
350
351   // Support label based line numbers.
352   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
353   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
354
355   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
356   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
357   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
358   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
359
360   // Use the default implementation.
361   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
362   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
363   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
364   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
365   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
366   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
367   setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
368   // FIXME: Shouldn't need this, since no register is used, but the legalizer
369   // doesn't yet know how to not do that for SjLj.
370   setExceptionSelectorRegister(ARM::R0);
371   if (Subtarget->isThumb())
372     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
373   else
374     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
375   setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
376
377   if (!Subtarget->hasV6Ops() && !Subtarget->isThumb2()) {
378     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
379     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
380   }
381   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
382
383   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())
384     // Turn f64->i64 into FMRRD, i64 -> f64 to FMDRR iff target supports vfp2.
385     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
386
387   // We want to custom lower some of our intrinsics.
388   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
389   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
390   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
391
392   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
393   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
394   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
395   setOperationAction(ISD::SELECT,    MVT::i32, Expand);
396   setOperationAction(ISD::SELECT,    MVT::f32, Expand);
397   setOperationAction(ISD::SELECT,    MVT::f64, Expand);
398   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
399   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
400   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
401
402   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
403   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
404   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
405   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
406   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
407
408   // We don't support sin/cos/fmod/copysign/pow
409   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
410   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
411   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
412   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
413   setOperationAction(ISD::FREM,      MVT::f64, Expand);
414   setOperationAction(ISD::FREM,      MVT::f32, Expand);
415   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
416     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
417     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
418   }
419   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
420   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
421
422   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
423   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
424     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
425     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
426     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
427     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
428   }
429
430   // We have target-specific dag combine patterns for the following nodes:
431   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
432   setTargetDAGCombine(ISD::ADD);
433   setTargetDAGCombine(ISD::SUB);
434
435   setStackPointerRegisterToSaveRestore(ARM::SP);
436   setSchedulingPreference(SchedulingForRegPressure);
437
438   // FIXME: If-converter should use instruction latency to determine
439   // profitability rather than relying on fixed limits.
440   if (Subtarget->getCPUString() == "generic") {
441     // Generic (and overly aggressive) if-conversion limits.
442     setIfCvtBlockSizeLimit(10);
443     setIfCvtDupBlockSizeLimit(2);
444   } else if (Subtarget->hasV6Ops()) {
445     setIfCvtBlockSizeLimit(2);
446     setIfCvtDupBlockSizeLimit(1);
447   } else {
448     setIfCvtBlockSizeLimit(3);
449     setIfCvtDupBlockSizeLimit(2);
450   }
451
452   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
453   // Do not enable CodePlacementOpt for now: it currently runs after the
454   // ARMConstantIslandPass and messes up branch relaxation and placement
455   // of constant islands.
456   // benefitFromCodePlacementOpt = true;
457 }
458
459 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
460   switch (Opcode) {
461   default: return 0;
462   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
463   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
464   case ARMISD::CALL:          return "ARMISD::CALL";
465   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
466   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
467   case ARMISD::tCALL:         return "ARMISD::tCALL";
468   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
469   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
470   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
471   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
472   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
473   case ARMISD::CMP:           return "ARMISD::CMP";
474   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
475   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
476   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
477   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
478   case ARMISD::CMOV:          return "ARMISD::CMOV";
479   case ARMISD::CNEG:          return "ARMISD::CNEG";
480
481   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
482   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
483   case ARMISD::SITOF:         return "ARMISD::SITOF";
484   case ARMISD::UITOF:         return "ARMISD::UITOF";
485
486   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
487   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
488   case ARMISD::RRX:           return "ARMISD::RRX";
489
490   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
491   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
492
493   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
494
495   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
496
497   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
498   case ARMISD::VCGE:          return "ARMISD::VCGE";
499   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
500   case ARMISD::VCGT:          return "ARMISD::VCGT";
501   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
502   case ARMISD::VTST:          return "ARMISD::VTST";
503
504   case ARMISD::VSHL:          return "ARMISD::VSHL";
505   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
506   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
507   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
508   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
509   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
510   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
511   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
512   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
513   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
514   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
515   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
516   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
517   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
518   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
519   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
520   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
521   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
522   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
523   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
524   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
525   case ARMISD::VDUP:          return "ARMISD::VDUP";
526   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
527   case ARMISD::VEXT:          return "ARMISD::VEXT";
528   case ARMISD::VREV64:        return "ARMISD::VREV64";
529   case ARMISD::VREV32:        return "ARMISD::VREV32";
530   case ARMISD::VREV16:        return "ARMISD::VREV16";
531   case ARMISD::VZIP:          return "ARMISD::VZIP";
532   case ARMISD::VUZP:          return "ARMISD::VUZP";
533   case ARMISD::VTRN:          return "ARMISD::VTRN";
534   }
535 }
536
537 /// getFunctionAlignment - Return the Log2 alignment of this function.
538 unsigned ARMTargetLowering::getFunctionAlignment(const Function *F) const {
539   return getTargetMachine().getSubtarget<ARMSubtarget>().isThumb() ? 1 : 2;
540 }
541
542 //===----------------------------------------------------------------------===//
543 // Lowering Code
544 //===----------------------------------------------------------------------===//
545
546 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
547 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
548   switch (CC) {
549   default: llvm_unreachable("Unknown condition code!");
550   case ISD::SETNE:  return ARMCC::NE;
551   case ISD::SETEQ:  return ARMCC::EQ;
552   case ISD::SETGT:  return ARMCC::GT;
553   case ISD::SETGE:  return ARMCC::GE;
554   case ISD::SETLT:  return ARMCC::LT;
555   case ISD::SETLE:  return ARMCC::LE;
556   case ISD::SETUGT: return ARMCC::HI;
557   case ISD::SETUGE: return ARMCC::HS;
558   case ISD::SETULT: return ARMCC::LO;
559   case ISD::SETULE: return ARMCC::LS;
560   }
561 }
562
563 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
564 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
565                         ARMCC::CondCodes &CondCode2) {
566   CondCode2 = ARMCC::AL;
567   switch (CC) {
568   default: llvm_unreachable("Unknown FP condition!");
569   case ISD::SETEQ:
570   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
571   case ISD::SETGT:
572   case ISD::SETOGT: CondCode = ARMCC::GT; break;
573   case ISD::SETGE:
574   case ISD::SETOGE: CondCode = ARMCC::GE; break;
575   case ISD::SETOLT: CondCode = ARMCC::MI; break;
576   case ISD::SETOLE: CondCode = ARMCC::LS; break;
577   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
578   case ISD::SETO:   CondCode = ARMCC::VC; break;
579   case ISD::SETUO:  CondCode = ARMCC::VS; break;
580   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
581   case ISD::SETUGT: CondCode = ARMCC::HI; break;
582   case ISD::SETUGE: CondCode = ARMCC::PL; break;
583   case ISD::SETLT:
584   case ISD::SETULT: CondCode = ARMCC::LT; break;
585   case ISD::SETLE:
586   case ISD::SETULE: CondCode = ARMCC::LE; break;
587   case ISD::SETNE:
588   case ISD::SETUNE: CondCode = ARMCC::NE; break;
589   }
590 }
591
592 //===----------------------------------------------------------------------===//
593 //                      Calling Convention Implementation
594 //===----------------------------------------------------------------------===//
595
596 #include "ARMGenCallingConv.inc"
597
598 // APCS f64 is in register pairs, possibly split to stack
599 static bool f64AssignAPCS(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
600                           CCValAssign::LocInfo &LocInfo,
601                           CCState &State, bool CanFail) {
602   static const unsigned RegList[] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 };
603
604   // Try to get the first register.
605   if (unsigned Reg = State.AllocateReg(RegList, 4))
606     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
607   else {
608     // For the 2nd half of a v2f64, do not fail.
609     if (CanFail)
610       return false;
611
612     // Put the whole thing on the stack.
613     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
614                                            State.AllocateStack(8, 4),
615                                            LocVT, LocInfo));
616     return true;
617   }
618
619   // Try to get the second register.
620   if (unsigned Reg = State.AllocateReg(RegList, 4))
621     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
622   else
623     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
624                                            State.AllocateStack(4, 4),
625                                            LocVT, LocInfo));
626   return true;
627 }
628
629 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
630                                    CCValAssign::LocInfo &LocInfo,
631                                    ISD::ArgFlagsTy &ArgFlags,
632                                    CCState &State) {
633   if (!f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
634     return false;
635   if (LocVT == MVT::v2f64 &&
636       !f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
637     return false;
638   return true;  // we handled it
639 }
640
641 // AAPCS f64 is in aligned register pairs
642 static bool f64AssignAAPCS(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
643                            CCValAssign::LocInfo &LocInfo,
644                            CCState &State, bool CanFail) {
645   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
646   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
647
648   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
649   if (Reg == 0) {
650     // For the 2nd half of a v2f64, do not just fail.
651     if (CanFail)
652       return false;
653
654     // Put the whole thing on the stack.
655     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
656                                            State.AllocateStack(8, 8),
657                                            LocVT, LocInfo));
658     return true;
659   }
660
661   unsigned i;
662   for (i = 0; i < 2; ++i)
663     if (HiRegList[i] == Reg)
664       break;
665
666   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
667   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
668                                          LocVT, LocInfo));
669   return true;
670 }
671
672 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
673                                     CCValAssign::LocInfo &LocInfo,
674                                     ISD::ArgFlagsTy &ArgFlags,
675                                     CCState &State) {
676   if (!f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
677     return false;
678   if (LocVT == MVT::v2f64 &&
679       !f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
680     return false;
681   return true;  // we handled it
682 }
683
684 static bool f64RetAssign(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
685                          CCValAssign::LocInfo &LocInfo, CCState &State) {
686   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
687   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
688
689   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
690   if (Reg == 0)
691     return false; // we didn't handle it
692
693   unsigned i;
694   for (i = 0; i < 2; ++i)
695     if (HiRegList[i] == Reg)
696       break;
697
698   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
699   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
700                                          LocVT, LocInfo));
701   return true;
702 }
703
704 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
705                                       CCValAssign::LocInfo &LocInfo,
706                                       ISD::ArgFlagsTy &ArgFlags,
707                                       CCState &State) {
708   if (!f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
709     return false;
710   if (LocVT == MVT::v2f64 && !f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
711     return false;
712   return true;  // we handled it
713 }
714
715 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
716                                        CCValAssign::LocInfo &LocInfo,
717                                        ISD::ArgFlagsTy &ArgFlags,
718                                        CCState &State) {
719   return RetCC_ARM_APCS_Custom_f64(ValNo, ValVT, LocVT, LocInfo, ArgFlags,
720                                    State);
721 }
722
723 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
724 /// given CallingConvention value.
725 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
726                                                  bool Return,
727                                                  bool isVarArg) const {
728   switch (CC) {
729   default:
730     llvm_unreachable("Unsupported calling convention");
731   case CallingConv::C:
732   case CallingConv::Fast:
733     // Use target triple & subtarget features to do actual dispatch.
734     if (Subtarget->isAAPCS_ABI()) {
735       if (Subtarget->hasVFP2() &&
736           FloatABIType == FloatABI::Hard && !isVarArg)
737         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
738       else
739         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
740     } else
741         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
742   case CallingConv::ARM_AAPCS_VFP:
743     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
744   case CallingConv::ARM_AAPCS:
745     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
746   case CallingConv::ARM_APCS:
747     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
748   }
749 }
750
751 /// LowerCallResult - Lower the result values of a call into the
752 /// appropriate copies out of appropriate physical registers.
753 SDValue
754 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
755                                    CallingConv::ID CallConv, bool isVarArg,
756                                    const SmallVectorImpl<ISD::InputArg> &Ins,
757                                    DebugLoc dl, SelectionDAG &DAG,
758                                    SmallVectorImpl<SDValue> &InVals) {
759
760   // Assign locations to each value returned by this call.
761   SmallVector<CCValAssign, 16> RVLocs;
762   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
763                  RVLocs, *DAG.getContext());
764   CCInfo.AnalyzeCallResult(Ins,
765                            CCAssignFnForNode(CallConv, /* Return*/ true,
766                                              isVarArg));
767
768   // Copy all of the result registers out of their specified physreg.
769   for (unsigned i = 0; i != RVLocs.size(); ++i) {
770     CCValAssign VA = RVLocs[i];
771
772     SDValue Val;
773     if (VA.needsCustom()) {
774       // Handle f64 or half of a v2f64.
775       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
776                                       InFlag);
777       Chain = Lo.getValue(1);
778       InFlag = Lo.getValue(2);
779       VA = RVLocs[++i]; // skip ahead to next loc
780       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
781                                       InFlag);
782       Chain = Hi.getValue(1);
783       InFlag = Hi.getValue(2);
784       Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
785
786       if (VA.getLocVT() == MVT::v2f64) {
787         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
788         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
789                           DAG.getConstant(0, MVT::i32));
790
791         VA = RVLocs[++i]; // skip ahead to next loc
792         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
793         Chain = Lo.getValue(1);
794         InFlag = Lo.getValue(2);
795         VA = RVLocs[++i]; // skip ahead to next loc
796         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
797         Chain = Hi.getValue(1);
798         InFlag = Hi.getValue(2);
799         Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
800         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
801                           DAG.getConstant(1, MVT::i32));
802       }
803     } else {
804       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
805                                InFlag);
806       Chain = Val.getValue(1);
807       InFlag = Val.getValue(2);
808     }
809
810     switch (VA.getLocInfo()) {
811     default: llvm_unreachable("Unknown loc info!");
812     case CCValAssign::Full: break;
813     case CCValAssign::BCvt:
814       Val = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), Val);
815       break;
816     }
817
818     InVals.push_back(Val);
819   }
820
821   return Chain;
822 }
823
824 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
825 /// by "Src" to address "Dst" of size "Size".  Alignment information is
826 /// specified by the specific parameter attribute.  The copy will be passed as
827 /// a byval function parameter.
828 /// Sometimes what we are copying is the end of a larger object, the part that
829 /// does not fit in registers.
830 static SDValue
831 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
832                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
833                           DebugLoc dl) {
834   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
835   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
836                        /*AlwaysInline=*/false, NULL, 0, NULL, 0);
837 }
838
839 /// LowerMemOpCallTo - Store the argument to the stack.
840 SDValue
841 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
842                                     SDValue StackPtr, SDValue Arg,
843                                     DebugLoc dl, SelectionDAG &DAG,
844                                     const CCValAssign &VA,
845                                     ISD::ArgFlagsTy Flags) {
846   unsigned LocMemOffset = VA.getLocMemOffset();
847   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
848   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
849   if (Flags.isByVal()) {
850     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
851   }
852   return DAG.getStore(Chain, dl, Arg, PtrOff,
853                       PseudoSourceValue::getStack(), LocMemOffset);
854 }
855
856 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
857                                          SDValue Chain, SDValue &Arg,
858                                          RegsToPassVector &RegsToPass,
859                                          CCValAssign &VA, CCValAssign &NextVA,
860                                          SDValue &StackPtr,
861                                          SmallVector<SDValue, 8> &MemOpChains,
862                                          ISD::ArgFlagsTy Flags) {
863
864   SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
865                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
866   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
867
868   if (NextVA.isRegLoc())
869     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
870   else {
871     assert(NextVA.isMemLoc());
872     if (StackPtr.getNode() == 0)
873       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
874
875     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
876                                            dl, DAG, NextVA,
877                                            Flags));
878   }
879 }
880
881 /// LowerCall - Lowering a call into a callseq_start <-
882 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
883 /// nodes.
884 SDValue
885 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
886                              CallingConv::ID CallConv, bool isVarArg,
887                              bool isTailCall,
888                              const SmallVectorImpl<ISD::OutputArg> &Outs,
889                              const SmallVectorImpl<ISD::InputArg> &Ins,
890                              DebugLoc dl, SelectionDAG &DAG,
891                              SmallVectorImpl<SDValue> &InVals) {
892
893   // Analyze operands of the call, assigning locations to each operand.
894   SmallVector<CCValAssign, 16> ArgLocs;
895   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
896                  *DAG.getContext());
897   CCInfo.AnalyzeCallOperands(Outs,
898                              CCAssignFnForNode(CallConv, /* Return*/ false,
899                                                isVarArg));
900
901   // Get a count of how many bytes are to be pushed on the stack.
902   unsigned NumBytes = CCInfo.getNextStackOffset();
903
904   // Adjust the stack pointer for the new arguments...
905   // These operations are automatically eliminated by the prolog/epilog pass
906   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
907
908   SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
909
910   RegsToPassVector RegsToPass;
911   SmallVector<SDValue, 8> MemOpChains;
912
913   // Walk the register/memloc assignments, inserting copies/loads.  In the case
914   // of tail call optimization, arguments are handled later.
915   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
916        i != e;
917        ++i, ++realArgIdx) {
918     CCValAssign &VA = ArgLocs[i];
919     SDValue Arg = Outs[realArgIdx].Val;
920     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
921
922     // Promote the value if needed.
923     switch (VA.getLocInfo()) {
924     default: llvm_unreachable("Unknown loc info!");
925     case CCValAssign::Full: break;
926     case CCValAssign::SExt:
927       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
928       break;
929     case CCValAssign::ZExt:
930       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
931       break;
932     case CCValAssign::AExt:
933       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
934       break;
935     case CCValAssign::BCvt:
936       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
937       break;
938     }
939
940     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
941     if (VA.needsCustom()) {
942       if (VA.getLocVT() == MVT::v2f64) {
943         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
944                                   DAG.getConstant(0, MVT::i32));
945         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
946                                   DAG.getConstant(1, MVT::i32));
947
948         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
949                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
950
951         VA = ArgLocs[++i]; // skip ahead to next loc
952         if (VA.isRegLoc()) {
953           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
954                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
955         } else {
956           assert(VA.isMemLoc());
957           if (StackPtr.getNode() == 0)
958             StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
959
960           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
961                                                  dl, DAG, VA, Flags));
962         }
963       } else {
964         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
965                          StackPtr, MemOpChains, Flags);
966       }
967     } else if (VA.isRegLoc()) {
968       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
969     } else {
970       assert(VA.isMemLoc());
971       if (StackPtr.getNode() == 0)
972         StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
973
974       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
975                                              dl, DAG, VA, Flags));
976     }
977   }
978
979   if (!MemOpChains.empty())
980     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
981                         &MemOpChains[0], MemOpChains.size());
982
983   // Build a sequence of copy-to-reg nodes chained together with token chain
984   // and flag operands which copy the outgoing args into the appropriate regs.
985   SDValue InFlag;
986   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
987     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
988                              RegsToPass[i].second, InFlag);
989     InFlag = Chain.getValue(1);
990   }
991
992   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
993   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
994   // node so that legalize doesn't hack it.
995   bool isDirect = false;
996   bool isARMFunc = false;
997   bool isLocalARMFunc = false;
998   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
999     GlobalValue *GV = G->getGlobal();
1000     isDirect = true;
1001     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1002     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1003                    getTargetMachine().getRelocationModel() != Reloc::Static;
1004     isARMFunc = !Subtarget->isThumb() || isStub;
1005     // ARM call to a local ARM function is predicable.
1006     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
1007     // tBX takes a register source operand.
1008     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1009       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1010                                                            ARMPCLabelIndex,
1011                                                            ARMCP::CPValue, 4);
1012       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1013       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1014       Callee = DAG.getLoad(getPointerTy(), dl,
1015                            DAG.getEntryNode(), CPAddr, NULL, 0);
1016       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1017       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1018                            getPointerTy(), Callee, PICLabel);
1019    } else
1020       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
1021   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1022     isDirect = true;
1023     bool isStub = Subtarget->isTargetDarwin() &&
1024                   getTargetMachine().getRelocationModel() != Reloc::Static;
1025     isARMFunc = !Subtarget->isThumb() || isStub;
1026     // tBX takes a register source operand.
1027     const char *Sym = S->getSymbol();
1028     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1029       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1030                                                        Sym, ARMPCLabelIndex, 4);
1031       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1032       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1033       Callee = DAG.getLoad(getPointerTy(), dl,
1034                            DAG.getEntryNode(), CPAddr, NULL, 0);
1035       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1036       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1037                            getPointerTy(), Callee, PICLabel);
1038     } else
1039       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1040   }
1041
1042   // FIXME: handle tail calls differently.
1043   unsigned CallOpc;
1044   if (Subtarget->isThumb()) {
1045     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1046       CallOpc = ARMISD::CALL_NOLINK;
1047     else
1048       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1049   } else {
1050     CallOpc = (isDirect || Subtarget->hasV5TOps())
1051       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1052       : ARMISD::CALL_NOLINK;
1053   }
1054   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb1Only()) {
1055     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
1056     Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
1057     InFlag = Chain.getValue(1);
1058   }
1059
1060   std::vector<SDValue> Ops;
1061   Ops.push_back(Chain);
1062   Ops.push_back(Callee);
1063
1064   // Add argument registers to the end of the list so that they are known live
1065   // into the call.
1066   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1067     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1068                                   RegsToPass[i].second.getValueType()));
1069
1070   if (InFlag.getNode())
1071     Ops.push_back(InFlag);
1072   // Returns a chain and a flag for retval copy to use.
1073   Chain = DAG.getNode(CallOpc, dl, DAG.getVTList(MVT::Other, MVT::Flag),
1074                       &Ops[0], Ops.size());
1075   InFlag = Chain.getValue(1);
1076
1077   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1078                              DAG.getIntPtrConstant(0, true), InFlag);
1079   if (!Ins.empty())
1080     InFlag = Chain.getValue(1);
1081
1082   // Handle result values, copying them out of physregs into vregs that we
1083   // return.
1084   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1085                          dl, DAG, InVals);
1086 }
1087
1088 SDValue
1089 ARMTargetLowering::LowerReturn(SDValue Chain,
1090                                CallingConv::ID CallConv, bool isVarArg,
1091                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1092                                DebugLoc dl, SelectionDAG &DAG) {
1093
1094   // CCValAssign - represent the assignment of the return value to a location.
1095   SmallVector<CCValAssign, 16> RVLocs;
1096
1097   // CCState - Info about the registers and stack slots.
1098   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1099                  *DAG.getContext());
1100
1101   // Analyze outgoing return values.
1102   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1103                                                isVarArg));
1104
1105   // If this is the first return lowered for this function, add
1106   // the regs to the liveout set for the function.
1107   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1108     for (unsigned i = 0; i != RVLocs.size(); ++i)
1109       if (RVLocs[i].isRegLoc())
1110         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1111   }
1112
1113   SDValue Flag;
1114
1115   // Copy the result values into the output registers.
1116   for (unsigned i = 0, realRVLocIdx = 0;
1117        i != RVLocs.size();
1118        ++i, ++realRVLocIdx) {
1119     CCValAssign &VA = RVLocs[i];
1120     assert(VA.isRegLoc() && "Can only return in registers!");
1121
1122     SDValue Arg = Outs[realRVLocIdx].Val;
1123
1124     switch (VA.getLocInfo()) {
1125     default: llvm_unreachable("Unknown loc info!");
1126     case CCValAssign::Full: break;
1127     case CCValAssign::BCvt:
1128       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
1129       break;
1130     }
1131
1132     if (VA.needsCustom()) {
1133       if (VA.getLocVT() == MVT::v2f64) {
1134         // Extract the first half and return it in two registers.
1135         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1136                                    DAG.getConstant(0, MVT::i32));
1137         SDValue HalfGPRs = DAG.getNode(ARMISD::FMRRD, dl,
1138                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1139
1140         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1141         Flag = Chain.getValue(1);
1142         VA = RVLocs[++i]; // skip ahead to next loc
1143         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1144                                  HalfGPRs.getValue(1), Flag);
1145         Flag = Chain.getValue(1);
1146         VA = RVLocs[++i]; // skip ahead to next loc
1147
1148         // Extract the 2nd half and fall through to handle it as an f64 value.
1149         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1150                           DAG.getConstant(1, MVT::i32));
1151       }
1152       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1153       // available.
1154       SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
1155                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1156       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1157       Flag = Chain.getValue(1);
1158       VA = RVLocs[++i]; // skip ahead to next loc
1159       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1160                                Flag);
1161     } else
1162       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1163
1164     // Guarantee that all emitted copies are
1165     // stuck together, avoiding something bad.
1166     Flag = Chain.getValue(1);
1167   }
1168
1169   SDValue result;
1170   if (Flag.getNode())
1171     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1172   else // Return Void
1173     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1174
1175   return result;
1176 }
1177
1178 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1179 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1180 // one of the above mentioned nodes. It has to be wrapped because otherwise
1181 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1182 // be used to form addressing mode. These wrapped nodes will be selected
1183 // into MOVi.
1184 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1185   EVT PtrVT = Op.getValueType();
1186   // FIXME there is no actual debug info here
1187   DebugLoc dl = Op.getDebugLoc();
1188   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1189   SDValue Res;
1190   if (CP->isMachineConstantPoolEntry())
1191     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1192                                     CP->getAlignment());
1193   else
1194     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1195                                     CP->getAlignment());
1196   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1197 }
1198
1199 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1200 SDValue
1201 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1202                                                  SelectionDAG &DAG) {
1203   DebugLoc dl = GA->getDebugLoc();
1204   EVT PtrVT = getPointerTy();
1205   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1206   ARMConstantPoolValue *CPV =
1207     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1208                              ARMCP::CPValue, PCAdj, "tlsgd", true);
1209   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1210   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1211   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, NULL, 0);
1212   SDValue Chain = Argument.getValue(1);
1213
1214   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1215   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1216
1217   // call __tls_get_addr.
1218   ArgListTy Args;
1219   ArgListEntry Entry;
1220   Entry.Node = Argument;
1221   Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1222   Args.push_back(Entry);
1223   // FIXME: is there useful debug info available here?
1224   std::pair<SDValue, SDValue> CallResult =
1225     LowerCallTo(Chain, (const Type *) Type::getInt32Ty(*DAG.getContext()),
1226                 false, false, false, false,
1227                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1228                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1229   return CallResult.first;
1230 }
1231
1232 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1233 // "local exec" model.
1234 SDValue
1235 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1236                                         SelectionDAG &DAG) {
1237   GlobalValue *GV = GA->getGlobal();
1238   DebugLoc dl = GA->getDebugLoc();
1239   SDValue Offset;
1240   SDValue Chain = DAG.getEntryNode();
1241   EVT PtrVT = getPointerTy();
1242   // Get the Thread Pointer
1243   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1244
1245   if (GV->isDeclaration()) {
1246     // initial exec model
1247     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1248     ARMConstantPoolValue *CPV =
1249       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1250                                ARMCP::CPValue, PCAdj, "gottpoff", true);
1251     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1252     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1253     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1254     Chain = Offset.getValue(1);
1255
1256     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1257     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
1258
1259     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1260   } else {
1261     // local exec model
1262     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, "tpoff");
1263     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1264     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1265     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1266   }
1267
1268   // The address of the thread local variable is the add of the thread
1269   // pointer with the offset of the variable.
1270   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1271 }
1272
1273 SDValue
1274 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
1275   // TODO: implement the "local dynamic" model
1276   assert(Subtarget->isTargetELF() &&
1277          "TLS not implemented for non-ELF targets");
1278   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1279   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
1280   // otherwise use the "Local Exec" TLS Model
1281   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
1282     return LowerToTLSGeneralDynamicModel(GA, DAG);
1283   else
1284     return LowerToTLSExecModels(GA, DAG);
1285 }
1286
1287 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
1288                                                  SelectionDAG &DAG) {
1289   EVT PtrVT = getPointerTy();
1290   DebugLoc dl = Op.getDebugLoc();
1291   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1292   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1293   if (RelocM == Reloc::PIC_) {
1294     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
1295     ARMConstantPoolValue *CPV =
1296       new ARMConstantPoolValue(GV, UseGOTOFF ? "GOTOFF" : "GOT");
1297     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1298     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1299     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1300                                  CPAddr, NULL, 0);
1301     SDValue Chain = Result.getValue(1);
1302     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1303     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
1304     if (!UseGOTOFF)
1305       Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1306     return Result;
1307   } else {
1308     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1309     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1310     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1311   }
1312 }
1313
1314 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
1315                                                     SelectionDAG &DAG) {
1316   EVT PtrVT = getPointerTy();
1317   DebugLoc dl = Op.getDebugLoc();
1318   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1319   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1320   SDValue CPAddr;
1321   if (RelocM == Reloc::Static)
1322     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1323   else {
1324     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
1325     ARMConstantPoolValue *CPV =
1326       new ARMConstantPoolValue(GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj);
1327     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1328   }
1329   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1330
1331   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1332   SDValue Chain = Result.getValue(1);
1333
1334   if (RelocM == Reloc::PIC_) {
1335     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1336     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1337   }
1338
1339   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
1340     Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1341
1342   return Result;
1343 }
1344
1345 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
1346                                                     SelectionDAG &DAG){
1347   assert(Subtarget->isTargetELF() &&
1348          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
1349   EVT PtrVT = getPointerTy();
1350   DebugLoc dl = Op.getDebugLoc();
1351   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1352   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1353                                                        "_GLOBAL_OFFSET_TABLE_",
1354                                                        ARMPCLabelIndex, PCAdj);
1355   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1356   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1357   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1358   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1359   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1360 }
1361
1362 static SDValue LowerNeonVLDIntrinsic(SDValue Op, SelectionDAG &DAG,
1363                                      unsigned NumVecs) {
1364   SDNode *Node = Op.getNode();
1365   EVT VT = Node->getValueType(0);
1366
1367   // No expansion needed for 64-bit vectors.
1368   if (VT.is64BitVector())
1369     return SDValue();
1370
1371   // FIXME: We need to expand VLD3 and VLD4 of 128-bit vectors into separate
1372   // operations to load the even and odd registers.
1373   return SDValue();
1374 }
1375
1376 static SDValue LowerNeonVSTIntrinsic(SDValue Op, SelectionDAG &DAG,
1377                                      unsigned NumVecs) {
1378   SDNode *Node = Op.getNode();
1379   EVT VT = Node->getOperand(3).getValueType();
1380
1381   // No expansion needed for 64-bit vectors.
1382   if (VT.is64BitVector())
1383     return SDValue();
1384
1385   // FIXME: We need to expand VST3 and VST4 of 128-bit vectors into separate
1386   // operations to store the even and odd registers.
1387   return SDValue();
1388 }
1389
1390 static SDValue LowerNeonVLDLaneIntrinsic(SDValue Op, SelectionDAG &DAG,
1391                                          unsigned NumVecs) {
1392   SDNode *Node = Op.getNode();
1393   EVT VT = Node->getValueType(0);
1394
1395   if (!VT.is64BitVector())
1396     return SDValue(); // unimplemented
1397
1398   // Change the lane number operand to be a TargetConstant; otherwise it
1399   // will be legalized into a register.
1400   ConstantSDNode *Lane = dyn_cast<ConstantSDNode>(Node->getOperand(NumVecs+3));
1401   if (!Lane) {
1402     assert(false && "vld lane number must be a constant");
1403     return SDValue();
1404   }
1405   SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1406   Ops[NumVecs+3] = DAG.getTargetConstant(Lane->getZExtValue(), MVT::i32);
1407   return DAG.UpdateNodeOperands(Op, &Ops[0], Ops.size());
1408 }
1409
1410 static SDValue LowerNeonVSTLaneIntrinsic(SDValue Op, SelectionDAG &DAG,
1411                                          unsigned NumVecs) {
1412   SDNode *Node = Op.getNode();
1413   EVT VT = Node->getOperand(3).getValueType();
1414
1415   if (!VT.is64BitVector())
1416     return SDValue(); // unimplemented
1417
1418   // Change the lane number operand to be a TargetConstant; otherwise it
1419   // will be legalized into a register.
1420   ConstantSDNode *Lane = dyn_cast<ConstantSDNode>(Node->getOperand(NumVecs+3));
1421   if (!Lane) {
1422     assert(false && "vst lane number must be a constant");
1423     return SDValue();
1424   }
1425   SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1426   Ops[NumVecs+3] = DAG.getTargetConstant(Lane->getZExtValue(), MVT::i32);
1427   return DAG.UpdateNodeOperands(Op, &Ops[0], Ops.size());
1428 }
1429
1430 SDValue
1431 ARMTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
1432   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1433   switch (IntNo) {
1434   case Intrinsic::arm_neon_vld3:
1435     return LowerNeonVLDIntrinsic(Op, DAG, 3);
1436   case Intrinsic::arm_neon_vld4:
1437     return LowerNeonVLDIntrinsic(Op, DAG, 4);
1438   case Intrinsic::arm_neon_vld2lane:
1439     return LowerNeonVLDLaneIntrinsic(Op, DAG, 2);
1440   case Intrinsic::arm_neon_vld3lane:
1441     return LowerNeonVLDLaneIntrinsic(Op, DAG, 3);
1442   case Intrinsic::arm_neon_vld4lane:
1443     return LowerNeonVLDLaneIntrinsic(Op, DAG, 4);
1444   case Intrinsic::arm_neon_vst3:
1445     return LowerNeonVSTIntrinsic(Op, DAG, 3);
1446   case Intrinsic::arm_neon_vst4:
1447     return LowerNeonVSTIntrinsic(Op, DAG, 4);
1448   case Intrinsic::arm_neon_vst2lane:
1449     return LowerNeonVSTLaneIntrinsic(Op, DAG, 2);
1450   case Intrinsic::arm_neon_vst3lane:
1451     return LowerNeonVSTLaneIntrinsic(Op, DAG, 3);
1452   case Intrinsic::arm_neon_vst4lane:
1453     return LowerNeonVSTLaneIntrinsic(Op, DAG, 4);
1454   default: return SDValue();    // Don't custom lower most intrinsics.
1455   }
1456 }
1457
1458 SDValue
1459 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
1460   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1461   DebugLoc dl = Op.getDebugLoc();
1462   switch (IntNo) {
1463   default: return SDValue();    // Don't custom lower most intrinsics.
1464   case Intrinsic::arm_thread_pointer: {
1465     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1466     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1467   }
1468   case Intrinsic::eh_sjlj_lsda: {
1469     MachineFunction &MF = DAG.getMachineFunction();
1470     EVT PtrVT = getPointerTy();
1471     DebugLoc dl = Op.getDebugLoc();
1472     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1473     SDValue CPAddr;
1474     unsigned PCAdj = (RelocM != Reloc::PIC_)
1475       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1476     ARMConstantPoolValue *CPV =
1477       new ARMConstantPoolValue(MF.getFunction(), ARMPCLabelIndex,
1478                                ARMCP::CPLSDA, PCAdj);
1479     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1480     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1481     SDValue Result =
1482       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1483     SDValue Chain = Result.getValue(1);
1484
1485     if (RelocM == Reloc::PIC_) {
1486       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1487       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1488     }
1489     return Result;
1490   }
1491   case Intrinsic::eh_sjlj_setjmp:
1492     return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(1));
1493   }
1494 }
1495
1496 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1497                             unsigned VarArgsFrameIndex) {
1498   // vastart just stores the address of the VarArgsFrameIndex slot into the
1499   // memory location argument.
1500   DebugLoc dl = Op.getDebugLoc();
1501   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1502   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1503   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1504   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1505 }
1506
1507 SDValue
1508 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1509   SDNode *Node = Op.getNode();
1510   DebugLoc dl = Node->getDebugLoc();
1511   EVT VT = Node->getValueType(0);
1512   SDValue Chain = Op.getOperand(0);
1513   SDValue Size  = Op.getOperand(1);
1514   SDValue Align = Op.getOperand(2);
1515
1516   // Chain the dynamic stack allocation so that it doesn't modify the stack
1517   // pointer when other instructions are using the stack.
1518   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1519
1520   unsigned AlignVal = cast<ConstantSDNode>(Align)->getZExtValue();
1521   unsigned StackAlign = getTargetMachine().getFrameInfo()->getStackAlignment();
1522   if (AlignVal > StackAlign)
1523     // Do this now since selection pass cannot introduce new target
1524     // independent node.
1525     Align = DAG.getConstant(-(uint64_t)AlignVal, VT);
1526
1527   // In Thumb1 mode, there isn't a "sub r, sp, r" instruction, we will end up
1528   // using a "add r, sp, r" instead. Negate the size now so we don't have to
1529   // do even more horrible hack later.
1530   MachineFunction &MF = DAG.getMachineFunction();
1531   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1532   if (AFI->isThumb1OnlyFunction()) {
1533     bool Negate = true;
1534     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Size);
1535     if (C) {
1536       uint32_t Val = C->getZExtValue();
1537       if (Val <= 508 && ((Val & 3) == 0))
1538         Negate = false;
1539     }
1540     if (Negate)
1541       Size = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, VT), Size);
1542   }
1543
1544   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1545   SDValue Ops1[] = { Chain, Size, Align };
1546   SDValue Res = DAG.getNode(ARMISD::DYN_ALLOC, dl, VTList, Ops1, 3);
1547   Chain = Res.getValue(1);
1548   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1549                              DAG.getIntPtrConstant(0, true), SDValue());
1550   SDValue Ops2[] = { Res, Chain };
1551   return DAG.getMergeValues(Ops2, 2, dl);
1552 }
1553
1554 SDValue
1555 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
1556                                         SDValue &Root, SelectionDAG &DAG,
1557                                         DebugLoc dl) {
1558   MachineFunction &MF = DAG.getMachineFunction();
1559   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1560
1561   TargetRegisterClass *RC;
1562   if (AFI->isThumb1OnlyFunction())
1563     RC = ARM::tGPRRegisterClass;
1564   else
1565     RC = ARM::GPRRegisterClass;
1566
1567   // Transform the arguments stored in physical registers into virtual ones.
1568   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1569   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1570
1571   SDValue ArgValue2;
1572   if (NextVA.isMemLoc()) {
1573     unsigned ArgSize = NextVA.getLocVT().getSizeInBits()/8;
1574     MachineFrameInfo *MFI = MF.getFrameInfo();
1575     int FI = MFI->CreateFixedObject(ArgSize, NextVA.getLocMemOffset());
1576
1577     // Create load node to retrieve arguments from the stack.
1578     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1579     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
1580   } else {
1581     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1582     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1583   }
1584
1585   return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
1586 }
1587
1588 SDValue
1589 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
1590                                         CallingConv::ID CallConv, bool isVarArg,
1591                                         const SmallVectorImpl<ISD::InputArg>
1592                                           &Ins,
1593                                         DebugLoc dl, SelectionDAG &DAG,
1594                                         SmallVectorImpl<SDValue> &InVals) {
1595
1596   MachineFunction &MF = DAG.getMachineFunction();
1597   MachineFrameInfo *MFI = MF.getFrameInfo();
1598
1599   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1600
1601   // Assign locations to all of the incoming arguments.
1602   SmallVector<CCValAssign, 16> ArgLocs;
1603   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1604                  *DAG.getContext());
1605   CCInfo.AnalyzeFormalArguments(Ins,
1606                                 CCAssignFnForNode(CallConv, /* Return*/ false,
1607                                                   isVarArg));
1608
1609   SmallVector<SDValue, 16> ArgValues;
1610
1611   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1612     CCValAssign &VA = ArgLocs[i];
1613
1614     // Arguments stored in registers.
1615     if (VA.isRegLoc()) {
1616       EVT RegVT = VA.getLocVT();
1617
1618       SDValue ArgValue;
1619       if (VA.needsCustom()) {
1620         // f64 and vector types are split up into multiple registers or
1621         // combinations of registers and stack slots.
1622         RegVT = MVT::i32;
1623
1624         if (VA.getLocVT() == MVT::v2f64) {
1625           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
1626                                                    Chain, DAG, dl);
1627           VA = ArgLocs[++i]; // skip ahead to next loc
1628           SDValue ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
1629                                                    Chain, DAG, dl);
1630           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1631           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1632                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
1633           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1634                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
1635         } else
1636           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
1637
1638       } else {
1639         TargetRegisterClass *RC;
1640
1641         if (RegVT == MVT::f32)
1642           RC = ARM::SPRRegisterClass;
1643         else if (RegVT == MVT::f64)
1644           RC = ARM::DPRRegisterClass;
1645         else if (RegVT == MVT::v2f64)
1646           RC = ARM::QPRRegisterClass;
1647         else if (RegVT == MVT::i32)
1648           RC = (AFI->isThumb1OnlyFunction() ?
1649                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
1650         else
1651           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1652
1653         // Transform the arguments in physical registers into virtual ones.
1654         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1655         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1656       }
1657
1658       // If this is an 8 or 16-bit value, it is really passed promoted
1659       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1660       // truncate to the right size.
1661       switch (VA.getLocInfo()) {
1662       default: llvm_unreachable("Unknown loc info!");
1663       case CCValAssign::Full: break;
1664       case CCValAssign::BCvt:
1665         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1666         break;
1667       case CCValAssign::SExt:
1668         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1669                                DAG.getValueType(VA.getValVT()));
1670         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1671         break;
1672       case CCValAssign::ZExt:
1673         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1674                                DAG.getValueType(VA.getValVT()));
1675         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1676         break;
1677       }
1678
1679       InVals.push_back(ArgValue);
1680
1681     } else { // VA.isRegLoc()
1682
1683       // sanity check
1684       assert(VA.isMemLoc());
1685       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1686
1687       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1688       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1689
1690       // Create load nodes to retrieve arguments from the stack.
1691       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1692       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0));
1693     }
1694   }
1695
1696   // varargs
1697   if (isVarArg) {
1698     static const unsigned GPRArgRegs[] = {
1699       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1700     };
1701
1702     unsigned NumGPRs = CCInfo.getFirstUnallocated
1703       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1704
1705     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1706     unsigned VARegSize = (4 - NumGPRs) * 4;
1707     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1708     unsigned ArgOffset = 0;
1709     if (VARegSaveSize) {
1710       // If this function is vararg, store any remaining integer argument regs
1711       // to their spots on the stack so that they may be loaded by deferencing
1712       // the result of va_next.
1713       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1714       ArgOffset = CCInfo.getNextStackOffset();
1715       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1716                                                  VARegSaveSize - VARegSize);
1717       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1718
1719       SmallVector<SDValue, 4> MemOps;
1720       for (; NumGPRs < 4; ++NumGPRs) {
1721         TargetRegisterClass *RC;
1722         if (AFI->isThumb1OnlyFunction())
1723           RC = ARM::tGPRRegisterClass;
1724         else
1725           RC = ARM::GPRRegisterClass;
1726
1727         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1728         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1729         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1730         MemOps.push_back(Store);
1731         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1732                           DAG.getConstant(4, getPointerTy()));
1733       }
1734       if (!MemOps.empty())
1735         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1736                             &MemOps[0], MemOps.size());
1737     } else
1738       // This will point to the next argument passed via stack.
1739       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1740   }
1741
1742   return Chain;
1743 }
1744
1745 /// isFloatingPointZero - Return true if this is +0.0.
1746 static bool isFloatingPointZero(SDValue Op) {
1747   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1748     return CFP->getValueAPF().isPosZero();
1749   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1750     // Maybe this has already been legalized into the constant pool?
1751     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1752       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1753       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1754         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1755           return CFP->getValueAPF().isPosZero();
1756     }
1757   }
1758   return false;
1759 }
1760
1761 static bool isLegalCmpImmediate(unsigned C, bool isThumb1Only) {
1762   return ( isThumb1Only && (C & ~255U) == 0) ||
1763          (!isThumb1Only && ARM_AM::getSOImmVal(C) != -1);
1764 }
1765
1766 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1767 /// the given operands.
1768 static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1769                          SDValue &ARMCC, SelectionDAG &DAG, bool isThumb1Only,
1770                          DebugLoc dl) {
1771   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1772     unsigned C = RHSC->getZExtValue();
1773     if (!isLegalCmpImmediate(C, isThumb1Only)) {
1774       // Constant does not fit, try adjusting it by one?
1775       switch (CC) {
1776       default: break;
1777       case ISD::SETLT:
1778       case ISD::SETGE:
1779         if (isLegalCmpImmediate(C-1, isThumb1Only)) {
1780           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1781           RHS = DAG.getConstant(C-1, MVT::i32);
1782         }
1783         break;
1784       case ISD::SETULT:
1785       case ISD::SETUGE:
1786         if (C > 0 && isLegalCmpImmediate(C-1, isThumb1Only)) {
1787           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1788           RHS = DAG.getConstant(C-1, MVT::i32);
1789         }
1790         break;
1791       case ISD::SETLE:
1792       case ISD::SETGT:
1793         if (isLegalCmpImmediate(C+1, isThumb1Only)) {
1794           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1795           RHS = DAG.getConstant(C+1, MVT::i32);
1796         }
1797         break;
1798       case ISD::SETULE:
1799       case ISD::SETUGT:
1800         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb1Only)) {
1801           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1802           RHS = DAG.getConstant(C+1, MVT::i32);
1803         }
1804         break;
1805       }
1806     }
1807   }
1808
1809   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1810   ARMISD::NodeType CompareType;
1811   switch (CondCode) {
1812   default:
1813     CompareType = ARMISD::CMP;
1814     break;
1815   case ARMCC::EQ:
1816   case ARMCC::NE:
1817     // Uses only Z Flag
1818     CompareType = ARMISD::CMPZ;
1819     break;
1820   }
1821   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1822   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1823 }
1824
1825 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1826 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1827                          DebugLoc dl) {
1828   SDValue Cmp;
1829   if (!isFloatingPointZero(RHS))
1830     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1831   else
1832     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1833   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1834 }
1835
1836 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1837                               const ARMSubtarget *ST) {
1838   EVT VT = Op.getValueType();
1839   SDValue LHS = Op.getOperand(0);
1840   SDValue RHS = Op.getOperand(1);
1841   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1842   SDValue TrueVal = Op.getOperand(2);
1843   SDValue FalseVal = Op.getOperand(3);
1844   DebugLoc dl = Op.getDebugLoc();
1845
1846   if (LHS.getValueType() == MVT::i32) {
1847     SDValue ARMCC;
1848     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1849     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1850     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1851   }
1852
1853   ARMCC::CondCodes CondCode, CondCode2;
1854   FPCCToARMCC(CC, CondCode, CondCode2);
1855
1856   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1857   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1858   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1859   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1860                                  ARMCC, CCR, Cmp);
1861   if (CondCode2 != ARMCC::AL) {
1862     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1863     // FIXME: Needs another CMP because flag can have but one use.
1864     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1865     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1866                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1867   }
1868   return Result;
1869 }
1870
1871 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1872                           const ARMSubtarget *ST) {
1873   SDValue  Chain = Op.getOperand(0);
1874   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1875   SDValue    LHS = Op.getOperand(2);
1876   SDValue    RHS = Op.getOperand(3);
1877   SDValue   Dest = Op.getOperand(4);
1878   DebugLoc dl = Op.getDebugLoc();
1879
1880   if (LHS.getValueType() == MVT::i32) {
1881     SDValue ARMCC;
1882     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1883     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1884     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1885                        Chain, Dest, ARMCC, CCR,Cmp);
1886   }
1887
1888   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1889   ARMCC::CondCodes CondCode, CondCode2;
1890   FPCCToARMCC(CC, CondCode, CondCode2);
1891
1892   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1893   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1894   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1895   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1896   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1897   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1898   if (CondCode2 != ARMCC::AL) {
1899     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1900     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1901     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1902   }
1903   return Res;
1904 }
1905
1906 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1907   SDValue Chain = Op.getOperand(0);
1908   SDValue Table = Op.getOperand(1);
1909   SDValue Index = Op.getOperand(2);
1910   DebugLoc dl = Op.getDebugLoc();
1911
1912   EVT PTy = getPointerTy();
1913   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1914   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1915   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
1916   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1917   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1918   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1919   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1920   if (Subtarget->isThumb2()) {
1921     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
1922     // which does another jump to the destination. This also makes it easier
1923     // to translate it to TBB / TBH later.
1924     // FIXME: This might not work if the function is extremely large.
1925     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
1926                        Addr, Op.getOperand(2), JTI, UId);
1927   }
1928   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1929     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, NULL, 0);
1930     Chain = Addr.getValue(1);
1931     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1932     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1933   } else {
1934     Addr = DAG.getLoad(PTy, dl, Chain, Addr, NULL, 0);
1935     Chain = Addr.getValue(1);
1936     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1937   }
1938 }
1939
1940 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1941   DebugLoc dl = Op.getDebugLoc();
1942   unsigned Opc =
1943     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1944   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1945   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1946 }
1947
1948 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1949   EVT VT = Op.getValueType();
1950   DebugLoc dl = Op.getDebugLoc();
1951   unsigned Opc =
1952     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1953
1954   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1955   return DAG.getNode(Opc, dl, VT, Op);
1956 }
1957
1958 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1959   // Implement fcopysign with a fabs and a conditional fneg.
1960   SDValue Tmp0 = Op.getOperand(0);
1961   SDValue Tmp1 = Op.getOperand(1);
1962   DebugLoc dl = Op.getDebugLoc();
1963   EVT VT = Op.getValueType();
1964   EVT SrcVT = Tmp1.getValueType();
1965   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1966   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1967   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1968   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1969   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1970 }
1971
1972 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1973   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1974   MFI->setFrameAddressIsTaken(true);
1975   EVT VT = Op.getValueType();
1976   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1977   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1978   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
1979     ? ARM::R7 : ARM::R11;
1980   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1981   while (Depth--)
1982     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1983   return FrameAddr;
1984 }
1985
1986 SDValue
1987 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1988                                            SDValue Chain,
1989                                            SDValue Dst, SDValue Src,
1990                                            SDValue Size, unsigned Align,
1991                                            bool AlwaysInline,
1992                                          const Value *DstSV, uint64_t DstSVOff,
1993                                          const Value *SrcSV, uint64_t SrcSVOff){
1994   // Do repeated 4-byte loads and stores. To be improved.
1995   // This requires 4-byte alignment.
1996   if ((Align & 3) != 0)
1997     return SDValue();
1998   // This requires the copy size to be a constant, preferrably
1999   // within a subtarget-specific limit.
2000   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2001   if (!ConstantSize)
2002     return SDValue();
2003   uint64_t SizeVal = ConstantSize->getZExtValue();
2004   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
2005     return SDValue();
2006
2007   unsigned BytesLeft = SizeVal & 3;
2008   unsigned NumMemOps = SizeVal >> 2;
2009   unsigned EmittedNumMemOps = 0;
2010   EVT VT = MVT::i32;
2011   unsigned VTSize = 4;
2012   unsigned i = 0;
2013   const unsigned MAX_LOADS_IN_LDM = 6;
2014   SDValue TFOps[MAX_LOADS_IN_LDM];
2015   SDValue Loads[MAX_LOADS_IN_LDM];
2016   uint64_t SrcOff = 0, DstOff = 0;
2017
2018   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
2019   // same number of stores.  The loads and stores will get combined into
2020   // ldm/stm later on.
2021   while (EmittedNumMemOps < NumMemOps) {
2022     for (i = 0;
2023          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
2024       Loads[i] = DAG.getLoad(VT, dl, Chain,
2025                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
2026                                          DAG.getConstant(SrcOff, MVT::i32)),
2027                              SrcSV, SrcSVOff + SrcOff);
2028       TFOps[i] = Loads[i].getValue(1);
2029       SrcOff += VTSize;
2030     }
2031     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2032
2033     for (i = 0;
2034          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
2035       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
2036                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
2037                                        DAG.getConstant(DstOff, MVT::i32)),
2038                            DstSV, DstSVOff + DstOff);
2039       DstOff += VTSize;
2040     }
2041     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2042
2043     EmittedNumMemOps += i;
2044   }
2045
2046   if (BytesLeft == 0)
2047     return Chain;
2048
2049   // Issue loads / stores for the trailing (1 - 3) bytes.
2050   unsigned BytesLeftSave = BytesLeft;
2051   i = 0;
2052   while (BytesLeft) {
2053     if (BytesLeft >= 2) {
2054       VT = MVT::i16;
2055       VTSize = 2;
2056     } else {
2057       VT = MVT::i8;
2058       VTSize = 1;
2059     }
2060
2061     Loads[i] = DAG.getLoad(VT, dl, Chain,
2062                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
2063                                        DAG.getConstant(SrcOff, MVT::i32)),
2064                            SrcSV, SrcSVOff + SrcOff);
2065     TFOps[i] = Loads[i].getValue(1);
2066     ++i;
2067     SrcOff += VTSize;
2068     BytesLeft -= VTSize;
2069   }
2070   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2071
2072   i = 0;
2073   BytesLeft = BytesLeftSave;
2074   while (BytesLeft) {
2075     if (BytesLeft >= 2) {
2076       VT = MVT::i16;
2077       VTSize = 2;
2078     } else {
2079       VT = MVT::i8;
2080       VTSize = 1;
2081     }
2082
2083     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
2084                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
2085                                         DAG.getConstant(DstOff, MVT::i32)),
2086                             DstSV, DstSVOff + DstOff);
2087     ++i;
2088     DstOff += VTSize;
2089     BytesLeft -= VTSize;
2090   }
2091   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2092 }
2093
2094 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
2095   SDValue Op = N->getOperand(0);
2096   DebugLoc dl = N->getDebugLoc();
2097   if (N->getValueType(0) == MVT::f64) {
2098     // Turn i64->f64 into FMDRR.
2099     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2100                              DAG.getConstant(0, MVT::i32));
2101     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2102                              DAG.getConstant(1, MVT::i32));
2103     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
2104   }
2105
2106   // Turn f64->i64 into FMRRD.
2107   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
2108                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
2109
2110   // Merge the pieces into a single i64 value.
2111   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
2112 }
2113
2114 /// getZeroVector - Returns a vector of specified type with all zero elements.
2115 ///
2116 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2117   assert(VT.isVector() && "Expected a vector type");
2118
2119   // Zero vectors are used to represent vector negation and in those cases
2120   // will be implemented with the NEON VNEG instruction.  However, VNEG does
2121   // not support i64 elements, so sometimes the zero vectors will need to be
2122   // explicitly constructed.  For those cases, and potentially other uses in
2123   // the future, always build zero vectors as <16 x i8> or <8 x i8> bitcasted
2124   // to their dest type.  This ensures they get CSE'd.
2125   SDValue Vec;
2126   SDValue Cst = DAG.getTargetConstant(0, MVT::i8);
2127   SmallVector<SDValue, 8> Ops;
2128   MVT TVT;
2129
2130   if (VT.getSizeInBits() == 64) {
2131     Ops.assign(8, Cst); TVT = MVT::v8i8;
2132   } else {
2133     Ops.assign(16, Cst); TVT = MVT::v16i8;
2134   }
2135   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2136
2137   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2138 }
2139
2140 /// getOnesVector - Returns a vector of specified type with all bits set.
2141 ///
2142 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2143   assert(VT.isVector() && "Expected a vector type");
2144
2145   // Always build ones vectors as <16 x i32> or <8 x i32> bitcasted to their
2146   // dest type. This ensures they get CSE'd.
2147   SDValue Vec;
2148   SDValue Cst = DAG.getTargetConstant(0xFF, MVT::i8);
2149   SmallVector<SDValue, 8> Ops;
2150   MVT TVT;
2151
2152   if (VT.getSizeInBits() == 64) {
2153     Ops.assign(8, Cst); TVT = MVT::v8i8;
2154   } else {
2155     Ops.assign(16, Cst); TVT = MVT::v16i8;
2156   }
2157   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2158
2159   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2160 }
2161
2162 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
2163                           const ARMSubtarget *ST) {
2164   EVT VT = N->getValueType(0);
2165   DebugLoc dl = N->getDebugLoc();
2166
2167   // Lower vector shifts on NEON to use VSHL.
2168   if (VT.isVector()) {
2169     assert(ST->hasNEON() && "unexpected vector shift");
2170
2171     // Left shifts translate directly to the vshiftu intrinsic.
2172     if (N->getOpcode() == ISD::SHL)
2173       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2174                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
2175                          N->getOperand(0), N->getOperand(1));
2176
2177     assert((N->getOpcode() == ISD::SRA ||
2178             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
2179
2180     // NEON uses the same intrinsics for both left and right shifts.  For
2181     // right shifts, the shift amounts are negative, so negate the vector of
2182     // shift amounts.
2183     EVT ShiftVT = N->getOperand(1).getValueType();
2184     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2185                                        getZeroVector(ShiftVT, DAG, dl),
2186                                        N->getOperand(1));
2187     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2188                                Intrinsic::arm_neon_vshifts :
2189                                Intrinsic::arm_neon_vshiftu);
2190     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2191                        DAG.getConstant(vshiftInt, MVT::i32),
2192                        N->getOperand(0), NegatedCount);
2193   }
2194
2195   // We can get here for a node like i32 = ISD::SHL i32, i64
2196   if (VT != MVT::i64)
2197     return SDValue();
2198
2199   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2200          "Unknown shift to lower!");
2201
2202   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2203   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2204       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2205     return SDValue();
2206
2207   // If we are in thumb mode, we don't have RRX.
2208   if (ST->isThumb1Only()) return SDValue();
2209
2210   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2211   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2212                              DAG.getConstant(0, MVT::i32));
2213   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2214                              DAG.getConstant(1, MVT::i32));
2215
2216   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2217   // captures the result into a carry flag.
2218   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2219   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2220
2221   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2222   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2223
2224   // Merge the pieces into a single i64 value.
2225  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2226 }
2227
2228 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2229   SDValue TmpOp0, TmpOp1;
2230   bool Invert = false;
2231   bool Swap = false;
2232   unsigned Opc = 0;
2233
2234   SDValue Op0 = Op.getOperand(0);
2235   SDValue Op1 = Op.getOperand(1);
2236   SDValue CC = Op.getOperand(2);
2237   EVT VT = Op.getValueType();
2238   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2239   DebugLoc dl = Op.getDebugLoc();
2240
2241   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2242     switch (SetCCOpcode) {
2243     default: llvm_unreachable("Illegal FP comparison"); break;
2244     case ISD::SETUNE:
2245     case ISD::SETNE:  Invert = true; // Fallthrough
2246     case ISD::SETOEQ:
2247     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2248     case ISD::SETOLT:
2249     case ISD::SETLT: Swap = true; // Fallthrough
2250     case ISD::SETOGT:
2251     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2252     case ISD::SETOLE:
2253     case ISD::SETLE:  Swap = true; // Fallthrough
2254     case ISD::SETOGE:
2255     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2256     case ISD::SETUGE: Swap = true; // Fallthrough
2257     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2258     case ISD::SETUGT: Swap = true; // Fallthrough
2259     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2260     case ISD::SETUEQ: Invert = true; // Fallthrough
2261     case ISD::SETONE:
2262       // Expand this to (OLT | OGT).
2263       TmpOp0 = Op0;
2264       TmpOp1 = Op1;
2265       Opc = ISD::OR;
2266       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2267       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2268       break;
2269     case ISD::SETUO: Invert = true; // Fallthrough
2270     case ISD::SETO:
2271       // Expand this to (OLT | OGE).
2272       TmpOp0 = Op0;
2273       TmpOp1 = Op1;
2274       Opc = ISD::OR;
2275       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2276       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2277       break;
2278     }
2279   } else {
2280     // Integer comparisons.
2281     switch (SetCCOpcode) {
2282     default: llvm_unreachable("Illegal integer comparison"); break;
2283     case ISD::SETNE:  Invert = true;
2284     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2285     case ISD::SETLT:  Swap = true;
2286     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2287     case ISD::SETLE:  Swap = true;
2288     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2289     case ISD::SETULT: Swap = true;
2290     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2291     case ISD::SETULE: Swap = true;
2292     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2293     }
2294
2295     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2296     if (Opc == ARMISD::VCEQ) {
2297
2298       SDValue AndOp;
2299       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2300         AndOp = Op0;
2301       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2302         AndOp = Op1;
2303
2304       // Ignore bitconvert.
2305       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2306         AndOp = AndOp.getOperand(0);
2307
2308       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2309         Opc = ARMISD::VTST;
2310         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2311         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2312         Invert = !Invert;
2313       }
2314     }
2315   }
2316
2317   if (Swap)
2318     std::swap(Op0, Op1);
2319
2320   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2321
2322   if (Invert)
2323     Result = DAG.getNOT(dl, Result, VT);
2324
2325   return Result;
2326 }
2327
2328 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2329 /// VMOV instruction, and if so, return the constant being splatted.
2330 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2331                            unsigned SplatBitSize, SelectionDAG &DAG) {
2332   switch (SplatBitSize) {
2333   case 8:
2334     // Any 1-byte value is OK.
2335     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2336     return DAG.getTargetConstant(SplatBits, MVT::i8);
2337
2338   case 16:
2339     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2340     if ((SplatBits & ~0xff) == 0 ||
2341         (SplatBits & ~0xff00) == 0)
2342       return DAG.getTargetConstant(SplatBits, MVT::i16);
2343     break;
2344
2345   case 32:
2346     // NEON's 32-bit VMOV supports splat values where:
2347     // * only one byte is nonzero, or
2348     // * the least significant byte is 0xff and the second byte is nonzero, or
2349     // * the least significant 2 bytes are 0xff and the third is nonzero.
2350     if ((SplatBits & ~0xff) == 0 ||
2351         (SplatBits & ~0xff00) == 0 ||
2352         (SplatBits & ~0xff0000) == 0 ||
2353         (SplatBits & ~0xff000000) == 0)
2354       return DAG.getTargetConstant(SplatBits, MVT::i32);
2355
2356     if ((SplatBits & ~0xffff) == 0 &&
2357         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2358       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2359
2360     if ((SplatBits & ~0xffffff) == 0 &&
2361         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2362       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2363
2364     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2365     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2366     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2367     // and fall through here to test for a valid 64-bit splat.  But, then the
2368     // caller would also need to check and handle the change in size.
2369     break;
2370
2371   case 64: {
2372     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2373     uint64_t BitMask = 0xff;
2374     uint64_t Val = 0;
2375     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2376       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2377         Val |= BitMask;
2378       else if ((SplatBits & BitMask) != 0)
2379         return SDValue();
2380       BitMask <<= 8;
2381     }
2382     return DAG.getTargetConstant(Val, MVT::i64);
2383   }
2384
2385   default:
2386     llvm_unreachable("unexpected size for isVMOVSplat");
2387     break;
2388   }
2389
2390   return SDValue();
2391 }
2392
2393 /// getVMOVImm - If this is a build_vector of constants which can be
2394 /// formed by using a VMOV instruction of the specified element size,
2395 /// return the constant being splatted.  The ByteSize field indicates the
2396 /// number of bytes of each element [1248].
2397 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2398   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2399   APInt SplatBits, SplatUndef;
2400   unsigned SplatBitSize;
2401   bool HasAnyUndefs;
2402   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2403                                       HasAnyUndefs, ByteSize * 8))
2404     return SDValue();
2405
2406   if (SplatBitSize > ByteSize * 8)
2407     return SDValue();
2408
2409   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2410                      SplatBitSize, DAG);
2411 }
2412
2413 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
2414                        bool &ReverseVEXT, unsigned &Imm) {
2415   unsigned NumElts = VT.getVectorNumElements();
2416   ReverseVEXT = false;
2417   Imm = M[0];
2418
2419   // If this is a VEXT shuffle, the immediate value is the index of the first
2420   // element.  The other shuffle indices must be the successive elements after
2421   // the first one.
2422   unsigned ExpectedElt = Imm;
2423   for (unsigned i = 1; i < NumElts; ++i) {
2424     // Increment the expected index.  If it wraps around, it may still be
2425     // a VEXT but the source vectors must be swapped.
2426     ExpectedElt += 1;
2427     if (ExpectedElt == NumElts * 2) {
2428       ExpectedElt = 0;
2429       ReverseVEXT = true;
2430     }
2431
2432     if (ExpectedElt != static_cast<unsigned>(M[i]))
2433       return false;
2434   }
2435
2436   // Adjust the index value if the source operands will be swapped.
2437   if (ReverseVEXT)
2438     Imm -= NumElts;
2439
2440   return true;
2441 }
2442
2443 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2444 /// instruction with the specified blocksize.  (The order of the elements
2445 /// within each block of the vector is reversed.)
2446 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
2447                        unsigned BlockSize) {
2448   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2449          "Only possible block sizes for VREV are: 16, 32, 64");
2450
2451   unsigned NumElts = VT.getVectorNumElements();
2452   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2453   unsigned BlockElts = M[0] + 1;
2454
2455   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2456     return false;
2457
2458   for (unsigned i = 0; i < NumElts; ++i) {
2459     if ((unsigned) M[i] !=
2460         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2461       return false;
2462   }
2463
2464   return true;
2465 }
2466
2467 static bool isVTRNMask(const SmallVectorImpl<int> &M, EVT VT,
2468                        unsigned &WhichResult) {
2469   unsigned NumElts = VT.getVectorNumElements();
2470   WhichResult = (M[0] == 0 ? 0 : 1);
2471   for (unsigned i = 0; i < NumElts; i += 2) {
2472     if ((unsigned) M[i] != i + WhichResult ||
2473         (unsigned) M[i+1] != i + NumElts + WhichResult)
2474       return false;
2475   }
2476   return true;
2477 }
2478
2479 static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
2480                        unsigned &WhichResult) {
2481   unsigned NumElts = VT.getVectorNumElements();
2482   WhichResult = (M[0] == 0 ? 0 : 1);
2483   for (unsigned i = 0; i != NumElts; ++i) {
2484     if ((unsigned) M[i] != 2 * i + WhichResult)
2485       return false;
2486   }
2487
2488   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2489   if (VT.is64BitVector() && VT.getVectorElementType().getSizeInBits() == 32)
2490     return false;
2491
2492   return true;
2493 }
2494
2495 static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
2496                        unsigned &WhichResult) {
2497   unsigned NumElts = VT.getVectorNumElements();
2498   WhichResult = (M[0] == 0 ? 0 : 1);
2499   unsigned Idx = WhichResult * NumElts / 2;
2500   for (unsigned i = 0; i != NumElts; i += 2) {
2501     if ((unsigned) M[i] != Idx ||
2502         (unsigned) M[i+1] != Idx + NumElts)
2503       return false;
2504     Idx += 1;
2505   }
2506
2507   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2508   if (VT.is64BitVector() && VT.getVectorElementType().getSizeInBits() == 32)
2509     return false;
2510
2511   return true;
2512 }
2513
2514 static SDValue BuildSplat(SDValue Val, EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2515   // Canonicalize all-zeros and all-ones vectors.
2516   ConstantSDNode *ConstVal = cast<ConstantSDNode>(Val.getNode());
2517   if (ConstVal->isNullValue())
2518     return getZeroVector(VT, DAG, dl);
2519   if (ConstVal->isAllOnesValue())
2520     return getOnesVector(VT, DAG, dl);
2521
2522   EVT CanonicalVT;
2523   if (VT.is64BitVector()) {
2524     switch (Val.getValueType().getSizeInBits()) {
2525     case 8:  CanonicalVT = MVT::v8i8; break;
2526     case 16: CanonicalVT = MVT::v4i16; break;
2527     case 32: CanonicalVT = MVT::v2i32; break;
2528     case 64: CanonicalVT = MVT::v1i64; break;
2529     default: llvm_unreachable("unexpected splat element type"); break;
2530     }
2531   } else {
2532     assert(VT.is128BitVector() && "unknown splat vector size");
2533     switch (Val.getValueType().getSizeInBits()) {
2534     case 8:  CanonicalVT = MVT::v16i8; break;
2535     case 16: CanonicalVT = MVT::v8i16; break;
2536     case 32: CanonicalVT = MVT::v4i32; break;
2537     case 64: CanonicalVT = MVT::v2i64; break;
2538     default: llvm_unreachable("unexpected splat element type"); break;
2539     }
2540   }
2541
2542   // Build a canonical splat for this value.
2543   SmallVector<SDValue, 8> Ops;
2544   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2545   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2546                             Ops.size());
2547   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2548 }
2549
2550 // If this is a case we can't handle, return null and let the default
2551 // expansion code take care of it.
2552 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2553   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
2554   DebugLoc dl = Op.getDebugLoc();
2555   EVT VT = Op.getValueType();
2556
2557   APInt SplatBits, SplatUndef;
2558   unsigned SplatBitSize;
2559   bool HasAnyUndefs;
2560   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2561     if (SplatBitSize <= 64) {
2562       SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2563                                 SplatUndef.getZExtValue(), SplatBitSize, DAG);
2564       if (Val.getNode())
2565         return BuildSplat(Val, VT, DAG, dl);
2566     }
2567   }
2568
2569   // If there are only 2 elements in a 128-bit vector, insert them into an
2570   // undef vector.  This handles the common case for 128-bit vector argument
2571   // passing, where the insertions should be translated to subreg accesses
2572   // with no real instructions.
2573   if (VT.is128BitVector() && Op.getNumOperands() == 2) {
2574     SDValue Val = DAG.getUNDEF(VT);
2575     SDValue Op0 = Op.getOperand(0);
2576     SDValue Op1 = Op.getOperand(1);
2577     if (Op0.getOpcode() != ISD::UNDEF)
2578       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op0,
2579                         DAG.getIntPtrConstant(0));
2580     if (Op1.getOpcode() != ISD::UNDEF)
2581       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op1,
2582                         DAG.getIntPtrConstant(1));
2583     return Val;
2584   }
2585
2586   return SDValue();
2587 }
2588
2589 /// isShuffleMaskLegal - Targets can use this to indicate that they only
2590 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
2591 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
2592 /// are assumed to be legal.
2593 bool
2594 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
2595                                       EVT VT) const {
2596   if (VT.getVectorNumElements() == 4 &&
2597       (VT.is128BitVector() || VT.is64BitVector())) {
2598     unsigned PFIndexes[4];
2599     for (unsigned i = 0; i != 4; ++i) {
2600       if (M[i] < 0)
2601         PFIndexes[i] = 8;
2602       else
2603         PFIndexes[i] = M[i];
2604     }
2605
2606     // Compute the index in the perfect shuffle table.
2607     unsigned PFTableIndex =
2608       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2609     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2610     unsigned Cost = (PFEntry >> 30);
2611
2612     if (Cost <= 4)
2613       return true;
2614   }
2615
2616   bool ReverseVEXT;
2617   unsigned Imm, WhichResult;
2618
2619   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
2620           isVREVMask(M, VT, 64) ||
2621           isVREVMask(M, VT, 32) ||
2622           isVREVMask(M, VT, 16) ||
2623           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
2624           isVTRNMask(M, VT, WhichResult) ||
2625           isVUZPMask(M, VT, WhichResult) ||
2626           isVZIPMask(M, VT, WhichResult));
2627 }
2628
2629 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
2630 /// the specified operations to build the shuffle.
2631 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
2632                                       SDValue RHS, SelectionDAG &DAG,
2633                                       DebugLoc dl) {
2634   unsigned OpNum = (PFEntry >> 26) & 0x0F;
2635   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
2636   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
2637
2638   enum {
2639     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
2640     OP_VREV,
2641     OP_VDUP0,
2642     OP_VDUP1,
2643     OP_VDUP2,
2644     OP_VDUP3,
2645     OP_VEXT1,
2646     OP_VEXT2,
2647     OP_VEXT3,
2648     OP_VUZPL, // VUZP, left result
2649     OP_VUZPR, // VUZP, right result
2650     OP_VZIPL, // VZIP, left result
2651     OP_VZIPR, // VZIP, right result
2652     OP_VTRNL, // VTRN, left result
2653     OP_VTRNR  // VTRN, right result
2654   };
2655
2656   if (OpNum == OP_COPY) {
2657     if (LHSID == (1*9+2)*9+3) return LHS;
2658     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
2659     return RHS;
2660   }
2661
2662   SDValue OpLHS, OpRHS;
2663   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
2664   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
2665   EVT VT = OpLHS.getValueType();
2666
2667   switch (OpNum) {
2668   default: llvm_unreachable("Unknown shuffle opcode!");
2669   case OP_VREV:
2670     return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
2671   case OP_VDUP0:
2672   case OP_VDUP1:
2673   case OP_VDUP2:
2674   case OP_VDUP3:
2675     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
2676                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
2677   case OP_VEXT1:
2678   case OP_VEXT2:
2679   case OP_VEXT3:
2680     return DAG.getNode(ARMISD::VEXT, dl, VT,
2681                        OpLHS, OpRHS,
2682                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
2683   case OP_VUZPL:
2684   case OP_VUZPR:
2685     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
2686                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
2687   case OP_VZIPL:
2688   case OP_VZIPR:
2689     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
2690                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
2691   case OP_VTRNL:
2692   case OP_VTRNR:
2693     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
2694                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
2695   }
2696 }
2697
2698 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2699   SDValue V1 = Op.getOperand(0);
2700   SDValue V2 = Op.getOperand(1);
2701   DebugLoc dl = Op.getDebugLoc();
2702   EVT VT = Op.getValueType();
2703   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2704   SmallVector<int, 8> ShuffleMask;
2705
2706   // Convert shuffles that are directly supported on NEON to target-specific
2707   // DAG nodes, instead of keeping them as shuffles and matching them again
2708   // during code selection.  This is more efficient and avoids the possibility
2709   // of inconsistencies between legalization and selection.
2710   // FIXME: floating-point vectors should be canonicalized to integer vectors
2711   // of the same time so that they get CSEd properly.
2712   SVN->getMask(ShuffleMask);
2713
2714   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
2715     int Lane = SVN->getSplatIndex();
2716     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
2717       return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
2718     }
2719     return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
2720                        DAG.getConstant(Lane, MVT::i32));
2721   }
2722
2723   bool ReverseVEXT;
2724   unsigned Imm;
2725   if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
2726     if (ReverseVEXT)
2727       std::swap(V1, V2);
2728     return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
2729                        DAG.getConstant(Imm, MVT::i32));
2730   }
2731
2732   if (isVREVMask(ShuffleMask, VT, 64))
2733     return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
2734   if (isVREVMask(ShuffleMask, VT, 32))
2735     return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
2736   if (isVREVMask(ShuffleMask, VT, 16))
2737     return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
2738
2739   // Check for Neon shuffles that modify both input vectors in place.
2740   // If both results are used, i.e., if there are two shuffles with the same
2741   // source operands and with masks corresponding to both results of one of
2742   // these operations, DAG memoization will ensure that a single node is
2743   // used for both shuffles.
2744   unsigned WhichResult;
2745   if (isVTRNMask(ShuffleMask, VT, WhichResult))
2746     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
2747                        V1, V2).getValue(WhichResult);
2748   if (isVUZPMask(ShuffleMask, VT, WhichResult))
2749     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
2750                        V1, V2).getValue(WhichResult);
2751   if (isVZIPMask(ShuffleMask, VT, WhichResult))
2752     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
2753                        V1, V2).getValue(WhichResult);
2754
2755   // If the shuffle is not directly supported and it has 4 elements, use
2756   // the PerfectShuffle-generated table to synthesize it from other shuffles.
2757   if (VT.getVectorNumElements() == 4 &&
2758       (VT.is128BitVector() || VT.is64BitVector())) {
2759     unsigned PFIndexes[4];
2760     for (unsigned i = 0; i != 4; ++i) {
2761       if (ShuffleMask[i] < 0)
2762         PFIndexes[i] = 8;
2763       else
2764         PFIndexes[i] = ShuffleMask[i];
2765     }
2766
2767     // Compute the index in the perfect shuffle table.
2768     unsigned PFTableIndex =
2769       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2770
2771     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2772     unsigned Cost = (PFEntry >> 30);
2773
2774     if (Cost <= 4)
2775       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
2776   }
2777
2778   return SDValue();
2779 }
2780
2781 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
2782   EVT VT = Op.getValueType();
2783   DebugLoc dl = Op.getDebugLoc();
2784   SDValue Vec = Op.getOperand(0);
2785   SDValue Lane = Op.getOperand(1);
2786
2787   // FIXME: This is invalid for 8 and 16-bit elements - the information about
2788   // sign / zero extension is lost!
2789   Op = DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
2790   Op = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Op, DAG.getValueType(VT));
2791
2792   if (VT.bitsLT(MVT::i32))
2793     Op = DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
2794   else if (VT.bitsGT(MVT::i32))
2795     Op = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op);
2796
2797   return Op;
2798 }
2799
2800 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
2801   // The only time a CONCAT_VECTORS operation can have legal types is when
2802   // two 64-bit vectors are concatenated to a 128-bit vector.
2803   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
2804          "unexpected CONCAT_VECTORS");
2805   DebugLoc dl = Op.getDebugLoc();
2806   SDValue Val = DAG.getUNDEF(MVT::v2f64);
2807   SDValue Op0 = Op.getOperand(0);
2808   SDValue Op1 = Op.getOperand(1);
2809   if (Op0.getOpcode() != ISD::UNDEF)
2810     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2811                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
2812                       DAG.getIntPtrConstant(0));
2813   if (Op1.getOpcode() != ISD::UNDEF)
2814     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2815                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
2816                       DAG.getIntPtrConstant(1));
2817   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
2818 }
2819
2820 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
2821   switch (Op.getOpcode()) {
2822   default: llvm_unreachable("Don't know how to custom lower this!");
2823   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
2824   case ISD::GlobalAddress:
2825     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
2826       LowerGlobalAddressELF(Op, DAG);
2827   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2828   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
2829   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
2830   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
2831   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
2832   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
2833   case ISD::SINT_TO_FP:
2834   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
2835   case ISD::FP_TO_SINT:
2836   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
2837   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
2838   case ISD::RETURNADDR:    break;
2839   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2840   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2841   case ISD::INTRINSIC_VOID:
2842   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2843   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2844   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
2845   case ISD::SHL:
2846   case ISD::SRL:
2847   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
2848   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
2849   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
2850   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2851   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2852   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
2853   }
2854   return SDValue();
2855 }
2856
2857 /// ReplaceNodeResults - Replace the results of node with an illegal result
2858 /// type with new values built out of custom code.
2859 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
2860                                            SmallVectorImpl<SDValue>&Results,
2861                                            SelectionDAG &DAG) {
2862   switch (N->getOpcode()) {
2863   default:
2864     llvm_unreachable("Don't know how to custom expand this!");
2865     return;
2866   case ISD::BIT_CONVERT:
2867     Results.push_back(ExpandBIT_CONVERT(N, DAG));
2868     return;
2869   case ISD::SRL:
2870   case ISD::SRA: {
2871     SDValue Res = LowerShift(N, DAG, Subtarget);
2872     if (Res.getNode())
2873       Results.push_back(Res);
2874     return;
2875   }
2876   }
2877 }
2878
2879 //===----------------------------------------------------------------------===//
2880 //                           ARM Scheduler Hooks
2881 //===----------------------------------------------------------------------===//
2882
2883 MachineBasicBlock *
2884 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2885                                                MachineBasicBlock *BB) const {
2886   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2887   DebugLoc dl = MI->getDebugLoc();
2888   switch (MI->getOpcode()) {
2889   default:
2890     llvm_unreachable("Unexpected instr type to insert");
2891   case ARM::tMOVCCr_pseudo: {
2892     // To "insert" a SELECT_CC instruction, we actually have to insert the
2893     // diamond control-flow pattern.  The incoming instruction knows the
2894     // destination vreg to set, the condition code register to branch on, the
2895     // true/false values to select between, and a branch opcode to use.
2896     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2897     MachineFunction::iterator It = BB;
2898     ++It;
2899
2900     //  thisMBB:
2901     //  ...
2902     //   TrueVal = ...
2903     //   cmpTY ccX, r1, r2
2904     //   bCC copy1MBB
2905     //   fallthrough --> copy0MBB
2906     MachineBasicBlock *thisMBB  = BB;
2907     MachineFunction *F = BB->getParent();
2908     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2909     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
2910     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
2911       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
2912     F->insert(It, copy0MBB);
2913     F->insert(It, sinkMBB);
2914     // Update machine-CFG edges by first adding all successors of the current
2915     // block to the new block which will contain the Phi node for the select.
2916     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
2917         e = BB->succ_end(); i != e; ++i)
2918       sinkMBB->addSuccessor(*i);
2919     // Next, remove all successors of the current block, and add the true
2920     // and fallthrough blocks as its successors.
2921     while(!BB->succ_empty())
2922       BB->removeSuccessor(BB->succ_begin());
2923     BB->addSuccessor(copy0MBB);
2924     BB->addSuccessor(sinkMBB);
2925
2926     //  copy0MBB:
2927     //   %FalseValue = ...
2928     //   # fallthrough to sinkMBB
2929     BB = copy0MBB;
2930
2931     // Update machine-CFG edges
2932     BB->addSuccessor(sinkMBB);
2933
2934     //  sinkMBB:
2935     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2936     //  ...
2937     BB = sinkMBB;
2938     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
2939       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
2940       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
2941
2942     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2943     return BB;
2944   }
2945
2946   case ARM::tANDsp:
2947   case ARM::tADDspr_:
2948   case ARM::tSUBspi_:
2949   case ARM::t2SUBrSPi_:
2950   case ARM::t2SUBrSPi12_:
2951   case ARM::t2SUBrSPs_: {
2952     MachineFunction *MF = BB->getParent();
2953     unsigned DstReg = MI->getOperand(0).getReg();
2954     unsigned SrcReg = MI->getOperand(1).getReg();
2955     bool DstIsDead = MI->getOperand(0).isDead();
2956     bool SrcIsKill = MI->getOperand(1).isKill();
2957
2958     if (SrcReg != ARM::SP) {
2959       // Copy the source to SP from virtual register.
2960       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(SrcReg);
2961       unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
2962         ? ARM::tMOVtgpr2gpr : ARM::tMOVgpr2gpr;
2963       BuildMI(BB, dl, TII->get(CopyOpc), ARM::SP)
2964         .addReg(SrcReg, getKillRegState(SrcIsKill));
2965     }
2966
2967     unsigned OpOpc = 0;
2968     bool NeedPred = false, NeedCC = false, NeedOp3 = false;
2969     switch (MI->getOpcode()) {
2970     default:
2971       llvm_unreachable("Unexpected pseudo instruction!");
2972     case ARM::tANDsp:
2973       OpOpc = ARM::tAND;
2974       NeedPred = true;
2975       break;
2976     case ARM::tADDspr_:
2977       OpOpc = ARM::tADDspr;
2978       break;
2979     case ARM::tSUBspi_:
2980       OpOpc = ARM::tSUBspi;
2981       break;
2982     case ARM::t2SUBrSPi_:
2983       OpOpc = ARM::t2SUBrSPi;
2984       NeedPred = true; NeedCC = true;
2985       break;
2986     case ARM::t2SUBrSPi12_:
2987       OpOpc = ARM::t2SUBrSPi12;
2988       NeedPred = true;
2989       break;
2990     case ARM::t2SUBrSPs_:
2991       OpOpc = ARM::t2SUBrSPs;
2992       NeedPred = true; NeedCC = true; NeedOp3 = true;
2993       break;
2994     }
2995     MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(OpOpc), ARM::SP);
2996     if (OpOpc == ARM::tAND)
2997       AddDefaultT1CC(MIB);
2998     MIB.addReg(ARM::SP);
2999     MIB.addOperand(MI->getOperand(2));
3000     if (NeedOp3)
3001       MIB.addOperand(MI->getOperand(3));
3002     if (NeedPred)
3003       AddDefaultPred(MIB);
3004     if (NeedCC)
3005       AddDefaultCC(MIB);
3006
3007     // Copy the result from SP to virtual register.
3008     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(DstReg);
3009     unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
3010       ? ARM::tMOVgpr2tgpr : ARM::tMOVgpr2gpr;
3011     BuildMI(BB, dl, TII->get(CopyOpc))
3012       .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstIsDead))
3013       .addReg(ARM::SP);
3014     MF->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
3015     return BB;
3016   }
3017   }
3018 }
3019
3020 //===----------------------------------------------------------------------===//
3021 //                           ARM Optimization Hooks
3022 //===----------------------------------------------------------------------===//
3023
3024 static
3025 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
3026                             TargetLowering::DAGCombinerInfo &DCI) {
3027   SelectionDAG &DAG = DCI.DAG;
3028   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3029   EVT VT = N->getValueType(0);
3030   unsigned Opc = N->getOpcode();
3031   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
3032   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
3033   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
3034   ISD::CondCode CC = ISD::SETCC_INVALID;
3035
3036   if (isSlctCC) {
3037     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
3038   } else {
3039     SDValue CCOp = Slct.getOperand(0);
3040     if (CCOp.getOpcode() == ISD::SETCC)
3041       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
3042   }
3043
3044   bool DoXform = false;
3045   bool InvCC = false;
3046   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
3047           "Bad input!");
3048
3049   if (LHS.getOpcode() == ISD::Constant &&
3050       cast<ConstantSDNode>(LHS)->isNullValue()) {
3051     DoXform = true;
3052   } else if (CC != ISD::SETCC_INVALID &&
3053              RHS.getOpcode() == ISD::Constant &&
3054              cast<ConstantSDNode>(RHS)->isNullValue()) {
3055     std::swap(LHS, RHS);
3056     SDValue Op0 = Slct.getOperand(0);
3057     EVT OpVT = isSlctCC ? Op0.getValueType() :
3058                           Op0.getOperand(0).getValueType();
3059     bool isInt = OpVT.isInteger();
3060     CC = ISD::getSetCCInverse(CC, isInt);
3061
3062     if (!TLI.isCondCodeLegal(CC, OpVT))
3063       return SDValue();         // Inverse operator isn't legal.
3064
3065     DoXform = true;
3066     InvCC = true;
3067   }
3068
3069   if (DoXform) {
3070     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
3071     if (isSlctCC)
3072       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
3073                              Slct.getOperand(0), Slct.getOperand(1), CC);
3074     SDValue CCOp = Slct.getOperand(0);
3075     if (InvCC)
3076       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
3077                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
3078     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3079                        CCOp, OtherOp, Result);
3080   }
3081   return SDValue();
3082 }
3083
3084 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
3085 static SDValue PerformADDCombine(SDNode *N,
3086                                  TargetLowering::DAGCombinerInfo &DCI) {
3087   // added by evan in r37685 with no testcase.
3088   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3089
3090   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
3091   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
3092     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
3093     if (Result.getNode()) return Result;
3094   }
3095   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
3096     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
3097     if (Result.getNode()) return Result;
3098   }
3099
3100   return SDValue();
3101 }
3102
3103 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
3104 static SDValue PerformSUBCombine(SDNode *N,
3105                                  TargetLowering::DAGCombinerInfo &DCI) {
3106   // added by evan in r37685 with no testcase.
3107   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3108
3109   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
3110   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
3111     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
3112     if (Result.getNode()) return Result;
3113   }
3114
3115   return SDValue();
3116 }
3117
3118
3119 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
3120 static SDValue PerformFMRRDCombine(SDNode *N,
3121                                    TargetLowering::DAGCombinerInfo &DCI) {
3122   // fmrrd(fmdrr x, y) -> x,y
3123   SDValue InDouble = N->getOperand(0);
3124   if (InDouble.getOpcode() == ARMISD::FMDRR)
3125     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
3126   return SDValue();
3127 }
3128
3129 /// getVShiftImm - Check if this is a valid build_vector for the immediate
3130 /// operand of a vector shift operation, where all the elements of the
3131 /// build_vector must have the same constant integer value.
3132 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3133   // Ignore bit_converts.
3134   while (Op.getOpcode() == ISD::BIT_CONVERT)
3135     Op = Op.getOperand(0);
3136   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3137   APInt SplatBits, SplatUndef;
3138   unsigned SplatBitSize;
3139   bool HasAnyUndefs;
3140   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3141                                       HasAnyUndefs, ElementBits) ||
3142       SplatBitSize > ElementBits)
3143     return false;
3144   Cnt = SplatBits.getSExtValue();
3145   return true;
3146 }
3147
3148 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
3149 /// operand of a vector shift left operation.  That value must be in the range:
3150 ///   0 <= Value < ElementBits for a left shift; or
3151 ///   0 <= Value <= ElementBits for a long left shift.
3152 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
3153   assert(VT.isVector() && "vector shift count is not a vector type");
3154   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3155   if (! getVShiftImm(Op, ElementBits, Cnt))
3156     return false;
3157   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
3158 }
3159
3160 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
3161 /// operand of a vector shift right operation.  For a shift opcode, the value
3162 /// is positive, but for an intrinsic the value count must be negative. The
3163 /// absolute value must be in the range:
3164 ///   1 <= |Value| <= ElementBits for a right shift; or
3165 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
3166 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
3167                          int64_t &Cnt) {
3168   assert(VT.isVector() && "vector shift count is not a vector type");
3169   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3170   if (! getVShiftImm(Op, ElementBits, Cnt))
3171     return false;
3172   if (isIntrinsic)
3173     Cnt = -Cnt;
3174   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
3175 }
3176
3177 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
3178 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3179   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3180   switch (IntNo) {
3181   default:
3182     // Don't do anything for most intrinsics.
3183     break;
3184
3185   // Vector shifts: check for immediate versions and lower them.
3186   // Note: This is done during DAG combining instead of DAG legalizing because
3187   // the build_vectors for 64-bit vector element shift counts are generally
3188   // not legal, and it is hard to see their values after they get legalized to
3189   // loads from a constant pool.
3190   case Intrinsic::arm_neon_vshifts:
3191   case Intrinsic::arm_neon_vshiftu:
3192   case Intrinsic::arm_neon_vshiftls:
3193   case Intrinsic::arm_neon_vshiftlu:
3194   case Intrinsic::arm_neon_vshiftn:
3195   case Intrinsic::arm_neon_vrshifts:
3196   case Intrinsic::arm_neon_vrshiftu:
3197   case Intrinsic::arm_neon_vrshiftn:
3198   case Intrinsic::arm_neon_vqshifts:
3199   case Intrinsic::arm_neon_vqshiftu:
3200   case Intrinsic::arm_neon_vqshiftsu:
3201   case Intrinsic::arm_neon_vqshiftns:
3202   case Intrinsic::arm_neon_vqshiftnu:
3203   case Intrinsic::arm_neon_vqshiftnsu:
3204   case Intrinsic::arm_neon_vqrshiftns:
3205   case Intrinsic::arm_neon_vqrshiftnu:
3206   case Intrinsic::arm_neon_vqrshiftnsu: {
3207     EVT VT = N->getOperand(1).getValueType();
3208     int64_t Cnt;
3209     unsigned VShiftOpc = 0;
3210
3211     switch (IntNo) {
3212     case Intrinsic::arm_neon_vshifts:
3213     case Intrinsic::arm_neon_vshiftu:
3214       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
3215         VShiftOpc = ARMISD::VSHL;
3216         break;
3217       }
3218       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
3219         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
3220                      ARMISD::VSHRs : ARMISD::VSHRu);
3221         break;
3222       }
3223       return SDValue();
3224
3225     case Intrinsic::arm_neon_vshiftls:
3226     case Intrinsic::arm_neon_vshiftlu:
3227       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
3228         break;
3229       llvm_unreachable("invalid shift count for vshll intrinsic");
3230
3231     case Intrinsic::arm_neon_vrshifts:
3232     case Intrinsic::arm_neon_vrshiftu:
3233       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
3234         break;
3235       return SDValue();
3236
3237     case Intrinsic::arm_neon_vqshifts:
3238     case Intrinsic::arm_neon_vqshiftu:
3239       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3240         break;
3241       return SDValue();
3242
3243     case Intrinsic::arm_neon_vqshiftsu:
3244       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3245         break;
3246       llvm_unreachable("invalid shift count for vqshlu intrinsic");
3247
3248     case Intrinsic::arm_neon_vshiftn:
3249     case Intrinsic::arm_neon_vrshiftn:
3250     case Intrinsic::arm_neon_vqshiftns:
3251     case Intrinsic::arm_neon_vqshiftnu:
3252     case Intrinsic::arm_neon_vqshiftnsu:
3253     case Intrinsic::arm_neon_vqrshiftns:
3254     case Intrinsic::arm_neon_vqrshiftnu:
3255     case Intrinsic::arm_neon_vqrshiftnsu:
3256       // Narrowing shifts require an immediate right shift.
3257       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
3258         break;
3259       llvm_unreachable("invalid shift count for narrowing vector shift intrinsic");
3260
3261     default:
3262       llvm_unreachable("unhandled vector shift");
3263     }
3264
3265     switch (IntNo) {
3266     case Intrinsic::arm_neon_vshifts:
3267     case Intrinsic::arm_neon_vshiftu:
3268       // Opcode already set above.
3269       break;
3270     case Intrinsic::arm_neon_vshiftls:
3271     case Intrinsic::arm_neon_vshiftlu:
3272       if (Cnt == VT.getVectorElementType().getSizeInBits())
3273         VShiftOpc = ARMISD::VSHLLi;
3274       else
3275         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
3276                      ARMISD::VSHLLs : ARMISD::VSHLLu);
3277       break;
3278     case Intrinsic::arm_neon_vshiftn:
3279       VShiftOpc = ARMISD::VSHRN; break;
3280     case Intrinsic::arm_neon_vrshifts:
3281       VShiftOpc = ARMISD::VRSHRs; break;
3282     case Intrinsic::arm_neon_vrshiftu:
3283       VShiftOpc = ARMISD::VRSHRu; break;
3284     case Intrinsic::arm_neon_vrshiftn:
3285       VShiftOpc = ARMISD::VRSHRN; break;
3286     case Intrinsic::arm_neon_vqshifts:
3287       VShiftOpc = ARMISD::VQSHLs; break;
3288     case Intrinsic::arm_neon_vqshiftu:
3289       VShiftOpc = ARMISD::VQSHLu; break;
3290     case Intrinsic::arm_neon_vqshiftsu:
3291       VShiftOpc = ARMISD::VQSHLsu; break;
3292     case Intrinsic::arm_neon_vqshiftns:
3293       VShiftOpc = ARMISD::VQSHRNs; break;
3294     case Intrinsic::arm_neon_vqshiftnu:
3295       VShiftOpc = ARMISD::VQSHRNu; break;
3296     case Intrinsic::arm_neon_vqshiftnsu:
3297       VShiftOpc = ARMISD::VQSHRNsu; break;
3298     case Intrinsic::arm_neon_vqrshiftns:
3299       VShiftOpc = ARMISD::VQRSHRNs; break;
3300     case Intrinsic::arm_neon_vqrshiftnu:
3301       VShiftOpc = ARMISD::VQRSHRNu; break;
3302     case Intrinsic::arm_neon_vqrshiftnsu:
3303       VShiftOpc = ARMISD::VQRSHRNsu; break;
3304     }
3305
3306     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3307                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3308   }
3309
3310   case Intrinsic::arm_neon_vshiftins: {
3311     EVT VT = N->getOperand(1).getValueType();
3312     int64_t Cnt;
3313     unsigned VShiftOpc = 0;
3314
3315     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
3316       VShiftOpc = ARMISD::VSLI;
3317     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
3318       VShiftOpc = ARMISD::VSRI;
3319     else {
3320       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
3321     }
3322
3323     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3324                        N->getOperand(1), N->getOperand(2),
3325                        DAG.getConstant(Cnt, MVT::i32));
3326   }
3327
3328   case Intrinsic::arm_neon_vqrshifts:
3329   case Intrinsic::arm_neon_vqrshiftu:
3330     // No immediate versions of these to check for.
3331     break;
3332   }
3333
3334   return SDValue();
3335 }
3336
3337 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
3338 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
3339 /// combining instead of DAG legalizing because the build_vectors for 64-bit
3340 /// vector element shift counts are generally not legal, and it is hard to see
3341 /// their values after they get legalized to loads from a constant pool.
3342 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
3343                                    const ARMSubtarget *ST) {
3344   EVT VT = N->getValueType(0);
3345
3346   // Nothing to be done for scalar shifts.
3347   if (! VT.isVector())
3348     return SDValue();
3349
3350   assert(ST->hasNEON() && "unexpected vector shift");
3351   int64_t Cnt;
3352
3353   switch (N->getOpcode()) {
3354   default: llvm_unreachable("unexpected shift opcode");
3355
3356   case ISD::SHL:
3357     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
3358       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
3359                          DAG.getConstant(Cnt, MVT::i32));
3360     break;
3361
3362   case ISD::SRA:
3363   case ISD::SRL:
3364     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
3365       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
3366                             ARMISD::VSHRs : ARMISD::VSHRu);
3367       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
3368                          DAG.getConstant(Cnt, MVT::i32));
3369     }
3370   }
3371   return SDValue();
3372 }
3373
3374 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
3375 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
3376 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
3377                                     const ARMSubtarget *ST) {
3378   SDValue N0 = N->getOperand(0);
3379
3380   // Check for sign- and zero-extensions of vector extract operations of 8-
3381   // and 16-bit vector elements.  NEON supports these directly.  They are
3382   // handled during DAG combining because type legalization will promote them
3383   // to 32-bit types and it is messy to recognize the operations after that.
3384   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
3385     SDValue Vec = N0.getOperand(0);
3386     SDValue Lane = N0.getOperand(1);
3387     EVT VT = N->getValueType(0);
3388     EVT EltVT = N0.getValueType();
3389     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3390
3391     if (VT == MVT::i32 &&
3392         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
3393         TLI.isTypeLegal(Vec.getValueType())) {
3394
3395       unsigned Opc = 0;
3396       switch (N->getOpcode()) {
3397       default: llvm_unreachable("unexpected opcode");
3398       case ISD::SIGN_EXTEND:
3399         Opc = ARMISD::VGETLANEs;
3400         break;
3401       case ISD::ZERO_EXTEND:
3402       case ISD::ANY_EXTEND:
3403         Opc = ARMISD::VGETLANEu;
3404         break;
3405       }
3406       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
3407     }
3408   }
3409
3410   return SDValue();
3411 }
3412
3413 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
3414                                              DAGCombinerInfo &DCI) const {
3415   switch (N->getOpcode()) {
3416   default: break;
3417   case ISD::ADD:      return PerformADDCombine(N, DCI);
3418   case ISD::SUB:      return PerformSUBCombine(N, DCI);
3419   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
3420   case ISD::INTRINSIC_WO_CHAIN:
3421     return PerformIntrinsicCombine(N, DCI.DAG);
3422   case ISD::SHL:
3423   case ISD::SRA:
3424   case ISD::SRL:
3425     return PerformShiftCombine(N, DCI.DAG, Subtarget);
3426   case ISD::SIGN_EXTEND:
3427   case ISD::ZERO_EXTEND:
3428   case ISD::ANY_EXTEND:
3429     return PerformExtendCombine(N, DCI.DAG, Subtarget);
3430   }
3431   return SDValue();
3432 }
3433
3434 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
3435   if (!Subtarget->hasV6Ops())
3436     // Pre-v6 does not support unaligned mem access.
3437     return false;
3438   else if (!Subtarget->hasV6Ops()) {
3439     // v6 may or may not support unaligned mem access.
3440     if (!Subtarget->isTargetDarwin())
3441       return false;
3442   }
3443
3444   switch (VT.getSimpleVT().SimpleTy) {
3445   default:
3446     return false;
3447   case MVT::i8:
3448   case MVT::i16:
3449   case MVT::i32:
3450     return true;
3451   // FIXME: VLD1 etc with standard alignment is legal.
3452   }
3453 }
3454
3455 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
3456   if (V < 0)
3457     return false;
3458
3459   unsigned Scale = 1;
3460   switch (VT.getSimpleVT().SimpleTy) {
3461   default: return false;
3462   case MVT::i1:
3463   case MVT::i8:
3464     // Scale == 1;
3465     break;
3466   case MVT::i16:
3467     // Scale == 2;
3468     Scale = 2;
3469     break;
3470   case MVT::i32:
3471     // Scale == 4;
3472     Scale = 4;
3473     break;
3474   }
3475
3476   if ((V & (Scale - 1)) != 0)
3477     return false;
3478   V /= Scale;
3479   return V == (V & ((1LL << 5) - 1));
3480 }
3481
3482 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
3483                                       const ARMSubtarget *Subtarget) {
3484   bool isNeg = false;
3485   if (V < 0) {
3486     isNeg = true;
3487     V = - V;
3488   }
3489
3490   switch (VT.getSimpleVT().SimpleTy) {
3491   default: return false;
3492   case MVT::i1:
3493   case MVT::i8:
3494   case MVT::i16:
3495   case MVT::i32:
3496     // + imm12 or - imm8
3497     if (isNeg)
3498       return V == (V & ((1LL << 8) - 1));
3499     return V == (V & ((1LL << 12) - 1));
3500   case MVT::f32:
3501   case MVT::f64:
3502     // Same as ARM mode. FIXME: NEON?
3503     if (!Subtarget->hasVFP2())
3504       return false;
3505     if ((V & 3) != 0)
3506       return false;
3507     V >>= 2;
3508     return V == (V & ((1LL << 8) - 1));
3509   }
3510 }
3511
3512 /// isLegalAddressImmediate - Return true if the integer value can be used
3513 /// as the offset of the target addressing mode for load / store of the
3514 /// given type.
3515 static bool isLegalAddressImmediate(int64_t V, EVT VT,
3516                                     const ARMSubtarget *Subtarget) {
3517   if (V == 0)
3518     return true;
3519
3520   if (!VT.isSimple())
3521     return false;
3522
3523   if (Subtarget->isThumb1Only())
3524     return isLegalT1AddressImmediate(V, VT);
3525   else if (Subtarget->isThumb2())
3526     return isLegalT2AddressImmediate(V, VT, Subtarget);
3527
3528   // ARM mode.
3529   if (V < 0)
3530     V = - V;
3531   switch (VT.getSimpleVT().SimpleTy) {
3532   default: return false;
3533   case MVT::i1:
3534   case MVT::i8:
3535   case MVT::i32:
3536     // +- imm12
3537     return V == (V & ((1LL << 12) - 1));
3538   case MVT::i16:
3539     // +- imm8
3540     return V == (V & ((1LL << 8) - 1));
3541   case MVT::f32:
3542   case MVT::f64:
3543     if (!Subtarget->hasVFP2()) // FIXME: NEON?
3544       return false;
3545     if ((V & 3) != 0)
3546       return false;
3547     V >>= 2;
3548     return V == (V & ((1LL << 8) - 1));
3549   }
3550 }
3551
3552 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
3553                                                       EVT VT) const {
3554   int Scale = AM.Scale;
3555   if (Scale < 0)
3556     return false;
3557
3558   switch (VT.getSimpleVT().SimpleTy) {
3559   default: return false;
3560   case MVT::i1:
3561   case MVT::i8:
3562   case MVT::i16:
3563   case MVT::i32:
3564     if (Scale == 1)
3565       return true;
3566     // r + r << imm
3567     Scale = Scale & ~1;
3568     return Scale == 2 || Scale == 4 || Scale == 8;
3569   case MVT::i64:
3570     // r + r
3571     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3572       return true;
3573     return false;
3574   case MVT::isVoid:
3575     // Note, we allow "void" uses (basically, uses that aren't loads or
3576     // stores), because arm allows folding a scale into many arithmetic
3577     // operations.  This should be made more precise and revisited later.
3578
3579     // Allow r << imm, but the imm has to be a multiple of two.
3580     if (Scale & 1) return false;
3581     return isPowerOf2_32(Scale);
3582   }
3583 }
3584
3585 /// isLegalAddressingMode - Return true if the addressing mode represented
3586 /// by AM is legal for this target, for a load/store of the specified type.
3587 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3588                                               const Type *Ty) const {
3589   EVT VT = getValueType(Ty, true);
3590   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
3591     return false;
3592
3593   // Can never fold addr of global into load/store.
3594   if (AM.BaseGV)
3595     return false;
3596
3597   switch (AM.Scale) {
3598   case 0:  // no scale reg, must be "r+i" or "r", or "i".
3599     break;
3600   case 1:
3601     if (Subtarget->isThumb1Only())
3602       return false;
3603     // FALL THROUGH.
3604   default:
3605     // ARM doesn't support any R+R*scale+imm addr modes.
3606     if (AM.BaseOffs)
3607       return false;
3608
3609     if (!VT.isSimple())
3610       return false;
3611
3612     if (Subtarget->isThumb2())
3613       return isLegalT2ScaledAddressingMode(AM, VT);
3614
3615     int Scale = AM.Scale;
3616     switch (VT.getSimpleVT().SimpleTy) {
3617     default: return false;
3618     case MVT::i1:
3619     case MVT::i8:
3620     case MVT::i32:
3621       if (Scale < 0) Scale = -Scale;
3622       if (Scale == 1)
3623         return true;
3624       // r + r << imm
3625       return isPowerOf2_32(Scale & ~1);
3626     case MVT::i16:
3627     case MVT::i64:
3628       // r + r
3629       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3630         return true;
3631       return false;
3632
3633     case MVT::isVoid:
3634       // Note, we allow "void" uses (basically, uses that aren't loads or
3635       // stores), because arm allows folding a scale into many arithmetic
3636       // operations.  This should be made more precise and revisited later.
3637
3638       // Allow r << imm, but the imm has to be a multiple of two.
3639       if (Scale & 1) return false;
3640       return isPowerOf2_32(Scale);
3641     }
3642     break;
3643   }
3644   return true;
3645 }
3646
3647 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
3648                                       bool isSEXTLoad, SDValue &Base,
3649                                       SDValue &Offset, bool &isInc,
3650                                       SelectionDAG &DAG) {
3651   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3652     return false;
3653
3654   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
3655     // AddressingMode 3
3656     Base = Ptr->getOperand(0);
3657     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3658       int RHSC = (int)RHS->getZExtValue();
3659       if (RHSC < 0 && RHSC > -256) {
3660         assert(Ptr->getOpcode() == ISD::ADD);
3661         isInc = false;
3662         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3663         return true;
3664       }
3665     }
3666     isInc = (Ptr->getOpcode() == ISD::ADD);
3667     Offset = Ptr->getOperand(1);
3668     return true;
3669   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
3670     // AddressingMode 2
3671     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3672       int RHSC = (int)RHS->getZExtValue();
3673       if (RHSC < 0 && RHSC > -0x1000) {
3674         assert(Ptr->getOpcode() == ISD::ADD);
3675         isInc = false;
3676         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3677         Base = Ptr->getOperand(0);
3678         return true;
3679       }
3680     }
3681
3682     if (Ptr->getOpcode() == ISD::ADD) {
3683       isInc = true;
3684       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
3685       if (ShOpcVal != ARM_AM::no_shift) {
3686         Base = Ptr->getOperand(1);
3687         Offset = Ptr->getOperand(0);
3688       } else {
3689         Base = Ptr->getOperand(0);
3690         Offset = Ptr->getOperand(1);
3691       }
3692       return true;
3693     }
3694
3695     isInc = (Ptr->getOpcode() == ISD::ADD);
3696     Base = Ptr->getOperand(0);
3697     Offset = Ptr->getOperand(1);
3698     return true;
3699   }
3700
3701   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
3702   return false;
3703 }
3704
3705 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
3706                                      bool isSEXTLoad, SDValue &Base,
3707                                      SDValue &Offset, bool &isInc,
3708                                      SelectionDAG &DAG) {
3709   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3710     return false;
3711
3712   Base = Ptr->getOperand(0);
3713   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3714     int RHSC = (int)RHS->getZExtValue();
3715     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
3716       assert(Ptr->getOpcode() == ISD::ADD);
3717       isInc = false;
3718       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3719       return true;
3720     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
3721       isInc = Ptr->getOpcode() == ISD::ADD;
3722       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
3723       return true;
3724     }
3725   }
3726
3727   return false;
3728 }
3729
3730 /// getPreIndexedAddressParts - returns true by value, base pointer and
3731 /// offset pointer and addressing mode by reference if the node's address
3732 /// can be legally represented as pre-indexed load / store address.
3733 bool
3734 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3735                                              SDValue &Offset,
3736                                              ISD::MemIndexedMode &AM,
3737                                              SelectionDAG &DAG) const {
3738   if (Subtarget->isThumb1Only())
3739     return false;
3740
3741   EVT VT;
3742   SDValue Ptr;
3743   bool isSEXTLoad = false;
3744   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3745     Ptr = LD->getBasePtr();
3746     VT  = LD->getMemoryVT();
3747     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3748   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3749     Ptr = ST->getBasePtr();
3750     VT  = ST->getMemoryVT();
3751   } else
3752     return false;
3753
3754   bool isInc;
3755   bool isLegal = false;
3756   if (Subtarget->isThumb2())
3757     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3758                                        Offset, isInc, DAG);
3759   else
3760     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3761                                         Offset, isInc, DAG);
3762   if (!isLegal)
3763     return false;
3764
3765   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
3766   return true;
3767 }
3768
3769 /// getPostIndexedAddressParts - returns true by value, base pointer and
3770 /// offset pointer and addressing mode by reference if this node can be
3771 /// combined with a load / store to form a post-indexed load / store.
3772 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
3773                                                    SDValue &Base,
3774                                                    SDValue &Offset,
3775                                                    ISD::MemIndexedMode &AM,
3776                                                    SelectionDAG &DAG) const {
3777   if (Subtarget->isThumb1Only())
3778     return false;
3779
3780   EVT VT;
3781   SDValue Ptr;
3782   bool isSEXTLoad = false;
3783   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3784     VT  = LD->getMemoryVT();
3785     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3786   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3787     VT  = ST->getMemoryVT();
3788   } else
3789     return false;
3790
3791   bool isInc;
3792   bool isLegal = false;
3793   if (Subtarget->isThumb2())
3794     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3795                                         isInc, DAG);
3796   else
3797     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3798                                         isInc, DAG);
3799   if (!isLegal)
3800     return false;
3801
3802   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
3803   return true;
3804 }
3805
3806 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
3807                                                        const APInt &Mask,
3808                                                        APInt &KnownZero,
3809                                                        APInt &KnownOne,
3810                                                        const SelectionDAG &DAG,
3811                                                        unsigned Depth) const {
3812   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3813   switch (Op.getOpcode()) {
3814   default: break;
3815   case ARMISD::CMOV: {
3816     // Bits are known zero/one if known on the LHS and RHS.
3817     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
3818     if (KnownZero == 0 && KnownOne == 0) return;
3819
3820     APInt KnownZeroRHS, KnownOneRHS;
3821     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
3822                           KnownZeroRHS, KnownOneRHS, Depth+1);
3823     KnownZero &= KnownZeroRHS;
3824     KnownOne  &= KnownOneRHS;
3825     return;
3826   }
3827   }
3828 }
3829
3830 //===----------------------------------------------------------------------===//
3831 //                           ARM Inline Assembly Support
3832 //===----------------------------------------------------------------------===//
3833
3834 /// getConstraintType - Given a constraint letter, return the type of
3835 /// constraint it is for this target.
3836 ARMTargetLowering::ConstraintType
3837 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
3838   if (Constraint.size() == 1) {
3839     switch (Constraint[0]) {
3840     default:  break;
3841     case 'l': return C_RegisterClass;
3842     case 'w': return C_RegisterClass;
3843     }
3844   }
3845   return TargetLowering::getConstraintType(Constraint);
3846 }
3847
3848 std::pair<unsigned, const TargetRegisterClass*>
3849 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3850                                                 EVT VT) const {
3851   if (Constraint.size() == 1) {
3852     // GCC RS6000 Constraint Letters
3853     switch (Constraint[0]) {
3854     case 'l':
3855       if (Subtarget->isThumb1Only())
3856         return std::make_pair(0U, ARM::tGPRRegisterClass);
3857       else
3858         return std::make_pair(0U, ARM::GPRRegisterClass);
3859     case 'r':
3860       return std::make_pair(0U, ARM::GPRRegisterClass);
3861     case 'w':
3862       if (VT == MVT::f32)
3863         return std::make_pair(0U, ARM::SPRRegisterClass);
3864       if (VT == MVT::f64)
3865         return std::make_pair(0U, ARM::DPRRegisterClass);
3866       break;
3867     }
3868   }
3869   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3870 }
3871
3872 std::vector<unsigned> ARMTargetLowering::
3873 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3874                                   EVT VT) const {
3875   if (Constraint.size() != 1)
3876     return std::vector<unsigned>();
3877
3878   switch (Constraint[0]) {      // GCC ARM Constraint Letters
3879   default: break;
3880   case 'l':
3881     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3882                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3883                                  0);
3884   case 'r':
3885     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3886                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3887                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
3888                                  ARM::R12, ARM::LR, 0);
3889   case 'w':
3890     if (VT == MVT::f32)
3891       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
3892                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
3893                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
3894                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
3895                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
3896                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
3897                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
3898                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
3899     if (VT == MVT::f64)
3900       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
3901                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
3902                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
3903                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
3904       break;
3905   }
3906
3907   return std::vector<unsigned>();
3908 }
3909
3910 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3911 /// vector.  If it is invalid, don't add anything to Ops.
3912 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3913                                                      char Constraint,
3914                                                      bool hasMemory,
3915                                                      std::vector<SDValue>&Ops,
3916                                                      SelectionDAG &DAG) const {
3917   SDValue Result(0, 0);
3918
3919   switch (Constraint) {
3920   default: break;
3921   case 'I': case 'J': case 'K': case 'L':
3922   case 'M': case 'N': case 'O':
3923     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3924     if (!C)
3925       return;
3926
3927     int64_t CVal64 = C->getSExtValue();
3928     int CVal = (int) CVal64;
3929     // None of these constraints allow values larger than 32 bits.  Check
3930     // that the value fits in an int.
3931     if (CVal != CVal64)
3932       return;
3933
3934     switch (Constraint) {
3935       case 'I':
3936         if (Subtarget->isThumb1Only()) {
3937           // This must be a constant between 0 and 255, for ADD
3938           // immediates.
3939           if (CVal >= 0 && CVal <= 255)
3940             break;
3941         } else if (Subtarget->isThumb2()) {
3942           // A constant that can be used as an immediate value in a
3943           // data-processing instruction.
3944           if (ARM_AM::getT2SOImmVal(CVal) != -1)
3945             break;
3946         } else {
3947           // A constant that can be used as an immediate value in a
3948           // data-processing instruction.
3949           if (ARM_AM::getSOImmVal(CVal) != -1)
3950             break;
3951         }
3952         return;
3953
3954       case 'J':
3955         if (Subtarget->isThumb()) {  // FIXME thumb2
3956           // This must be a constant between -255 and -1, for negated ADD
3957           // immediates. This can be used in GCC with an "n" modifier that
3958           // prints the negated value, for use with SUB instructions. It is
3959           // not useful otherwise but is implemented for compatibility.
3960           if (CVal >= -255 && CVal <= -1)
3961             break;
3962         } else {
3963           // This must be a constant between -4095 and 4095. It is not clear
3964           // what this constraint is intended for. Implemented for
3965           // compatibility with GCC.
3966           if (CVal >= -4095 && CVal <= 4095)
3967             break;
3968         }
3969         return;
3970
3971       case 'K':
3972         if (Subtarget->isThumb1Only()) {
3973           // A 32-bit value where only one byte has a nonzero value. Exclude
3974           // zero to match GCC. This constraint is used by GCC internally for
3975           // constants that can be loaded with a move/shift combination.
3976           // It is not useful otherwise but is implemented for compatibility.
3977           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
3978             break;
3979         } else if (Subtarget->isThumb2()) {
3980           // A constant whose bitwise inverse can be used as an immediate
3981           // value in a data-processing instruction. This can be used in GCC
3982           // with a "B" modifier that prints the inverted value, for use with
3983           // BIC and MVN instructions. It is not useful otherwise but is
3984           // implemented for compatibility.
3985           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
3986             break;
3987         } else {
3988           // A constant whose bitwise inverse can be used as an immediate
3989           // value in a data-processing instruction. This can be used in GCC
3990           // with a "B" modifier that prints the inverted value, for use with
3991           // BIC and MVN instructions. It is not useful otherwise but is
3992           // implemented for compatibility.
3993           if (ARM_AM::getSOImmVal(~CVal) != -1)
3994             break;
3995         }
3996         return;
3997
3998       case 'L':
3999         if (Subtarget->isThumb1Only()) {
4000           // This must be a constant between -7 and 7,
4001           // for 3-operand ADD/SUB immediate instructions.
4002           if (CVal >= -7 && CVal < 7)
4003             break;
4004         } else if (Subtarget->isThumb2()) {
4005           // A constant whose negation can be used as an immediate value in a
4006           // data-processing instruction. This can be used in GCC with an "n"
4007           // modifier that prints the negated value, for use with SUB
4008           // instructions. It is not useful otherwise but is implemented for
4009           // compatibility.
4010           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
4011             break;
4012         } else {
4013           // A constant whose negation can be used as an immediate value in a
4014           // data-processing instruction. This can be used in GCC with an "n"
4015           // modifier that prints the negated value, for use with SUB
4016           // instructions. It is not useful otherwise but is implemented for
4017           // compatibility.
4018           if (ARM_AM::getSOImmVal(-CVal) != -1)
4019             break;
4020         }
4021         return;
4022
4023       case 'M':
4024         if (Subtarget->isThumb()) { // FIXME thumb2
4025           // This must be a multiple of 4 between 0 and 1020, for
4026           // ADD sp + immediate.
4027           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
4028             break;
4029         } else {
4030           // A power of two or a constant between 0 and 32.  This is used in
4031           // GCC for the shift amount on shifted register operands, but it is
4032           // useful in general for any shift amounts.
4033           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
4034             break;
4035         }
4036         return;
4037
4038       case 'N':
4039         if (Subtarget->isThumb()) {  // FIXME thumb2
4040           // This must be a constant between 0 and 31, for shift amounts.
4041           if (CVal >= 0 && CVal <= 31)
4042             break;
4043         }
4044         return;
4045
4046       case 'O':
4047         if (Subtarget->isThumb()) {  // FIXME thumb2
4048           // This must be a multiple of 4 between -508 and 508, for
4049           // ADD/SUB sp = sp + immediate.
4050           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
4051             break;
4052         }
4053         return;
4054     }
4055     Result = DAG.getTargetConstant(CVal, Op.getValueType());
4056     break;
4057   }
4058
4059   if (Result.getNode()) {
4060     Ops.push_back(Result);
4061     return;
4062   }
4063   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
4064                                                       Ops, DAG);
4065 }