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