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