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