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