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