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