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