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