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