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