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