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