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