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