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