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