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