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