5c604a92cf422e8318b8275eda80a544c0880224
[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::RET_FLAG:      return "ARMISD::RET_FLAG";
406   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
407   case ARMISD::CMP:           return "ARMISD::CMP";
408   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
409   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
410   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
411   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
412   case ARMISD::CMOV:          return "ARMISD::CMOV";
413   case ARMISD::CNEG:          return "ARMISD::CNEG";
414
415   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
416   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
417   case ARMISD::SITOF:         return "ARMISD::SITOF";
418   case ARMISD::UITOF:         return "ARMISD::UITOF";
419
420   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
421   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
422   case ARMISD::RRX:           return "ARMISD::RRX";
423
424   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
425   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
426
427   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
428
429   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
430   case ARMISD::VCGE:          return "ARMISD::VCGE";
431   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
432   case ARMISD::VCGT:          return "ARMISD::VCGT";
433   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
434   case ARMISD::VTST:          return "ARMISD::VTST";
435
436   case ARMISD::VSHL:          return "ARMISD::VSHL";
437   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
438   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
439   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
440   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
441   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
442   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
443   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
444   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
445   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
446   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
447   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
448   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
449   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
450   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
451   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
452   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
453   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
454   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
455   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
456   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
457   case ARMISD::VDUPLANEQ:     return "ARMISD::VDUPLANEQ";
458   }
459 }
460
461 /// getFunctionAlignment - Return the Log2 alignment of this function.
462 unsigned ARMTargetLowering::getFunctionAlignment(const Function *F) const {
463   return getTargetMachine().getSubtarget<ARMSubtarget>().isThumb() ? 1 : 2;
464 }
465
466 //===----------------------------------------------------------------------===//
467 // Lowering Code
468 //===----------------------------------------------------------------------===//
469
470 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
471 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
472   switch (CC) {
473   default: assert(0 && "Unknown condition code!");
474   case ISD::SETNE:  return ARMCC::NE;
475   case ISD::SETEQ:  return ARMCC::EQ;
476   case ISD::SETGT:  return ARMCC::GT;
477   case ISD::SETGE:  return ARMCC::GE;
478   case ISD::SETLT:  return ARMCC::LT;
479   case ISD::SETLE:  return ARMCC::LE;
480   case ISD::SETUGT: return ARMCC::HI;
481   case ISD::SETUGE: return ARMCC::HS;
482   case ISD::SETULT: return ARMCC::LO;
483   case ISD::SETULE: return ARMCC::LS;
484   }
485 }
486
487 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
488 /// returns true if the operands should be inverted to form the proper
489 /// comparison.
490 static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
491                         ARMCC::CondCodes &CondCode2) {
492   bool Invert = false;
493   CondCode2 = ARMCC::AL;
494   switch (CC) {
495   default: assert(0 && "Unknown FP condition!");
496   case ISD::SETEQ:
497   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
498   case ISD::SETGT:
499   case ISD::SETOGT: CondCode = ARMCC::GT; break;
500   case ISD::SETGE:
501   case ISD::SETOGE: CondCode = ARMCC::GE; break;
502   case ISD::SETOLT: CondCode = ARMCC::MI; break;
503   case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
504   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
505   case ISD::SETO:   CondCode = ARMCC::VC; break;
506   case ISD::SETUO:  CondCode = ARMCC::VS; break;
507   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
508   case ISD::SETUGT: CondCode = ARMCC::HI; break;
509   case ISD::SETUGE: CondCode = ARMCC::PL; break;
510   case ISD::SETLT:
511   case ISD::SETULT: CondCode = ARMCC::LT; break;
512   case ISD::SETLE:
513   case ISD::SETULE: CondCode = ARMCC::LE; break;
514   case ISD::SETNE:
515   case ISD::SETUNE: CondCode = ARMCC::NE; break;
516   }
517   return Invert;
518 }
519
520 //===----------------------------------------------------------------------===//
521 //                      Calling Convention Implementation
522 //
523 //  The lower operations present on calling convention works on this order:
524 //      LowerCALL (virt regs --> phys regs, virt regs --> stack)
525 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
526 //      LowerRET (virt regs --> phys regs)
527 //      LowerCALL (phys regs --> virt regs)
528 //
529 //===----------------------------------------------------------------------===//
530
531 #include "ARMGenCallingConv.inc"
532
533 // APCS f64 is in register pairs, possibly split to stack
534 static bool f64AssignAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
535                           CCValAssign::LocInfo &LocInfo,
536                           CCState &State, bool CanFail) {
537   static const unsigned RegList[] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 };
538
539   // Try to get the first register.
540   if (unsigned Reg = State.AllocateReg(RegList, 4))
541     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
542   else {
543     // For the 2nd half of a v2f64, do not fail.
544     if (CanFail)
545       return false;
546
547     // Put the whole thing on the stack.
548     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
549                                            State.AllocateStack(8, 4),
550                                            LocVT, LocInfo));
551     return true;
552   }
553
554   // Try to get the second register.
555   if (unsigned Reg = State.AllocateReg(RegList, 4))
556     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
557   else
558     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
559                                            State.AllocateStack(4, 4),
560                                            LocVT, LocInfo));
561   return true;
562 }
563
564 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
565                                    CCValAssign::LocInfo &LocInfo,
566                                    ISD::ArgFlagsTy &ArgFlags,
567                                    CCState &State) {
568   if (!f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
569     return false;
570   if (LocVT == MVT::v2f64 &&
571       !f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
572     return false;
573   return true;  // we handled it
574 }
575
576 // AAPCS f64 is in aligned register pairs
577 static bool f64AssignAAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
578                            CCValAssign::LocInfo &LocInfo,
579                            CCState &State, bool CanFail) {
580   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
581   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
582
583   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
584   if (Reg == 0) {
585     // For the 2nd half of a v2f64, do not just fail.
586     if (CanFail)
587       return false;
588
589     // Put the whole thing on the stack.
590     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
591                                            State.AllocateStack(8, 8),
592                                            LocVT, LocInfo));
593     return true;
594   }
595
596   unsigned i;
597   for (i = 0; i < 2; ++i)
598     if (HiRegList[i] == Reg)
599       break;
600
601   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
602   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
603                                          LocVT, LocInfo));
604   return true;
605 }
606
607 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
608                                     CCValAssign::LocInfo &LocInfo,
609                                     ISD::ArgFlagsTy &ArgFlags,
610                                     CCState &State) {
611   if (!f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
612     return false;
613   if (LocVT == MVT::v2f64 &&
614       !f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
615     return false;
616   return true;  // we handled it
617 }
618
619 static bool f64RetAssign(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
620                          CCValAssign::LocInfo &LocInfo, CCState &State) {
621   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
622   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
623
624   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
625   if (Reg == 0)
626     return false; // we didn't handle it
627
628   unsigned i;
629   for (i = 0; i < 2; ++i)
630     if (HiRegList[i] == Reg)
631       break;
632
633   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
634   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
635                                          LocVT, LocInfo));
636   return true;
637 }
638
639 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
640                                       CCValAssign::LocInfo &LocInfo,
641                                       ISD::ArgFlagsTy &ArgFlags,
642                                       CCState &State) {
643   if (!f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
644     return false;
645   if (LocVT == MVT::v2f64 && !f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
646     return false;
647   return true;  // we handled it
648 }
649
650 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
651                                        CCValAssign::LocInfo &LocInfo,
652                                        ISD::ArgFlagsTy &ArgFlags,
653                                        CCState &State) {
654   return RetCC_ARM_APCS_Custom_f64(ValNo, ValVT, LocVT, LocInfo, ArgFlags,
655                                    State);
656 }
657
658 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
659 /// given CallingConvention value.
660 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(unsigned CC,
661                                                  bool Return) const {
662   switch (CC) {
663   default:
664    assert(0 && "Unsupported calling convention");
665   case CallingConv::C:
666   case CallingConv::Fast:
667    // Use target triple & subtarget features to do actual dispatch.
668    if (Subtarget->isAAPCS_ABI()) {
669      if (Subtarget->hasVFP2() &&
670          FloatABIType == FloatABI::Hard)
671        return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
672      else
673        return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
674    } else
675      return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
676   case CallingConv::ARM_AAPCS_VFP:
677    return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
678   case CallingConv::ARM_AAPCS:
679    return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
680   case CallingConv::ARM_APCS:
681    return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
682   }
683 }
684
685 /// LowerCallResult - Lower the result values of an ISD::CALL into the
686 /// appropriate copies out of appropriate physical registers.  This assumes that
687 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
688 /// being lowered.  The returns a SDNode with the same number of values as the
689 /// ISD::CALL.
690 SDNode *ARMTargetLowering::
691 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
692                 unsigned CallingConv, SelectionDAG &DAG) {
693
694   DebugLoc dl = TheCall->getDebugLoc();
695   // Assign locations to each value returned by this call.
696   SmallVector<CCValAssign, 16> RVLocs;
697   bool isVarArg = TheCall->isVarArg();
698   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
699                  RVLocs, DAG.getContext());
700   CCInfo.AnalyzeCallResult(TheCall,
701                            CCAssignFnForNode(CallingConv, /* Return*/ true));
702
703   SmallVector<SDValue, 8> ResultVals;
704
705   // Copy all of the result registers out of their specified physreg.
706   for (unsigned i = 0; i != RVLocs.size(); ++i) {
707     CCValAssign VA = RVLocs[i];
708
709     SDValue Val;
710     if (VA.needsCustom()) {
711       // Handle f64 or half of a v2f64.
712       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
713                                       InFlag);
714       Chain = Lo.getValue(1);
715       InFlag = Lo.getValue(2);
716       VA = RVLocs[++i]; // skip ahead to next loc
717       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
718                                       InFlag);
719       Chain = Hi.getValue(1);
720       InFlag = Hi.getValue(2);
721       Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
722
723       if (VA.getLocVT() == MVT::v2f64) {
724         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
725         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
726                           DAG.getConstant(0, MVT::i32));
727
728         VA = RVLocs[++i]; // skip ahead to next loc
729         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
730         Chain = Lo.getValue(1);
731         InFlag = Lo.getValue(2);
732         VA = RVLocs[++i]; // skip ahead to next loc
733         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
734         Chain = Hi.getValue(1);
735         InFlag = Hi.getValue(2);
736         Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
737         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
738                           DAG.getConstant(1, MVT::i32));
739       }
740     } else {
741       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
742                                InFlag);
743       Chain = Val.getValue(1);
744       InFlag = Val.getValue(2);
745     }
746
747     switch (VA.getLocInfo()) {
748     default: assert(0 && "Unknown loc info!");
749     case CCValAssign::Full: break;
750     case CCValAssign::BCvt:
751       Val = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), Val);
752       break;
753     }
754
755     ResultVals.push_back(Val);
756   }
757
758   // Merge everything together with a MERGE_VALUES node.
759   ResultVals.push_back(Chain);
760   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
761                      &ResultVals[0], ResultVals.size()).getNode();
762 }
763
764 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
765 /// by "Src" to address "Dst" of size "Size".  Alignment information is
766 /// specified by the specific parameter attribute.  The copy will be passed as
767 /// a byval function parameter.
768 /// Sometimes what we are copying is the end of a larger object, the part that
769 /// does not fit in registers.
770 static SDValue
771 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
772                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
773                           DebugLoc dl) {
774   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
775   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
776                        /*AlwaysInline=*/false, NULL, 0, NULL, 0);
777 }
778
779 /// LowerMemOpCallTo - Store the argument to the stack.
780 SDValue
781 ARMTargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
782                                     const SDValue &StackPtr,
783                                     const CCValAssign &VA, SDValue Chain,
784                                     SDValue Arg, ISD::ArgFlagsTy Flags) {
785   DebugLoc dl = TheCall->getDebugLoc();
786   unsigned LocMemOffset = VA.getLocMemOffset();
787   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
788   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
789   if (Flags.isByVal()) {
790     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
791   }
792   return DAG.getStore(Chain, dl, Arg, PtrOff,
793                       PseudoSourceValue::getStack(), LocMemOffset);
794 }
795
796 void ARMTargetLowering::PassF64ArgInRegs(CallSDNode *TheCall, SelectionDAG &DAG,
797                                          SDValue Chain, SDValue &Arg,
798                                          RegsToPassVector &RegsToPass,
799                                          CCValAssign &VA, CCValAssign &NextVA,
800                                          SDValue &StackPtr,
801                                          SmallVector<SDValue, 8> &MemOpChains,
802                                          ISD::ArgFlagsTy Flags) {
803   DebugLoc dl = TheCall->getDebugLoc();
804
805   SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
806                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
807   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
808
809   if (NextVA.isRegLoc())
810     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
811   else {
812     assert(NextVA.isMemLoc());
813     if (StackPtr.getNode() == 0)
814       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
815
816     MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, NextVA,
817                                            Chain, fmrrd.getValue(1), Flags));
818   }
819 }
820
821 /// LowerCALL - Lowering a ISD::CALL node into a callseq_start <-
822 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
823 /// nodes.
824 SDValue ARMTargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
825   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
826   MVT RetVT           = TheCall->getRetValType(0);
827   SDValue Chain       = TheCall->getChain();
828   unsigned CC         = TheCall->getCallingConv();
829   bool isVarArg       = TheCall->isVarArg();
830   SDValue Callee      = TheCall->getCallee();
831   DebugLoc dl         = TheCall->getDebugLoc();
832
833   // Analyze operands of the call, assigning locations to each operand.
834   SmallVector<CCValAssign, 16> ArgLocs;
835   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
836   CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC, /* Return*/ false));
837
838   // Get a count of how many bytes are to be pushed on the stack.
839   unsigned NumBytes = CCInfo.getNextStackOffset();
840
841   // Adjust the stack pointer for the new arguments...
842   // These operations are automatically eliminated by the prolog/epilog pass
843   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
844
845   SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
846
847   RegsToPassVector RegsToPass;
848   SmallVector<SDValue, 8> MemOpChains;
849
850   // Walk the register/memloc assignments, inserting copies/loads.  In the case
851   // of tail call optimization, arguments are handled later.
852   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
853        i != e;
854        ++i, ++realArgIdx) {
855     CCValAssign &VA = ArgLocs[i];
856     SDValue Arg = TheCall->getArg(realArgIdx);
857     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(realArgIdx);
858
859     // Promote the value if needed.
860     switch (VA.getLocInfo()) {
861     default: assert(0 && "Unknown loc info!");
862     case CCValAssign::Full: break;
863     case CCValAssign::SExt:
864       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
865       break;
866     case CCValAssign::ZExt:
867       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
868       break;
869     case CCValAssign::AExt:
870       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
871       break;
872     case CCValAssign::BCvt:
873       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
874       break;
875     }
876
877     // f64 and v2f64 are passed in i32 pairs and must be split into pieces
878     if (VA.needsCustom()) {
879       if (VA.getLocVT() == MVT::v2f64) {
880         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
881                                   DAG.getConstant(0, MVT::i32));
882         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
883                                   DAG.getConstant(1, MVT::i32));
884
885         PassF64ArgInRegs(TheCall, DAG, Chain, Op0, RegsToPass,
886                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
887
888         VA = ArgLocs[++i]; // skip ahead to next loc
889         if (VA.isRegLoc()) {
890           PassF64ArgInRegs(TheCall, DAG, Chain, Op1, RegsToPass,
891                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
892         } else {
893           assert(VA.isMemLoc());
894           if (StackPtr.getNode() == 0)
895             StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
896
897           MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
898                                                  Chain, Op1, Flags));
899         }
900       } else {
901         PassF64ArgInRegs(TheCall, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
902                          StackPtr, MemOpChains, Flags);
903       }
904     } else if (VA.isRegLoc()) {
905       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
906     } else {
907       assert(VA.isMemLoc());
908       if (StackPtr.getNode() == 0)
909         StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
910
911       MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
912                                              Chain, Arg, Flags));
913     }
914   }
915
916   if (!MemOpChains.empty())
917     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
918                         &MemOpChains[0], MemOpChains.size());
919
920   // Build a sequence of copy-to-reg nodes chained together with token chain
921   // and flag operands which copy the outgoing args into the appropriate regs.
922   SDValue InFlag;
923   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
924     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
925                              RegsToPass[i].second, InFlag);
926     InFlag = Chain.getValue(1);
927   }
928
929   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
930   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
931   // node so that legalize doesn't hack it.
932   bool isDirect = false;
933   bool isARMFunc = false;
934   bool isLocalARMFunc = false;
935   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
936     GlobalValue *GV = G->getGlobal();
937     isDirect = true;
938     bool isExt = (GV->isDeclaration() || GV->hasWeakLinkage() ||
939                   GV->hasLinkOnceLinkage());
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: assert(0 && "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 countpart 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->hasNotBeenReadFromBitcode();
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: assert(0 && "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   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1709   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1710   bool isPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1711   Addr = DAG.getLoad(isPIC ? (MVT)MVT::i32 : PTy, dl,
1712                      Chain, Addr, NULL, 0);
1713   Chain = Addr.getValue(1);
1714   if (isPIC)
1715     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1716   return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1717 }
1718
1719 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1720   DebugLoc dl = Op.getDebugLoc();
1721   unsigned Opc =
1722     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1723   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1724   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1725 }
1726
1727 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1728   MVT VT = Op.getValueType();
1729   DebugLoc dl = Op.getDebugLoc();
1730   unsigned Opc =
1731     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1732
1733   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1734   return DAG.getNode(Opc, dl, VT, Op);
1735 }
1736
1737 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1738   // Implement fcopysign with a fabs and a conditional fneg.
1739   SDValue Tmp0 = Op.getOperand(0);
1740   SDValue Tmp1 = Op.getOperand(1);
1741   DebugLoc dl = Op.getDebugLoc();
1742   MVT VT = Op.getValueType();
1743   MVT SrcVT = Tmp1.getValueType();
1744   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1745   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1746   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1747   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1748   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1749 }
1750
1751 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1752   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1753   MFI->setFrameAddressIsTaken(true);
1754   MVT VT = Op.getValueType();
1755   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1756   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1757   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
1758     ? ARM::R7 : ARM::R11;
1759   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1760   while (Depth--)
1761     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1762   return FrameAddr;
1763 }
1764
1765 SDValue
1766 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1767                                            SDValue Chain,
1768                                            SDValue Dst, SDValue Src,
1769                                            SDValue Size, unsigned Align,
1770                                            bool AlwaysInline,
1771                                          const Value *DstSV, uint64_t DstSVOff,
1772                                          const Value *SrcSV, uint64_t SrcSVOff){
1773   // Do repeated 4-byte loads and stores. To be improved.
1774   // This requires 4-byte alignment.
1775   if ((Align & 3) != 0)
1776     return SDValue();
1777   // This requires the copy size to be a constant, preferrably
1778   // within a subtarget-specific limit.
1779   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1780   if (!ConstantSize)
1781     return SDValue();
1782   uint64_t SizeVal = ConstantSize->getZExtValue();
1783   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1784     return SDValue();
1785
1786   unsigned BytesLeft = SizeVal & 3;
1787   unsigned NumMemOps = SizeVal >> 2;
1788   unsigned EmittedNumMemOps = 0;
1789   MVT VT = MVT::i32;
1790   unsigned VTSize = 4;
1791   unsigned i = 0;
1792   const unsigned MAX_LOADS_IN_LDM = 6;
1793   SDValue TFOps[MAX_LOADS_IN_LDM];
1794   SDValue Loads[MAX_LOADS_IN_LDM];
1795   uint64_t SrcOff = 0, DstOff = 0;
1796
1797   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1798   // same number of stores.  The loads and stores will get combined into
1799   // ldm/stm later on.
1800   while (EmittedNumMemOps < NumMemOps) {
1801     for (i = 0;
1802          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1803       Loads[i] = DAG.getLoad(VT, dl, Chain,
1804                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1805                                          DAG.getConstant(SrcOff, MVT::i32)),
1806                              SrcSV, SrcSVOff + SrcOff);
1807       TFOps[i] = Loads[i].getValue(1);
1808       SrcOff += VTSize;
1809     }
1810     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1811
1812     for (i = 0;
1813          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1814       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1815                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1816                                        DAG.getConstant(DstOff, MVT::i32)),
1817                            DstSV, DstSVOff + DstOff);
1818       DstOff += VTSize;
1819     }
1820     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1821
1822     EmittedNumMemOps += i;
1823   }
1824
1825   if (BytesLeft == 0)
1826     return Chain;
1827
1828   // Issue loads / stores for the trailing (1 - 3) bytes.
1829   unsigned BytesLeftSave = BytesLeft;
1830   i = 0;
1831   while (BytesLeft) {
1832     if (BytesLeft >= 2) {
1833       VT = MVT::i16;
1834       VTSize = 2;
1835     } else {
1836       VT = MVT::i8;
1837       VTSize = 1;
1838     }
1839
1840     Loads[i] = DAG.getLoad(VT, dl, Chain,
1841                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1842                                        DAG.getConstant(SrcOff, MVT::i32)),
1843                            SrcSV, SrcSVOff + SrcOff);
1844     TFOps[i] = Loads[i].getValue(1);
1845     ++i;
1846     SrcOff += VTSize;
1847     BytesLeft -= VTSize;
1848   }
1849   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1850
1851   i = 0;
1852   BytesLeft = BytesLeftSave;
1853   while (BytesLeft) {
1854     if (BytesLeft >= 2) {
1855       VT = MVT::i16;
1856       VTSize = 2;
1857     } else {
1858       VT = MVT::i8;
1859       VTSize = 1;
1860     }
1861
1862     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1863                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1864                                         DAG.getConstant(DstOff, MVT::i32)),
1865                             DstSV, DstSVOff + DstOff);
1866     ++i;
1867     DstOff += VTSize;
1868     BytesLeft -= VTSize;
1869   }
1870   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1871 }
1872
1873 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1874   SDValue Op = N->getOperand(0);
1875   DebugLoc dl = N->getDebugLoc();
1876   if (N->getValueType(0) == MVT::f64) {
1877     // Turn i64->f64 into FMDRR.
1878     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1879                              DAG.getConstant(0, MVT::i32));
1880     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1881                              DAG.getConstant(1, MVT::i32));
1882     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
1883   }
1884
1885   // Turn f64->i64 into FMRRD.
1886   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
1887                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
1888
1889   // Merge the pieces into a single i64 value.
1890   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
1891 }
1892
1893 /// getZeroVector - Returns a vector of specified type with all zero elements.
1894 ///
1895 static SDValue getZeroVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
1896   assert(VT.isVector() && "Expected a vector type");
1897
1898   // Zero vectors are used to represent vector negation and in those cases
1899   // will be implemented with the NEON VNEG instruction.  However, VNEG does
1900   // not support i64 elements, so sometimes the zero vectors will need to be
1901   // explicitly constructed.  For those cases, and potentially other uses in
1902   // the future, always build zero vectors as <4 x i32> or <2 x i32> bitcasted
1903   // to their dest type.  This ensures they get CSE'd.
1904   SDValue Vec;
1905   SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
1906   if (VT.getSizeInBits() == 64)
1907     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
1908   else
1909     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
1910
1911   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
1912 }
1913
1914 /// getOnesVector - Returns a vector of specified type with all bits set.
1915 ///
1916 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
1917   assert(VT.isVector() && "Expected a vector type");
1918
1919   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
1920   // type.  This ensures they get CSE'd.
1921   SDValue Vec;
1922   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
1923   if (VT.getSizeInBits() == 64)
1924     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
1925   else
1926     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
1927
1928   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
1929 }
1930
1931 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
1932                           const ARMSubtarget *ST) {
1933   MVT VT = N->getValueType(0);
1934   DebugLoc dl = N->getDebugLoc();
1935
1936   // Lower vector shifts on NEON to use VSHL.
1937   if (VT.isVector()) {
1938     assert(ST->hasNEON() && "unexpected vector shift");
1939
1940     // Left shifts translate directly to the vshiftu intrinsic.
1941     if (N->getOpcode() == ISD::SHL)
1942       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
1943                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
1944                          N->getOperand(0), N->getOperand(1));
1945
1946     assert((N->getOpcode() == ISD::SRA ||
1947             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
1948
1949     // NEON uses the same intrinsics for both left and right shifts.  For
1950     // right shifts, the shift amounts are negative, so negate the vector of
1951     // shift amounts.
1952     MVT ShiftVT = N->getOperand(1).getValueType();
1953     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
1954                                        getZeroVector(ShiftVT, DAG, dl),
1955                                        N->getOperand(1));
1956     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
1957                                Intrinsic::arm_neon_vshifts :
1958                                Intrinsic::arm_neon_vshiftu);
1959     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
1960                        DAG.getConstant(vshiftInt, MVT::i32),
1961                        N->getOperand(0), NegatedCount);
1962   }
1963
1964   assert(VT == MVT::i64 &&
1965          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
1966          "Unknown shift to lower!");
1967
1968   // We only lower SRA, SRL of 1 here, all others use generic lowering.
1969   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
1970       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
1971     return SDValue();
1972
1973   // If we are in thumb mode, we don't have RRX.
1974   if (ST->isThumb1Only()) return SDValue();
1975
1976   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
1977   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
1978                              DAG.getConstant(0, MVT::i32));
1979   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
1980                              DAG.getConstant(1, MVT::i32));
1981
1982   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
1983   // captures the result into a carry flag.
1984   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
1985   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
1986
1987   // The low part is an ARMISD::RRX operand, which shifts the carry in.
1988   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
1989
1990   // Merge the pieces into a single i64 value.
1991  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1992 }
1993
1994 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
1995   SDValue TmpOp0, TmpOp1;
1996   bool Invert = false;
1997   bool Swap = false;
1998   unsigned Opc = 0;
1999
2000   SDValue Op0 = Op.getOperand(0);
2001   SDValue Op1 = Op.getOperand(1);
2002   SDValue CC = Op.getOperand(2);
2003   MVT VT = Op.getValueType();
2004   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2005   DebugLoc dl = Op.getDebugLoc();
2006
2007   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2008     switch (SetCCOpcode) {
2009     default: assert(0 && "Illegal FP comparison"); break;
2010     case ISD::SETUNE:
2011     case ISD::SETNE:  Invert = true; // Fallthrough
2012     case ISD::SETOEQ:
2013     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2014     case ISD::SETOLT:
2015     case ISD::SETLT: Swap = true; // Fallthrough
2016     case ISD::SETOGT:
2017     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2018     case ISD::SETOLE:
2019     case ISD::SETLE:  Swap = true; // Fallthrough
2020     case ISD::SETOGE:
2021     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2022     case ISD::SETUGE: Swap = true; // Fallthrough
2023     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2024     case ISD::SETUGT: Swap = true; // Fallthrough
2025     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2026     case ISD::SETUEQ: Invert = true; // Fallthrough
2027     case ISD::SETONE:
2028       // Expand this to (OLT | OGT).
2029       TmpOp0 = Op0;
2030       TmpOp1 = Op1;
2031       Opc = ISD::OR;
2032       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2033       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2034       break;
2035     case ISD::SETUO: Invert = true; // Fallthrough
2036     case ISD::SETO:
2037       // Expand this to (OLT | OGE).
2038       TmpOp0 = Op0;
2039       TmpOp1 = Op1;
2040       Opc = ISD::OR;
2041       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2042       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2043       break;
2044     }
2045   } else {
2046     // Integer comparisons.
2047     switch (SetCCOpcode) {
2048     default: assert(0 && "Illegal integer comparison"); break;
2049     case ISD::SETNE:  Invert = true;
2050     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2051     case ISD::SETLT:  Swap = true;
2052     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2053     case ISD::SETLE:  Swap = true;
2054     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2055     case ISD::SETULT: Swap = true;
2056     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2057     case ISD::SETULE: Swap = true;
2058     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2059     }
2060
2061     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2062     if (Opc == ARMISD::VCEQ) {
2063
2064       SDValue AndOp;
2065       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2066         AndOp = Op0;
2067       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2068         AndOp = Op1;
2069
2070       // Ignore bitconvert.
2071       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2072         AndOp = AndOp.getOperand(0);
2073
2074       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2075         Opc = ARMISD::VTST;
2076         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2077         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2078         Invert = !Invert;
2079       }
2080     }
2081   }
2082
2083   if (Swap)
2084     std::swap(Op0, Op1);
2085
2086   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2087
2088   if (Invert)
2089     Result = DAG.getNOT(dl, Result, VT);
2090
2091   return Result;
2092 }
2093
2094 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2095 /// VMOV instruction, and if so, return the constant being splatted.
2096 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2097                            unsigned SplatBitSize, SelectionDAG &DAG) {
2098   switch (SplatBitSize) {
2099   case 8:
2100     // Any 1-byte value is OK.
2101     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2102     return DAG.getTargetConstant(SplatBits, MVT::i8);
2103
2104   case 16:
2105     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2106     if ((SplatBits & ~0xff) == 0 ||
2107         (SplatBits & ~0xff00) == 0)
2108       return DAG.getTargetConstant(SplatBits, MVT::i16);
2109     break;
2110
2111   case 32:
2112     // NEON's 32-bit VMOV supports splat values where:
2113     // * only one byte is nonzero, or
2114     // * the least significant byte is 0xff and the second byte is nonzero, or
2115     // * the least significant 2 bytes are 0xff and the third is nonzero.
2116     if ((SplatBits & ~0xff) == 0 ||
2117         (SplatBits & ~0xff00) == 0 ||
2118         (SplatBits & ~0xff0000) == 0 ||
2119         (SplatBits & ~0xff000000) == 0)
2120       return DAG.getTargetConstant(SplatBits, MVT::i32);
2121
2122     if ((SplatBits & ~0xffff) == 0 &&
2123         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2124       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2125
2126     if ((SplatBits & ~0xffffff) == 0 &&
2127         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2128       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2129
2130     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2131     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2132     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2133     // and fall through here to test for a valid 64-bit splat.  But, then the
2134     // caller would also need to check and handle the change in size.
2135     break;
2136
2137   case 64: {
2138     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2139     uint64_t BitMask = 0xff;
2140     uint64_t Val = 0;
2141     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2142       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2143         Val |= BitMask;
2144       else if ((SplatBits & BitMask) != 0)
2145         return SDValue();
2146       BitMask <<= 8;
2147     }
2148     return DAG.getTargetConstant(Val, MVT::i64);
2149   }
2150
2151   default:
2152     assert(0 && "unexpected size for isVMOVSplat");
2153     break;
2154   }
2155
2156   return SDValue();
2157 }
2158
2159 /// getVMOVImm - If this is a build_vector of constants which can be
2160 /// formed by using a VMOV instruction of the specified element size,
2161 /// return the constant being splatted.  The ByteSize field indicates the
2162 /// number of bytes of each element [1248].
2163 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2164   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2165   APInt SplatBits, SplatUndef;
2166   unsigned SplatBitSize;
2167   bool HasAnyUndefs;
2168   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2169                                       HasAnyUndefs, ByteSize * 8))
2170     return SDValue();
2171
2172   if (SplatBitSize > ByteSize * 8)
2173     return SDValue();
2174
2175   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2176                      SplatBitSize, DAG);
2177 }
2178
2179 static SDValue BuildSplat(SDValue Val, MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2180   // Canonicalize all-zeros and all-ones vectors.
2181   ConstantSDNode *ConstVal = dyn_cast<ConstantSDNode>(Val.getNode());
2182   if (ConstVal->isNullValue())
2183     return getZeroVector(VT, DAG, dl);
2184   if (ConstVal->isAllOnesValue())
2185     return getOnesVector(VT, DAG, dl);
2186
2187   MVT CanonicalVT;
2188   if (VT.is64BitVector()) {
2189     switch (Val.getValueType().getSizeInBits()) {
2190     case 8:  CanonicalVT = MVT::v8i8; break;
2191     case 16: CanonicalVT = MVT::v4i16; break;
2192     case 32: CanonicalVT = MVT::v2i32; break;
2193     case 64: CanonicalVT = MVT::v1i64; break;
2194     default: assert(0 && "unexpected splat element type"); break;
2195     }
2196   } else {
2197     assert(VT.is128BitVector() && "unknown splat vector size");
2198     switch (Val.getValueType().getSizeInBits()) {
2199     case 8:  CanonicalVT = MVT::v16i8; break;
2200     case 16: CanonicalVT = MVT::v8i16; break;
2201     case 32: CanonicalVT = MVT::v4i32; break;
2202     case 64: CanonicalVT = MVT::v2i64; break;
2203     default: assert(0 && "unexpected splat element type"); break;
2204     }
2205   }
2206
2207   // Build a canonical splat for this value.
2208   SmallVector<SDValue, 8> Ops;
2209   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2210   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2211                             Ops.size());
2212   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2213 }
2214
2215 // If this is a case we can't handle, return null and let the default
2216 // expansion code take care of it.
2217 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2218   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2219   assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
2220   DebugLoc dl = Op.getDebugLoc();
2221
2222   APInt SplatBits, SplatUndef;
2223   unsigned SplatBitSize;
2224   bool HasAnyUndefs;
2225   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2226     SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2227                               SplatUndef.getZExtValue(), SplatBitSize, DAG);
2228     if (Val.getNode())
2229       return BuildSplat(Val, Op.getValueType(), DAG, dl);
2230   }
2231
2232   return SDValue();
2233 }
2234
2235 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2236   return Op;
2237 }
2238
2239 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
2240   return Op;
2241 }
2242
2243 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
2244   MVT VT = Op.getValueType();
2245   DebugLoc dl = Op.getDebugLoc();
2246   assert((VT == MVT::i8 || VT == MVT::i16) &&
2247          "unexpected type for custom-lowering vector extract");
2248   SDValue Vec = Op.getOperand(0);
2249   SDValue Lane = Op.getOperand(1);
2250   Op = DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
2251   Op = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Op, DAG.getValueType(VT));
2252   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
2253 }
2254
2255 static SDValue LowerCONCAT_VECTORS(SDValue Op) {
2256   if (Op.getValueType().is128BitVector() && Op.getNumOperands() == 2)
2257     return Op;
2258   return SDValue();
2259 }
2260
2261 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
2262   switch (Op.getOpcode()) {
2263   default: LLVM_UNREACHABLE("Don't know how to custom lower this!");
2264   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
2265   case ISD::GlobalAddress:
2266     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
2267       LowerGlobalAddressELF(Op, DAG);
2268   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2269   case ISD::CALL:          return LowerCALL(Op, DAG);
2270   case ISD::RET:           return LowerRET(Op, DAG);
2271   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
2272   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
2273   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
2274   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
2275   case ISD::SINT_TO_FP:
2276   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
2277   case ISD::FP_TO_SINT:
2278   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
2279   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
2280   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
2281   case ISD::RETURNADDR:    break;
2282   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2283   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2284   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2285   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
2286   case ISD::SHL:
2287   case ISD::SRL:
2288   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
2289   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
2290   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
2291   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2292   case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
2293   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2294   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op);
2295   }
2296   return SDValue();
2297 }
2298
2299 /// ReplaceNodeResults - Replace the results of node with an illegal result
2300 /// type with new values built out of custom code.
2301 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
2302                                            SmallVectorImpl<SDValue>&Results,
2303                                            SelectionDAG &DAG) {
2304   switch (N->getOpcode()) {
2305   default:
2306     assert(0 && "Don't know how to custom expand this!");
2307     return;
2308   case ISD::BIT_CONVERT:
2309     Results.push_back(ExpandBIT_CONVERT(N, DAG));
2310     return;
2311   case ISD::SRL:
2312   case ISD::SRA: {
2313     SDValue Res = LowerShift(N, DAG, Subtarget);
2314     if (Res.getNode())
2315       Results.push_back(Res);
2316     return;
2317   }
2318   }
2319 }
2320
2321 //===----------------------------------------------------------------------===//
2322 //                           ARM Scheduler Hooks
2323 //===----------------------------------------------------------------------===//
2324
2325 MachineBasicBlock *
2326 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2327                                                MachineBasicBlock *BB) const {
2328   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2329   DebugLoc dl = MI->getDebugLoc();
2330   switch (MI->getOpcode()) {
2331   default: assert(false && "Unexpected instr type to insert");
2332   case ARM::tMOVCCr: {
2333     // To "insert" a SELECT_CC instruction, we actually have to insert the
2334     // diamond control-flow pattern.  The incoming instruction knows the
2335     // destination vreg to set, the condition code register to branch on, the
2336     // true/false values to select between, and a branch opcode to use.
2337     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2338     MachineFunction::iterator It = BB;
2339     ++It;
2340
2341     //  thisMBB:
2342     //  ...
2343     //   TrueVal = ...
2344     //   cmpTY ccX, r1, r2
2345     //   bCC copy1MBB
2346     //   fallthrough --> copy0MBB
2347     MachineBasicBlock *thisMBB  = BB;
2348     MachineFunction *F = BB->getParent();
2349     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2350     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
2351     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
2352       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
2353     F->insert(It, copy0MBB);
2354     F->insert(It, sinkMBB);
2355     // Update machine-CFG edges by first adding all successors of the current
2356     // block to the new block which will contain the Phi node for the select.
2357     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
2358         e = BB->succ_end(); i != e; ++i)
2359       sinkMBB->addSuccessor(*i);
2360     // Next, remove all successors of the current block, and add the true
2361     // and fallthrough blocks as its successors.
2362     while(!BB->succ_empty())
2363       BB->removeSuccessor(BB->succ_begin());
2364     BB->addSuccessor(copy0MBB);
2365     BB->addSuccessor(sinkMBB);
2366
2367     //  copy0MBB:
2368     //   %FalseValue = ...
2369     //   # fallthrough to sinkMBB
2370     BB = copy0MBB;
2371
2372     // Update machine-CFG edges
2373     BB->addSuccessor(sinkMBB);
2374
2375     //  sinkMBB:
2376     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2377     //  ...
2378     BB = sinkMBB;
2379     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
2380       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
2381       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
2382
2383     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2384     return BB;
2385   }
2386   }
2387 }
2388
2389 //===----------------------------------------------------------------------===//
2390 //                           ARM Optimization Hooks
2391 //===----------------------------------------------------------------------===//
2392
2393 static
2394 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
2395                             TargetLowering::DAGCombinerInfo &DCI) {
2396   SelectionDAG &DAG = DCI.DAG;
2397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2398   MVT VT = N->getValueType(0);
2399   unsigned Opc = N->getOpcode();
2400   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
2401   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
2402   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
2403   ISD::CondCode CC = ISD::SETCC_INVALID;
2404
2405   if (isSlctCC) {
2406     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
2407   } else {
2408     SDValue CCOp = Slct.getOperand(0);
2409     if (CCOp.getOpcode() == ISD::SETCC)
2410       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
2411   }
2412
2413   bool DoXform = false;
2414   bool InvCC = false;
2415   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
2416           "Bad input!");
2417
2418   if (LHS.getOpcode() == ISD::Constant &&
2419       cast<ConstantSDNode>(LHS)->isNullValue()) {
2420     DoXform = true;
2421   } else if (CC != ISD::SETCC_INVALID &&
2422              RHS.getOpcode() == ISD::Constant &&
2423              cast<ConstantSDNode>(RHS)->isNullValue()) {
2424     std::swap(LHS, RHS);
2425     SDValue Op0 = Slct.getOperand(0);
2426     MVT OpVT = isSlctCC ? Op0.getValueType() :
2427                           Op0.getOperand(0).getValueType();
2428     bool isInt = OpVT.isInteger();
2429     CC = ISD::getSetCCInverse(CC, isInt);
2430
2431     if (!TLI.isCondCodeLegal(CC, OpVT))
2432       return SDValue();         // Inverse operator isn't legal.
2433
2434     DoXform = true;
2435     InvCC = true;
2436   }
2437
2438   if (DoXform) {
2439     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
2440     if (isSlctCC)
2441       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
2442                              Slct.getOperand(0), Slct.getOperand(1), CC);
2443     SDValue CCOp = Slct.getOperand(0);
2444     if (InvCC)
2445       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
2446                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
2447     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
2448                        CCOp, OtherOp, Result);
2449   }
2450   return SDValue();
2451 }
2452
2453 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
2454 static SDValue PerformADDCombine(SDNode *N,
2455                                  TargetLowering::DAGCombinerInfo &DCI) {
2456   // added by evan in r37685 with no testcase.
2457   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2458
2459   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
2460   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
2461     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
2462     if (Result.getNode()) return Result;
2463   }
2464   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2465     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2466     if (Result.getNode()) return Result;
2467   }
2468
2469   return SDValue();
2470 }
2471
2472 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
2473 static SDValue PerformSUBCombine(SDNode *N,
2474                                  TargetLowering::DAGCombinerInfo &DCI) {
2475   // added by evan in r37685 with no testcase.
2476   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2477
2478   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
2479   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2480     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2481     if (Result.getNode()) return Result;
2482   }
2483
2484   return SDValue();
2485 }
2486
2487
2488 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
2489 static SDValue PerformFMRRDCombine(SDNode *N,
2490                                    TargetLowering::DAGCombinerInfo &DCI) {
2491   // fmrrd(fmdrr x, y) -> x,y
2492   SDValue InDouble = N->getOperand(0);
2493   if (InDouble.getOpcode() == ARMISD::FMDRR)
2494     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
2495   return SDValue();
2496 }
2497
2498 /// getVShiftImm - Check if this is a valid build_vector for the immediate
2499 /// operand of a vector shift operation, where all the elements of the
2500 /// build_vector must have the same constant integer value.
2501 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
2502   // Ignore bit_converts.
2503   while (Op.getOpcode() == ISD::BIT_CONVERT)
2504     Op = Op.getOperand(0);
2505   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2506   APInt SplatBits, SplatUndef;
2507   unsigned SplatBitSize;
2508   bool HasAnyUndefs;
2509   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2510                                       HasAnyUndefs, ElementBits) ||
2511       SplatBitSize > ElementBits)
2512     return false;
2513   Cnt = SplatBits.getSExtValue();
2514   return true;
2515 }
2516
2517 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
2518 /// operand of a vector shift left operation.  That value must be in the range:
2519 ///   0 <= Value < ElementBits for a left shift; or
2520 ///   0 <= Value <= ElementBits for a long left shift.
2521 static bool isVShiftLImm(SDValue Op, MVT VT, bool isLong, int64_t &Cnt) {
2522   assert(VT.isVector() && "vector shift count is not a vector type");
2523   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2524   if (! getVShiftImm(Op, ElementBits, Cnt))
2525     return false;
2526   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
2527 }
2528
2529 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
2530 /// operand of a vector shift right operation.  For a shift opcode, the value
2531 /// is positive, but for an intrinsic the value count must be negative. The
2532 /// absolute value must be in the range:
2533 ///   1 <= |Value| <= ElementBits for a right shift; or
2534 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
2535 static bool isVShiftRImm(SDValue Op, MVT VT, bool isNarrow, bool isIntrinsic,
2536                          int64_t &Cnt) {
2537   assert(VT.isVector() && "vector shift count is not a vector type");
2538   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2539   if (! getVShiftImm(Op, ElementBits, Cnt))
2540     return false;
2541   if (isIntrinsic)
2542     Cnt = -Cnt;
2543   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
2544 }
2545
2546 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
2547 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
2548   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2549   switch (IntNo) {
2550   default:
2551     // Don't do anything for most intrinsics.
2552     break;
2553
2554   // Vector shifts: check for immediate versions and lower them.
2555   // Note: This is done during DAG combining instead of DAG legalizing because
2556   // the build_vectors for 64-bit vector element shift counts are generally
2557   // not legal, and it is hard to see their values after they get legalized to
2558   // loads from a constant pool.
2559   case Intrinsic::arm_neon_vshifts:
2560   case Intrinsic::arm_neon_vshiftu:
2561   case Intrinsic::arm_neon_vshiftls:
2562   case Intrinsic::arm_neon_vshiftlu:
2563   case Intrinsic::arm_neon_vshiftn:
2564   case Intrinsic::arm_neon_vrshifts:
2565   case Intrinsic::arm_neon_vrshiftu:
2566   case Intrinsic::arm_neon_vrshiftn:
2567   case Intrinsic::arm_neon_vqshifts:
2568   case Intrinsic::arm_neon_vqshiftu:
2569   case Intrinsic::arm_neon_vqshiftsu:
2570   case Intrinsic::arm_neon_vqshiftns:
2571   case Intrinsic::arm_neon_vqshiftnu:
2572   case Intrinsic::arm_neon_vqshiftnsu:
2573   case Intrinsic::arm_neon_vqrshiftns:
2574   case Intrinsic::arm_neon_vqrshiftnu:
2575   case Intrinsic::arm_neon_vqrshiftnsu: {
2576     MVT VT = N->getOperand(1).getValueType();
2577     int64_t Cnt;
2578     unsigned VShiftOpc = 0;
2579
2580     switch (IntNo) {
2581     case Intrinsic::arm_neon_vshifts:
2582     case Intrinsic::arm_neon_vshiftu:
2583       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
2584         VShiftOpc = ARMISD::VSHL;
2585         break;
2586       }
2587       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
2588         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
2589                      ARMISD::VSHRs : ARMISD::VSHRu);
2590         break;
2591       }
2592       return SDValue();
2593
2594     case Intrinsic::arm_neon_vshiftls:
2595     case Intrinsic::arm_neon_vshiftlu:
2596       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
2597         break;
2598       LLVM_UNREACHABLE("invalid shift count for vshll intrinsic");
2599
2600     case Intrinsic::arm_neon_vrshifts:
2601     case Intrinsic::arm_neon_vrshiftu:
2602       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
2603         break;
2604       return SDValue();
2605
2606     case Intrinsic::arm_neon_vqshifts:
2607     case Intrinsic::arm_neon_vqshiftu:
2608       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2609         break;
2610       return SDValue();
2611
2612     case Intrinsic::arm_neon_vqshiftsu:
2613       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2614         break;
2615       LLVM_UNREACHABLE("invalid shift count for vqshlu intrinsic");
2616
2617     case Intrinsic::arm_neon_vshiftn:
2618     case Intrinsic::arm_neon_vrshiftn:
2619     case Intrinsic::arm_neon_vqshiftns:
2620     case Intrinsic::arm_neon_vqshiftnu:
2621     case Intrinsic::arm_neon_vqshiftnsu:
2622     case Intrinsic::arm_neon_vqrshiftns:
2623     case Intrinsic::arm_neon_vqrshiftnu:
2624     case Intrinsic::arm_neon_vqrshiftnsu:
2625       // Narrowing shifts require an immediate right shift.
2626       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
2627         break;
2628       LLVM_UNREACHABLE("invalid shift count for narrowing vector shift intrinsic");
2629
2630     default:
2631       assert(0 && "unhandled vector shift");
2632     }
2633
2634     switch (IntNo) {
2635     case Intrinsic::arm_neon_vshifts:
2636     case Intrinsic::arm_neon_vshiftu:
2637       // Opcode already set above.
2638       break;
2639     case Intrinsic::arm_neon_vshiftls:
2640     case Intrinsic::arm_neon_vshiftlu:
2641       if (Cnt == VT.getVectorElementType().getSizeInBits())
2642         VShiftOpc = ARMISD::VSHLLi;
2643       else
2644         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
2645                      ARMISD::VSHLLs : ARMISD::VSHLLu);
2646       break;
2647     case Intrinsic::arm_neon_vshiftn:
2648       VShiftOpc = ARMISD::VSHRN; break;
2649     case Intrinsic::arm_neon_vrshifts:
2650       VShiftOpc = ARMISD::VRSHRs; break;
2651     case Intrinsic::arm_neon_vrshiftu:
2652       VShiftOpc = ARMISD::VRSHRu; break;
2653     case Intrinsic::arm_neon_vrshiftn:
2654       VShiftOpc = ARMISD::VRSHRN; break;
2655     case Intrinsic::arm_neon_vqshifts:
2656       VShiftOpc = ARMISD::VQSHLs; break;
2657     case Intrinsic::arm_neon_vqshiftu:
2658       VShiftOpc = ARMISD::VQSHLu; break;
2659     case Intrinsic::arm_neon_vqshiftsu:
2660       VShiftOpc = ARMISD::VQSHLsu; break;
2661     case Intrinsic::arm_neon_vqshiftns:
2662       VShiftOpc = ARMISD::VQSHRNs; break;
2663     case Intrinsic::arm_neon_vqshiftnu:
2664       VShiftOpc = ARMISD::VQSHRNu; break;
2665     case Intrinsic::arm_neon_vqshiftnsu:
2666       VShiftOpc = ARMISD::VQSHRNsu; break;
2667     case Intrinsic::arm_neon_vqrshiftns:
2668       VShiftOpc = ARMISD::VQRSHRNs; break;
2669     case Intrinsic::arm_neon_vqrshiftnu:
2670       VShiftOpc = ARMISD::VQRSHRNu; break;
2671     case Intrinsic::arm_neon_vqrshiftnsu:
2672       VShiftOpc = ARMISD::VQRSHRNsu; break;
2673     }
2674
2675     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2676                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
2677   }
2678
2679   case Intrinsic::arm_neon_vshiftins: {
2680     MVT VT = N->getOperand(1).getValueType();
2681     int64_t Cnt;
2682     unsigned VShiftOpc = 0;
2683
2684     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
2685       VShiftOpc = ARMISD::VSLI;
2686     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
2687       VShiftOpc = ARMISD::VSRI;
2688     else {
2689       LLVM_UNREACHABLE("invalid shift count for vsli/vsri intrinsic");
2690     }
2691
2692     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2693                        N->getOperand(1), N->getOperand(2),
2694                        DAG.getConstant(Cnt, MVT::i32));
2695   }
2696
2697   case Intrinsic::arm_neon_vqrshifts:
2698   case Intrinsic::arm_neon_vqrshiftu:
2699     // No immediate versions of these to check for.
2700     break;
2701   }
2702
2703   return SDValue();
2704 }
2705
2706 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
2707 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
2708 /// combining instead of DAG legalizing because the build_vectors for 64-bit
2709 /// vector element shift counts are generally not legal, and it is hard to see
2710 /// their values after they get legalized to loads from a constant pool.
2711 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
2712                                    const ARMSubtarget *ST) {
2713   MVT VT = N->getValueType(0);
2714
2715   // Nothing to be done for scalar shifts.
2716   if (! VT.isVector())
2717     return SDValue();
2718
2719   assert(ST->hasNEON() && "unexpected vector shift");
2720   int64_t Cnt;
2721
2722   switch (N->getOpcode()) {
2723   default: assert(0 && "unexpected shift opcode");
2724
2725   case ISD::SHL:
2726     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
2727       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
2728                          DAG.getConstant(Cnt, MVT::i32));
2729     break;
2730
2731   case ISD::SRA:
2732   case ISD::SRL:
2733     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
2734       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
2735                             ARMISD::VSHRs : ARMISD::VSHRu);
2736       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
2737                          DAG.getConstant(Cnt, MVT::i32));
2738     }
2739   }
2740   return SDValue();
2741 }
2742
2743 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
2744 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
2745 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
2746                                     const ARMSubtarget *ST) {
2747   SDValue N0 = N->getOperand(0);
2748
2749   // Check for sign- and zero-extensions of vector extract operations of 8-
2750   // and 16-bit vector elements.  NEON supports these directly.  They are
2751   // handled during DAG combining because type legalization will promote them
2752   // to 32-bit types and it is messy to recognize the operations after that.
2753   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2754     SDValue Vec = N0.getOperand(0);
2755     SDValue Lane = N0.getOperand(1);
2756     MVT VT = N->getValueType(0);
2757     MVT EltVT = N0.getValueType();
2758     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2759
2760     if (VT == MVT::i32 &&
2761         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
2762         TLI.isTypeLegal(Vec.getValueType())) {
2763
2764       unsigned Opc = 0;
2765       switch (N->getOpcode()) {
2766       default: assert(0 && "unexpected opcode");
2767       case ISD::SIGN_EXTEND:
2768         Opc = ARMISD::VGETLANEs;
2769         break;
2770       case ISD::ZERO_EXTEND:
2771       case ISD::ANY_EXTEND:
2772         Opc = ARMISD::VGETLANEu;
2773         break;
2774       }
2775       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
2776     }
2777   }
2778
2779   return SDValue();
2780 }
2781
2782 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
2783                                              DAGCombinerInfo &DCI) const {
2784   switch (N->getOpcode()) {
2785   default: break;
2786   case ISD::ADD:      return PerformADDCombine(N, DCI);
2787   case ISD::SUB:      return PerformSUBCombine(N, DCI);
2788   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
2789   case ISD::INTRINSIC_WO_CHAIN:
2790     return PerformIntrinsicCombine(N, DCI.DAG);
2791   case ISD::SHL:
2792   case ISD::SRA:
2793   case ISD::SRL:
2794     return PerformShiftCombine(N, DCI.DAG, Subtarget);
2795   case ISD::SIGN_EXTEND:
2796   case ISD::ZERO_EXTEND:
2797   case ISD::ANY_EXTEND:
2798     return PerformExtendCombine(N, DCI.DAG, Subtarget);
2799   }
2800   return SDValue();
2801 }
2802
2803 /// isLegalAddressImmediate - Return true if the integer value can be used
2804 /// as the offset of the target addressing mode for load / store of the
2805 /// given type.
2806 static bool isLegalAddressImmediate(int64_t V, MVT VT,
2807                                     const ARMSubtarget *Subtarget) {
2808   if (V == 0)
2809     return true;
2810
2811   if (!VT.isSimple())
2812     return false;
2813
2814   if (Subtarget->isThumb()) { // FIXME for thumb2
2815     if (V < 0)
2816       return false;
2817
2818     unsigned Scale = 1;
2819     switch (VT.getSimpleVT()) {
2820     default: return false;
2821     case MVT::i1:
2822     case MVT::i8:
2823       // Scale == 1;
2824       break;
2825     case MVT::i16:
2826       // Scale == 2;
2827       Scale = 2;
2828       break;
2829     case MVT::i32:
2830       // Scale == 4;
2831       Scale = 4;
2832       break;
2833     }
2834
2835     if ((V & (Scale - 1)) != 0)
2836       return false;
2837     V /= Scale;
2838     return V == (V & ((1LL << 5) - 1));
2839   }
2840
2841   if (V < 0)
2842     V = - V;
2843   switch (VT.getSimpleVT()) {
2844   default: return false;
2845   case MVT::i1:
2846   case MVT::i8:
2847   case MVT::i32:
2848     // +- imm12
2849     return V == (V & ((1LL << 12) - 1));
2850   case MVT::i16:
2851     // +- imm8
2852     return V == (V & ((1LL << 8) - 1));
2853   case MVT::f32:
2854   case MVT::f64:
2855     if (!Subtarget->hasVFP2())
2856       return false;
2857     if ((V & 3) != 0)
2858       return false;
2859     V >>= 2;
2860     return V == (V & ((1LL << 8) - 1));
2861   }
2862 }
2863
2864 /// isLegalAddressingMode - Return true if the addressing mode represented
2865 /// by AM is legal for this target, for a load/store of the specified type.
2866 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
2867                                               const Type *Ty) const {
2868   MVT VT = getValueType(Ty, true);
2869   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
2870     return false;
2871
2872   // Can never fold addr of global into load/store.
2873   if (AM.BaseGV)
2874     return false;
2875
2876   switch (AM.Scale) {
2877   case 0:  // no scale reg, must be "r+i" or "r", or "i".
2878     break;
2879   case 1:
2880     if (Subtarget->isThumb())  // FIXME for thumb2
2881       return false;
2882     // FALL THROUGH.
2883   default:
2884     // ARM doesn't support any R+R*scale+imm addr modes.
2885     if (AM.BaseOffs)
2886       return false;
2887
2888     if (!VT.isSimple())
2889       return false;
2890
2891     int Scale = AM.Scale;
2892     switch (VT.getSimpleVT()) {
2893     default: return false;
2894     case MVT::i1:
2895     case MVT::i8:
2896     case MVT::i32:
2897     case MVT::i64:
2898       // This assumes i64 is legalized to a pair of i32. If not (i.e.
2899       // ldrd / strd are used, then its address mode is same as i16.
2900       // r + r
2901       if (Scale < 0) Scale = -Scale;
2902       if (Scale == 1)
2903         return true;
2904       // r + r << imm
2905       return isPowerOf2_32(Scale & ~1);
2906     case MVT::i16:
2907       // r + r
2908       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
2909         return true;
2910       return false;
2911
2912     case MVT::isVoid:
2913       // Note, we allow "void" uses (basically, uses that aren't loads or
2914       // stores), because arm allows folding a scale into many arithmetic
2915       // operations.  This should be made more precise and revisited later.
2916
2917       // Allow r << imm, but the imm has to be a multiple of two.
2918       if (AM.Scale & 1) return false;
2919       return isPowerOf2_32(AM.Scale);
2920     }
2921     break;
2922   }
2923   return true;
2924 }
2925
2926 static bool getARMIndexedAddressParts(SDNode *Ptr, MVT VT,
2927                                       bool isSEXTLoad, SDValue &Base,
2928                                       SDValue &Offset, bool &isInc,
2929                                       SelectionDAG &DAG) {
2930   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
2931     return false;
2932
2933   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
2934     // AddressingMode 3
2935     Base = Ptr->getOperand(0);
2936     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
2937       int RHSC = (int)RHS->getZExtValue();
2938       if (RHSC < 0 && RHSC > -256) {
2939         assert(Ptr->getOpcode() == ISD::ADD);
2940         isInc = false;
2941         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
2942         return true;
2943       }
2944     }
2945     isInc = (Ptr->getOpcode() == ISD::ADD);
2946     Offset = Ptr->getOperand(1);
2947     return true;
2948   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
2949     // AddressingMode 2
2950     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
2951       int RHSC = (int)RHS->getZExtValue();
2952       if (RHSC < 0 && RHSC > -0x1000) {
2953         assert(Ptr->getOpcode() == ISD::ADD);
2954         isInc = false;
2955         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
2956         Base = Ptr->getOperand(0);
2957         return true;
2958       }
2959     }
2960
2961     if (Ptr->getOpcode() == ISD::ADD) {
2962       isInc = true;
2963       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
2964       if (ShOpcVal != ARM_AM::no_shift) {
2965         Base = Ptr->getOperand(1);
2966         Offset = Ptr->getOperand(0);
2967       } else {
2968         Base = Ptr->getOperand(0);
2969         Offset = Ptr->getOperand(1);
2970       }
2971       return true;
2972     }
2973
2974     isInc = (Ptr->getOpcode() == ISD::ADD);
2975     Base = Ptr->getOperand(0);
2976     Offset = Ptr->getOperand(1);
2977     return true;
2978   }
2979
2980   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
2981   return false;
2982 }
2983
2984 static bool getT2IndexedAddressParts(SDNode *Ptr, MVT VT,
2985                                      bool isSEXTLoad, SDValue &Base,
2986                                      SDValue &Offset, bool &isInc,
2987                                      SelectionDAG &DAG) {
2988   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
2989     return false;
2990
2991   Base = Ptr->getOperand(0);
2992   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
2993     int RHSC = (int)RHS->getZExtValue();
2994     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
2995       assert(Ptr->getOpcode() == ISD::ADD);
2996       isInc = false;
2997       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
2998       return true;
2999     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
3000       isInc = Ptr->getOpcode() == ISD::ADD;
3001       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
3002       return true;
3003     }
3004   }
3005
3006   return false;
3007 }
3008
3009 /// getPreIndexedAddressParts - returns true by value, base pointer and
3010 /// offset pointer and addressing mode by reference if the node's address
3011 /// can be legally represented as pre-indexed load / store address.
3012 bool
3013 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3014                                              SDValue &Offset,
3015                                              ISD::MemIndexedMode &AM,
3016                                              SelectionDAG &DAG) const {
3017   if (Subtarget->isThumb1Only())
3018     return false;
3019
3020   MVT VT;
3021   SDValue Ptr;
3022   bool isSEXTLoad = false;
3023   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3024     Ptr = LD->getBasePtr();
3025     VT  = LD->getMemoryVT();
3026     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3027   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3028     Ptr = ST->getBasePtr();
3029     VT  = ST->getMemoryVT();
3030   } else
3031     return false;
3032
3033   bool isInc;
3034   bool isLegal = false;
3035   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3036     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3037                                        Offset, isInc, DAG);
3038   else 
3039     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3040                                         Offset, isInc, DAG);
3041   if (!isLegal)
3042     return false;
3043
3044   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
3045   return true;
3046 }
3047
3048 /// getPostIndexedAddressParts - returns true by value, base pointer and
3049 /// offset pointer and addressing mode by reference if this node can be
3050 /// combined with a load / store to form a post-indexed load / store.
3051 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
3052                                                    SDValue &Base,
3053                                                    SDValue &Offset,
3054                                                    ISD::MemIndexedMode &AM,
3055                                                    SelectionDAG &DAG) const {
3056   if (Subtarget->isThumb1Only())
3057     return false;
3058
3059   MVT VT;
3060   SDValue Ptr;
3061   bool isSEXTLoad = false;
3062   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3063     VT  = LD->getMemoryVT();
3064     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3065   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3066     VT  = ST->getMemoryVT();
3067   } else
3068     return false;
3069
3070   bool isInc;
3071   bool isLegal = false;
3072   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3073     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3074                                         isInc, DAG);
3075   else 
3076     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3077                                         isInc, DAG);
3078   if (!isLegal)
3079     return false;
3080
3081   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
3082   return true;
3083 }
3084
3085 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
3086                                                        const APInt &Mask,
3087                                                        APInt &KnownZero,
3088                                                        APInt &KnownOne,
3089                                                        const SelectionDAG &DAG,
3090                                                        unsigned Depth) const {
3091   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3092   switch (Op.getOpcode()) {
3093   default: break;
3094   case ARMISD::CMOV: {
3095     // Bits are known zero/one if known on the LHS and RHS.
3096     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
3097     if (KnownZero == 0 && KnownOne == 0) return;
3098
3099     APInt KnownZeroRHS, KnownOneRHS;
3100     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
3101                           KnownZeroRHS, KnownOneRHS, Depth+1);
3102     KnownZero &= KnownZeroRHS;
3103     KnownOne  &= KnownOneRHS;
3104     return;
3105   }
3106   }
3107 }
3108
3109 //===----------------------------------------------------------------------===//
3110 //                           ARM Inline Assembly Support
3111 //===----------------------------------------------------------------------===//
3112
3113 /// getConstraintType - Given a constraint letter, return the type of
3114 /// constraint it is for this target.
3115 ARMTargetLowering::ConstraintType
3116 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
3117   if (Constraint.size() == 1) {
3118     switch (Constraint[0]) {
3119     default:  break;
3120     case 'l': return C_RegisterClass;
3121     case 'w': return C_RegisterClass;
3122     }
3123   }
3124   return TargetLowering::getConstraintType(Constraint);
3125 }
3126
3127 std::pair<unsigned, const TargetRegisterClass*>
3128 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3129                                                 MVT VT) const {
3130   if (Constraint.size() == 1) {
3131     // GCC RS6000 Constraint Letters
3132     switch (Constraint[0]) {
3133     case 'l':
3134       if (Subtarget->isThumb1Only())
3135         return std::make_pair(0U, ARM::tGPRRegisterClass);
3136       else
3137         return std::make_pair(0U, ARM::GPRRegisterClass);
3138     case 'r':
3139       return std::make_pair(0U, ARM::GPRRegisterClass);
3140     case 'w':
3141       if (VT == MVT::f32)
3142         return std::make_pair(0U, ARM::SPRRegisterClass);
3143       if (VT == MVT::f64)
3144         return std::make_pair(0U, ARM::DPRRegisterClass);
3145       break;
3146     }
3147   }
3148   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3149 }
3150
3151 std::vector<unsigned> ARMTargetLowering::
3152 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3153                                   MVT VT) const {
3154   if (Constraint.size() != 1)
3155     return std::vector<unsigned>();
3156
3157   switch (Constraint[0]) {      // GCC ARM Constraint Letters
3158   default: break;
3159   case 'l':
3160     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3161                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3162                                  0);
3163   case 'r':
3164     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3165                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3166                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
3167                                  ARM::R12, ARM::LR, 0);
3168   case 'w':
3169     if (VT == MVT::f32)
3170       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
3171                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
3172                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
3173                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
3174                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
3175                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
3176                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
3177                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
3178     if (VT == MVT::f64)
3179       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
3180                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
3181                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
3182                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
3183       break;
3184   }
3185
3186   return std::vector<unsigned>();
3187 }
3188
3189 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3190 /// vector.  If it is invalid, don't add anything to Ops.
3191 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3192                                                      char Constraint,
3193                                                      bool hasMemory,
3194                                                      std::vector<SDValue>&Ops,
3195                                                      SelectionDAG &DAG) const {
3196   SDValue Result(0, 0);
3197
3198   switch (Constraint) {
3199   default: break;
3200   case 'I': case 'J': case 'K': case 'L':
3201   case 'M': case 'N': case 'O':
3202     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3203     if (!C)
3204       return;
3205
3206     int64_t CVal64 = C->getSExtValue();
3207     int CVal = (int) CVal64;
3208     // None of these constraints allow values larger than 32 bits.  Check
3209     // that the value fits in an int.
3210     if (CVal != CVal64)
3211       return;
3212
3213     switch (Constraint) {
3214       case 'I':
3215         if (Subtarget->isThumb1Only()) {
3216           // This must be a constant between 0 and 255, for ADD
3217           // immediates.
3218           if (CVal >= 0 && CVal <= 255)
3219             break;
3220         } else if (Subtarget->isThumb2()) {
3221           // A constant that can be used as an immediate value in a
3222           // data-processing instruction.
3223           if (ARM_AM::getT2SOImmVal(CVal) != -1)
3224             break;
3225         } else {
3226           // A constant that can be used as an immediate value in a
3227           // data-processing instruction.
3228           if (ARM_AM::getSOImmVal(CVal) != -1)
3229             break;
3230         }
3231         return;
3232
3233       case 'J':
3234         if (Subtarget->isThumb()) {  // FIXME thumb2
3235           // This must be a constant between -255 and -1, for negated ADD
3236           // immediates. This can be used in GCC with an "n" modifier that
3237           // prints the negated value, for use with SUB instructions. It is
3238           // not useful otherwise but is implemented for compatibility.
3239           if (CVal >= -255 && CVal <= -1)
3240             break;
3241         } else {
3242           // This must be a constant between -4095 and 4095. It is not clear
3243           // what this constraint is intended for. Implemented for
3244           // compatibility with GCC.
3245           if (CVal >= -4095 && CVal <= 4095)
3246             break;
3247         }
3248         return;
3249
3250       case 'K':
3251         if (Subtarget->isThumb1Only()) {
3252           // A 32-bit value where only one byte has a nonzero value. Exclude
3253           // zero to match GCC. This constraint is used by GCC internally for
3254           // constants that can be loaded with a move/shift combination.
3255           // It is not useful otherwise but is implemented for compatibility.
3256           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
3257             break;
3258         } else if (Subtarget->isThumb2()) {
3259           // A constant whose bitwise inverse can be used as an immediate
3260           // value in a data-processing instruction. This can be used in GCC
3261           // with a "B" modifier that prints the inverted value, for use with
3262           // BIC and MVN instructions. It is not useful otherwise but is
3263           // implemented for compatibility.
3264           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
3265             break;
3266         } else {
3267           // A constant whose bitwise inverse can be used as an immediate
3268           // value in a data-processing instruction. This can be used in GCC
3269           // with a "B" modifier that prints the inverted value, for use with
3270           // BIC and MVN instructions. It is not useful otherwise but is
3271           // implemented for compatibility.
3272           if (ARM_AM::getSOImmVal(~CVal) != -1)
3273             break;
3274         }
3275         return;
3276
3277       case 'L':
3278         if (Subtarget->isThumb1Only()) {
3279           // This must be a constant between -7 and 7,
3280           // for 3-operand ADD/SUB immediate instructions.
3281           if (CVal >= -7 && CVal < 7)
3282             break;
3283         } else if (Subtarget->isThumb2()) {
3284           // A constant whose negation can be used as an immediate value in a
3285           // data-processing instruction. This can be used in GCC with an "n"
3286           // modifier that prints the negated value, for use with SUB
3287           // instructions. It is not useful otherwise but is implemented for
3288           // compatibility.
3289           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
3290             break;
3291         } else {
3292           // A constant whose negation can be used as an immediate value in a
3293           // data-processing instruction. This can be used in GCC with an "n"
3294           // modifier that prints the negated value, for use with SUB
3295           // instructions. It is not useful otherwise but is implemented for
3296           // compatibility.
3297           if (ARM_AM::getSOImmVal(-CVal) != -1)
3298             break;
3299         }
3300         return;
3301
3302       case 'M':
3303         if (Subtarget->isThumb()) { // FIXME thumb2
3304           // This must be a multiple of 4 between 0 and 1020, for
3305           // ADD sp + immediate.
3306           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
3307             break;
3308         } else {
3309           // A power of two or a constant between 0 and 32.  This is used in
3310           // GCC for the shift amount on shifted register operands, but it is
3311           // useful in general for any shift amounts.
3312           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
3313             break;
3314         }
3315         return;
3316
3317       case 'N':
3318         if (Subtarget->isThumb()) {  // FIXME thumb2
3319           // This must be a constant between 0 and 31, for shift amounts.
3320           if (CVal >= 0 && CVal <= 31)
3321             break;
3322         }
3323         return;
3324
3325       case 'O':
3326         if (Subtarget->isThumb()) {  // FIXME thumb2
3327           // This must be a multiple of 4 between -508 and 508, for
3328           // ADD/SUB sp = sp + immediate.
3329           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
3330             break;
3331         }
3332         return;
3333     }
3334     Result = DAG.getTargetConstant(CVal, Op.getValueType());
3335     break;
3336   }
3337
3338   if (Result.getNode()) {
3339     Ops.push_back(Result);
3340     return;
3341   }
3342   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
3343                                                       Ops, DAG);
3344 }