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