Don't flush the raw_ostream between each MachineFunction. These flush
[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) {
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(2) };
1336   return DAG.getNode(Opcode, dl, Node->getVTList(), Ops, 2);
1337 }
1338
1339 SDValue
1340 ARMTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
1341   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1342   switch (IntNo) {
1343   case Intrinsic::arm_neon_vld2i:
1344   case Intrinsic::arm_neon_vld2f:
1345     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD2D);
1346   case Intrinsic::arm_neon_vld3i:
1347   case Intrinsic::arm_neon_vld3f:
1348     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD3D);
1349   case Intrinsic::arm_neon_vld4i:
1350   case Intrinsic::arm_neon_vld4f:
1351     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD4D);
1352   case Intrinsic::arm_neon_vst2i:
1353   case Intrinsic::arm_neon_vst2f:
1354   case Intrinsic::arm_neon_vst3i:
1355   case Intrinsic::arm_neon_vst3f:
1356   case Intrinsic::arm_neon_vst4i:
1357   case Intrinsic::arm_neon_vst4f:
1358   default: return SDValue();    // Don't custom lower most intrinsics.
1359   }
1360 }
1361
1362 SDValue
1363 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
1364   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1365   DebugLoc dl = Op.getDebugLoc();
1366   switch (IntNo) {
1367   default: return SDValue();    // Don't custom lower most intrinsics.
1368   case Intrinsic::arm_thread_pointer: {
1369     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1370     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1371   }
1372   case Intrinsic::eh_sjlj_setjmp:
1373     return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(1));
1374   }
1375 }
1376
1377 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1378                             unsigned VarArgsFrameIndex) {
1379   // vastart just stores the address of the VarArgsFrameIndex slot into the
1380   // memory location argument.
1381   DebugLoc dl = Op.getDebugLoc();
1382   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1383   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1384   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1385   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1386 }
1387
1388 SDValue
1389 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
1390                                         SDValue &Root, SelectionDAG &DAG,
1391                                         DebugLoc dl) {
1392   MachineFunction &MF = DAG.getMachineFunction();
1393   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1394
1395   TargetRegisterClass *RC;
1396   if (AFI->isThumb1OnlyFunction())
1397     RC = ARM::tGPRRegisterClass;
1398   else
1399     RC = ARM::GPRRegisterClass;
1400
1401   // Transform the arguments stored in physical registers into virtual ones.
1402   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1403   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1404
1405   SDValue ArgValue2;
1406   if (NextVA.isMemLoc()) {
1407     unsigned ArgSize = NextVA.getLocVT().getSizeInBits()/8;
1408     MachineFrameInfo *MFI = MF.getFrameInfo();
1409     int FI = MFI->CreateFixedObject(ArgSize, NextVA.getLocMemOffset());
1410
1411     // Create load node to retrieve arguments from the stack.
1412     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1413     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
1414   } else {
1415     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1416     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1417   }
1418
1419   return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
1420 }
1421
1422 SDValue
1423 ARMTargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1424   MachineFunction &MF = DAG.getMachineFunction();
1425   MachineFrameInfo *MFI = MF.getFrameInfo();
1426
1427   SDValue Root = Op.getOperand(0);
1428   DebugLoc dl = Op.getDebugLoc();
1429   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1430   unsigned CC = MF.getFunction()->getCallingConv();
1431   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1432
1433   // Assign locations to all of the incoming arguments.
1434   SmallVector<CCValAssign, 16> ArgLocs;
1435   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
1436   CCInfo.AnalyzeFormalArguments(Op.getNode(),
1437                                 CCAssignFnForNode(CC, /* Return*/ false));
1438
1439   SmallVector<SDValue, 16> ArgValues;
1440
1441   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1442     CCValAssign &VA = ArgLocs[i];
1443
1444     // Arguments stored in registers.
1445     if (VA.isRegLoc()) {
1446       MVT RegVT = VA.getLocVT();
1447
1448       SDValue ArgValue;
1449       if (VA.needsCustom()) {
1450         // f64 and vector types are split up into multiple registers or
1451         // combinations of registers and stack slots.
1452         RegVT = MVT::i32;
1453
1454         if (VA.getLocVT() == MVT::v2f64) {
1455           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
1456                                                    Root, DAG, dl);
1457           VA = ArgLocs[++i]; // skip ahead to next loc
1458           SDValue ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
1459                                                    Root, DAG, dl);
1460           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1461           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1462                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
1463           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1464                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
1465         } else
1466           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Root, DAG, dl);
1467
1468       } else {
1469         TargetRegisterClass *RC;
1470         if (FloatABIType == FloatABI::Hard && RegVT == MVT::f32)
1471           RC = ARM::SPRRegisterClass;
1472         else if (FloatABIType == FloatABI::Hard && RegVT == MVT::f64)
1473           RC = ARM::DPRRegisterClass;
1474         else if (AFI->isThumb1OnlyFunction())
1475           RC = ARM::tGPRRegisterClass;
1476         else
1477           RC = ARM::GPRRegisterClass;
1478
1479         assert((RegVT == MVT::i32 || RegVT == MVT::f32 ||
1480                 (FloatABIType == FloatABI::Hard && RegVT == MVT::f64)) &&
1481                "RegVT not supported by FORMAL_ARGUMENTS Lowering");
1482
1483         // Transform the arguments in physical registers into virtual ones.
1484         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1485         ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1486       }
1487
1488       // If this is an 8 or 16-bit value, it is really passed promoted
1489       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1490       // truncate to the right size.
1491       switch (VA.getLocInfo()) {
1492       default: llvm_unreachable("Unknown loc info!");
1493       case CCValAssign::Full: break;
1494       case CCValAssign::BCvt:
1495         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1496         break;
1497       case CCValAssign::SExt:
1498         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1499                                DAG.getValueType(VA.getValVT()));
1500         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1501         break;
1502       case CCValAssign::ZExt:
1503         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1504                                DAG.getValueType(VA.getValVT()));
1505         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1506         break;
1507       }
1508
1509       ArgValues.push_back(ArgValue);
1510
1511     } else { // VA.isRegLoc()
1512
1513       // sanity check
1514       assert(VA.isMemLoc());
1515       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1516
1517       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1518       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1519
1520       // Create load nodes to retrieve arguments from the stack.
1521       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1522       ArgValues.push_back(DAG.getLoad(VA.getValVT(), dl, Root, FIN, NULL, 0));
1523     }
1524   }
1525
1526   // varargs
1527   if (isVarArg) {
1528     static const unsigned GPRArgRegs[] = {
1529       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1530     };
1531
1532     unsigned NumGPRs = CCInfo.getFirstUnallocated
1533       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1534
1535     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1536     unsigned VARegSize = (4 - NumGPRs) * 4;
1537     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1538     unsigned ArgOffset = 0;
1539     if (VARegSaveSize) {
1540       // If this function is vararg, store any remaining integer argument regs
1541       // to their spots on the stack so that they may be loaded by deferencing
1542       // the result of va_next.
1543       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1544       ArgOffset = CCInfo.getNextStackOffset();
1545       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1546                                                  VARegSaveSize - VARegSize);
1547       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1548
1549       SmallVector<SDValue, 4> MemOps;
1550       for (; NumGPRs < 4; ++NumGPRs) {
1551         TargetRegisterClass *RC;
1552         if (AFI->isThumb1OnlyFunction())
1553           RC = ARM::tGPRRegisterClass;
1554         else
1555           RC = ARM::GPRRegisterClass;
1556
1557         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1558         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
1559         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1560         MemOps.push_back(Store);
1561         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1562                           DAG.getConstant(4, getPointerTy()));
1563       }
1564       if (!MemOps.empty())
1565         Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1566                            &MemOps[0], MemOps.size());
1567     } else
1568       // This will point to the next argument passed via stack.
1569       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1570   }
1571
1572   ArgValues.push_back(Root);
1573
1574   // Return the new list of results.
1575   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1576                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1577 }
1578
1579 /// isFloatingPointZero - Return true if this is +0.0.
1580 static bool isFloatingPointZero(SDValue Op) {
1581   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1582     return CFP->getValueAPF().isPosZero();
1583   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1584     // Maybe this has already been legalized into the constant pool?
1585     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1586       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1587       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1588         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1589           return CFP->getValueAPF().isPosZero();
1590     }
1591   }
1592   return false;
1593 }
1594
1595 static bool isLegalCmpImmediate(unsigned C, bool isThumb1Only) {
1596   return ( isThumb1Only && (C & ~255U) == 0) ||
1597          (!isThumb1Only && ARM_AM::getSOImmVal(C) != -1);
1598 }
1599
1600 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1601 /// the given operands.
1602 static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1603                          SDValue &ARMCC, SelectionDAG &DAG, bool isThumb1Only,
1604                          DebugLoc dl) {
1605   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1606     unsigned C = RHSC->getZExtValue();
1607     if (!isLegalCmpImmediate(C, isThumb1Only)) {
1608       // Constant does not fit, try adjusting it by one?
1609       switch (CC) {
1610       default: break;
1611       case ISD::SETLT:
1612       case ISD::SETGE:
1613         if (isLegalCmpImmediate(C-1, isThumb1Only)) {
1614           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1615           RHS = DAG.getConstant(C-1, MVT::i32);
1616         }
1617         break;
1618       case ISD::SETULT:
1619       case ISD::SETUGE:
1620         if (C > 0 && isLegalCmpImmediate(C-1, isThumb1Only)) {
1621           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1622           RHS = DAG.getConstant(C-1, MVT::i32);
1623         }
1624         break;
1625       case ISD::SETLE:
1626       case ISD::SETGT:
1627         if (isLegalCmpImmediate(C+1, isThumb1Only)) {
1628           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1629           RHS = DAG.getConstant(C+1, MVT::i32);
1630         }
1631         break;
1632       case ISD::SETULE:
1633       case ISD::SETUGT:
1634         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb1Only)) {
1635           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1636           RHS = DAG.getConstant(C+1, MVT::i32);
1637         }
1638         break;
1639       }
1640     }
1641   }
1642
1643   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1644   ARMISD::NodeType CompareType;
1645   switch (CondCode) {
1646   default:
1647     CompareType = ARMISD::CMP;
1648     break;
1649   case ARMCC::EQ:
1650   case ARMCC::NE:
1651     // Uses only Z Flag
1652     CompareType = ARMISD::CMPZ;
1653     break;
1654   }
1655   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1656   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1657 }
1658
1659 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1660 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1661                          DebugLoc dl) {
1662   SDValue Cmp;
1663   if (!isFloatingPointZero(RHS))
1664     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1665   else
1666     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1667   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1668 }
1669
1670 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1671                               const ARMSubtarget *ST) {
1672   MVT VT = Op.getValueType();
1673   SDValue LHS = Op.getOperand(0);
1674   SDValue RHS = Op.getOperand(1);
1675   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1676   SDValue TrueVal = Op.getOperand(2);
1677   SDValue FalseVal = Op.getOperand(3);
1678   DebugLoc dl = Op.getDebugLoc();
1679
1680   if (LHS.getValueType() == MVT::i32) {
1681     SDValue ARMCC;
1682     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1683     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1684     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1685   }
1686
1687   ARMCC::CondCodes CondCode, CondCode2;
1688   if (FPCCToARMCC(CC, CondCode, CondCode2))
1689     std::swap(TrueVal, FalseVal);
1690
1691   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1692   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1693   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1694   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1695                                  ARMCC, CCR, Cmp);
1696   if (CondCode2 != ARMCC::AL) {
1697     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1698     // FIXME: Needs another CMP because flag can have but one use.
1699     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1700     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1701                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1702   }
1703   return Result;
1704 }
1705
1706 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1707                           const ARMSubtarget *ST) {
1708   SDValue  Chain = Op.getOperand(0);
1709   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1710   SDValue    LHS = Op.getOperand(2);
1711   SDValue    RHS = Op.getOperand(3);
1712   SDValue   Dest = Op.getOperand(4);
1713   DebugLoc dl = Op.getDebugLoc();
1714
1715   if (LHS.getValueType() == MVT::i32) {
1716     SDValue ARMCC;
1717     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1718     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1719     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1720                        Chain, Dest, ARMCC, CCR,Cmp);
1721   }
1722
1723   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1724   ARMCC::CondCodes CondCode, CondCode2;
1725   if (FPCCToARMCC(CC, CondCode, CondCode2))
1726     // Swap the LHS/RHS of the comparison if needed.
1727     std::swap(LHS, RHS);
1728
1729   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1730   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1731   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1732   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1733   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1734   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1735   if (CondCode2 != ARMCC::AL) {
1736     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1737     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1738     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1739   }
1740   return Res;
1741 }
1742
1743 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1744   SDValue Chain = Op.getOperand(0);
1745   SDValue Table = Op.getOperand(1);
1746   SDValue Index = Op.getOperand(2);
1747   DebugLoc dl = Op.getDebugLoc();
1748
1749   MVT PTy = getPointerTy();
1750   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1751   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1752   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
1753   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1754   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1755   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1756   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1757   if (Subtarget->isThumb2()) {
1758     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
1759     // which does another jump to the destination. This also makes it easier
1760     // to translate it to TBB / TBH later.
1761     // FIXME: This might not work if the function is extremely large.
1762     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
1763                        Addr, Op.getOperand(2), JTI, UId);
1764   }
1765   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1766     Addr = DAG.getLoad((MVT)MVT::i32, dl, Chain, Addr, NULL, 0);
1767     Chain = Addr.getValue(1);
1768     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1769     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1770   } else {
1771     Addr = DAG.getLoad(PTy, dl, Chain, Addr, NULL, 0);
1772     Chain = Addr.getValue(1);
1773     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1774   }
1775 }
1776
1777 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1778   DebugLoc dl = Op.getDebugLoc();
1779   unsigned Opc =
1780     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1781   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1782   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1783 }
1784
1785 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1786   MVT VT = Op.getValueType();
1787   DebugLoc dl = Op.getDebugLoc();
1788   unsigned Opc =
1789     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1790
1791   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1792   return DAG.getNode(Opc, dl, VT, Op);
1793 }
1794
1795 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1796   // Implement fcopysign with a fabs and a conditional fneg.
1797   SDValue Tmp0 = Op.getOperand(0);
1798   SDValue Tmp1 = Op.getOperand(1);
1799   DebugLoc dl = Op.getDebugLoc();
1800   MVT VT = Op.getValueType();
1801   MVT SrcVT = Tmp1.getValueType();
1802   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1803   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1804   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1805   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1806   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1807 }
1808
1809 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1810   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1811   MFI->setFrameAddressIsTaken(true);
1812   MVT VT = Op.getValueType();
1813   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1814   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1815   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
1816     ? ARM::R7 : ARM::R11;
1817   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1818   while (Depth--)
1819     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1820   return FrameAddr;
1821 }
1822
1823 SDValue
1824 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1825                                            SDValue Chain,
1826                                            SDValue Dst, SDValue Src,
1827                                            SDValue Size, unsigned Align,
1828                                            bool AlwaysInline,
1829                                          const Value *DstSV, uint64_t DstSVOff,
1830                                          const Value *SrcSV, uint64_t SrcSVOff){
1831   // Do repeated 4-byte loads and stores. To be improved.
1832   // This requires 4-byte alignment.
1833   if ((Align & 3) != 0)
1834     return SDValue();
1835   // This requires the copy size to be a constant, preferrably
1836   // within a subtarget-specific limit.
1837   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1838   if (!ConstantSize)
1839     return SDValue();
1840   uint64_t SizeVal = ConstantSize->getZExtValue();
1841   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1842     return SDValue();
1843
1844   unsigned BytesLeft = SizeVal & 3;
1845   unsigned NumMemOps = SizeVal >> 2;
1846   unsigned EmittedNumMemOps = 0;
1847   MVT VT = MVT::i32;
1848   unsigned VTSize = 4;
1849   unsigned i = 0;
1850   const unsigned MAX_LOADS_IN_LDM = 6;
1851   SDValue TFOps[MAX_LOADS_IN_LDM];
1852   SDValue Loads[MAX_LOADS_IN_LDM];
1853   uint64_t SrcOff = 0, DstOff = 0;
1854
1855   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1856   // same number of stores.  The loads and stores will get combined into
1857   // ldm/stm later on.
1858   while (EmittedNumMemOps < NumMemOps) {
1859     for (i = 0;
1860          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1861       Loads[i] = DAG.getLoad(VT, dl, Chain,
1862                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1863                                          DAG.getConstant(SrcOff, MVT::i32)),
1864                              SrcSV, SrcSVOff + SrcOff);
1865       TFOps[i] = Loads[i].getValue(1);
1866       SrcOff += VTSize;
1867     }
1868     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1869
1870     for (i = 0;
1871          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1872       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1873                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1874                                        DAG.getConstant(DstOff, MVT::i32)),
1875                            DstSV, DstSVOff + DstOff);
1876       DstOff += VTSize;
1877     }
1878     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1879
1880     EmittedNumMemOps += i;
1881   }
1882
1883   if (BytesLeft == 0)
1884     return Chain;
1885
1886   // Issue loads / stores for the trailing (1 - 3) bytes.
1887   unsigned BytesLeftSave = BytesLeft;
1888   i = 0;
1889   while (BytesLeft) {
1890     if (BytesLeft >= 2) {
1891       VT = MVT::i16;
1892       VTSize = 2;
1893     } else {
1894       VT = MVT::i8;
1895       VTSize = 1;
1896     }
1897
1898     Loads[i] = DAG.getLoad(VT, dl, Chain,
1899                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1900                                        DAG.getConstant(SrcOff, MVT::i32)),
1901                            SrcSV, SrcSVOff + SrcOff);
1902     TFOps[i] = Loads[i].getValue(1);
1903     ++i;
1904     SrcOff += VTSize;
1905     BytesLeft -= VTSize;
1906   }
1907   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1908
1909   i = 0;
1910   BytesLeft = BytesLeftSave;
1911   while (BytesLeft) {
1912     if (BytesLeft >= 2) {
1913       VT = MVT::i16;
1914       VTSize = 2;
1915     } else {
1916       VT = MVT::i8;
1917       VTSize = 1;
1918     }
1919
1920     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1921                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1922                                         DAG.getConstant(DstOff, MVT::i32)),
1923                             DstSV, DstSVOff + DstOff);
1924     ++i;
1925     DstOff += VTSize;
1926     BytesLeft -= VTSize;
1927   }
1928   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1929 }
1930
1931 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1932   SDValue Op = N->getOperand(0);
1933   DebugLoc dl = N->getDebugLoc();
1934   if (N->getValueType(0) == MVT::f64) {
1935     // Turn i64->f64 into FMDRR.
1936     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1937                              DAG.getConstant(0, MVT::i32));
1938     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1939                              DAG.getConstant(1, MVT::i32));
1940     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
1941   }
1942
1943   // Turn f64->i64 into FMRRD.
1944   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
1945                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
1946
1947   // Merge the pieces into a single i64 value.
1948   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
1949 }
1950
1951 /// getZeroVector - Returns a vector of specified type with all zero elements.
1952 ///
1953 static SDValue getZeroVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
1954   assert(VT.isVector() && "Expected a vector type");
1955
1956   // Zero vectors are used to represent vector negation and in those cases
1957   // will be implemented with the NEON VNEG instruction.  However, VNEG does
1958   // not support i64 elements, so sometimes the zero vectors will need to be
1959   // explicitly constructed.  For those cases, and potentially other uses in
1960   // the future, always build zero vectors as <4 x i32> or <2 x i32> bitcasted
1961   // to their dest type.  This ensures they get CSE'd.
1962   SDValue Vec;
1963   SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
1964   if (VT.getSizeInBits() == 64)
1965     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
1966   else
1967     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
1968
1969   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
1970 }
1971
1972 /// getOnesVector - Returns a vector of specified type with all bits set.
1973 ///
1974 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
1975   assert(VT.isVector() && "Expected a vector type");
1976
1977   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
1978   // type.  This ensures they get CSE'd.
1979   SDValue Vec;
1980   SDValue Cst = DAG.getTargetConstant(~0U, 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 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
1990                           const ARMSubtarget *ST) {
1991   MVT VT = N->getValueType(0);
1992   DebugLoc dl = N->getDebugLoc();
1993
1994   // Lower vector shifts on NEON to use VSHL.
1995   if (VT.isVector()) {
1996     assert(ST->hasNEON() && "unexpected vector shift");
1997
1998     // Left shifts translate directly to the vshiftu intrinsic.
1999     if (N->getOpcode() == ISD::SHL)
2000       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2001                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
2002                          N->getOperand(0), N->getOperand(1));
2003
2004     assert((N->getOpcode() == ISD::SRA ||
2005             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
2006
2007     // NEON uses the same intrinsics for both left and right shifts.  For
2008     // right shifts, the shift amounts are negative, so negate the vector of
2009     // shift amounts.
2010     MVT ShiftVT = N->getOperand(1).getValueType();
2011     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2012                                        getZeroVector(ShiftVT, DAG, dl),
2013                                        N->getOperand(1));
2014     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2015                                Intrinsic::arm_neon_vshifts :
2016                                Intrinsic::arm_neon_vshiftu);
2017     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2018                        DAG.getConstant(vshiftInt, MVT::i32),
2019                        N->getOperand(0), NegatedCount);
2020   }
2021
2022   assert(VT == MVT::i64 &&
2023          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2024          "Unknown shift to lower!");
2025
2026   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2027   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2028       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2029     return SDValue();
2030
2031   // If we are in thumb mode, we don't have RRX.
2032   if (ST->isThumb1Only()) return SDValue();
2033
2034   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2035   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2036                              DAG.getConstant(0, MVT::i32));
2037   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2038                              DAG.getConstant(1, MVT::i32));
2039
2040   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2041   // captures the result into a carry flag.
2042   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2043   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2044
2045   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2046   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2047
2048   // Merge the pieces into a single i64 value.
2049  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2050 }
2051
2052 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2053   SDValue TmpOp0, TmpOp1;
2054   bool Invert = false;
2055   bool Swap = false;
2056   unsigned Opc = 0;
2057
2058   SDValue Op0 = Op.getOperand(0);
2059   SDValue Op1 = Op.getOperand(1);
2060   SDValue CC = Op.getOperand(2);
2061   MVT VT = Op.getValueType();
2062   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2063   DebugLoc dl = Op.getDebugLoc();
2064
2065   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2066     switch (SetCCOpcode) {
2067     default: llvm_unreachable("Illegal FP comparison"); break;
2068     case ISD::SETUNE:
2069     case ISD::SETNE:  Invert = true; // Fallthrough
2070     case ISD::SETOEQ:
2071     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2072     case ISD::SETOLT:
2073     case ISD::SETLT: Swap = true; // Fallthrough
2074     case ISD::SETOGT:
2075     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2076     case ISD::SETOLE:
2077     case ISD::SETLE:  Swap = true; // Fallthrough
2078     case ISD::SETOGE:
2079     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2080     case ISD::SETUGE: Swap = true; // Fallthrough
2081     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2082     case ISD::SETUGT: Swap = true; // Fallthrough
2083     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2084     case ISD::SETUEQ: Invert = true; // Fallthrough
2085     case ISD::SETONE:
2086       // Expand this to (OLT | OGT).
2087       TmpOp0 = Op0;
2088       TmpOp1 = Op1;
2089       Opc = ISD::OR;
2090       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2091       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2092       break;
2093     case ISD::SETUO: Invert = true; // Fallthrough
2094     case ISD::SETO:
2095       // Expand this to (OLT | OGE).
2096       TmpOp0 = Op0;
2097       TmpOp1 = Op1;
2098       Opc = ISD::OR;
2099       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2100       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2101       break;
2102     }
2103   } else {
2104     // Integer comparisons.
2105     switch (SetCCOpcode) {
2106     default: llvm_unreachable("Illegal integer comparison"); break;
2107     case ISD::SETNE:  Invert = true;
2108     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2109     case ISD::SETLT:  Swap = true;
2110     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2111     case ISD::SETLE:  Swap = true;
2112     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2113     case ISD::SETULT: Swap = true;
2114     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2115     case ISD::SETULE: Swap = true;
2116     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2117     }
2118
2119     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2120     if (Opc == ARMISD::VCEQ) {
2121
2122       SDValue AndOp;
2123       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2124         AndOp = Op0;
2125       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2126         AndOp = Op1;
2127
2128       // Ignore bitconvert.
2129       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2130         AndOp = AndOp.getOperand(0);
2131
2132       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2133         Opc = ARMISD::VTST;
2134         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2135         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2136         Invert = !Invert;
2137       }
2138     }
2139   }
2140
2141   if (Swap)
2142     std::swap(Op0, Op1);
2143
2144   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2145
2146   if (Invert)
2147     Result = DAG.getNOT(dl, Result, VT);
2148
2149   return Result;
2150 }
2151
2152 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2153 /// VMOV instruction, and if so, return the constant being splatted.
2154 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2155                            unsigned SplatBitSize, SelectionDAG &DAG) {
2156   switch (SplatBitSize) {
2157   case 8:
2158     // Any 1-byte value is OK.
2159     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2160     return DAG.getTargetConstant(SplatBits, MVT::i8);
2161
2162   case 16:
2163     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2164     if ((SplatBits & ~0xff) == 0 ||
2165         (SplatBits & ~0xff00) == 0)
2166       return DAG.getTargetConstant(SplatBits, MVT::i16);
2167     break;
2168
2169   case 32:
2170     // NEON's 32-bit VMOV supports splat values where:
2171     // * only one byte is nonzero, or
2172     // * the least significant byte is 0xff and the second byte is nonzero, or
2173     // * the least significant 2 bytes are 0xff and the third is nonzero.
2174     if ((SplatBits & ~0xff) == 0 ||
2175         (SplatBits & ~0xff00) == 0 ||
2176         (SplatBits & ~0xff0000) == 0 ||
2177         (SplatBits & ~0xff000000) == 0)
2178       return DAG.getTargetConstant(SplatBits, MVT::i32);
2179
2180     if ((SplatBits & ~0xffff) == 0 &&
2181         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2182       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2183
2184     if ((SplatBits & ~0xffffff) == 0 &&
2185         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2186       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2187
2188     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2189     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2190     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2191     // and fall through here to test for a valid 64-bit splat.  But, then the
2192     // caller would also need to check and handle the change in size.
2193     break;
2194
2195   case 64: {
2196     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2197     uint64_t BitMask = 0xff;
2198     uint64_t Val = 0;
2199     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2200       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2201         Val |= BitMask;
2202       else if ((SplatBits & BitMask) != 0)
2203         return SDValue();
2204       BitMask <<= 8;
2205     }
2206     return DAG.getTargetConstant(Val, MVT::i64);
2207   }
2208
2209   default:
2210     llvm_unreachable("unexpected size for isVMOVSplat");
2211     break;
2212   }
2213
2214   return SDValue();
2215 }
2216
2217 /// getVMOVImm - If this is a build_vector of constants which can be
2218 /// formed by using a VMOV instruction of the specified element size,
2219 /// return the constant being splatted.  The ByteSize field indicates the
2220 /// number of bytes of each element [1248].
2221 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2222   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2223   APInt SplatBits, SplatUndef;
2224   unsigned SplatBitSize;
2225   bool HasAnyUndefs;
2226   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2227                                       HasAnyUndefs, ByteSize * 8))
2228     return SDValue();
2229
2230   if (SplatBitSize > ByteSize * 8)
2231     return SDValue();
2232
2233   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2234                      SplatBitSize, DAG);
2235 }
2236
2237 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2238 /// instruction with the specified blocksize.  (The order of the elements
2239 /// within each block of the vector is reversed.)
2240 bool ARM::isVREVMask(ShuffleVectorSDNode *N, unsigned BlockSize) {
2241   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2242          "Only possible block sizes for VREV are: 16, 32, 64");
2243
2244   MVT VT = N->getValueType(0);
2245   unsigned NumElts = VT.getVectorNumElements();
2246   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2247   unsigned BlockElts = N->getMaskElt(0) + 1;
2248
2249   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2250     return false;
2251
2252   for (unsigned i = 0; i < NumElts; ++i) {
2253     if ((unsigned) N->getMaskElt(i) !=
2254         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2255       return false;
2256   }
2257
2258   return true;
2259 }
2260
2261 static SDValue BuildSplat(SDValue Val, MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2262   // Canonicalize all-zeros and all-ones vectors.
2263   ConstantSDNode *ConstVal = dyn_cast<ConstantSDNode>(Val.getNode());
2264   if (ConstVal->isNullValue())
2265     return getZeroVector(VT, DAG, dl);
2266   if (ConstVal->isAllOnesValue())
2267     return getOnesVector(VT, DAG, dl);
2268
2269   MVT CanonicalVT;
2270   if (VT.is64BitVector()) {
2271     switch (Val.getValueType().getSizeInBits()) {
2272     case 8:  CanonicalVT = MVT::v8i8; break;
2273     case 16: CanonicalVT = MVT::v4i16; break;
2274     case 32: CanonicalVT = MVT::v2i32; break;
2275     case 64: CanonicalVT = MVT::v1i64; break;
2276     default: llvm_unreachable("unexpected splat element type"); break;
2277     }
2278   } else {
2279     assert(VT.is128BitVector() && "unknown splat vector size");
2280     switch (Val.getValueType().getSizeInBits()) {
2281     case 8:  CanonicalVT = MVT::v16i8; break;
2282     case 16: CanonicalVT = MVT::v8i16; break;
2283     case 32: CanonicalVT = MVT::v4i32; break;
2284     case 64: CanonicalVT = MVT::v2i64; break;
2285     default: llvm_unreachable("unexpected splat element type"); break;
2286     }
2287   }
2288
2289   // Build a canonical splat for this value.
2290   SmallVector<SDValue, 8> Ops;
2291   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2292   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2293                             Ops.size());
2294   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2295 }
2296
2297 // If this is a case we can't handle, return null and let the default
2298 // expansion code take care of it.
2299 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2300   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2301   assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
2302   DebugLoc dl = Op.getDebugLoc();
2303   MVT VT = Op.getValueType();
2304
2305   APInt SplatBits, SplatUndef;
2306   unsigned SplatBitSize;
2307   bool HasAnyUndefs;
2308   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2309     SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2310                               SplatUndef.getZExtValue(), SplatBitSize, DAG);
2311     if (Val.getNode())
2312       return BuildSplat(Val, VT, DAG, dl);
2313   }
2314
2315   // If there are only 2 elements in a 128-bit vector, insert them into an
2316   // undef vector.  This handles the common case for 128-bit vector argument
2317   // passing, where the insertions should be translated to subreg accesses
2318   // with no real instructions.
2319   if (VT.is128BitVector() && Op.getNumOperands() == 2) {
2320     SDValue Val = DAG.getUNDEF(VT);
2321     SDValue Op0 = Op.getOperand(0);
2322     SDValue Op1 = Op.getOperand(1);
2323     if (Op0.getOpcode() != ISD::UNDEF)
2324       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op0,
2325                         DAG.getIntPtrConstant(0));
2326     if (Op1.getOpcode() != ISD::UNDEF)
2327       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op1,
2328                         DAG.getIntPtrConstant(1));
2329     return Val;
2330   }
2331
2332   return SDValue();
2333 }
2334
2335 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2336   return Op;
2337 }
2338
2339 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
2340   return Op;
2341 }
2342
2343 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
2344   MVT VT = Op.getValueType();
2345   DebugLoc dl = Op.getDebugLoc();
2346   assert((VT == MVT::i8 || VT == MVT::i16) &&
2347          "unexpected type for custom-lowering vector extract");
2348   SDValue Vec = Op.getOperand(0);
2349   SDValue Lane = Op.getOperand(1);
2350   Op = DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
2351   Op = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Op, DAG.getValueType(VT));
2352   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
2353 }
2354
2355 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
2356   // The only time a CONCAT_VECTORS operation can have legal types is when
2357   // two 64-bit vectors are concatenated to a 128-bit vector.
2358   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
2359          "unexpected CONCAT_VECTORS");
2360   DebugLoc dl = Op.getDebugLoc();
2361   SDValue Val = DAG.getUNDEF(MVT::v2f64);
2362   SDValue Op0 = Op.getOperand(0);
2363   SDValue Op1 = Op.getOperand(1);
2364   if (Op0.getOpcode() != ISD::UNDEF)
2365     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2366                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
2367                       DAG.getIntPtrConstant(0));
2368   if (Op1.getOpcode() != ISD::UNDEF)
2369     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2370                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
2371                       DAG.getIntPtrConstant(1));
2372   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
2373 }
2374
2375 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
2376   switch (Op.getOpcode()) {
2377   default: llvm_unreachable("Don't know how to custom lower this!");
2378   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
2379   case ISD::GlobalAddress:
2380     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
2381       LowerGlobalAddressELF(Op, DAG);
2382   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2383   case ISD::CALL:          return LowerCALL(Op, DAG);
2384   case ISD::RET:           return LowerRET(Op, DAG);
2385   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
2386   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
2387   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
2388   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
2389   case ISD::SINT_TO_FP:
2390   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
2391   case ISD::FP_TO_SINT:
2392   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
2393   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
2394   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
2395   case ISD::RETURNADDR:    break;
2396   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2397   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2398   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2399   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2400   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
2401   case ISD::SHL:
2402   case ISD::SRL:
2403   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
2404   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
2405   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
2406   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2407   case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
2408   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2409   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
2410   }
2411   return SDValue();
2412 }
2413
2414 /// ReplaceNodeResults - Replace the results of node with an illegal result
2415 /// type with new values built out of custom code.
2416 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
2417                                            SmallVectorImpl<SDValue>&Results,
2418                                            SelectionDAG &DAG) {
2419   switch (N->getOpcode()) {
2420   default:
2421     llvm_unreachable("Don't know how to custom expand this!");
2422     return;
2423   case ISD::BIT_CONVERT:
2424     Results.push_back(ExpandBIT_CONVERT(N, DAG));
2425     return;
2426   case ISD::SRL:
2427   case ISD::SRA: {
2428     SDValue Res = LowerShift(N, DAG, Subtarget);
2429     if (Res.getNode())
2430       Results.push_back(Res);
2431     return;
2432   }
2433   }
2434 }
2435
2436 //===----------------------------------------------------------------------===//
2437 //                           ARM Scheduler Hooks
2438 //===----------------------------------------------------------------------===//
2439
2440 MachineBasicBlock *
2441 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2442                                                MachineBasicBlock *BB) const {
2443   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2444   DebugLoc dl = MI->getDebugLoc();
2445   switch (MI->getOpcode()) {
2446   default: assert(false && "Unexpected instr type to insert");
2447   case ARM::tMOVCCr: {
2448     // To "insert" a SELECT_CC instruction, we actually have to insert the
2449     // diamond control-flow pattern.  The incoming instruction knows the
2450     // destination vreg to set, the condition code register to branch on, the
2451     // true/false values to select between, and a branch opcode to use.
2452     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2453     MachineFunction::iterator It = BB;
2454     ++It;
2455
2456     //  thisMBB:
2457     //  ...
2458     //   TrueVal = ...
2459     //   cmpTY ccX, r1, r2
2460     //   bCC copy1MBB
2461     //   fallthrough --> copy0MBB
2462     MachineBasicBlock *thisMBB  = BB;
2463     MachineFunction *F = BB->getParent();
2464     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2465     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
2466     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
2467       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
2468     F->insert(It, copy0MBB);
2469     F->insert(It, sinkMBB);
2470     // Update machine-CFG edges by first adding all successors of the current
2471     // block to the new block which will contain the Phi node for the select.
2472     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
2473         e = BB->succ_end(); i != e; ++i)
2474       sinkMBB->addSuccessor(*i);
2475     // Next, remove all successors of the current block, and add the true
2476     // and fallthrough blocks as its successors.
2477     while(!BB->succ_empty())
2478       BB->removeSuccessor(BB->succ_begin());
2479     BB->addSuccessor(copy0MBB);
2480     BB->addSuccessor(sinkMBB);
2481
2482     //  copy0MBB:
2483     //   %FalseValue = ...
2484     //   # fallthrough to sinkMBB
2485     BB = copy0MBB;
2486
2487     // Update machine-CFG edges
2488     BB->addSuccessor(sinkMBB);
2489
2490     //  sinkMBB:
2491     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2492     //  ...
2493     BB = sinkMBB;
2494     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
2495       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
2496       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
2497
2498     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2499     return BB;
2500   }
2501   }
2502 }
2503
2504 //===----------------------------------------------------------------------===//
2505 //                           ARM Optimization Hooks
2506 //===----------------------------------------------------------------------===//
2507
2508 static
2509 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
2510                             TargetLowering::DAGCombinerInfo &DCI) {
2511   SelectionDAG &DAG = DCI.DAG;
2512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2513   MVT VT = N->getValueType(0);
2514   unsigned Opc = N->getOpcode();
2515   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
2516   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
2517   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
2518   ISD::CondCode CC = ISD::SETCC_INVALID;
2519
2520   if (isSlctCC) {
2521     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
2522   } else {
2523     SDValue CCOp = Slct.getOperand(0);
2524     if (CCOp.getOpcode() == ISD::SETCC)
2525       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
2526   }
2527
2528   bool DoXform = false;
2529   bool InvCC = false;
2530   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
2531           "Bad input!");
2532
2533   if (LHS.getOpcode() == ISD::Constant &&
2534       cast<ConstantSDNode>(LHS)->isNullValue()) {
2535     DoXform = true;
2536   } else if (CC != ISD::SETCC_INVALID &&
2537              RHS.getOpcode() == ISD::Constant &&
2538              cast<ConstantSDNode>(RHS)->isNullValue()) {
2539     std::swap(LHS, RHS);
2540     SDValue Op0 = Slct.getOperand(0);
2541     MVT OpVT = isSlctCC ? Op0.getValueType() :
2542                           Op0.getOperand(0).getValueType();
2543     bool isInt = OpVT.isInteger();
2544     CC = ISD::getSetCCInverse(CC, isInt);
2545
2546     if (!TLI.isCondCodeLegal(CC, OpVT))
2547       return SDValue();         // Inverse operator isn't legal.
2548
2549     DoXform = true;
2550     InvCC = true;
2551   }
2552
2553   if (DoXform) {
2554     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
2555     if (isSlctCC)
2556       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
2557                              Slct.getOperand(0), Slct.getOperand(1), CC);
2558     SDValue CCOp = Slct.getOperand(0);
2559     if (InvCC)
2560       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
2561                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
2562     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
2563                        CCOp, OtherOp, Result);
2564   }
2565   return SDValue();
2566 }
2567
2568 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
2569 static SDValue PerformADDCombine(SDNode *N,
2570                                  TargetLowering::DAGCombinerInfo &DCI) {
2571   // added by evan in r37685 with no testcase.
2572   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2573
2574   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
2575   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
2576     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
2577     if (Result.getNode()) return Result;
2578   }
2579   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2580     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2581     if (Result.getNode()) return Result;
2582   }
2583
2584   return SDValue();
2585 }
2586
2587 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
2588 static SDValue PerformSUBCombine(SDNode *N,
2589                                  TargetLowering::DAGCombinerInfo &DCI) {
2590   // added by evan in r37685 with no testcase.
2591   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2592
2593   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
2594   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2595     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2596     if (Result.getNode()) return Result;
2597   }
2598
2599   return SDValue();
2600 }
2601
2602
2603 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
2604 static SDValue PerformFMRRDCombine(SDNode *N,
2605                                    TargetLowering::DAGCombinerInfo &DCI) {
2606   // fmrrd(fmdrr x, y) -> x,y
2607   SDValue InDouble = N->getOperand(0);
2608   if (InDouble.getOpcode() == ARMISD::FMDRR)
2609     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
2610   return SDValue();
2611 }
2612
2613 /// getVShiftImm - Check if this is a valid build_vector for the immediate
2614 /// operand of a vector shift operation, where all the elements of the
2615 /// build_vector must have the same constant integer value.
2616 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
2617   // Ignore bit_converts.
2618   while (Op.getOpcode() == ISD::BIT_CONVERT)
2619     Op = Op.getOperand(0);
2620   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2621   APInt SplatBits, SplatUndef;
2622   unsigned SplatBitSize;
2623   bool HasAnyUndefs;
2624   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2625                                       HasAnyUndefs, ElementBits) ||
2626       SplatBitSize > ElementBits)
2627     return false;
2628   Cnt = SplatBits.getSExtValue();
2629   return true;
2630 }
2631
2632 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
2633 /// operand of a vector shift left operation.  That value must be in the range:
2634 ///   0 <= Value < ElementBits for a left shift; or
2635 ///   0 <= Value <= ElementBits for a long left shift.
2636 static bool isVShiftLImm(SDValue Op, MVT VT, bool isLong, int64_t &Cnt) {
2637   assert(VT.isVector() && "vector shift count is not a vector type");
2638   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2639   if (! getVShiftImm(Op, ElementBits, Cnt))
2640     return false;
2641   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
2642 }
2643
2644 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
2645 /// operand of a vector shift right operation.  For a shift opcode, the value
2646 /// is positive, but for an intrinsic the value count must be negative. The
2647 /// absolute value must be in the range:
2648 ///   1 <= |Value| <= ElementBits for a right shift; or
2649 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
2650 static bool isVShiftRImm(SDValue Op, MVT VT, bool isNarrow, bool isIntrinsic,
2651                          int64_t &Cnt) {
2652   assert(VT.isVector() && "vector shift count is not a vector type");
2653   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2654   if (! getVShiftImm(Op, ElementBits, Cnt))
2655     return false;
2656   if (isIntrinsic)
2657     Cnt = -Cnt;
2658   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
2659 }
2660
2661 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
2662 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
2663   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2664   switch (IntNo) {
2665   default:
2666     // Don't do anything for most intrinsics.
2667     break;
2668
2669   // Vector shifts: check for immediate versions and lower them.
2670   // Note: This is done during DAG combining instead of DAG legalizing because
2671   // the build_vectors for 64-bit vector element shift counts are generally
2672   // not legal, and it is hard to see their values after they get legalized to
2673   // loads from a constant pool.
2674   case Intrinsic::arm_neon_vshifts:
2675   case Intrinsic::arm_neon_vshiftu:
2676   case Intrinsic::arm_neon_vshiftls:
2677   case Intrinsic::arm_neon_vshiftlu:
2678   case Intrinsic::arm_neon_vshiftn:
2679   case Intrinsic::arm_neon_vrshifts:
2680   case Intrinsic::arm_neon_vrshiftu:
2681   case Intrinsic::arm_neon_vrshiftn:
2682   case Intrinsic::arm_neon_vqshifts:
2683   case Intrinsic::arm_neon_vqshiftu:
2684   case Intrinsic::arm_neon_vqshiftsu:
2685   case Intrinsic::arm_neon_vqshiftns:
2686   case Intrinsic::arm_neon_vqshiftnu:
2687   case Intrinsic::arm_neon_vqshiftnsu:
2688   case Intrinsic::arm_neon_vqrshiftns:
2689   case Intrinsic::arm_neon_vqrshiftnu:
2690   case Intrinsic::arm_neon_vqrshiftnsu: {
2691     MVT VT = N->getOperand(1).getValueType();
2692     int64_t Cnt;
2693     unsigned VShiftOpc = 0;
2694
2695     switch (IntNo) {
2696     case Intrinsic::arm_neon_vshifts:
2697     case Intrinsic::arm_neon_vshiftu:
2698       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
2699         VShiftOpc = ARMISD::VSHL;
2700         break;
2701       }
2702       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
2703         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
2704                      ARMISD::VSHRs : ARMISD::VSHRu);
2705         break;
2706       }
2707       return SDValue();
2708
2709     case Intrinsic::arm_neon_vshiftls:
2710     case Intrinsic::arm_neon_vshiftlu:
2711       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
2712         break;
2713       llvm_unreachable("invalid shift count for vshll intrinsic");
2714
2715     case Intrinsic::arm_neon_vrshifts:
2716     case Intrinsic::arm_neon_vrshiftu:
2717       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
2718         break;
2719       return SDValue();
2720
2721     case Intrinsic::arm_neon_vqshifts:
2722     case Intrinsic::arm_neon_vqshiftu:
2723       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2724         break;
2725       return SDValue();
2726
2727     case Intrinsic::arm_neon_vqshiftsu:
2728       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2729         break;
2730       llvm_unreachable("invalid shift count for vqshlu intrinsic");
2731
2732     case Intrinsic::arm_neon_vshiftn:
2733     case Intrinsic::arm_neon_vrshiftn:
2734     case Intrinsic::arm_neon_vqshiftns:
2735     case Intrinsic::arm_neon_vqshiftnu:
2736     case Intrinsic::arm_neon_vqshiftnsu:
2737     case Intrinsic::arm_neon_vqrshiftns:
2738     case Intrinsic::arm_neon_vqrshiftnu:
2739     case Intrinsic::arm_neon_vqrshiftnsu:
2740       // Narrowing shifts require an immediate right shift.
2741       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
2742         break;
2743       llvm_unreachable("invalid shift count for narrowing vector shift intrinsic");
2744
2745     default:
2746       llvm_unreachable("unhandled vector shift");
2747     }
2748
2749     switch (IntNo) {
2750     case Intrinsic::arm_neon_vshifts:
2751     case Intrinsic::arm_neon_vshiftu:
2752       // Opcode already set above.
2753       break;
2754     case Intrinsic::arm_neon_vshiftls:
2755     case Intrinsic::arm_neon_vshiftlu:
2756       if (Cnt == VT.getVectorElementType().getSizeInBits())
2757         VShiftOpc = ARMISD::VSHLLi;
2758       else
2759         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
2760                      ARMISD::VSHLLs : ARMISD::VSHLLu);
2761       break;
2762     case Intrinsic::arm_neon_vshiftn:
2763       VShiftOpc = ARMISD::VSHRN; break;
2764     case Intrinsic::arm_neon_vrshifts:
2765       VShiftOpc = ARMISD::VRSHRs; break;
2766     case Intrinsic::arm_neon_vrshiftu:
2767       VShiftOpc = ARMISD::VRSHRu; break;
2768     case Intrinsic::arm_neon_vrshiftn:
2769       VShiftOpc = ARMISD::VRSHRN; break;
2770     case Intrinsic::arm_neon_vqshifts:
2771       VShiftOpc = ARMISD::VQSHLs; break;
2772     case Intrinsic::arm_neon_vqshiftu:
2773       VShiftOpc = ARMISD::VQSHLu; break;
2774     case Intrinsic::arm_neon_vqshiftsu:
2775       VShiftOpc = ARMISD::VQSHLsu; break;
2776     case Intrinsic::arm_neon_vqshiftns:
2777       VShiftOpc = ARMISD::VQSHRNs; break;
2778     case Intrinsic::arm_neon_vqshiftnu:
2779       VShiftOpc = ARMISD::VQSHRNu; break;
2780     case Intrinsic::arm_neon_vqshiftnsu:
2781       VShiftOpc = ARMISD::VQSHRNsu; break;
2782     case Intrinsic::arm_neon_vqrshiftns:
2783       VShiftOpc = ARMISD::VQRSHRNs; break;
2784     case Intrinsic::arm_neon_vqrshiftnu:
2785       VShiftOpc = ARMISD::VQRSHRNu; break;
2786     case Intrinsic::arm_neon_vqrshiftnsu:
2787       VShiftOpc = ARMISD::VQRSHRNsu; break;
2788     }
2789
2790     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2791                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
2792   }
2793
2794   case Intrinsic::arm_neon_vshiftins: {
2795     MVT VT = N->getOperand(1).getValueType();
2796     int64_t Cnt;
2797     unsigned VShiftOpc = 0;
2798
2799     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
2800       VShiftOpc = ARMISD::VSLI;
2801     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
2802       VShiftOpc = ARMISD::VSRI;
2803     else {
2804       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
2805     }
2806
2807     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2808                        N->getOperand(1), N->getOperand(2),
2809                        DAG.getConstant(Cnt, MVT::i32));
2810   }
2811
2812   case Intrinsic::arm_neon_vqrshifts:
2813   case Intrinsic::arm_neon_vqrshiftu:
2814     // No immediate versions of these to check for.
2815     break;
2816   }
2817
2818   return SDValue();
2819 }
2820
2821 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
2822 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
2823 /// combining instead of DAG legalizing because the build_vectors for 64-bit
2824 /// vector element shift counts are generally not legal, and it is hard to see
2825 /// their values after they get legalized to loads from a constant pool.
2826 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
2827                                    const ARMSubtarget *ST) {
2828   MVT VT = N->getValueType(0);
2829
2830   // Nothing to be done for scalar shifts.
2831   if (! VT.isVector())
2832     return SDValue();
2833
2834   assert(ST->hasNEON() && "unexpected vector shift");
2835   int64_t Cnt;
2836
2837   switch (N->getOpcode()) {
2838   default: llvm_unreachable("unexpected shift opcode");
2839
2840   case ISD::SHL:
2841     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
2842       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
2843                          DAG.getConstant(Cnt, MVT::i32));
2844     break;
2845
2846   case ISD::SRA:
2847   case ISD::SRL:
2848     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
2849       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
2850                             ARMISD::VSHRs : ARMISD::VSHRu);
2851       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
2852                          DAG.getConstant(Cnt, MVT::i32));
2853     }
2854   }
2855   return SDValue();
2856 }
2857
2858 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
2859 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
2860 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
2861                                     const ARMSubtarget *ST) {
2862   SDValue N0 = N->getOperand(0);
2863
2864   // Check for sign- and zero-extensions of vector extract operations of 8-
2865   // and 16-bit vector elements.  NEON supports these directly.  They are
2866   // handled during DAG combining because type legalization will promote them
2867   // to 32-bit types and it is messy to recognize the operations after that.
2868   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2869     SDValue Vec = N0.getOperand(0);
2870     SDValue Lane = N0.getOperand(1);
2871     MVT VT = N->getValueType(0);
2872     MVT EltVT = N0.getValueType();
2873     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2874
2875     if (VT == MVT::i32 &&
2876         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
2877         TLI.isTypeLegal(Vec.getValueType())) {
2878
2879       unsigned Opc = 0;
2880       switch (N->getOpcode()) {
2881       default: llvm_unreachable("unexpected opcode");
2882       case ISD::SIGN_EXTEND:
2883         Opc = ARMISD::VGETLANEs;
2884         break;
2885       case ISD::ZERO_EXTEND:
2886       case ISD::ANY_EXTEND:
2887         Opc = ARMISD::VGETLANEu;
2888         break;
2889       }
2890       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
2891     }
2892   }
2893
2894   return SDValue();
2895 }
2896
2897 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
2898                                              DAGCombinerInfo &DCI) const {
2899   switch (N->getOpcode()) {
2900   default: break;
2901   case ISD::ADD:      return PerformADDCombine(N, DCI);
2902   case ISD::SUB:      return PerformSUBCombine(N, DCI);
2903   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
2904   case ISD::INTRINSIC_WO_CHAIN:
2905     return PerformIntrinsicCombine(N, DCI.DAG);
2906   case ISD::SHL:
2907   case ISD::SRA:
2908   case ISD::SRL:
2909     return PerformShiftCombine(N, DCI.DAG, Subtarget);
2910   case ISD::SIGN_EXTEND:
2911   case ISD::ZERO_EXTEND:
2912   case ISD::ANY_EXTEND:
2913     return PerformExtendCombine(N, DCI.DAG, Subtarget);
2914   }
2915   return SDValue();
2916 }
2917
2918 /// isLegalAddressImmediate - Return true if the integer value can be used
2919 /// as the offset of the target addressing mode for load / store of the
2920 /// given type.
2921 static bool isLegalAddressImmediate(int64_t V, MVT VT,
2922                                     const ARMSubtarget *Subtarget) {
2923   if (V == 0)
2924     return true;
2925
2926   if (!VT.isSimple())
2927     return false;
2928
2929   if (Subtarget->isThumb()) { // FIXME for thumb2
2930     if (V < 0)
2931       return false;
2932
2933     unsigned Scale = 1;
2934     switch (VT.getSimpleVT()) {
2935     default: return false;
2936     case MVT::i1:
2937     case MVT::i8:
2938       // Scale == 1;
2939       break;
2940     case MVT::i16:
2941       // Scale == 2;
2942       Scale = 2;
2943       break;
2944     case MVT::i32:
2945       // Scale == 4;
2946       Scale = 4;
2947       break;
2948     }
2949
2950     if ((V & (Scale - 1)) != 0)
2951       return false;
2952     V /= Scale;
2953     return V == (V & ((1LL << 5) - 1));
2954   }
2955
2956   if (V < 0)
2957     V = - V;
2958   switch (VT.getSimpleVT()) {
2959   default: return false;
2960   case MVT::i1:
2961   case MVT::i8:
2962   case MVT::i32:
2963     // +- imm12
2964     return V == (V & ((1LL << 12) - 1));
2965   case MVT::i16:
2966     // +- imm8
2967     return V == (V & ((1LL << 8) - 1));
2968   case MVT::f32:
2969   case MVT::f64:
2970     if (!Subtarget->hasVFP2())
2971       return false;
2972     if ((V & 3) != 0)
2973       return false;
2974     V >>= 2;
2975     return V == (V & ((1LL << 8) - 1));
2976   }
2977 }
2978
2979 /// isLegalAddressingMode - Return true if the addressing mode represented
2980 /// by AM is legal for this target, for a load/store of the specified type.
2981 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
2982                                               const Type *Ty) const {
2983   MVT VT = getValueType(Ty, true);
2984   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
2985     return false;
2986
2987   // Can never fold addr of global into load/store.
2988   if (AM.BaseGV)
2989     return false;
2990
2991   switch (AM.Scale) {
2992   case 0:  // no scale reg, must be "r+i" or "r", or "i".
2993     break;
2994   case 1:
2995     if (Subtarget->isThumb())  // FIXME for thumb2
2996       return false;
2997     // FALL THROUGH.
2998   default:
2999     // ARM doesn't support any R+R*scale+imm addr modes.
3000     if (AM.BaseOffs)
3001       return false;
3002
3003     if (!VT.isSimple())
3004       return false;
3005
3006     int Scale = AM.Scale;
3007     switch (VT.getSimpleVT()) {
3008     default: return false;
3009     case MVT::i1:
3010     case MVT::i8:
3011     case MVT::i32:
3012     case MVT::i64:
3013       // This assumes i64 is legalized to a pair of i32. If not (i.e.
3014       // ldrd / strd are used, then its address mode is same as i16.
3015       // r + r
3016       if (Scale < 0) Scale = -Scale;
3017       if (Scale == 1)
3018         return true;
3019       // r + r << imm
3020       return isPowerOf2_32(Scale & ~1);
3021     case MVT::i16:
3022       // r + r
3023       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3024         return true;
3025       return false;
3026
3027     case MVT::isVoid:
3028       // Note, we allow "void" uses (basically, uses that aren't loads or
3029       // stores), because arm allows folding a scale into many arithmetic
3030       // operations.  This should be made more precise and revisited later.
3031
3032       // Allow r << imm, but the imm has to be a multiple of two.
3033       if (AM.Scale & 1) return false;
3034       return isPowerOf2_32(AM.Scale);
3035     }
3036     break;
3037   }
3038   return true;
3039 }
3040
3041 static bool getARMIndexedAddressParts(SDNode *Ptr, MVT VT,
3042                                       bool isSEXTLoad, SDValue &Base,
3043                                       SDValue &Offset, bool &isInc,
3044                                       SelectionDAG &DAG) {
3045   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3046     return false;
3047
3048   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
3049     // AddressingMode 3
3050     Base = Ptr->getOperand(0);
3051     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3052       int RHSC = (int)RHS->getZExtValue();
3053       if (RHSC < 0 && RHSC > -256) {
3054         assert(Ptr->getOpcode() == ISD::ADD);
3055         isInc = false;
3056         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3057         return true;
3058       }
3059     }
3060     isInc = (Ptr->getOpcode() == ISD::ADD);
3061     Offset = Ptr->getOperand(1);
3062     return true;
3063   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
3064     // AddressingMode 2
3065     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3066       int RHSC = (int)RHS->getZExtValue();
3067       if (RHSC < 0 && RHSC > -0x1000) {
3068         assert(Ptr->getOpcode() == ISD::ADD);
3069         isInc = false;
3070         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3071         Base = Ptr->getOperand(0);
3072         return true;
3073       }
3074     }
3075
3076     if (Ptr->getOpcode() == ISD::ADD) {
3077       isInc = true;
3078       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
3079       if (ShOpcVal != ARM_AM::no_shift) {
3080         Base = Ptr->getOperand(1);
3081         Offset = Ptr->getOperand(0);
3082       } else {
3083         Base = Ptr->getOperand(0);
3084         Offset = Ptr->getOperand(1);
3085       }
3086       return true;
3087     }
3088
3089     isInc = (Ptr->getOpcode() == ISD::ADD);
3090     Base = Ptr->getOperand(0);
3091     Offset = Ptr->getOperand(1);
3092     return true;
3093   }
3094
3095   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
3096   return false;
3097 }
3098
3099 static bool getT2IndexedAddressParts(SDNode *Ptr, MVT VT,
3100                                      bool isSEXTLoad, SDValue &Base,
3101                                      SDValue &Offset, bool &isInc,
3102                                      SelectionDAG &DAG) {
3103   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3104     return false;
3105
3106   Base = Ptr->getOperand(0);
3107   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3108     int RHSC = (int)RHS->getZExtValue();
3109     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
3110       assert(Ptr->getOpcode() == ISD::ADD);
3111       isInc = false;
3112       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3113       return true;
3114     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
3115       isInc = Ptr->getOpcode() == ISD::ADD;
3116       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
3117       return true;
3118     }
3119   }
3120
3121   return false;
3122 }
3123
3124 /// getPreIndexedAddressParts - returns true by value, base pointer and
3125 /// offset pointer and addressing mode by reference if the node's address
3126 /// can be legally represented as pre-indexed load / store address.
3127 bool
3128 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3129                                              SDValue &Offset,
3130                                              ISD::MemIndexedMode &AM,
3131                                              SelectionDAG &DAG) const {
3132   if (Subtarget->isThumb1Only())
3133     return false;
3134
3135   MVT VT;
3136   SDValue Ptr;
3137   bool isSEXTLoad = false;
3138   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3139     Ptr = LD->getBasePtr();
3140     VT  = LD->getMemoryVT();
3141     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3142   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3143     Ptr = ST->getBasePtr();
3144     VT  = ST->getMemoryVT();
3145   } else
3146     return false;
3147
3148   bool isInc;
3149   bool isLegal = false;
3150   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3151     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3152                                        Offset, isInc, DAG);
3153   else 
3154     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3155                                         Offset, isInc, DAG);
3156   if (!isLegal)
3157     return false;
3158
3159   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
3160   return true;
3161 }
3162
3163 /// getPostIndexedAddressParts - returns true by value, base pointer and
3164 /// offset pointer and addressing mode by reference if this node can be
3165 /// combined with a load / store to form a post-indexed load / store.
3166 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
3167                                                    SDValue &Base,
3168                                                    SDValue &Offset,
3169                                                    ISD::MemIndexedMode &AM,
3170                                                    SelectionDAG &DAG) const {
3171   if (Subtarget->isThumb1Only())
3172     return false;
3173
3174   MVT VT;
3175   SDValue Ptr;
3176   bool isSEXTLoad = false;
3177   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3178     VT  = LD->getMemoryVT();
3179     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3180   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3181     VT  = ST->getMemoryVT();
3182   } else
3183     return false;
3184
3185   bool isInc;
3186   bool isLegal = false;
3187   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3188     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3189                                         isInc, DAG);
3190   else 
3191     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3192                                         isInc, DAG);
3193   if (!isLegal)
3194     return false;
3195
3196   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
3197   return true;
3198 }
3199
3200 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
3201                                                        const APInt &Mask,
3202                                                        APInt &KnownZero,
3203                                                        APInt &KnownOne,
3204                                                        const SelectionDAG &DAG,
3205                                                        unsigned Depth) const {
3206   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3207   switch (Op.getOpcode()) {
3208   default: break;
3209   case ARMISD::CMOV: {
3210     // Bits are known zero/one if known on the LHS and RHS.
3211     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
3212     if (KnownZero == 0 && KnownOne == 0) return;
3213
3214     APInt KnownZeroRHS, KnownOneRHS;
3215     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
3216                           KnownZeroRHS, KnownOneRHS, Depth+1);
3217     KnownZero &= KnownZeroRHS;
3218     KnownOne  &= KnownOneRHS;
3219     return;
3220   }
3221   }
3222 }
3223
3224 //===----------------------------------------------------------------------===//
3225 //                           ARM Inline Assembly Support
3226 //===----------------------------------------------------------------------===//
3227
3228 /// getConstraintType - Given a constraint letter, return the type of
3229 /// constraint it is for this target.
3230 ARMTargetLowering::ConstraintType
3231 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
3232   if (Constraint.size() == 1) {
3233     switch (Constraint[0]) {
3234     default:  break;
3235     case 'l': return C_RegisterClass;
3236     case 'w': return C_RegisterClass;
3237     }
3238   }
3239   return TargetLowering::getConstraintType(Constraint);
3240 }
3241
3242 std::pair<unsigned, const TargetRegisterClass*>
3243 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3244                                                 MVT VT) const {
3245   if (Constraint.size() == 1) {
3246     // GCC RS6000 Constraint Letters
3247     switch (Constraint[0]) {
3248     case 'l':
3249       if (Subtarget->isThumb1Only())
3250         return std::make_pair(0U, ARM::tGPRRegisterClass);
3251       else
3252         return std::make_pair(0U, ARM::GPRRegisterClass);
3253     case 'r':
3254       return std::make_pair(0U, ARM::GPRRegisterClass);
3255     case 'w':
3256       if (VT == MVT::f32)
3257         return std::make_pair(0U, ARM::SPRRegisterClass);
3258       if (VT == MVT::f64)
3259         return std::make_pair(0U, ARM::DPRRegisterClass);
3260       break;
3261     }
3262   }
3263   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3264 }
3265
3266 std::vector<unsigned> ARMTargetLowering::
3267 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3268                                   MVT VT) const {
3269   if (Constraint.size() != 1)
3270     return std::vector<unsigned>();
3271
3272   switch (Constraint[0]) {      // GCC ARM Constraint Letters
3273   default: break;
3274   case 'l':
3275     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3276                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3277                                  0);
3278   case 'r':
3279     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3280                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3281                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
3282                                  ARM::R12, ARM::LR, 0);
3283   case 'w':
3284     if (VT == MVT::f32)
3285       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
3286                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
3287                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
3288                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
3289                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
3290                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
3291                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
3292                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
3293     if (VT == MVT::f64)
3294       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
3295                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
3296                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
3297                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
3298       break;
3299   }
3300
3301   return std::vector<unsigned>();
3302 }
3303
3304 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3305 /// vector.  If it is invalid, don't add anything to Ops.
3306 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3307                                                      char Constraint,
3308                                                      bool hasMemory,
3309                                                      std::vector<SDValue>&Ops,
3310                                                      SelectionDAG &DAG) const {
3311   SDValue Result(0, 0);
3312
3313   switch (Constraint) {
3314   default: break;
3315   case 'I': case 'J': case 'K': case 'L':
3316   case 'M': case 'N': case 'O':
3317     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3318     if (!C)
3319       return;
3320
3321     int64_t CVal64 = C->getSExtValue();
3322     int CVal = (int) CVal64;
3323     // None of these constraints allow values larger than 32 bits.  Check
3324     // that the value fits in an int.
3325     if (CVal != CVal64)
3326       return;
3327
3328     switch (Constraint) {
3329       case 'I':
3330         if (Subtarget->isThumb1Only()) {
3331           // This must be a constant between 0 and 255, for ADD
3332           // immediates.
3333           if (CVal >= 0 && CVal <= 255)
3334             break;
3335         } else if (Subtarget->isThumb2()) {
3336           // A constant that can be used as an immediate value in a
3337           // data-processing instruction.
3338           if (ARM_AM::getT2SOImmVal(CVal) != -1)
3339             break;
3340         } else {
3341           // A constant that can be used as an immediate value in a
3342           // data-processing instruction.
3343           if (ARM_AM::getSOImmVal(CVal) != -1)
3344             break;
3345         }
3346         return;
3347
3348       case 'J':
3349         if (Subtarget->isThumb()) {  // FIXME thumb2
3350           // This must be a constant between -255 and -1, for negated ADD
3351           // immediates. This can be used in GCC with an "n" modifier that
3352           // prints the negated value, for use with SUB instructions. It is
3353           // not useful otherwise but is implemented for compatibility.
3354           if (CVal >= -255 && CVal <= -1)
3355             break;
3356         } else {
3357           // This must be a constant between -4095 and 4095. It is not clear
3358           // what this constraint is intended for. Implemented for
3359           // compatibility with GCC.
3360           if (CVal >= -4095 && CVal <= 4095)
3361             break;
3362         }
3363         return;
3364
3365       case 'K':
3366         if (Subtarget->isThumb1Only()) {
3367           // A 32-bit value where only one byte has a nonzero value. Exclude
3368           // zero to match GCC. This constraint is used by GCC internally for
3369           // constants that can be loaded with a move/shift combination.
3370           // It is not useful otherwise but is implemented for compatibility.
3371           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
3372             break;
3373         } else if (Subtarget->isThumb2()) {
3374           // A constant whose bitwise inverse can be used as an immediate
3375           // value in a data-processing instruction. This can be used in GCC
3376           // with a "B" modifier that prints the inverted value, for use with
3377           // BIC and MVN instructions. It is not useful otherwise but is
3378           // implemented for compatibility.
3379           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
3380             break;
3381         } else {
3382           // A constant whose bitwise inverse can be used as an immediate
3383           // value in a data-processing instruction. This can be used in GCC
3384           // with a "B" modifier that prints the inverted value, for use with
3385           // BIC and MVN instructions. It is not useful otherwise but is
3386           // implemented for compatibility.
3387           if (ARM_AM::getSOImmVal(~CVal) != -1)
3388             break;
3389         }
3390         return;
3391
3392       case 'L':
3393         if (Subtarget->isThumb1Only()) {
3394           // This must be a constant between -7 and 7,
3395           // for 3-operand ADD/SUB immediate instructions.
3396           if (CVal >= -7 && CVal < 7)
3397             break;
3398         } else if (Subtarget->isThumb2()) {
3399           // A constant whose negation can be used as an immediate value in a
3400           // data-processing instruction. This can be used in GCC with an "n"
3401           // modifier that prints the negated value, for use with SUB
3402           // instructions. It is not useful otherwise but is implemented for
3403           // compatibility.
3404           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
3405             break;
3406         } else {
3407           // A constant whose negation can be used as an immediate value in a
3408           // data-processing instruction. This can be used in GCC with an "n"
3409           // modifier that prints the negated value, for use with SUB
3410           // instructions. It is not useful otherwise but is implemented for
3411           // compatibility.
3412           if (ARM_AM::getSOImmVal(-CVal) != -1)
3413             break;
3414         }
3415         return;
3416
3417       case 'M':
3418         if (Subtarget->isThumb()) { // FIXME thumb2
3419           // This must be a multiple of 4 between 0 and 1020, for
3420           // ADD sp + immediate.
3421           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
3422             break;
3423         } else {
3424           // A power of two or a constant between 0 and 32.  This is used in
3425           // GCC for the shift amount on shifted register operands, but it is
3426           // useful in general for any shift amounts.
3427           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
3428             break;
3429         }
3430         return;
3431
3432       case 'N':
3433         if (Subtarget->isThumb()) {  // FIXME thumb2
3434           // This must be a constant between 0 and 31, for shift amounts.
3435           if (CVal >= 0 && CVal <= 31)
3436             break;
3437         }
3438         return;
3439
3440       case 'O':
3441         if (Subtarget->isThumb()) {  // FIXME thumb2
3442           // This must be a multiple of 4 between -508 and 508, for
3443           // ADD/SUB sp = sp + immediate.
3444           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
3445             break;
3446         }
3447         return;
3448     }
3449     Result = DAG.getTargetConstant(CVal, Op.getValueType());
3450     break;
3451   }
3452
3453   if (Result.getNode()) {
3454     Ops.push_back(Result);
3455     return;
3456   }
3457   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
3458                                                       Ops, DAG);
3459 }