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