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