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