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