Unbreak the stuff, this is ugly, but we cannot do better for now with 'plain' C calli...
[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 "ARMRegisterInfo.h"
21 #include "ARMSubtarget.h"
22 #include "ARMTargetMachine.h"
23 #include "ARMTargetObjectFile.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instruction.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/CodeGen/CallingConvLower.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/VectorExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MathExtras.h"
42 using namespace llvm;
43
44 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
45                                    CCValAssign::LocInfo &LocInfo,
46                                    ISD::ArgFlagsTy &ArgFlags,
47                                    CCState &State);
48 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
49                                     CCValAssign::LocInfo &LocInfo,
50                                     ISD::ArgFlagsTy &ArgFlags,
51                                     CCState &State);
52 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
53                                       CCValAssign::LocInfo &LocInfo,
54                                       ISD::ArgFlagsTy &ArgFlags,
55                                       CCState &State);
56 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
57                                        CCValAssign::LocInfo &LocInfo,
58                                        ISD::ArgFlagsTy &ArgFlags,
59                                        CCState &State);
60
61 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
62                                        MVT PromotedBitwiseVT) {
63   if (VT != PromotedLdStVT) {
64     setOperationAction(ISD::LOAD, VT, Promote);
65     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
66
67     setOperationAction(ISD::STORE, VT, Promote);
68     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
69   }
70
71   MVT ElemTy = VT.getVectorElementType();
72   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
73     setOperationAction(ISD::VSETCC, VT, Custom);
74   if (ElemTy == MVT::i8 || ElemTy == MVT::i16)
75     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
76   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
77   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
78   setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
79   setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
80   if (VT.isInteger()) {
81     setOperationAction(ISD::SHL, VT, Custom);
82     setOperationAction(ISD::SRA, VT, Custom);
83     setOperationAction(ISD::SRL, VT, Custom);
84   }
85
86   // Promote all bit-wise operations.
87   if (VT.isInteger() && VT != PromotedBitwiseVT) {
88     setOperationAction(ISD::AND, VT, Promote);
89     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
90     setOperationAction(ISD::OR,  VT, Promote);
91     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
92     setOperationAction(ISD::XOR, VT, Promote);
93     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
94   }
95 }
96
97 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
98   addRegisterClass(VT, ARM::DPRRegisterClass);
99   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
100 }
101
102 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
103   addRegisterClass(VT, ARM::QPRRegisterClass);
104   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
105 }
106
107 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
108   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
109     return new TargetLoweringObjectFileMachO();
110   return new ARMElfTargetObjectFile();
111 }
112
113 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
114     : TargetLowering(TM, createTLOF(TM)), ARMPCLabelIndex(0) {
115   Subtarget = &TM.getSubtarget<ARMSubtarget>();
116
117   if (Subtarget->isTargetDarwin()) {
118     // Uses VFP for Thumb libfuncs if available.
119     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
120       // Single-precision floating-point arithmetic.
121       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
122       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
123       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
124       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
125
126       // Double-precision floating-point arithmetic.
127       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
128       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
129       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
130       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
131
132       // Single-precision comparisons.
133       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
134       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
135       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
136       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
137       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
138       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
139       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
140       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
141
142       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
143       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
144       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
145       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
146       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
147       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
148       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
149       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
150
151       // Double-precision comparisons.
152       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
153       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
154       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
155       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
156       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
157       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
158       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
159       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
160
161       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
162       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
163       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
164       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
165       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
166       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
167       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
168       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
169
170       // Floating-point to integer conversions.
171       // i64 conversions are done via library routines even when generating VFP
172       // instructions, so use the same ones.
173       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
174       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
175       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
176       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
177
178       // Conversions between floating types.
179       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
180       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
181
182       // Integer to floating-point conversions.
183       // i64 conversions are done via library routines even when generating VFP
184       // instructions, so use the same ones.
185       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
186       // e.g., __floatunsidf vs. __floatunssidfvfp.
187       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
188       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
189       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
190       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
191     }
192   }
193
194   // These libcalls are not available in 32-bit.
195   setLibcallName(RTLIB::SHL_I128, 0);
196   setLibcallName(RTLIB::SRL_I128, 0);
197   setLibcallName(RTLIB::SRA_I128, 0);
198
199   if (Subtarget->isThumb1Only())
200     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
201   else
202     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
203   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
204     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
205     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
206
207     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
208   }
209
210   if (Subtarget->hasNEON()) {
211     addDRTypeForNEON(MVT::v2f32);
212     addDRTypeForNEON(MVT::v8i8);
213     addDRTypeForNEON(MVT::v4i16);
214     addDRTypeForNEON(MVT::v2i32);
215     addDRTypeForNEON(MVT::v1i64);
216
217     addQRTypeForNEON(MVT::v4f32);
218     addQRTypeForNEON(MVT::v2f64);
219     addQRTypeForNEON(MVT::v16i8);
220     addQRTypeForNEON(MVT::v8i16);
221     addQRTypeForNEON(MVT::v4i32);
222     addQRTypeForNEON(MVT::v2i64);
223
224     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
225     setTargetDAGCombine(ISD::SHL);
226     setTargetDAGCombine(ISD::SRL);
227     setTargetDAGCombine(ISD::SRA);
228     setTargetDAGCombine(ISD::SIGN_EXTEND);
229     setTargetDAGCombine(ISD::ZERO_EXTEND);
230     setTargetDAGCombine(ISD::ANY_EXTEND);
231   }
232
233   computeRegisterProperties();
234
235   // ARM does not have f32 extending load.
236   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
237
238   // ARM does not have i1 sign extending load.
239   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
240
241   // ARM supports all 4 flavors of integer indexed load / store.
242   if (!Subtarget->isThumb1Only()) {
243     for (unsigned im = (unsigned)ISD::PRE_INC;
244          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
245       setIndexedLoadAction(im,  MVT::i1,  Legal);
246       setIndexedLoadAction(im,  MVT::i8,  Legal);
247       setIndexedLoadAction(im,  MVT::i16, Legal);
248       setIndexedLoadAction(im,  MVT::i32, Legal);
249       setIndexedStoreAction(im, MVT::i1,  Legal);
250       setIndexedStoreAction(im, MVT::i8,  Legal);
251       setIndexedStoreAction(im, MVT::i16, Legal);
252       setIndexedStoreAction(im, MVT::i32, Legal);
253     }
254   }
255
256   // i64 operation support.
257   if (Subtarget->isThumb1Only()) {
258     setOperationAction(ISD::MUL,     MVT::i64, Expand);
259     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
260     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
261     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
262     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
263   } else {
264     setOperationAction(ISD::MUL,     MVT::i64, Expand);
265     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
266     if (!Subtarget->hasV6Ops())
267       setOperationAction(ISD::MULHS, MVT::i32, Expand);
268   }
269   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
270   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
271   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
272   setOperationAction(ISD::SRL,       MVT::i64, Custom);
273   setOperationAction(ISD::SRA,       MVT::i64, Custom);
274
275   // ARM does not have ROTL.
276   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
277   setOperationAction(ISD::CTTZ,  MVT::i32, Expand);
278   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
279   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
280     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
281
282   // Only ARMv6 has BSWAP.
283   if (!Subtarget->hasV6Ops())
284     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
285
286   // These are expanded into libcalls.
287   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
288   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
289   setOperationAction(ISD::SREM,  MVT::i32, Expand);
290   setOperationAction(ISD::UREM,  MVT::i32, Expand);
291   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
292   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
293
294   // Support label based line numbers.
295   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
296   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
297
298   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
299   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
300   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
301   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
302
303   // Use the default implementation.
304   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
305   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
306   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
307   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
308   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
309   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
310   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Expand);
311   setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
312
313   if (!Subtarget->hasV6Ops() && !Subtarget->isThumb2()) {
314     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
315     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
316   }
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
318
319   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())
320     // Turn f64->i64 into FMRRD, i64 -> f64 to FMDRR iff target supports vfp2.
321     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
322
323   // We want to custom lower some of our intrinsics.
324   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
325   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
326
327   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
328   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
329   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
330   setOperationAction(ISD::SELECT,    MVT::i32, Expand);
331   setOperationAction(ISD::SELECT,    MVT::f32, Expand);
332   setOperationAction(ISD::SELECT,    MVT::f64, Expand);
333   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
334   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
335   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
336
337   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
338   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
339   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
340   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
341   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
342
343   // We don't support sin/cos/fmod/copysign/pow
344   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
345   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
346   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
347   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
348   setOperationAction(ISD::FREM,      MVT::f64, Expand);
349   setOperationAction(ISD::FREM,      MVT::f32, Expand);
350   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
351     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
352     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
353   }
354   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
355   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
356
357   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
358   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
359     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
360     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
361     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
363   }
364
365   // We have target-specific dag combine patterns for the following nodes:
366   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
367   setTargetDAGCombine(ISD::ADD);
368   setTargetDAGCombine(ISD::SUB);
369
370   setStackPointerRegisterToSaveRestore(ARM::SP);
371   setSchedulingPreference(SchedulingForRegPressure);
372   setIfCvtBlockSizeLimit(Subtarget->isThumb() ? 0 : 10);
373   setIfCvtDupBlockSizeLimit(Subtarget->isThumb() ? 0 : 2);
374
375   if (!Subtarget->isThumb()) {
376     // Use branch latency information to determine if-conversion limits.
377     // FIXME: If-converter should use instruction latency of the branch being
378     // eliminated to compute the threshold. For ARMv6, the branch "latency"
379     // varies depending on whether it's dynamically or statically predicted
380     // and on whether the destination is in the prefetch buffer.
381     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
382     const InstrItineraryData &InstrItins = Subtarget->getInstrItineraryData();
383     unsigned Latency= InstrItins.getLatency(TII->get(ARM::Bcc).getSchedClass());
384     if (Latency > 1) {
385       setIfCvtBlockSizeLimit(Latency-1);
386       if (Latency > 2)
387         setIfCvtDupBlockSizeLimit(Latency-2);
388     } else {
389       setIfCvtBlockSizeLimit(10);
390       setIfCvtDupBlockSizeLimit(2);
391     }
392   }
393
394   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
395   // Do not enable CodePlacementOpt for now: it currently runs after the
396   // ARMConstantIslandPass and messes up branch relaxation and placement
397   // of constant islands.
398   // benefitFromCodePlacementOpt = true;
399 }
400
401 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
402   switch (Opcode) {
403   default: return 0;
404   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
405   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
406   case ARMISD::CALL:          return "ARMISD::CALL";
407   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
408   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
409   case ARMISD::tCALL:         return "ARMISD::tCALL";
410   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
411   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
412   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
413   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
414   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
415   case ARMISD::CMP:           return "ARMISD::CMP";
416   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
417   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
418   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
419   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
420   case ARMISD::CMOV:          return "ARMISD::CMOV";
421   case ARMISD::CNEG:          return "ARMISD::CNEG";
422
423   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
424   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
425   case ARMISD::SITOF:         return "ARMISD::SITOF";
426   case ARMISD::UITOF:         return "ARMISD::UITOF";
427
428   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
429   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
430   case ARMISD::RRX:           return "ARMISD::RRX";
431
432   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
433   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
434
435   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
436
437   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
438   case ARMISD::VCGE:          return "ARMISD::VCGE";
439   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
440   case ARMISD::VCGT:          return "ARMISD::VCGT";
441   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
442   case ARMISD::VTST:          return "ARMISD::VTST";
443
444   case ARMISD::VSHL:          return "ARMISD::VSHL";
445   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
446   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
447   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
448   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
449   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
450   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
451   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
452   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
453   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
454   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
455   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
456   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
457   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
458   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
459   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
460   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
461   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
462   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
463   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
464   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
465   case ARMISD::VDUPLANEQ:     return "ARMISD::VDUPLANEQ";
466   case ARMISD::VLD2D:         return "ARMISD::VLD2D";
467   case ARMISD::VLD3D:         return "ARMISD::VLD3D";
468   case ARMISD::VLD4D:         return "ARMISD::VLD4D";
469   }
470 }
471
472 /// getFunctionAlignment - Return the Log2 alignment of this function.
473 unsigned ARMTargetLowering::getFunctionAlignment(const Function *F) const {
474   return getTargetMachine().getSubtarget<ARMSubtarget>().isThumb() ? 1 : 2;
475 }
476
477 //===----------------------------------------------------------------------===//
478 // Lowering Code
479 //===----------------------------------------------------------------------===//
480
481 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
482 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
483   switch (CC) {
484   default: llvm_unreachable("Unknown condition code!");
485   case ISD::SETNE:  return ARMCC::NE;
486   case ISD::SETEQ:  return ARMCC::EQ;
487   case ISD::SETGT:  return ARMCC::GT;
488   case ISD::SETGE:  return ARMCC::GE;
489   case ISD::SETLT:  return ARMCC::LT;
490   case ISD::SETLE:  return ARMCC::LE;
491   case ISD::SETUGT: return ARMCC::HI;
492   case ISD::SETUGE: return ARMCC::HS;
493   case ISD::SETULT: return ARMCC::LO;
494   case ISD::SETULE: return ARMCC::LS;
495   }
496 }
497
498 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
499 /// returns true if the operands should be inverted to form the proper
500 /// comparison.
501 static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
502                         ARMCC::CondCodes &CondCode2) {
503   bool Invert = false;
504   CondCode2 = ARMCC::AL;
505   switch (CC) {
506   default: llvm_unreachable("Unknown FP condition!");
507   case ISD::SETEQ:
508   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
509   case ISD::SETGT:
510   case ISD::SETOGT: CondCode = ARMCC::GT; break;
511   case ISD::SETGE:
512   case ISD::SETOGE: CondCode = ARMCC::GE; break;
513   case ISD::SETOLT: CondCode = ARMCC::MI; break;
514   case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
515   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
516   case ISD::SETO:   CondCode = ARMCC::VC; break;
517   case ISD::SETUO:  CondCode = ARMCC::VS; break;
518   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
519   case ISD::SETUGT: CondCode = ARMCC::HI; break;
520   case ISD::SETUGE: CondCode = ARMCC::PL; break;
521   case ISD::SETLT:
522   case ISD::SETULT: CondCode = ARMCC::LT; break;
523   case ISD::SETLE:
524   case ISD::SETULE: CondCode = ARMCC::LE; break;
525   case ISD::SETNE:
526   case ISD::SETUNE: CondCode = ARMCC::NE; break;
527   }
528   return Invert;
529 }
530
531 //===----------------------------------------------------------------------===//
532 //                      Calling Convention Implementation
533 //===----------------------------------------------------------------------===//
534
535 #include "ARMGenCallingConv.inc"
536
537 // APCS f64 is in register pairs, possibly split to stack
538 static bool f64AssignAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
539                           CCValAssign::LocInfo &LocInfo,
540                           CCState &State, bool CanFail) {
541   static const unsigned RegList[] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 };
542
543   // Try to get the first register.
544   if (unsigned Reg = State.AllocateReg(RegList, 4))
545     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
546   else {
547     // For the 2nd half of a v2f64, do not fail.
548     if (CanFail)
549       return false;
550
551     // Put the whole thing on the stack.
552     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
553                                            State.AllocateStack(8, 4),
554                                            LocVT, LocInfo));
555     return true;
556   }
557
558   // Try to get the second register.
559   if (unsigned Reg = State.AllocateReg(RegList, 4))
560     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
561   else
562     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
563                                            State.AllocateStack(4, 4),
564                                            LocVT, LocInfo));
565   return true;
566 }
567
568 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
569                                    CCValAssign::LocInfo &LocInfo,
570                                    ISD::ArgFlagsTy &ArgFlags,
571                                    CCState &State) {
572   if (!f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
573     return false;
574   if (LocVT == MVT::v2f64 &&
575       !f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
576     return false;
577   return true;  // we handled it
578 }
579
580 // AAPCS f64 is in aligned register pairs
581 static bool f64AssignAAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
582                            CCValAssign::LocInfo &LocInfo,
583                            CCState &State, bool CanFail) {
584   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
585   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
586
587   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
588   if (Reg == 0) {
589     // For the 2nd half of a v2f64, do not just fail.
590     if (CanFail)
591       return false;
592
593     // Put the whole thing on the stack.
594     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
595                                            State.AllocateStack(8, 8),
596                                            LocVT, LocInfo));
597     return true;
598   }
599
600   unsigned i;
601   for (i = 0; i < 2; ++i)
602     if (HiRegList[i] == Reg)
603       break;
604
605   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
606   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
607                                          LocVT, LocInfo));
608   return true;
609 }
610
611 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
612                                     CCValAssign::LocInfo &LocInfo,
613                                     ISD::ArgFlagsTy &ArgFlags,
614                                     CCState &State) {
615   if (!f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
616     return false;
617   if (LocVT == MVT::v2f64 &&
618       !f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
619     return false;
620   return true;  // we handled it
621 }
622
623 static bool f64RetAssign(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
624                          CCValAssign::LocInfo &LocInfo, CCState &State) {
625   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
626   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
627
628   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
629   if (Reg == 0)
630     return false; // we didn't handle it
631
632   unsigned i;
633   for (i = 0; i < 2; ++i)
634     if (HiRegList[i] == Reg)
635       break;
636
637   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
638   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
639                                          LocVT, LocInfo));
640   return true;
641 }
642
643 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
644                                       CCValAssign::LocInfo &LocInfo,
645                                       ISD::ArgFlagsTy &ArgFlags,
646                                       CCState &State) {
647   if (!f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
648     return false;
649   if (LocVT == MVT::v2f64 && !f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
650     return false;
651   return true;  // we handled it
652 }
653
654 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
655                                        CCValAssign::LocInfo &LocInfo,
656                                        ISD::ArgFlagsTy &ArgFlags,
657                                        CCState &State) {
658   return RetCC_ARM_APCS_Custom_f64(ValNo, ValVT, LocVT, LocInfo, ArgFlags,
659                                    State);
660 }
661
662 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
663 /// given CallingConvention value.
664 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(unsigned CC,
665                                                  bool Return,
666                                                  bool isVarArg) const {
667   switch (CC) {
668   default:
669     llvm_unreachable("Unsupported calling convention");
670   case CallingConv::C:
671   case CallingConv::Fast:
672     // Use target triple & subtarget features to do actual dispatch.
673     if (Subtarget->isAAPCS_ABI()) {
674       if (Subtarget->hasVFP2() &&
675           FloatABIType == FloatABI::Hard && !isVarArg)
676         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
677       else
678         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
679     } else
680         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
681   case CallingConv::ARM_AAPCS_VFP:
682     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
683   case CallingConv::ARM_AAPCS:
684     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
685   case CallingConv::ARM_APCS:
686     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
687   }
688 }
689
690 /// LowerCallResult - Lower the result values of a call into the
691 /// appropriate copies out of appropriate physical registers.
692 SDValue
693 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
694                                    unsigned CallConv, bool isVarArg,
695                                    const SmallVectorImpl<ISD::InputArg> &Ins,
696                                    DebugLoc dl, SelectionDAG &DAG,
697                                    SmallVectorImpl<SDValue> &InVals) {
698
699   // Assign locations to each value returned by this call.
700   SmallVector<CCValAssign, 16> RVLocs;
701   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
702                  RVLocs, *DAG.getContext());
703   CCInfo.AnalyzeCallResult(Ins,
704                            CCAssignFnForNode(CallConv, /* Return*/ true,
705                                              isVarArg));
706
707   // Copy all of the result registers out of their specified physreg.
708   for (unsigned i = 0; i != RVLocs.size(); ++i) {
709     CCValAssign VA = RVLocs[i];
710
711     SDValue Val;
712     if (VA.needsCustom()) {
713       // Handle f64 or half of a v2f64.
714       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
715                                       InFlag);
716       Chain = Lo.getValue(1);
717       InFlag = Lo.getValue(2);
718       VA = RVLocs[++i]; // skip ahead to next loc
719       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
720                                       InFlag);
721       Chain = Hi.getValue(1);
722       InFlag = Hi.getValue(2);
723       Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
724
725       if (VA.getLocVT() == MVT::v2f64) {
726         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
727         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
728                           DAG.getConstant(0, MVT::i32));
729
730         VA = RVLocs[++i]; // skip ahead to next loc
731         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
732         Chain = Lo.getValue(1);
733         InFlag = Lo.getValue(2);
734         VA = RVLocs[++i]; // skip ahead to next loc
735         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
736         Chain = Hi.getValue(1);
737         InFlag = Hi.getValue(2);
738         Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
739         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
740                           DAG.getConstant(1, MVT::i32));
741       }
742     } else {
743       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
744                                InFlag);
745       Chain = Val.getValue(1);
746       InFlag = Val.getValue(2);
747     }
748
749     switch (VA.getLocInfo()) {
750     default: llvm_unreachable("Unknown loc info!");
751     case CCValAssign::Full: break;
752     case CCValAssign::BCvt:
753       Val = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), Val);
754       break;
755     }
756
757     InVals.push_back(Val);
758   }
759
760   return Chain;
761 }
762
763 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
764 /// by "Src" to address "Dst" of size "Size".  Alignment information is
765 /// specified by the specific parameter attribute.  The copy will be passed as
766 /// a byval function parameter.
767 /// Sometimes what we are copying is the end of a larger object, the part that
768 /// does not fit in registers.
769 static SDValue
770 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
771                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
772                           DebugLoc dl) {
773   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
774   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
775                        /*AlwaysInline=*/false, NULL, 0, NULL, 0);
776 }
777
778 /// LowerMemOpCallTo - Store the argument to the stack.
779 SDValue
780 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
781                                     SDValue StackPtr, SDValue Arg,
782                                     DebugLoc dl, SelectionDAG &DAG,
783                                     const CCValAssign &VA,
784                                     ISD::ArgFlagsTy Flags) {
785   unsigned LocMemOffset = VA.getLocMemOffset();
786   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
787   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
788   if (Flags.isByVal()) {
789     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
790   }
791   return DAG.getStore(Chain, dl, Arg, PtrOff,
792                       PseudoSourceValue::getStack(), LocMemOffset);
793 }
794
795 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
796                                          SDValue Chain, SDValue &Arg,
797                                          RegsToPassVector &RegsToPass,
798                                          CCValAssign &VA, CCValAssign &NextVA,
799                                          SDValue &StackPtr,
800                                          SmallVector<SDValue, 8> &MemOpChains,
801                                          ISD::ArgFlagsTy Flags) {
802
803   SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
804                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
805   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
806
807   if (NextVA.isRegLoc())
808     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
809   else {
810     assert(NextVA.isMemLoc());
811     if (StackPtr.getNode() == 0)
812       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
813
814     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
815                                            dl, DAG, NextVA,
816                                            Flags));
817   }
818 }
819
820 /// LowerCall - Lowering a call into a callseq_start <-
821 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
822 /// nodes.
823 SDValue
824 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
825                              unsigned CallConv, bool isVarArg,
826                              bool isTailCall,
827                              const SmallVectorImpl<ISD::OutputArg> &Outs,
828                              const SmallVectorImpl<ISD::InputArg> &Ins,
829                              DebugLoc dl, SelectionDAG &DAG,
830                              SmallVectorImpl<SDValue> &InVals) {
831
832   // Analyze operands of the call, assigning locations to each operand.
833   SmallVector<CCValAssign, 16> ArgLocs;
834   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
835                  *DAG.getContext());
836   CCInfo.AnalyzeCallOperands(Outs,
837                              CCAssignFnForNode(CallConv, /* Return*/ false,
838                                                isVarArg));
839
840   // Get a count of how many bytes are to be pushed on the stack.
841   unsigned NumBytes = CCInfo.getNextStackOffset();
842
843   // Adjust the stack pointer for the new arguments...
844   // These operations are automatically eliminated by the prolog/epilog pass
845   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
846
847   SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
848
849   RegsToPassVector RegsToPass;
850   SmallVector<SDValue, 8> MemOpChains;
851
852   // Walk the register/memloc assignments, inserting copies/loads.  In the case
853   // of tail call optimization, arguments are handled later.
854   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
855        i != e;
856        ++i, ++realArgIdx) {
857     CCValAssign &VA = ArgLocs[i];
858     SDValue Arg = Outs[realArgIdx].Val;
859     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
860
861     // Promote the value if needed.
862     switch (VA.getLocInfo()) {
863     default: llvm_unreachable("Unknown loc info!");
864     case CCValAssign::Full: break;
865     case CCValAssign::SExt:
866       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
867       break;
868     case CCValAssign::ZExt:
869       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
870       break;
871     case CCValAssign::AExt:
872       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
873       break;
874     case CCValAssign::BCvt:
875       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
876       break;
877     }
878
879     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
880     if (VA.needsCustom()) {
881       if (VA.getLocVT() == MVT::v2f64) {
882         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
883                                   DAG.getConstant(0, MVT::i32));
884         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
885                                   DAG.getConstant(1, MVT::i32));
886
887         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
888                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
889
890         VA = ArgLocs[++i]; // skip ahead to next loc
891         if (VA.isRegLoc()) {
892           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
893                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
894         } else {
895           assert(VA.isMemLoc());
896           if (StackPtr.getNode() == 0)
897             StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
898
899           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
900                                                  dl, DAG, VA, Flags));
901         }
902       } else {
903         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
904                          StackPtr, MemOpChains, Flags);
905       }
906     } else if (VA.isRegLoc()) {
907       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
908     } else {
909       assert(VA.isMemLoc());
910       if (StackPtr.getNode() == 0)
911         StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
912
913       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
914                                              dl, DAG, VA, Flags));
915     }
916   }
917
918   if (!MemOpChains.empty())
919     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
920                         &MemOpChains[0], MemOpChains.size());
921
922   // Build a sequence of copy-to-reg nodes chained together with token chain
923   // and flag operands which copy the outgoing args into the appropriate regs.
924   SDValue InFlag;
925   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
926     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
927                              RegsToPass[i].second, InFlag);
928     InFlag = Chain.getValue(1);
929   }
930
931   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
932   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
933   // node so that legalize doesn't hack it.
934   bool isDirect = false;
935   bool isARMFunc = false;
936   bool isLocalARMFunc = false;
937   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
938     GlobalValue *GV = G->getGlobal();
939     isDirect = true;
940     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
941     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
942                    getTargetMachine().getRelocationModel() != Reloc::Static;
943     isARMFunc = !Subtarget->isThumb() || isStub;
944     // ARM call to a local ARM function is predicable.
945     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
946     // tBX takes a register source operand.
947     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
948       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
949                                                            ARMCP::CPStub, 4);
950       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
951       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
952       Callee = DAG.getLoad(getPointerTy(), dl,
953                            DAG.getEntryNode(), CPAddr, NULL, 0);
954       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
955       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
956                            getPointerTy(), Callee, PICLabel);
957    } else
958       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
959   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
960     isDirect = true;
961     bool isStub = Subtarget->isTargetDarwin() &&
962                   getTargetMachine().getRelocationModel() != Reloc::Static;
963     isARMFunc = !Subtarget->isThumb() || isStub;
964     // tBX takes a register source operand.
965     const char *Sym = S->getSymbol();
966     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
967       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(Sym, ARMPCLabelIndex,
968                                                            ARMCP::CPStub, 4);
969       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
970       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
971       Callee = DAG.getLoad(getPointerTy(), dl,
972                            DAG.getEntryNode(), CPAddr, NULL, 0);
973       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
974       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
975                            getPointerTy(), Callee, PICLabel);
976     } else
977       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
978   }
979
980   // FIXME: handle tail calls differently.
981   unsigned CallOpc;
982   if (Subtarget->isThumb()) {
983     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
984       CallOpc = ARMISD::CALL_NOLINK;
985     else
986       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
987   } else {
988     CallOpc = (isDirect || Subtarget->hasV5TOps())
989       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
990       : ARMISD::CALL_NOLINK;
991   }
992   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb1Only()) {
993     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
994     Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
995     InFlag = Chain.getValue(1);
996   }
997
998   std::vector<SDValue> Ops;
999   Ops.push_back(Chain);
1000   Ops.push_back(Callee);
1001
1002   // Add argument registers to the end of the list so that they are known live
1003   // into the call.
1004   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1005     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1006                                   RegsToPass[i].second.getValueType()));
1007
1008   if (InFlag.getNode())
1009     Ops.push_back(InFlag);
1010   // Returns a chain and a flag for retval copy to use.
1011   Chain = DAG.getNode(CallOpc, dl, DAG.getVTList(MVT::Other, MVT::Flag),
1012                       &Ops[0], Ops.size());
1013   InFlag = Chain.getValue(1);
1014
1015   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1016                              DAG.getIntPtrConstant(0, true), InFlag);
1017   if (!Ins.empty())
1018     InFlag = Chain.getValue(1);
1019
1020   // Handle result values, copying them out of physregs into vregs that we
1021   // return.
1022   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1023                          dl, DAG, InVals);
1024 }
1025
1026 SDValue
1027 ARMTargetLowering::LowerReturn(SDValue Chain,
1028                                unsigned CallConv, bool isVarArg,
1029                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1030                                DebugLoc dl, SelectionDAG &DAG) {
1031
1032   // CCValAssign - represent the assignment of the return value to a location.
1033   SmallVector<CCValAssign, 16> RVLocs;
1034
1035   // CCState - Info about the registers and stack slots.
1036   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1037                  *DAG.getContext());
1038
1039   // Analyze outgoing return values.
1040   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1041                                                isVarArg));
1042
1043   // If this is the first return lowered for this function, add
1044   // the regs to the liveout set for the function.
1045   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1046     for (unsigned i = 0; i != RVLocs.size(); ++i)
1047       if (RVLocs[i].isRegLoc())
1048         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1049   }
1050
1051   SDValue Flag;
1052
1053   // Copy the result values into the output registers.
1054   for (unsigned i = 0, realRVLocIdx = 0;
1055        i != RVLocs.size();
1056        ++i, ++realRVLocIdx) {
1057     CCValAssign &VA = RVLocs[i];
1058     assert(VA.isRegLoc() && "Can only return in registers!");
1059
1060     SDValue Arg = Outs[realRVLocIdx].Val;
1061
1062     switch (VA.getLocInfo()) {
1063     default: llvm_unreachable("Unknown loc info!");
1064     case CCValAssign::Full: break;
1065     case CCValAssign::BCvt:
1066       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
1067       break;
1068     }
1069
1070     if (VA.needsCustom()) {
1071       if (VA.getLocVT() == MVT::v2f64) {
1072         // Extract the first half and return it in two registers.
1073         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1074                                    DAG.getConstant(0, MVT::i32));
1075         SDValue HalfGPRs = DAG.getNode(ARMISD::FMRRD, dl,
1076                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1077
1078         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1079         Flag = Chain.getValue(1);
1080         VA = RVLocs[++i]; // skip ahead to next loc
1081         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1082                                  HalfGPRs.getValue(1), Flag);
1083         Flag = Chain.getValue(1);
1084         VA = RVLocs[++i]; // skip ahead to next loc
1085
1086         // Extract the 2nd half and fall through to handle it as an f64 value.
1087         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1088                           DAG.getConstant(1, MVT::i32));
1089       }
1090       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1091       // available.
1092       SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
1093                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1094       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1095       Flag = Chain.getValue(1);
1096       VA = RVLocs[++i]; // skip ahead to next loc
1097       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1098                                Flag);
1099     } else
1100       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1101
1102     // Guarantee that all emitted copies are
1103     // stuck together, avoiding something bad.
1104     Flag = Chain.getValue(1);
1105   }
1106
1107   SDValue result;
1108   if (Flag.getNode())
1109     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1110   else // Return Void
1111     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1112
1113   return result;
1114 }
1115
1116 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1117 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1118 // one of the above mentioned nodes. It has to be wrapped because otherwise
1119 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1120 // be used to form addressing mode. These wrapped nodes will be selected
1121 // into MOVi.
1122 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1123   MVT PtrVT = Op.getValueType();
1124   // FIXME there is no actual debug info here
1125   DebugLoc dl = Op.getDebugLoc();
1126   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1127   SDValue Res;
1128   if (CP->isMachineConstantPoolEntry())
1129     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1130                                     CP->getAlignment());
1131   else
1132     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1133                                     CP->getAlignment());
1134   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1135 }
1136
1137 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1138 SDValue
1139 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1140                                                  SelectionDAG &DAG) {
1141   DebugLoc dl = GA->getDebugLoc();
1142   MVT PtrVT = getPointerTy();
1143   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1144   ARMConstantPoolValue *CPV =
1145     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
1146                              PCAdj, "tlsgd", true);
1147   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1148   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1149   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, NULL, 0);
1150   SDValue Chain = Argument.getValue(1);
1151
1152   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1153   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1154
1155   // call __tls_get_addr.
1156   ArgListTy Args;
1157   ArgListEntry Entry;
1158   Entry.Node = Argument;
1159   Entry.Ty = (const Type *) Type::Int32Ty;
1160   Args.push_back(Entry);
1161   // FIXME: is there useful debug info available here?
1162   std::pair<SDValue, SDValue> CallResult =
1163     LowerCallTo(Chain, (const Type *) Type::Int32Ty, false, false, false, false,
1164                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1165                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1166   return CallResult.first;
1167 }
1168
1169 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1170 // "local exec" model.
1171 SDValue
1172 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1173                                         SelectionDAG &DAG) {
1174   GlobalValue *GV = GA->getGlobal();
1175   DebugLoc dl = GA->getDebugLoc();
1176   SDValue Offset;
1177   SDValue Chain = DAG.getEntryNode();
1178   MVT PtrVT = getPointerTy();
1179   // Get the Thread Pointer
1180   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1181
1182   if (GV->isDeclaration()) {
1183     // initial exec model
1184     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1185     ARMConstantPoolValue *CPV =
1186       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
1187                                PCAdj, "gottpoff", true);
1188     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1189     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1190     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1191     Chain = Offset.getValue(1);
1192
1193     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1194     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
1195
1196     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1197   } else {
1198     // local exec model
1199     ARMConstantPoolValue *CPV =
1200       new ARMConstantPoolValue(GV, ARMCP::CPValue, "tpoff");
1201     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1202     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1203     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1204   }
1205
1206   // The address of the thread local variable is the add of the thread
1207   // pointer with the offset of the variable.
1208   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1209 }
1210
1211 SDValue
1212 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
1213   // TODO: implement the "local dynamic" model
1214   assert(Subtarget->isTargetELF() &&
1215          "TLS not implemented for non-ELF targets");
1216   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1217   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
1218   // otherwise use the "Local Exec" TLS Model
1219   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
1220     return LowerToTLSGeneralDynamicModel(GA, DAG);
1221   else
1222     return LowerToTLSExecModels(GA, DAG);
1223 }
1224
1225 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
1226                                                  SelectionDAG &DAG) {
1227   MVT PtrVT = getPointerTy();
1228   DebugLoc dl = Op.getDebugLoc();
1229   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1230   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1231   if (RelocM == Reloc::PIC_) {
1232     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
1233     ARMConstantPoolValue *CPV =
1234       new ARMConstantPoolValue(GV, ARMCP::CPValue, UseGOTOFF ? "GOTOFF":"GOT");
1235     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1236     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1237     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1238                                  CPAddr, NULL, 0);
1239     SDValue Chain = Result.getValue(1);
1240     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1241     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
1242     if (!UseGOTOFF)
1243       Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1244     return Result;
1245   } else {
1246     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1247     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1248     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1249   }
1250 }
1251
1252 /// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol
1253 /// even in non-static mode.
1254 static bool GVIsIndirectSymbol(GlobalValue *GV, Reloc::Model RelocM) {
1255   // If symbol visibility is hidden, the extra load is not needed if
1256   // the symbol is definitely defined in the current translation unit.
1257   bool isDecl = GV->isDeclaration() || GV->hasAvailableExternallyLinkage();
1258   if (GV->hasHiddenVisibility() && (!isDecl && !GV->hasCommonLinkage()))
1259     return false;
1260   return RelocM != Reloc::Static && (isDecl || GV->isWeakForLinker());
1261 }
1262
1263 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
1264                                                     SelectionDAG &DAG) {
1265   MVT PtrVT = getPointerTy();
1266   DebugLoc dl = Op.getDebugLoc();
1267   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1268   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1269   bool IsIndirect = GVIsIndirectSymbol(GV, RelocM);
1270   SDValue CPAddr;
1271   if (RelocM == Reloc::Static)
1272     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1273   else {
1274     unsigned PCAdj = (RelocM != Reloc::PIC_)
1275       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1276     ARMCP::ARMCPKind Kind = IsIndirect ? ARMCP::CPNonLazyPtr
1277       : ARMCP::CPValue;
1278     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
1279                                                          Kind, PCAdj);
1280     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1281   }
1282   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1283
1284   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1285   SDValue Chain = Result.getValue(1);
1286
1287   if (RelocM == Reloc::PIC_) {
1288     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1289     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1290   }
1291   if (IsIndirect)
1292     Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1293
1294   return Result;
1295 }
1296
1297 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
1298                                                     SelectionDAG &DAG){
1299   assert(Subtarget->isTargetELF() &&
1300          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
1301   MVT PtrVT = getPointerTy();
1302   DebugLoc dl = Op.getDebugLoc();
1303   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1304   ARMConstantPoolValue *CPV = new ARMConstantPoolValue("_GLOBAL_OFFSET_TABLE_",
1305                                                        ARMPCLabelIndex,
1306                                                        ARMCP::CPValue, PCAdj);
1307   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1308   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1309   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1310   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1311   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1312 }
1313
1314 static SDValue LowerNeonVLDIntrinsic(SDValue Op, SelectionDAG &DAG,
1315                                      unsigned Opcode) {
1316   SDNode *Node = Op.getNode();
1317   MVT VT = Node->getValueType(0);
1318   DebugLoc dl = Op.getDebugLoc();
1319
1320   if (!VT.is64BitVector())
1321     return SDValue(); // unimplemented
1322
1323   SDValue Ops[] = { Node->getOperand(0),
1324                     Node->getOperand(2) };
1325   return DAG.getNode(Opcode, dl, Node->getVTList(), Ops, 2);
1326 }
1327
1328 SDValue
1329 ARMTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
1330   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1331   switch (IntNo) {
1332   case Intrinsic::arm_neon_vld2i:
1333   case Intrinsic::arm_neon_vld2f:
1334     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD2D);
1335   case Intrinsic::arm_neon_vld3i:
1336   case Intrinsic::arm_neon_vld3f:
1337     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD3D);
1338   case Intrinsic::arm_neon_vld4i:
1339   case Intrinsic::arm_neon_vld4f:
1340     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD4D);
1341   case Intrinsic::arm_neon_vst2i:
1342   case Intrinsic::arm_neon_vst2f:
1343   case Intrinsic::arm_neon_vst3i:
1344   case Intrinsic::arm_neon_vst3f:
1345   case Intrinsic::arm_neon_vst4i:
1346   case Intrinsic::arm_neon_vst4f:
1347   default: return SDValue();    // Don't custom lower most intrinsics.
1348   }
1349 }
1350
1351 SDValue
1352 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
1353   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1354   DebugLoc dl = Op.getDebugLoc();
1355   switch (IntNo) {
1356   default: return SDValue();    // Don't custom lower most intrinsics.
1357   case Intrinsic::arm_thread_pointer: {
1358     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1359     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1360   }
1361   case Intrinsic::eh_sjlj_setjmp:
1362     return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(1));
1363   }
1364 }
1365
1366 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1367                             unsigned VarArgsFrameIndex) {
1368   // vastart just stores the address of the VarArgsFrameIndex slot into the
1369   // memory location argument.
1370   DebugLoc dl = Op.getDebugLoc();
1371   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1372   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1373   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1374   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1375 }
1376
1377 SDValue
1378 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
1379                                         SDValue &Root, SelectionDAG &DAG,
1380                                         DebugLoc dl) {
1381   MachineFunction &MF = DAG.getMachineFunction();
1382   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1383
1384   TargetRegisterClass *RC;
1385   if (AFI->isThumb1OnlyFunction())
1386     RC = ARM::tGPRRegisterClass;
1387   else
1388     RC = ARM::GPRRegisterClass;
1389
1390   // Transform the arguments stored in physical registers into virtual ones.
1391   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1392   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1393
1394   SDValue ArgValue2;
1395   if (NextVA.isMemLoc()) {
1396     unsigned ArgSize = NextVA.getLocVT().getSizeInBits()/8;
1397     MachineFrameInfo *MFI = MF.getFrameInfo();
1398     int FI = MFI->CreateFixedObject(ArgSize, NextVA.getLocMemOffset());
1399
1400     // Create load node to retrieve arguments from the stack.
1401     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1402     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
1403   } else {
1404     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1405     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1406   }
1407
1408   return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
1409 }
1410
1411 SDValue
1412 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
1413                                         unsigned CallConv, bool isVarArg,
1414                                         const SmallVectorImpl<ISD::InputArg>
1415                                           &Ins,
1416                                         DebugLoc dl, SelectionDAG &DAG,
1417                                         SmallVectorImpl<SDValue> &InVals) {
1418
1419   MachineFunction &MF = DAG.getMachineFunction();
1420   MachineFrameInfo *MFI = MF.getFrameInfo();
1421
1422   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1423
1424   // Assign locations to all of the incoming arguments.
1425   SmallVector<CCValAssign, 16> ArgLocs;
1426   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1427                  *DAG.getContext());
1428   CCInfo.AnalyzeFormalArguments(Ins,
1429                                 CCAssignFnForNode(CallConv, /* Return*/ false,
1430                                                   isVarArg));
1431
1432   SmallVector<SDValue, 16> ArgValues;
1433
1434   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1435     CCValAssign &VA = ArgLocs[i];
1436
1437     // Arguments stored in registers.
1438     if (VA.isRegLoc()) {
1439       MVT RegVT = VA.getLocVT();
1440
1441       SDValue ArgValue;
1442       if (VA.needsCustom()) {
1443         // f64 and vector types are split up into multiple registers or
1444         // combinations of registers and stack slots.
1445         RegVT = MVT::i32;
1446
1447         if (VA.getLocVT() == MVT::v2f64) {
1448           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
1449                                                    Chain, DAG, dl);
1450           VA = ArgLocs[++i]; // skip ahead to next loc
1451           SDValue ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
1452                                                    Chain, DAG, dl);
1453           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1454           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1455                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
1456           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1457                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
1458         } else
1459           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
1460
1461       } else {
1462         TargetRegisterClass *RC;
1463
1464         if (FloatABIType == FloatABI::Hard && RegVT == MVT::f32)
1465           RC = ARM::SPRRegisterClass;
1466         else if (FloatABIType == FloatABI::Hard && RegVT == MVT::f64)
1467           RC = ARM::DPRRegisterClass;
1468         else if (FloatABIType == FloatABI::Hard && RegVT == MVT::v2f64)
1469           RC = ARM::QPRRegisterClass;
1470         else if (AFI->isThumb1OnlyFunction())
1471           RC = ARM::tGPRRegisterClass;
1472         else
1473           RC = ARM::GPRRegisterClass;
1474
1475         assert((RegVT == MVT::i32 || RegVT == MVT::f32 ||
1476                 (FloatABIType == FloatABI::Hard &&
1477                  ((RegVT == MVT::f64) || (RegVT == MVT::v2f64)))) &&
1478                "RegVT not supported by FORMAL_ARGUMENTS Lowering");
1479
1480         // Transform the arguments in physical registers into virtual ones.
1481         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1482         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1483       }
1484
1485       // If this is an 8 or 16-bit value, it is really passed promoted
1486       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1487       // truncate to the right size.
1488       switch (VA.getLocInfo()) {
1489       default: llvm_unreachable("Unknown loc info!");
1490       case CCValAssign::Full: break;
1491       case CCValAssign::BCvt:
1492         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1493         break;
1494       case CCValAssign::SExt:
1495         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1496                                DAG.getValueType(VA.getValVT()));
1497         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1498         break;
1499       case CCValAssign::ZExt:
1500         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1501                                DAG.getValueType(VA.getValVT()));
1502         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1503         break;
1504       }
1505
1506       InVals.push_back(ArgValue);
1507
1508     } else { // VA.isRegLoc()
1509
1510       // sanity check
1511       assert(VA.isMemLoc());
1512       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1513
1514       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1515       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1516
1517       // Create load nodes to retrieve arguments from the stack.
1518       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1519       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0));
1520     }
1521   }
1522
1523   // varargs
1524   if (isVarArg) {
1525     static const unsigned GPRArgRegs[] = {
1526       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1527     };
1528
1529     unsigned NumGPRs = CCInfo.getFirstUnallocated
1530       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1531
1532     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1533     unsigned VARegSize = (4 - NumGPRs) * 4;
1534     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1535     unsigned ArgOffset = 0;
1536     if (VARegSaveSize) {
1537       // If this function is vararg, store any remaining integer argument regs
1538       // to their spots on the stack so that they may be loaded by deferencing
1539       // the result of va_next.
1540       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1541       ArgOffset = CCInfo.getNextStackOffset();
1542       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1543                                                  VARegSaveSize - VARegSize);
1544       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1545
1546       SmallVector<SDValue, 4> MemOps;
1547       for (; NumGPRs < 4; ++NumGPRs) {
1548         TargetRegisterClass *RC;
1549         if (AFI->isThumb1OnlyFunction())
1550           RC = ARM::tGPRRegisterClass;
1551         else
1552           RC = ARM::GPRRegisterClass;
1553
1554         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1555         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1556         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1557         MemOps.push_back(Store);
1558         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1559                           DAG.getConstant(4, getPointerTy()));
1560       }
1561       if (!MemOps.empty())
1562         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1563                             &MemOps[0], MemOps.size());
1564     } else
1565       // This will point to the next argument passed via stack.
1566       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1567   }
1568
1569   return Chain;
1570 }
1571
1572 /// isFloatingPointZero - Return true if this is +0.0.
1573 static bool isFloatingPointZero(SDValue Op) {
1574   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1575     return CFP->getValueAPF().isPosZero();
1576   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1577     // Maybe this has already been legalized into the constant pool?
1578     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1579       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1580       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1581         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1582           return CFP->getValueAPF().isPosZero();
1583     }
1584   }
1585   return false;
1586 }
1587
1588 static bool isLegalCmpImmediate(unsigned C, bool isThumb1Only) {
1589   return ( isThumb1Only && (C & ~255U) == 0) ||
1590          (!isThumb1Only && ARM_AM::getSOImmVal(C) != -1);
1591 }
1592
1593 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1594 /// the given operands.
1595 static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1596                          SDValue &ARMCC, SelectionDAG &DAG, bool isThumb1Only,
1597                          DebugLoc dl) {
1598   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1599     unsigned C = RHSC->getZExtValue();
1600     if (!isLegalCmpImmediate(C, isThumb1Only)) {
1601       // Constant does not fit, try adjusting it by one?
1602       switch (CC) {
1603       default: break;
1604       case ISD::SETLT:
1605       case ISD::SETGE:
1606         if (isLegalCmpImmediate(C-1, isThumb1Only)) {
1607           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1608           RHS = DAG.getConstant(C-1, MVT::i32);
1609         }
1610         break;
1611       case ISD::SETULT:
1612       case ISD::SETUGE:
1613         if (C > 0 && isLegalCmpImmediate(C-1, isThumb1Only)) {
1614           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1615           RHS = DAG.getConstant(C-1, MVT::i32);
1616         }
1617         break;
1618       case ISD::SETLE:
1619       case ISD::SETGT:
1620         if (isLegalCmpImmediate(C+1, isThumb1Only)) {
1621           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1622           RHS = DAG.getConstant(C+1, MVT::i32);
1623         }
1624         break;
1625       case ISD::SETULE:
1626       case ISD::SETUGT:
1627         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb1Only)) {
1628           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1629           RHS = DAG.getConstant(C+1, MVT::i32);
1630         }
1631         break;
1632       }
1633     }
1634   }
1635
1636   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1637   ARMISD::NodeType CompareType;
1638   switch (CondCode) {
1639   default:
1640     CompareType = ARMISD::CMP;
1641     break;
1642   case ARMCC::EQ:
1643   case ARMCC::NE:
1644     // Uses only Z Flag
1645     CompareType = ARMISD::CMPZ;
1646     break;
1647   }
1648   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1649   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1650 }
1651
1652 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1653 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1654                          DebugLoc dl) {
1655   SDValue Cmp;
1656   if (!isFloatingPointZero(RHS))
1657     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1658   else
1659     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1660   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1661 }
1662
1663 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1664                               const ARMSubtarget *ST) {
1665   MVT VT = Op.getValueType();
1666   SDValue LHS = Op.getOperand(0);
1667   SDValue RHS = Op.getOperand(1);
1668   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1669   SDValue TrueVal = Op.getOperand(2);
1670   SDValue FalseVal = Op.getOperand(3);
1671   DebugLoc dl = Op.getDebugLoc();
1672
1673   if (LHS.getValueType() == MVT::i32) {
1674     SDValue ARMCC;
1675     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1676     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1677     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1678   }
1679
1680   ARMCC::CondCodes CondCode, CondCode2;
1681   if (FPCCToARMCC(CC, CondCode, CondCode2))
1682     std::swap(TrueVal, FalseVal);
1683
1684   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1685   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1686   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1687   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1688                                  ARMCC, CCR, Cmp);
1689   if (CondCode2 != ARMCC::AL) {
1690     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1691     // FIXME: Needs another CMP because flag can have but one use.
1692     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1693     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1694                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1695   }
1696   return Result;
1697 }
1698
1699 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1700                           const ARMSubtarget *ST) {
1701   SDValue  Chain = Op.getOperand(0);
1702   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1703   SDValue    LHS = Op.getOperand(2);
1704   SDValue    RHS = Op.getOperand(3);
1705   SDValue   Dest = Op.getOperand(4);
1706   DebugLoc dl = Op.getDebugLoc();
1707
1708   if (LHS.getValueType() == MVT::i32) {
1709     SDValue ARMCC;
1710     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1711     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1712     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1713                        Chain, Dest, ARMCC, CCR,Cmp);
1714   }
1715
1716   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1717   ARMCC::CondCodes CondCode, CondCode2;
1718   if (FPCCToARMCC(CC, CondCode, CondCode2))
1719     // Swap the LHS/RHS of the comparison if needed.
1720     std::swap(LHS, RHS);
1721
1722   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1723   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1724   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1725   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1726   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1727   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1728   if (CondCode2 != ARMCC::AL) {
1729     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1730     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1731     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1732   }
1733   return Res;
1734 }
1735
1736 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1737   SDValue Chain = Op.getOperand(0);
1738   SDValue Table = Op.getOperand(1);
1739   SDValue Index = Op.getOperand(2);
1740   DebugLoc dl = Op.getDebugLoc();
1741
1742   MVT PTy = getPointerTy();
1743   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1744   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1745   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
1746   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1747   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1748   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1749   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1750   if (Subtarget->isThumb2()) {
1751     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
1752     // which does another jump to the destination. This also makes it easier
1753     // to translate it to TBB / TBH later.
1754     // FIXME: This might not work if the function is extremely large.
1755     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
1756                        Addr, Op.getOperand(2), JTI, UId);
1757   }
1758   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1759     Addr = DAG.getLoad((MVT)MVT::i32, dl, Chain, Addr, NULL, 0);
1760     Chain = Addr.getValue(1);
1761     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1762     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1763   } else {
1764     Addr = DAG.getLoad(PTy, dl, Chain, Addr, NULL, 0);
1765     Chain = Addr.getValue(1);
1766     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1767   }
1768 }
1769
1770 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1771   DebugLoc dl = Op.getDebugLoc();
1772   unsigned Opc =
1773     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1774   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1775   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1776 }
1777
1778 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1779   MVT VT = Op.getValueType();
1780   DebugLoc dl = Op.getDebugLoc();
1781   unsigned Opc =
1782     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1783
1784   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1785   return DAG.getNode(Opc, dl, VT, Op);
1786 }
1787
1788 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1789   // Implement fcopysign with a fabs and a conditional fneg.
1790   SDValue Tmp0 = Op.getOperand(0);
1791   SDValue Tmp1 = Op.getOperand(1);
1792   DebugLoc dl = Op.getDebugLoc();
1793   MVT VT = Op.getValueType();
1794   MVT SrcVT = Tmp1.getValueType();
1795   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1796   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1797   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1798   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1799   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1800 }
1801
1802 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1803   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1804   MFI->setFrameAddressIsTaken(true);
1805   MVT VT = Op.getValueType();
1806   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1807   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1808   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
1809     ? ARM::R7 : ARM::R11;
1810   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1811   while (Depth--)
1812     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1813   return FrameAddr;
1814 }
1815
1816 SDValue
1817 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1818                                            SDValue Chain,
1819                                            SDValue Dst, SDValue Src,
1820                                            SDValue Size, unsigned Align,
1821                                            bool AlwaysInline,
1822                                          const Value *DstSV, uint64_t DstSVOff,
1823                                          const Value *SrcSV, uint64_t SrcSVOff){
1824   // Do repeated 4-byte loads and stores. To be improved.
1825   // This requires 4-byte alignment.
1826   if ((Align & 3) != 0)
1827     return SDValue();
1828   // This requires the copy size to be a constant, preferrably
1829   // within a subtarget-specific limit.
1830   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1831   if (!ConstantSize)
1832     return SDValue();
1833   uint64_t SizeVal = ConstantSize->getZExtValue();
1834   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1835     return SDValue();
1836
1837   unsigned BytesLeft = SizeVal & 3;
1838   unsigned NumMemOps = SizeVal >> 2;
1839   unsigned EmittedNumMemOps = 0;
1840   MVT VT = MVT::i32;
1841   unsigned VTSize = 4;
1842   unsigned i = 0;
1843   const unsigned MAX_LOADS_IN_LDM = 6;
1844   SDValue TFOps[MAX_LOADS_IN_LDM];
1845   SDValue Loads[MAX_LOADS_IN_LDM];
1846   uint64_t SrcOff = 0, DstOff = 0;
1847
1848   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1849   // same number of stores.  The loads and stores will get combined into
1850   // ldm/stm later on.
1851   while (EmittedNumMemOps < NumMemOps) {
1852     for (i = 0;
1853          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1854       Loads[i] = DAG.getLoad(VT, dl, Chain,
1855                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1856                                          DAG.getConstant(SrcOff, MVT::i32)),
1857                              SrcSV, SrcSVOff + SrcOff);
1858       TFOps[i] = Loads[i].getValue(1);
1859       SrcOff += VTSize;
1860     }
1861     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1862
1863     for (i = 0;
1864          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1865       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1866                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1867                                        DAG.getConstant(DstOff, MVT::i32)),
1868                            DstSV, DstSVOff + DstOff);
1869       DstOff += VTSize;
1870     }
1871     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1872
1873     EmittedNumMemOps += i;
1874   }
1875
1876   if (BytesLeft == 0)
1877     return Chain;
1878
1879   // Issue loads / stores for the trailing (1 - 3) bytes.
1880   unsigned BytesLeftSave = BytesLeft;
1881   i = 0;
1882   while (BytesLeft) {
1883     if (BytesLeft >= 2) {
1884       VT = MVT::i16;
1885       VTSize = 2;
1886     } else {
1887       VT = MVT::i8;
1888       VTSize = 1;
1889     }
1890
1891     Loads[i] = DAG.getLoad(VT, dl, Chain,
1892                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1893                                        DAG.getConstant(SrcOff, MVT::i32)),
1894                            SrcSV, SrcSVOff + SrcOff);
1895     TFOps[i] = Loads[i].getValue(1);
1896     ++i;
1897     SrcOff += VTSize;
1898     BytesLeft -= VTSize;
1899   }
1900   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1901
1902   i = 0;
1903   BytesLeft = BytesLeftSave;
1904   while (BytesLeft) {
1905     if (BytesLeft >= 2) {
1906       VT = MVT::i16;
1907       VTSize = 2;
1908     } else {
1909       VT = MVT::i8;
1910       VTSize = 1;
1911     }
1912
1913     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1914                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1915                                         DAG.getConstant(DstOff, MVT::i32)),
1916                             DstSV, DstSVOff + DstOff);
1917     ++i;
1918     DstOff += VTSize;
1919     BytesLeft -= VTSize;
1920   }
1921   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1922 }
1923
1924 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1925   SDValue Op = N->getOperand(0);
1926   DebugLoc dl = N->getDebugLoc();
1927   if (N->getValueType(0) == MVT::f64) {
1928     // Turn i64->f64 into FMDRR.
1929     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1930                              DAG.getConstant(0, MVT::i32));
1931     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1932                              DAG.getConstant(1, MVT::i32));
1933     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
1934   }
1935
1936   // Turn f64->i64 into FMRRD.
1937   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
1938                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
1939
1940   // Merge the pieces into a single i64 value.
1941   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
1942 }
1943
1944 /// getZeroVector - Returns a vector of specified type with all zero elements.
1945 ///
1946 static SDValue getZeroVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
1947   assert(VT.isVector() && "Expected a vector type");
1948
1949   // Zero vectors are used to represent vector negation and in those cases
1950   // will be implemented with the NEON VNEG instruction.  However, VNEG does
1951   // not support i64 elements, so sometimes the zero vectors will need to be
1952   // explicitly constructed.  For those cases, and potentially other uses in
1953   // the future, always build zero vectors as <4 x i32> or <2 x i32> bitcasted
1954   // to their dest type.  This ensures they get CSE'd.
1955   SDValue Vec;
1956   SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
1957   if (VT.getSizeInBits() == 64)
1958     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
1959   else
1960     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
1961
1962   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
1963 }
1964
1965 /// getOnesVector - Returns a vector of specified type with all bits set.
1966 ///
1967 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
1968   assert(VT.isVector() && "Expected a vector type");
1969
1970   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
1971   // type.  This ensures they get CSE'd.
1972   SDValue Vec;
1973   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
1974   if (VT.getSizeInBits() == 64)
1975     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
1976   else
1977     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
1978
1979   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
1980 }
1981
1982 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
1983                           const ARMSubtarget *ST) {
1984   MVT VT = N->getValueType(0);
1985   DebugLoc dl = N->getDebugLoc();
1986
1987   // Lower vector shifts on NEON to use VSHL.
1988   if (VT.isVector()) {
1989     assert(ST->hasNEON() && "unexpected vector shift");
1990
1991     // Left shifts translate directly to the vshiftu intrinsic.
1992     if (N->getOpcode() == ISD::SHL)
1993       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
1994                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
1995                          N->getOperand(0), N->getOperand(1));
1996
1997     assert((N->getOpcode() == ISD::SRA ||
1998             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
1999
2000     // NEON uses the same intrinsics for both left and right shifts.  For
2001     // right shifts, the shift amounts are negative, so negate the vector of
2002     // shift amounts.
2003     MVT ShiftVT = N->getOperand(1).getValueType();
2004     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2005                                        getZeroVector(ShiftVT, DAG, dl),
2006                                        N->getOperand(1));
2007     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2008                                Intrinsic::arm_neon_vshifts :
2009                                Intrinsic::arm_neon_vshiftu);
2010     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2011                        DAG.getConstant(vshiftInt, MVT::i32),
2012                        N->getOperand(0), NegatedCount);
2013   }
2014
2015   assert(VT == MVT::i64 &&
2016          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2017          "Unknown shift to lower!");
2018
2019   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2020   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2021       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2022     return SDValue();
2023
2024   // If we are in thumb mode, we don't have RRX.
2025   if (ST->isThumb1Only()) return SDValue();
2026
2027   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2028   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2029                              DAG.getConstant(0, MVT::i32));
2030   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2031                              DAG.getConstant(1, MVT::i32));
2032
2033   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2034   // captures the result into a carry flag.
2035   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2036   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2037
2038   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2039   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2040
2041   // Merge the pieces into a single i64 value.
2042  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2043 }
2044
2045 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2046   SDValue TmpOp0, TmpOp1;
2047   bool Invert = false;
2048   bool Swap = false;
2049   unsigned Opc = 0;
2050
2051   SDValue Op0 = Op.getOperand(0);
2052   SDValue Op1 = Op.getOperand(1);
2053   SDValue CC = Op.getOperand(2);
2054   MVT VT = Op.getValueType();
2055   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2056   DebugLoc dl = Op.getDebugLoc();
2057
2058   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2059     switch (SetCCOpcode) {
2060     default: llvm_unreachable("Illegal FP comparison"); break;
2061     case ISD::SETUNE:
2062     case ISD::SETNE:  Invert = true; // Fallthrough
2063     case ISD::SETOEQ:
2064     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2065     case ISD::SETOLT:
2066     case ISD::SETLT: Swap = true; // Fallthrough
2067     case ISD::SETOGT:
2068     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2069     case ISD::SETOLE:
2070     case ISD::SETLE:  Swap = true; // Fallthrough
2071     case ISD::SETOGE:
2072     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2073     case ISD::SETUGE: Swap = true; // Fallthrough
2074     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2075     case ISD::SETUGT: Swap = true; // Fallthrough
2076     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2077     case ISD::SETUEQ: Invert = true; // Fallthrough
2078     case ISD::SETONE:
2079       // Expand this to (OLT | OGT).
2080       TmpOp0 = Op0;
2081       TmpOp1 = Op1;
2082       Opc = ISD::OR;
2083       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2084       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2085       break;
2086     case ISD::SETUO: Invert = true; // Fallthrough
2087     case ISD::SETO:
2088       // Expand this to (OLT | OGE).
2089       TmpOp0 = Op0;
2090       TmpOp1 = Op1;
2091       Opc = ISD::OR;
2092       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2093       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2094       break;
2095     }
2096   } else {
2097     // Integer comparisons.
2098     switch (SetCCOpcode) {
2099     default: llvm_unreachable("Illegal integer comparison"); break;
2100     case ISD::SETNE:  Invert = true;
2101     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2102     case ISD::SETLT:  Swap = true;
2103     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2104     case ISD::SETLE:  Swap = true;
2105     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2106     case ISD::SETULT: Swap = true;
2107     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2108     case ISD::SETULE: Swap = true;
2109     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2110     }
2111
2112     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2113     if (Opc == ARMISD::VCEQ) {
2114
2115       SDValue AndOp;
2116       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2117         AndOp = Op0;
2118       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2119         AndOp = Op1;
2120
2121       // Ignore bitconvert.
2122       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2123         AndOp = AndOp.getOperand(0);
2124
2125       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2126         Opc = ARMISD::VTST;
2127         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2128         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2129         Invert = !Invert;
2130       }
2131     }
2132   }
2133
2134   if (Swap)
2135     std::swap(Op0, Op1);
2136
2137   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2138
2139   if (Invert)
2140     Result = DAG.getNOT(dl, Result, VT);
2141
2142   return Result;
2143 }
2144
2145 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2146 /// VMOV instruction, and if so, return the constant being splatted.
2147 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2148                            unsigned SplatBitSize, SelectionDAG &DAG) {
2149   switch (SplatBitSize) {
2150   case 8:
2151     // Any 1-byte value is OK.
2152     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2153     return DAG.getTargetConstant(SplatBits, MVT::i8);
2154
2155   case 16:
2156     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2157     if ((SplatBits & ~0xff) == 0 ||
2158         (SplatBits & ~0xff00) == 0)
2159       return DAG.getTargetConstant(SplatBits, MVT::i16);
2160     break;
2161
2162   case 32:
2163     // NEON's 32-bit VMOV supports splat values where:
2164     // * only one byte is nonzero, or
2165     // * the least significant byte is 0xff and the second byte is nonzero, or
2166     // * the least significant 2 bytes are 0xff and the third is nonzero.
2167     if ((SplatBits & ~0xff) == 0 ||
2168         (SplatBits & ~0xff00) == 0 ||
2169         (SplatBits & ~0xff0000) == 0 ||
2170         (SplatBits & ~0xff000000) == 0)
2171       return DAG.getTargetConstant(SplatBits, MVT::i32);
2172
2173     if ((SplatBits & ~0xffff) == 0 &&
2174         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2175       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2176
2177     if ((SplatBits & ~0xffffff) == 0 &&
2178         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2179       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2180
2181     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2182     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2183     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2184     // and fall through here to test for a valid 64-bit splat.  But, then the
2185     // caller would also need to check and handle the change in size.
2186     break;
2187
2188   case 64: {
2189     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2190     uint64_t BitMask = 0xff;
2191     uint64_t Val = 0;
2192     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2193       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2194         Val |= BitMask;
2195       else if ((SplatBits & BitMask) != 0)
2196         return SDValue();
2197       BitMask <<= 8;
2198     }
2199     return DAG.getTargetConstant(Val, MVT::i64);
2200   }
2201
2202   default:
2203     llvm_unreachable("unexpected size for isVMOVSplat");
2204     break;
2205   }
2206
2207   return SDValue();
2208 }
2209
2210 /// getVMOVImm - If this is a build_vector of constants which can be
2211 /// formed by using a VMOV instruction of the specified element size,
2212 /// return the constant being splatted.  The ByteSize field indicates the
2213 /// number of bytes of each element [1248].
2214 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2215   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2216   APInt SplatBits, SplatUndef;
2217   unsigned SplatBitSize;
2218   bool HasAnyUndefs;
2219   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2220                                       HasAnyUndefs, ByteSize * 8))
2221     return SDValue();
2222
2223   if (SplatBitSize > ByteSize * 8)
2224     return SDValue();
2225
2226   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2227                      SplatBitSize, DAG);
2228 }
2229
2230 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2231 /// instruction with the specified blocksize.  (The order of the elements
2232 /// within each block of the vector is reversed.)
2233 bool ARM::isVREVMask(ShuffleVectorSDNode *N, unsigned BlockSize) {
2234   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2235          "Only possible block sizes for VREV are: 16, 32, 64");
2236
2237   MVT VT = N->getValueType(0);
2238   unsigned NumElts = VT.getVectorNumElements();
2239   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2240   unsigned BlockElts = N->getMaskElt(0) + 1;
2241
2242   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2243     return false;
2244
2245   for (unsigned i = 0; i < NumElts; ++i) {
2246     if ((unsigned) N->getMaskElt(i) !=
2247         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2248       return false;
2249   }
2250
2251   return true;
2252 }
2253
2254 static SDValue BuildSplat(SDValue Val, MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2255   // Canonicalize all-zeros and all-ones vectors.
2256   ConstantSDNode *ConstVal = dyn_cast<ConstantSDNode>(Val.getNode());
2257   if (ConstVal->isNullValue())
2258     return getZeroVector(VT, DAG, dl);
2259   if (ConstVal->isAllOnesValue())
2260     return getOnesVector(VT, DAG, dl);
2261
2262   MVT CanonicalVT;
2263   if (VT.is64BitVector()) {
2264     switch (Val.getValueType().getSizeInBits()) {
2265     case 8:  CanonicalVT = MVT::v8i8; break;
2266     case 16: CanonicalVT = MVT::v4i16; break;
2267     case 32: CanonicalVT = MVT::v2i32; break;
2268     case 64: CanonicalVT = MVT::v1i64; break;
2269     default: llvm_unreachable("unexpected splat element type"); break;
2270     }
2271   } else {
2272     assert(VT.is128BitVector() && "unknown splat vector size");
2273     switch (Val.getValueType().getSizeInBits()) {
2274     case 8:  CanonicalVT = MVT::v16i8; break;
2275     case 16: CanonicalVT = MVT::v8i16; break;
2276     case 32: CanonicalVT = MVT::v4i32; break;
2277     case 64: CanonicalVT = MVT::v2i64; break;
2278     default: llvm_unreachable("unexpected splat element type"); break;
2279     }
2280   }
2281
2282   // Build a canonical splat for this value.
2283   SmallVector<SDValue, 8> Ops;
2284   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2285   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2286                             Ops.size());
2287   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2288 }
2289
2290 // If this is a case we can't handle, return null and let the default
2291 // expansion code take care of it.
2292 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2293   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2294   assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
2295   DebugLoc dl = Op.getDebugLoc();
2296   MVT VT = Op.getValueType();
2297
2298   APInt SplatBits, SplatUndef;
2299   unsigned SplatBitSize;
2300   bool HasAnyUndefs;
2301   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2302     SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2303                               SplatUndef.getZExtValue(), SplatBitSize, DAG);
2304     if (Val.getNode())
2305       return BuildSplat(Val, VT, DAG, dl);
2306   }
2307
2308   // If there are only 2 elements in a 128-bit vector, insert them into an
2309   // undef vector.  This handles the common case for 128-bit vector argument
2310   // passing, where the insertions should be translated to subreg accesses
2311   // with no real instructions.
2312   if (VT.is128BitVector() && Op.getNumOperands() == 2) {
2313     SDValue Val = DAG.getUNDEF(VT);
2314     SDValue Op0 = Op.getOperand(0);
2315     SDValue Op1 = Op.getOperand(1);
2316     if (Op0.getOpcode() != ISD::UNDEF)
2317       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op0,
2318                         DAG.getIntPtrConstant(0));
2319     if (Op1.getOpcode() != ISD::UNDEF)
2320       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op1,
2321                         DAG.getIntPtrConstant(1));
2322     return Val;
2323   }
2324
2325   return SDValue();
2326 }
2327
2328 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2329   return Op;
2330 }
2331
2332 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
2333   return Op;
2334 }
2335
2336 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
2337   MVT VT = Op.getValueType();
2338   DebugLoc dl = Op.getDebugLoc();
2339   assert((VT == MVT::i8 || VT == MVT::i16) &&
2340          "unexpected type for custom-lowering vector extract");
2341   SDValue Vec = Op.getOperand(0);
2342   SDValue Lane = Op.getOperand(1);
2343   Op = DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
2344   Op = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Op, DAG.getValueType(VT));
2345   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
2346 }
2347
2348 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
2349   // The only time a CONCAT_VECTORS operation can have legal types is when
2350   // two 64-bit vectors are concatenated to a 128-bit vector.
2351   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
2352          "unexpected CONCAT_VECTORS");
2353   DebugLoc dl = Op.getDebugLoc();
2354   SDValue Val = DAG.getUNDEF(MVT::v2f64);
2355   SDValue Op0 = Op.getOperand(0);
2356   SDValue Op1 = Op.getOperand(1);
2357   if (Op0.getOpcode() != ISD::UNDEF)
2358     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2359                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
2360                       DAG.getIntPtrConstant(0));
2361   if (Op1.getOpcode() != ISD::UNDEF)
2362     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2363                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
2364                       DAG.getIntPtrConstant(1));
2365   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
2366 }
2367
2368 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
2369   switch (Op.getOpcode()) {
2370   default: llvm_unreachable("Don't know how to custom lower this!");
2371   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
2372   case ISD::GlobalAddress:
2373     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
2374       LowerGlobalAddressELF(Op, DAG);
2375   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2376   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
2377   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
2378   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
2379   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
2380   case ISD::SINT_TO_FP:
2381   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
2382   case ISD::FP_TO_SINT:
2383   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
2384   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
2385   case ISD::RETURNADDR:    break;
2386   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2387   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2388   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2389   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2390   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
2391   case ISD::SHL:
2392   case ISD::SRL:
2393   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
2394   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
2395   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
2396   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2397   case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
2398   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2399   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
2400   }
2401   return SDValue();
2402 }
2403
2404 /// ReplaceNodeResults - Replace the results of node with an illegal result
2405 /// type with new values built out of custom code.
2406 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
2407                                            SmallVectorImpl<SDValue>&Results,
2408                                            SelectionDAG &DAG) {
2409   switch (N->getOpcode()) {
2410   default:
2411     llvm_unreachable("Don't know how to custom expand this!");
2412     return;
2413   case ISD::BIT_CONVERT:
2414     Results.push_back(ExpandBIT_CONVERT(N, DAG));
2415     return;
2416   case ISD::SRL:
2417   case ISD::SRA: {
2418     SDValue Res = LowerShift(N, DAG, Subtarget);
2419     if (Res.getNode())
2420       Results.push_back(Res);
2421     return;
2422   }
2423   }
2424 }
2425
2426 //===----------------------------------------------------------------------===//
2427 //                           ARM Scheduler Hooks
2428 //===----------------------------------------------------------------------===//
2429
2430 MachineBasicBlock *
2431 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2432                                                MachineBasicBlock *BB) const {
2433   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2434   DebugLoc dl = MI->getDebugLoc();
2435   switch (MI->getOpcode()) {
2436   default: assert(false && "Unexpected instr type to insert");
2437   case ARM::tMOVCCr: {
2438     // To "insert" a SELECT_CC instruction, we actually have to insert the
2439     // diamond control-flow pattern.  The incoming instruction knows the
2440     // destination vreg to set, the condition code register to branch on, the
2441     // true/false values to select between, and a branch opcode to use.
2442     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2443     MachineFunction::iterator It = BB;
2444     ++It;
2445
2446     //  thisMBB:
2447     //  ...
2448     //   TrueVal = ...
2449     //   cmpTY ccX, r1, r2
2450     //   bCC copy1MBB
2451     //   fallthrough --> copy0MBB
2452     MachineBasicBlock *thisMBB  = BB;
2453     MachineFunction *F = BB->getParent();
2454     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2455     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
2456     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
2457       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
2458     F->insert(It, copy0MBB);
2459     F->insert(It, sinkMBB);
2460     // Update machine-CFG edges by first adding all successors of the current
2461     // block to the new block which will contain the Phi node for the select.
2462     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
2463         e = BB->succ_end(); i != e; ++i)
2464       sinkMBB->addSuccessor(*i);
2465     // Next, remove all successors of the current block, and add the true
2466     // and fallthrough blocks as its successors.
2467     while(!BB->succ_empty())
2468       BB->removeSuccessor(BB->succ_begin());
2469     BB->addSuccessor(copy0MBB);
2470     BB->addSuccessor(sinkMBB);
2471
2472     //  copy0MBB:
2473     //   %FalseValue = ...
2474     //   # fallthrough to sinkMBB
2475     BB = copy0MBB;
2476
2477     // Update machine-CFG edges
2478     BB->addSuccessor(sinkMBB);
2479
2480     //  sinkMBB:
2481     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2482     //  ...
2483     BB = sinkMBB;
2484     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
2485       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
2486       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
2487
2488     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2489     return BB;
2490   }
2491   }
2492 }
2493
2494 //===----------------------------------------------------------------------===//
2495 //                           ARM Optimization Hooks
2496 //===----------------------------------------------------------------------===//
2497
2498 static
2499 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
2500                             TargetLowering::DAGCombinerInfo &DCI) {
2501   SelectionDAG &DAG = DCI.DAG;
2502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2503   MVT VT = N->getValueType(0);
2504   unsigned Opc = N->getOpcode();
2505   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
2506   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
2507   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
2508   ISD::CondCode CC = ISD::SETCC_INVALID;
2509
2510   if (isSlctCC) {
2511     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
2512   } else {
2513     SDValue CCOp = Slct.getOperand(0);
2514     if (CCOp.getOpcode() == ISD::SETCC)
2515       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
2516   }
2517
2518   bool DoXform = false;
2519   bool InvCC = false;
2520   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
2521           "Bad input!");
2522
2523   if (LHS.getOpcode() == ISD::Constant &&
2524       cast<ConstantSDNode>(LHS)->isNullValue()) {
2525     DoXform = true;
2526   } else if (CC != ISD::SETCC_INVALID &&
2527              RHS.getOpcode() == ISD::Constant &&
2528              cast<ConstantSDNode>(RHS)->isNullValue()) {
2529     std::swap(LHS, RHS);
2530     SDValue Op0 = Slct.getOperand(0);
2531     MVT OpVT = isSlctCC ? Op0.getValueType() :
2532                           Op0.getOperand(0).getValueType();
2533     bool isInt = OpVT.isInteger();
2534     CC = ISD::getSetCCInverse(CC, isInt);
2535
2536     if (!TLI.isCondCodeLegal(CC, OpVT))
2537       return SDValue();         // Inverse operator isn't legal.
2538
2539     DoXform = true;
2540     InvCC = true;
2541   }
2542
2543   if (DoXform) {
2544     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
2545     if (isSlctCC)
2546       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
2547                              Slct.getOperand(0), Slct.getOperand(1), CC);
2548     SDValue CCOp = Slct.getOperand(0);
2549     if (InvCC)
2550       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
2551                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
2552     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
2553                        CCOp, OtherOp, Result);
2554   }
2555   return SDValue();
2556 }
2557
2558 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
2559 static SDValue PerformADDCombine(SDNode *N,
2560                                  TargetLowering::DAGCombinerInfo &DCI) {
2561   // added by evan in r37685 with no testcase.
2562   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2563
2564   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
2565   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
2566     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
2567     if (Result.getNode()) return Result;
2568   }
2569   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2570     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2571     if (Result.getNode()) return Result;
2572   }
2573
2574   return SDValue();
2575 }
2576
2577 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
2578 static SDValue PerformSUBCombine(SDNode *N,
2579                                  TargetLowering::DAGCombinerInfo &DCI) {
2580   // added by evan in r37685 with no testcase.
2581   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2582
2583   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
2584   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2585     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2586     if (Result.getNode()) return Result;
2587   }
2588
2589   return SDValue();
2590 }
2591
2592
2593 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
2594 static SDValue PerformFMRRDCombine(SDNode *N,
2595                                    TargetLowering::DAGCombinerInfo &DCI) {
2596   // fmrrd(fmdrr x, y) -> x,y
2597   SDValue InDouble = N->getOperand(0);
2598   if (InDouble.getOpcode() == ARMISD::FMDRR)
2599     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
2600   return SDValue();
2601 }
2602
2603 /// getVShiftImm - Check if this is a valid build_vector for the immediate
2604 /// operand of a vector shift operation, where all the elements of the
2605 /// build_vector must have the same constant integer value.
2606 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
2607   // Ignore bit_converts.
2608   while (Op.getOpcode() == ISD::BIT_CONVERT)
2609     Op = Op.getOperand(0);
2610   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2611   APInt SplatBits, SplatUndef;
2612   unsigned SplatBitSize;
2613   bool HasAnyUndefs;
2614   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2615                                       HasAnyUndefs, ElementBits) ||
2616       SplatBitSize > ElementBits)
2617     return false;
2618   Cnt = SplatBits.getSExtValue();
2619   return true;
2620 }
2621
2622 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
2623 /// operand of a vector shift left operation.  That value must be in the range:
2624 ///   0 <= Value < ElementBits for a left shift; or
2625 ///   0 <= Value <= ElementBits for a long left shift.
2626 static bool isVShiftLImm(SDValue Op, MVT VT, bool isLong, int64_t &Cnt) {
2627   assert(VT.isVector() && "vector shift count is not a vector type");
2628   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2629   if (! getVShiftImm(Op, ElementBits, Cnt))
2630     return false;
2631   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
2632 }
2633
2634 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
2635 /// operand of a vector shift right operation.  For a shift opcode, the value
2636 /// is positive, but for an intrinsic the value count must be negative. The
2637 /// absolute value must be in the range:
2638 ///   1 <= |Value| <= ElementBits for a right shift; or
2639 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
2640 static bool isVShiftRImm(SDValue Op, MVT VT, bool isNarrow, bool isIntrinsic,
2641                          int64_t &Cnt) {
2642   assert(VT.isVector() && "vector shift count is not a vector type");
2643   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2644   if (! getVShiftImm(Op, ElementBits, Cnt))
2645     return false;
2646   if (isIntrinsic)
2647     Cnt = -Cnt;
2648   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
2649 }
2650
2651 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
2652 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
2653   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2654   switch (IntNo) {
2655   default:
2656     // Don't do anything for most intrinsics.
2657     break;
2658
2659   // Vector shifts: check for immediate versions and lower them.
2660   // Note: This is done during DAG combining instead of DAG legalizing because
2661   // the build_vectors for 64-bit vector element shift counts are generally
2662   // not legal, and it is hard to see their values after they get legalized to
2663   // loads from a constant pool.
2664   case Intrinsic::arm_neon_vshifts:
2665   case Intrinsic::arm_neon_vshiftu:
2666   case Intrinsic::arm_neon_vshiftls:
2667   case Intrinsic::arm_neon_vshiftlu:
2668   case Intrinsic::arm_neon_vshiftn:
2669   case Intrinsic::arm_neon_vrshifts:
2670   case Intrinsic::arm_neon_vrshiftu:
2671   case Intrinsic::arm_neon_vrshiftn:
2672   case Intrinsic::arm_neon_vqshifts:
2673   case Intrinsic::arm_neon_vqshiftu:
2674   case Intrinsic::arm_neon_vqshiftsu:
2675   case Intrinsic::arm_neon_vqshiftns:
2676   case Intrinsic::arm_neon_vqshiftnu:
2677   case Intrinsic::arm_neon_vqshiftnsu:
2678   case Intrinsic::arm_neon_vqrshiftns:
2679   case Intrinsic::arm_neon_vqrshiftnu:
2680   case Intrinsic::arm_neon_vqrshiftnsu: {
2681     MVT VT = N->getOperand(1).getValueType();
2682     int64_t Cnt;
2683     unsigned VShiftOpc = 0;
2684
2685     switch (IntNo) {
2686     case Intrinsic::arm_neon_vshifts:
2687     case Intrinsic::arm_neon_vshiftu:
2688       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
2689         VShiftOpc = ARMISD::VSHL;
2690         break;
2691       }
2692       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
2693         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
2694                      ARMISD::VSHRs : ARMISD::VSHRu);
2695         break;
2696       }
2697       return SDValue();
2698
2699     case Intrinsic::arm_neon_vshiftls:
2700     case Intrinsic::arm_neon_vshiftlu:
2701       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
2702         break;
2703       llvm_unreachable("invalid shift count for vshll intrinsic");
2704
2705     case Intrinsic::arm_neon_vrshifts:
2706     case Intrinsic::arm_neon_vrshiftu:
2707       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
2708         break;
2709       return SDValue();
2710
2711     case Intrinsic::arm_neon_vqshifts:
2712     case Intrinsic::arm_neon_vqshiftu:
2713       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2714         break;
2715       return SDValue();
2716
2717     case Intrinsic::arm_neon_vqshiftsu:
2718       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2719         break;
2720       llvm_unreachable("invalid shift count for vqshlu intrinsic");
2721
2722     case Intrinsic::arm_neon_vshiftn:
2723     case Intrinsic::arm_neon_vrshiftn:
2724     case Intrinsic::arm_neon_vqshiftns:
2725     case Intrinsic::arm_neon_vqshiftnu:
2726     case Intrinsic::arm_neon_vqshiftnsu:
2727     case Intrinsic::arm_neon_vqrshiftns:
2728     case Intrinsic::arm_neon_vqrshiftnu:
2729     case Intrinsic::arm_neon_vqrshiftnsu:
2730       // Narrowing shifts require an immediate right shift.
2731       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
2732         break;
2733       llvm_unreachable("invalid shift count for narrowing vector shift intrinsic");
2734
2735     default:
2736       llvm_unreachable("unhandled vector shift");
2737     }
2738
2739     switch (IntNo) {
2740     case Intrinsic::arm_neon_vshifts:
2741     case Intrinsic::arm_neon_vshiftu:
2742       // Opcode already set above.
2743       break;
2744     case Intrinsic::arm_neon_vshiftls:
2745     case Intrinsic::arm_neon_vshiftlu:
2746       if (Cnt == VT.getVectorElementType().getSizeInBits())
2747         VShiftOpc = ARMISD::VSHLLi;
2748       else
2749         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
2750                      ARMISD::VSHLLs : ARMISD::VSHLLu);
2751       break;
2752     case Intrinsic::arm_neon_vshiftn:
2753       VShiftOpc = ARMISD::VSHRN; break;
2754     case Intrinsic::arm_neon_vrshifts:
2755       VShiftOpc = ARMISD::VRSHRs; break;
2756     case Intrinsic::arm_neon_vrshiftu:
2757       VShiftOpc = ARMISD::VRSHRu; break;
2758     case Intrinsic::arm_neon_vrshiftn:
2759       VShiftOpc = ARMISD::VRSHRN; break;
2760     case Intrinsic::arm_neon_vqshifts:
2761       VShiftOpc = ARMISD::VQSHLs; break;
2762     case Intrinsic::arm_neon_vqshiftu:
2763       VShiftOpc = ARMISD::VQSHLu; break;
2764     case Intrinsic::arm_neon_vqshiftsu:
2765       VShiftOpc = ARMISD::VQSHLsu; break;
2766     case Intrinsic::arm_neon_vqshiftns:
2767       VShiftOpc = ARMISD::VQSHRNs; break;
2768     case Intrinsic::arm_neon_vqshiftnu:
2769       VShiftOpc = ARMISD::VQSHRNu; break;
2770     case Intrinsic::arm_neon_vqshiftnsu:
2771       VShiftOpc = ARMISD::VQSHRNsu; break;
2772     case Intrinsic::arm_neon_vqrshiftns:
2773       VShiftOpc = ARMISD::VQRSHRNs; break;
2774     case Intrinsic::arm_neon_vqrshiftnu:
2775       VShiftOpc = ARMISD::VQRSHRNu; break;
2776     case Intrinsic::arm_neon_vqrshiftnsu:
2777       VShiftOpc = ARMISD::VQRSHRNsu; break;
2778     }
2779
2780     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2781                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
2782   }
2783
2784   case Intrinsic::arm_neon_vshiftins: {
2785     MVT VT = N->getOperand(1).getValueType();
2786     int64_t Cnt;
2787     unsigned VShiftOpc = 0;
2788
2789     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
2790       VShiftOpc = ARMISD::VSLI;
2791     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
2792       VShiftOpc = ARMISD::VSRI;
2793     else {
2794       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
2795     }
2796
2797     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2798                        N->getOperand(1), N->getOperand(2),
2799                        DAG.getConstant(Cnt, MVT::i32));
2800   }
2801
2802   case Intrinsic::arm_neon_vqrshifts:
2803   case Intrinsic::arm_neon_vqrshiftu:
2804     // No immediate versions of these to check for.
2805     break;
2806   }
2807
2808   return SDValue();
2809 }
2810
2811 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
2812 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
2813 /// combining instead of DAG legalizing because the build_vectors for 64-bit
2814 /// vector element shift counts are generally not legal, and it is hard to see
2815 /// their values after they get legalized to loads from a constant pool.
2816 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
2817                                    const ARMSubtarget *ST) {
2818   MVT VT = N->getValueType(0);
2819
2820   // Nothing to be done for scalar shifts.
2821   if (! VT.isVector())
2822     return SDValue();
2823
2824   assert(ST->hasNEON() && "unexpected vector shift");
2825   int64_t Cnt;
2826
2827   switch (N->getOpcode()) {
2828   default: llvm_unreachable("unexpected shift opcode");
2829
2830   case ISD::SHL:
2831     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
2832       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
2833                          DAG.getConstant(Cnt, MVT::i32));
2834     break;
2835
2836   case ISD::SRA:
2837   case ISD::SRL:
2838     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
2839       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
2840                             ARMISD::VSHRs : ARMISD::VSHRu);
2841       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
2842                          DAG.getConstant(Cnt, MVT::i32));
2843     }
2844   }
2845   return SDValue();
2846 }
2847
2848 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
2849 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
2850 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
2851                                     const ARMSubtarget *ST) {
2852   SDValue N0 = N->getOperand(0);
2853
2854   // Check for sign- and zero-extensions of vector extract operations of 8-
2855   // and 16-bit vector elements.  NEON supports these directly.  They are
2856   // handled during DAG combining because type legalization will promote them
2857   // to 32-bit types and it is messy to recognize the operations after that.
2858   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2859     SDValue Vec = N0.getOperand(0);
2860     SDValue Lane = N0.getOperand(1);
2861     MVT VT = N->getValueType(0);
2862     MVT EltVT = N0.getValueType();
2863     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2864
2865     if (VT == MVT::i32 &&
2866         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
2867         TLI.isTypeLegal(Vec.getValueType())) {
2868
2869       unsigned Opc = 0;
2870       switch (N->getOpcode()) {
2871       default: llvm_unreachable("unexpected opcode");
2872       case ISD::SIGN_EXTEND:
2873         Opc = ARMISD::VGETLANEs;
2874         break;
2875       case ISD::ZERO_EXTEND:
2876       case ISD::ANY_EXTEND:
2877         Opc = ARMISD::VGETLANEu;
2878         break;
2879       }
2880       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
2881     }
2882   }
2883
2884   return SDValue();
2885 }
2886
2887 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
2888                                              DAGCombinerInfo &DCI) const {
2889   switch (N->getOpcode()) {
2890   default: break;
2891   case ISD::ADD:      return PerformADDCombine(N, DCI);
2892   case ISD::SUB:      return PerformSUBCombine(N, DCI);
2893   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
2894   case ISD::INTRINSIC_WO_CHAIN:
2895     return PerformIntrinsicCombine(N, DCI.DAG);
2896   case ISD::SHL:
2897   case ISD::SRA:
2898   case ISD::SRL:
2899     return PerformShiftCombine(N, DCI.DAG, Subtarget);
2900   case ISD::SIGN_EXTEND:
2901   case ISD::ZERO_EXTEND:
2902   case ISD::ANY_EXTEND:
2903     return PerformExtendCombine(N, DCI.DAG, Subtarget);
2904   }
2905   return SDValue();
2906 }
2907
2908 /// isLegalAddressImmediate - Return true if the integer value can be used
2909 /// as the offset of the target addressing mode for load / store of the
2910 /// given type.
2911 static bool isLegalAddressImmediate(int64_t V, MVT VT,
2912                                     const ARMSubtarget *Subtarget) {
2913   if (V == 0)
2914     return true;
2915
2916   if (!VT.isSimple())
2917     return false;
2918
2919   if (Subtarget->isThumb()) { // FIXME for thumb2
2920     if (V < 0)
2921       return false;
2922
2923     unsigned Scale = 1;
2924     switch (VT.getSimpleVT()) {
2925     default: return false;
2926     case MVT::i1:
2927     case MVT::i8:
2928       // Scale == 1;
2929       break;
2930     case MVT::i16:
2931       // Scale == 2;
2932       Scale = 2;
2933       break;
2934     case MVT::i32:
2935       // Scale == 4;
2936       Scale = 4;
2937       break;
2938     }
2939
2940     if ((V & (Scale - 1)) != 0)
2941       return false;
2942     V /= Scale;
2943     return V == (V & ((1LL << 5) - 1));
2944   }
2945
2946   if (V < 0)
2947     V = - V;
2948   switch (VT.getSimpleVT()) {
2949   default: return false;
2950   case MVT::i1:
2951   case MVT::i8:
2952   case MVT::i32:
2953     // +- imm12
2954     return V == (V & ((1LL << 12) - 1));
2955   case MVT::i16:
2956     // +- imm8
2957     return V == (V & ((1LL << 8) - 1));
2958   case MVT::f32:
2959   case MVT::f64:
2960     if (!Subtarget->hasVFP2())
2961       return false;
2962     if ((V & 3) != 0)
2963       return false;
2964     V >>= 2;
2965     return V == (V & ((1LL << 8) - 1));
2966   }
2967 }
2968
2969 /// isLegalAddressingMode - Return true if the addressing mode represented
2970 /// by AM is legal for this target, for a load/store of the specified type.
2971 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
2972                                               const Type *Ty) const {
2973   MVT VT = getValueType(Ty, true);
2974   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
2975     return false;
2976
2977   // Can never fold addr of global into load/store.
2978   if (AM.BaseGV)
2979     return false;
2980
2981   switch (AM.Scale) {
2982   case 0:  // no scale reg, must be "r+i" or "r", or "i".
2983     break;
2984   case 1:
2985     if (Subtarget->isThumb())  // FIXME for thumb2
2986       return false;
2987     // FALL THROUGH.
2988   default:
2989     // ARM doesn't support any R+R*scale+imm addr modes.
2990     if (AM.BaseOffs)
2991       return false;
2992
2993     if (!VT.isSimple())
2994       return false;
2995
2996     int Scale = AM.Scale;
2997     switch (VT.getSimpleVT()) {
2998     default: return false;
2999     case MVT::i1:
3000     case MVT::i8:
3001     case MVT::i32:
3002     case MVT::i64:
3003       // This assumes i64 is legalized to a pair of i32. If not (i.e.
3004       // ldrd / strd are used, then its address mode is same as i16.
3005       // r + r
3006       if (Scale < 0) Scale = -Scale;
3007       if (Scale == 1)
3008         return true;
3009       // r + r << imm
3010       return isPowerOf2_32(Scale & ~1);
3011     case MVT::i16:
3012       // r + r
3013       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3014         return true;
3015       return false;
3016
3017     case MVT::isVoid:
3018       // Note, we allow "void" uses (basically, uses that aren't loads or
3019       // stores), because arm allows folding a scale into many arithmetic
3020       // operations.  This should be made more precise and revisited later.
3021
3022       // Allow r << imm, but the imm has to be a multiple of two.
3023       if (AM.Scale & 1) return false;
3024       return isPowerOf2_32(AM.Scale);
3025     }
3026     break;
3027   }
3028   return true;
3029 }
3030
3031 static bool getARMIndexedAddressParts(SDNode *Ptr, MVT VT,
3032                                       bool isSEXTLoad, SDValue &Base,
3033                                       SDValue &Offset, bool &isInc,
3034                                       SelectionDAG &DAG) {
3035   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3036     return false;
3037
3038   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
3039     // AddressingMode 3
3040     Base = Ptr->getOperand(0);
3041     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3042       int RHSC = (int)RHS->getZExtValue();
3043       if (RHSC < 0 && RHSC > -256) {
3044         assert(Ptr->getOpcode() == ISD::ADD);
3045         isInc = false;
3046         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3047         return true;
3048       }
3049     }
3050     isInc = (Ptr->getOpcode() == ISD::ADD);
3051     Offset = Ptr->getOperand(1);
3052     return true;
3053   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
3054     // AddressingMode 2
3055     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3056       int RHSC = (int)RHS->getZExtValue();
3057       if (RHSC < 0 && RHSC > -0x1000) {
3058         assert(Ptr->getOpcode() == ISD::ADD);
3059         isInc = false;
3060         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3061         Base = Ptr->getOperand(0);
3062         return true;
3063       }
3064     }
3065
3066     if (Ptr->getOpcode() == ISD::ADD) {
3067       isInc = true;
3068       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
3069       if (ShOpcVal != ARM_AM::no_shift) {
3070         Base = Ptr->getOperand(1);
3071         Offset = Ptr->getOperand(0);
3072       } else {
3073         Base = Ptr->getOperand(0);
3074         Offset = Ptr->getOperand(1);
3075       }
3076       return true;
3077     }
3078
3079     isInc = (Ptr->getOpcode() == ISD::ADD);
3080     Base = Ptr->getOperand(0);
3081     Offset = Ptr->getOperand(1);
3082     return true;
3083   }
3084
3085   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
3086   return false;
3087 }
3088
3089 static bool getT2IndexedAddressParts(SDNode *Ptr, MVT VT,
3090                                      bool isSEXTLoad, SDValue &Base,
3091                                      SDValue &Offset, bool &isInc,
3092                                      SelectionDAG &DAG) {
3093   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3094     return false;
3095
3096   Base = Ptr->getOperand(0);
3097   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3098     int RHSC = (int)RHS->getZExtValue();
3099     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
3100       assert(Ptr->getOpcode() == ISD::ADD);
3101       isInc = false;
3102       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3103       return true;
3104     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
3105       isInc = Ptr->getOpcode() == ISD::ADD;
3106       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
3107       return true;
3108     }
3109   }
3110
3111   return false;
3112 }
3113
3114 /// getPreIndexedAddressParts - returns true by value, base pointer and
3115 /// offset pointer and addressing mode by reference if the node's address
3116 /// can be legally represented as pre-indexed load / store address.
3117 bool
3118 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3119                                              SDValue &Offset,
3120                                              ISD::MemIndexedMode &AM,
3121                                              SelectionDAG &DAG) const {
3122   if (Subtarget->isThumb1Only())
3123     return false;
3124
3125   MVT VT;
3126   SDValue Ptr;
3127   bool isSEXTLoad = false;
3128   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3129     Ptr = LD->getBasePtr();
3130     VT  = LD->getMemoryVT();
3131     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3132   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3133     Ptr = ST->getBasePtr();
3134     VT  = ST->getMemoryVT();
3135   } else
3136     return false;
3137
3138   bool isInc;
3139   bool isLegal = false;
3140   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3141     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3142                                        Offset, isInc, DAG);
3143   else 
3144     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3145                                         Offset, isInc, DAG);
3146   if (!isLegal)
3147     return false;
3148
3149   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
3150   return true;
3151 }
3152
3153 /// getPostIndexedAddressParts - returns true by value, base pointer and
3154 /// offset pointer and addressing mode by reference if this node can be
3155 /// combined with a load / store to form a post-indexed load / store.
3156 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
3157                                                    SDValue &Base,
3158                                                    SDValue &Offset,
3159                                                    ISD::MemIndexedMode &AM,
3160                                                    SelectionDAG &DAG) const {
3161   if (Subtarget->isThumb1Only())
3162     return false;
3163
3164   MVT VT;
3165   SDValue Ptr;
3166   bool isSEXTLoad = false;
3167   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3168     VT  = LD->getMemoryVT();
3169     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3170   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3171     VT  = ST->getMemoryVT();
3172   } else
3173     return false;
3174
3175   bool isInc;
3176   bool isLegal = false;
3177   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3178     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3179                                         isInc, DAG);
3180   else 
3181     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3182                                         isInc, DAG);
3183   if (!isLegal)
3184     return false;
3185
3186   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
3187   return true;
3188 }
3189
3190 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
3191                                                        const APInt &Mask,
3192                                                        APInt &KnownZero,
3193                                                        APInt &KnownOne,
3194                                                        const SelectionDAG &DAG,
3195                                                        unsigned Depth) const {
3196   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3197   switch (Op.getOpcode()) {
3198   default: break;
3199   case ARMISD::CMOV: {
3200     // Bits are known zero/one if known on the LHS and RHS.
3201     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
3202     if (KnownZero == 0 && KnownOne == 0) return;
3203
3204     APInt KnownZeroRHS, KnownOneRHS;
3205     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
3206                           KnownZeroRHS, KnownOneRHS, Depth+1);
3207     KnownZero &= KnownZeroRHS;
3208     KnownOne  &= KnownOneRHS;
3209     return;
3210   }
3211   }
3212 }
3213
3214 //===----------------------------------------------------------------------===//
3215 //                           ARM Inline Assembly Support
3216 //===----------------------------------------------------------------------===//
3217
3218 /// getConstraintType - Given a constraint letter, return the type of
3219 /// constraint it is for this target.
3220 ARMTargetLowering::ConstraintType
3221 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
3222   if (Constraint.size() == 1) {
3223     switch (Constraint[0]) {
3224     default:  break;
3225     case 'l': return C_RegisterClass;
3226     case 'w': return C_RegisterClass;
3227     }
3228   }
3229   return TargetLowering::getConstraintType(Constraint);
3230 }
3231
3232 std::pair<unsigned, const TargetRegisterClass*>
3233 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3234                                                 MVT VT) const {
3235   if (Constraint.size() == 1) {
3236     // GCC RS6000 Constraint Letters
3237     switch (Constraint[0]) {
3238     case 'l':
3239       if (Subtarget->isThumb1Only())
3240         return std::make_pair(0U, ARM::tGPRRegisterClass);
3241       else
3242         return std::make_pair(0U, ARM::GPRRegisterClass);
3243     case 'r':
3244       return std::make_pair(0U, ARM::GPRRegisterClass);
3245     case 'w':
3246       if (VT == MVT::f32)
3247         return std::make_pair(0U, ARM::SPRRegisterClass);
3248       if (VT == MVT::f64)
3249         return std::make_pair(0U, ARM::DPRRegisterClass);
3250       break;
3251     }
3252   }
3253   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3254 }
3255
3256 std::vector<unsigned> ARMTargetLowering::
3257 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3258                                   MVT VT) const {
3259   if (Constraint.size() != 1)
3260     return std::vector<unsigned>();
3261
3262   switch (Constraint[0]) {      // GCC ARM Constraint Letters
3263   default: break;
3264   case 'l':
3265     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3266                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3267                                  0);
3268   case 'r':
3269     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3270                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3271                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
3272                                  ARM::R12, ARM::LR, 0);
3273   case 'w':
3274     if (VT == MVT::f32)
3275       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
3276                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
3277                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
3278                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
3279                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
3280                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
3281                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
3282                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
3283     if (VT == MVT::f64)
3284       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
3285                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
3286                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
3287                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
3288       break;
3289   }
3290
3291   return std::vector<unsigned>();
3292 }
3293
3294 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3295 /// vector.  If it is invalid, don't add anything to Ops.
3296 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3297                                                      char Constraint,
3298                                                      bool hasMemory,
3299                                                      std::vector<SDValue>&Ops,
3300                                                      SelectionDAG &DAG) const {
3301   SDValue Result(0, 0);
3302
3303   switch (Constraint) {
3304   default: break;
3305   case 'I': case 'J': case 'K': case 'L':
3306   case 'M': case 'N': case 'O':
3307     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3308     if (!C)
3309       return;
3310
3311     int64_t CVal64 = C->getSExtValue();
3312     int CVal = (int) CVal64;
3313     // None of these constraints allow values larger than 32 bits.  Check
3314     // that the value fits in an int.
3315     if (CVal != CVal64)
3316       return;
3317
3318     switch (Constraint) {
3319       case 'I':
3320         if (Subtarget->isThumb1Only()) {
3321           // This must be a constant between 0 and 255, for ADD
3322           // immediates.
3323           if (CVal >= 0 && CVal <= 255)
3324             break;
3325         } else if (Subtarget->isThumb2()) {
3326           // A constant that can be used as an immediate value in a
3327           // data-processing instruction.
3328           if (ARM_AM::getT2SOImmVal(CVal) != -1)
3329             break;
3330         } else {
3331           // A constant that can be used as an immediate value in a
3332           // data-processing instruction.
3333           if (ARM_AM::getSOImmVal(CVal) != -1)
3334             break;
3335         }
3336         return;
3337
3338       case 'J':
3339         if (Subtarget->isThumb()) {  // FIXME thumb2
3340           // This must be a constant between -255 and -1, for negated ADD
3341           // immediates. This can be used in GCC with an "n" modifier that
3342           // prints the negated value, for use with SUB instructions. It is
3343           // not useful otherwise but is implemented for compatibility.
3344           if (CVal >= -255 && CVal <= -1)
3345             break;
3346         } else {
3347           // This must be a constant between -4095 and 4095. It is not clear
3348           // what this constraint is intended for. Implemented for
3349           // compatibility with GCC.
3350           if (CVal >= -4095 && CVal <= 4095)
3351             break;
3352         }
3353         return;
3354
3355       case 'K':
3356         if (Subtarget->isThumb1Only()) {
3357           // A 32-bit value where only one byte has a nonzero value. Exclude
3358           // zero to match GCC. This constraint is used by GCC internally for
3359           // constants that can be loaded with a move/shift combination.
3360           // It is not useful otherwise but is implemented for compatibility.
3361           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
3362             break;
3363         } else if (Subtarget->isThumb2()) {
3364           // A constant whose bitwise inverse can be used as an immediate
3365           // value in a data-processing instruction. This can be used in GCC
3366           // with a "B" modifier that prints the inverted value, for use with
3367           // BIC and MVN instructions. It is not useful otherwise but is
3368           // implemented for compatibility.
3369           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
3370             break;
3371         } else {
3372           // A constant whose bitwise inverse can be used as an immediate
3373           // value in a data-processing instruction. This can be used in GCC
3374           // with a "B" modifier that prints the inverted value, for use with
3375           // BIC and MVN instructions. It is not useful otherwise but is
3376           // implemented for compatibility.
3377           if (ARM_AM::getSOImmVal(~CVal) != -1)
3378             break;
3379         }
3380         return;
3381
3382       case 'L':
3383         if (Subtarget->isThumb1Only()) {
3384           // This must be a constant between -7 and 7,
3385           // for 3-operand ADD/SUB immediate instructions.
3386           if (CVal >= -7 && CVal < 7)
3387             break;
3388         } else if (Subtarget->isThumb2()) {
3389           // A constant whose negation can be used as an immediate value in a
3390           // data-processing instruction. This can be used in GCC with an "n"
3391           // modifier that prints the negated value, for use with SUB
3392           // instructions. It is not useful otherwise but is implemented for
3393           // compatibility.
3394           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
3395             break;
3396         } else {
3397           // A constant whose negation can be used as an immediate value in a
3398           // data-processing instruction. This can be used in GCC with an "n"
3399           // modifier that prints the negated value, for use with SUB
3400           // instructions. It is not useful otherwise but is implemented for
3401           // compatibility.
3402           if (ARM_AM::getSOImmVal(-CVal) != -1)
3403             break;
3404         }
3405         return;
3406
3407       case 'M':
3408         if (Subtarget->isThumb()) { // FIXME thumb2
3409           // This must be a multiple of 4 between 0 and 1020, for
3410           // ADD sp + immediate.
3411           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
3412             break;
3413         } else {
3414           // A power of two or a constant between 0 and 32.  This is used in
3415           // GCC for the shift amount on shifted register operands, but it is
3416           // useful in general for any shift amounts.
3417           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
3418             break;
3419         }
3420         return;
3421
3422       case 'N':
3423         if (Subtarget->isThumb()) {  // FIXME thumb2
3424           // This must be a constant between 0 and 31, for shift amounts.
3425           if (CVal >= 0 && CVal <= 31)
3426             break;
3427         }
3428         return;
3429
3430       case 'O':
3431         if (Subtarget->isThumb()) {  // FIXME thumb2
3432           // This must be a multiple of 4 between -508 and 508, for
3433           // ADD/SUB sp = sp + immediate.
3434           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
3435             break;
3436         }
3437         return;
3438     }
3439     Result = DAG.getTargetConstant(CVal, Op.getValueType());
3440     break;
3441   }
3442
3443   if (Result.getNode()) {
3444     Ops.push_back(Result);
3445     return;
3446   }
3447   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
3448                                                       Ops, DAG);
3449 }