ARMISelLowering.cpp revision 6edd5884c91aea72661ed899b0c91dfb4f0ea80f
1//===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that ARM uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "arm-isel"
16#include "ARM.h"
17#include "ARMCallingConv.h"
18#include "ARMConstantPoolValue.h"
19#include "ARMISelLowering.h"
20#include "ARMMachineFunctionInfo.h"
21#include "ARMPerfectShuffle.h"
22#include "ARMRegisterInfo.h"
23#include "ARMSubtarget.h"
24#include "ARMTargetMachine.h"
25#include "ARMTargetObjectFile.h"
26#include "MCTargetDesc/ARMAddressingModes.h"
27#include "llvm/CallingConv.h"
28#include "llvm/Constants.h"
29#include "llvm/Function.h"
30#include "llvm/GlobalValue.h"
31#include "llvm/Instruction.h"
32#include "llvm/Instructions.h"
33#include "llvm/Intrinsics.h"
34#include "llvm/Type.h"
35#include "llvm/CodeGen/CallingConvLower.h"
36#include "llvm/CodeGen/IntrinsicLowering.h"
37#include "llvm/CodeGen/MachineBasicBlock.h"
38#include "llvm/CodeGen/MachineFrameInfo.h"
39#include "llvm/CodeGen/MachineFunction.h"
40#include "llvm/CodeGen/MachineInstrBuilder.h"
41#include "llvm/CodeGen/MachineModuleInfo.h"
42#include "llvm/CodeGen/MachineRegisterInfo.h"
43#include "llvm/CodeGen/SelectionDAG.h"
44#include "llvm/MC/MCSectionMachO.h"
45#include "llvm/Target/TargetOptions.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/ADT/Statistic.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
51#include "llvm/Support/raw_ostream.h"
52#include <sstream>
53using namespace llvm;
54
55STATISTIC(NumTailCalls, "Number of tail calls");
56STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57
58// This option should go away when tail calls fully work.
59static cl::opt<bool>
60EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61  cl::desc("Generate tail calls (TEMPORARY OPTION)."),
62  cl::init(false));
63
64cl::opt<bool>
65EnableARMLongCalls("arm-long-calls", cl::Hidden,
66  cl::desc("Generate calls via indirect call instructions"),
67  cl::init(false));
68
69static cl::opt<bool>
70ARMInterworking("arm-interworking", cl::Hidden,
71  cl::desc("Enable / disable ARM interworking (for debugging only)"),
72  cl::init(true));
73
74namespace {
75  class ARMCCState : public CCState {
76  public:
77    ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78               const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
79               LLVMContext &C, ParmContext PC)
80        : CCState(CC, isVarArg, MF, TM, locs, C) {
81      assert(((PC == Call) || (PC == Prologue)) &&
82             "ARMCCState users must specify whether their context is call"
83             "or prologue generation.");
84      CallOrPrologue = PC;
85    }
86  };
87}
88
89// The APCS parameter registers.
90static const unsigned GPRArgRegs[] = {
91  ARM::R0, ARM::R1, ARM::R2, ARM::R3
92};
93
94void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
95                                       EVT PromotedBitwiseVT) {
96  if (VT != PromotedLdStVT) {
97    setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
98    AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
99                       PromotedLdStVT.getSimpleVT());
100
101    setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
102    AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
103                       PromotedLdStVT.getSimpleVT());
104  }
105
106  EVT ElemTy = VT.getVectorElementType();
107  if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
108    setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
109  setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
110  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
111  if (ElemTy == MVT::i32) {
112    setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
113    setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
114    setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
115    setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
116  } else {
117    setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
118    setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
119    setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
120    setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
121  }
122  setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
123  setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
124  setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
125  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
126  setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
127  setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
128  setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
129  if (VT.isInteger()) {
130    setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
131    setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
132    setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
133  }
134
135  // Promote all bit-wise operations.
136  if (VT.isInteger() && VT != PromotedBitwiseVT) {
137    setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
138    AddPromotedToType (ISD::AND, VT.getSimpleVT(),
139                       PromotedBitwiseVT.getSimpleVT());
140    setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
141    AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
142                       PromotedBitwiseVT.getSimpleVT());
143    setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
144    AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
145                       PromotedBitwiseVT.getSimpleVT());
146  }
147
148  // Neon does not support vector divide/remainder operations.
149  setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
150  setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
151  setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
152  setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
153  setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
154  setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
155}
156
157void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
158  addRegisterClass(VT, ARM::DPRRegisterClass);
159  addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160}
161
162void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
163  addRegisterClass(VT, ARM::QPRRegisterClass);
164  addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165}
166
167static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
168  if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
169    return new TargetLoweringObjectFileMachO();
170
171  return new ARMElfTargetObjectFile();
172}
173
174ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
175    : TargetLowering(TM, createTLOF(TM)) {
176  Subtarget = &TM.getSubtarget<ARMSubtarget>();
177  RegInfo = TM.getRegisterInfo();
178  Itins = TM.getInstrItineraryData();
179
180  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
181
182  if (Subtarget->isTargetDarwin()) {
183    // Uses VFP for Thumb libfuncs if available.
184    if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
185      // Single-precision floating-point arithmetic.
186      setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
187      setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
188      setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
189      setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
190
191      // Double-precision floating-point arithmetic.
192      setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
193      setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
194      setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
195      setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
196
197      // Single-precision comparisons.
198      setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
199      setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
200      setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
201      setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
202      setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
203      setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
204      setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
205      setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
206
207      setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
208      setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
209      setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
210      setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
211      setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
212      setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
213      setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
214      setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
215
216      // Double-precision comparisons.
217      setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
218      setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
219      setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
220      setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
221      setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
222      setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
223      setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
224      setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
225
226      setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
227      setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
228      setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
229      setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
230      setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
231      setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
232      setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
233      setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
234
235      // Floating-point to integer conversions.
236      // i64 conversions are done via library routines even when generating VFP
237      // instructions, so use the same ones.
238      setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
239      setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
240      setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
241      setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
242
243      // Conversions between floating types.
244      setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
245      setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
246
247      // Integer to floating-point conversions.
248      // i64 conversions are done via library routines even when generating VFP
249      // instructions, so use the same ones.
250      // FIXME: There appears to be some naming inconsistency in ARM libgcc:
251      // e.g., __floatunsidf vs. __floatunssidfvfp.
252      setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
253      setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
254      setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
255      setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
256    }
257  }
258
259  // These libcalls are not available in 32-bit.
260  setLibcallName(RTLIB::SHL_I128, 0);
261  setLibcallName(RTLIB::SRL_I128, 0);
262  setLibcallName(RTLIB::SRA_I128, 0);
263
264  if (Subtarget->isAAPCS_ABI()) {
265    // Double-precision floating-point arithmetic helper functions
266    // RTABI chapter 4.1.2, Table 2
267    setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
268    setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
269    setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
270    setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
271    setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
272    setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
273    setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
274    setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
275
276    // Double-precision floating-point comparison helper functions
277    // RTABI chapter 4.1.2, Table 3
278    setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
279    setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
280    setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
281    setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
282    setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
283    setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
284    setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
285    setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
286    setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
287    setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
288    setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
289    setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
290    setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
291    setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
292    setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
293    setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
294    setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
295    setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
296    setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
297    setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
298    setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
299    setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
300    setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
301    setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
302
303    // Single-precision floating-point arithmetic helper functions
304    // RTABI chapter 4.1.2, Table 4
305    setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
306    setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
307    setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
308    setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
309    setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
310    setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
311    setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
312    setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
313
314    // Single-precision floating-point comparison helper functions
315    // RTABI chapter 4.1.2, Table 5
316    setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
317    setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
318    setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
319    setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
320    setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
321    setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
322    setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
323    setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
324    setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
325    setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
326    setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
327    setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
328    setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
329    setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
330    setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
331    setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
332    setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
333    setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
334    setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
335    setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
336    setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
337    setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
338    setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
339    setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
340
341    // Floating-point to integer conversions.
342    // RTABI chapter 4.1.2, Table 6
343    setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
344    setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
345    setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
346    setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
347    setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
348    setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
349    setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
350    setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
351    setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
352    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
353    setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
354    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
355    setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
356    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
357    setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
358    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
359
360    // Conversions between floating types.
361    // RTABI chapter 4.1.2, Table 7
362    setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
363    setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
364    setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
365    setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
366
367    // Integer to floating-point conversions.
368    // RTABI chapter 4.1.2, Table 8
369    setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
370    setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
371    setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
372    setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
373    setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
374    setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
375    setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
376    setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
377    setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378    setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
379    setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380    setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
381    setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382    setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
383    setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384    setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
385
386    // Long long helper functions
387    // RTABI chapter 4.2, Table 9
388    setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
389    setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
390    setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
391    setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
392    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
393    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
394    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
395    setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
396    setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
397    setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
398
399    // Integer division functions
400    // RTABI chapter 4.3.1
401    setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
402    setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
403    setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
404    setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
405    setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
406    setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
407    setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
408    setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
409    setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
410    setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
411    setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
412    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
413    setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
414    setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
415    setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
416    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
417
418    // Memory operations
419    // RTABI chapter 4.3.4
420    setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
421    setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
422    setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
423    setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
424    setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
425    setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
426  }
427
428  // Use divmod compiler-rt calls for iOS 5.0 and later.
429  if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
430      !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
431    setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
432    setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
433  }
434
435  if (Subtarget->isThumb1Only())
436    addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
437  else
438    addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
439  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
440      !Subtarget->isThumb1Only()) {
441    addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
442    if (!Subtarget->isFPOnlySP())
443      addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
444
445    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
446  }
447
448  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
450    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
452      setTruncStoreAction((MVT::SimpleValueType)VT,
453                          (MVT::SimpleValueType)InnerVT, Expand);
454    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
455    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
456    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
457  }
458
459  if (Subtarget->hasNEON()) {
460    addDRTypeForNEON(MVT::v2f32);
461    addDRTypeForNEON(MVT::v8i8);
462    addDRTypeForNEON(MVT::v4i16);
463    addDRTypeForNEON(MVT::v2i32);
464    addDRTypeForNEON(MVT::v1i64);
465
466    addQRTypeForNEON(MVT::v4f32);
467    addQRTypeForNEON(MVT::v2f64);
468    addQRTypeForNEON(MVT::v16i8);
469    addQRTypeForNEON(MVT::v8i16);
470    addQRTypeForNEON(MVT::v4i32);
471    addQRTypeForNEON(MVT::v2i64);
472
473    // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474    // neither Neon nor VFP support any arithmetic operations on it.
475    // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476    // supported for v4f32.
477    setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478    setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479    setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480    // FIXME: Code duplication: FDIV and FREM are expanded always, see
481    // ARMTargetLowering::addTypeForNEON method for details.
482    setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483    setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484    // FIXME: Create unittest.
485    // In another words, find a way when "copysign" appears in DAG with vector
486    // operands.
487    setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488    // FIXME: Code duplication: SETCC has custom operation action, see
489    // ARMTargetLowering::addTypeForNEON method for details.
490    setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491    // FIXME: Create unittest for FNEG and for FABS.
492    setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493    setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494    setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495    setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496    setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497    setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498    setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499    setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500    setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501    setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502    setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503    setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504    // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505    setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506    setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507    setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508    setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509    setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510
511    setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512    setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513    setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514    setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515    setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516    setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517    setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518    setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519    setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520    setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
521
522    // Neon does not support some operations on v1i64 and v2i64 types.
523    setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524    // Custom handling for some quad-vector types to detect VMULL.
525    setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526    setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527    setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528    // Custom handling for some vector types to avoid expensive expansions
529    setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530    setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531    setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532    setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533    setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534    setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535    // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536    // a destination type that is wider than the source.
537    setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
538    setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
539
540    setTargetDAGCombine(ISD::INTRINSIC_VOID);
541    setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
542    setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
543    setTargetDAGCombine(ISD::SHL);
544    setTargetDAGCombine(ISD::SRL);
545    setTargetDAGCombine(ISD::SRA);
546    setTargetDAGCombine(ISD::SIGN_EXTEND);
547    setTargetDAGCombine(ISD::ZERO_EXTEND);
548    setTargetDAGCombine(ISD::ANY_EXTEND);
549    setTargetDAGCombine(ISD::SELECT_CC);
550    setTargetDAGCombine(ISD::BUILD_VECTOR);
551    setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
552    setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
553    setTargetDAGCombine(ISD::STORE);
554    setTargetDAGCombine(ISD::FP_TO_SINT);
555    setTargetDAGCombine(ISD::FP_TO_UINT);
556    setTargetDAGCombine(ISD::FDIV);
557
558    setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Expand);
559  }
560
561  computeRegisterProperties();
562
563  // ARM does not have f32 extending load.
564  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
565
566  // ARM does not have i1 sign extending load.
567  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
568
569  // ARM supports all 4 flavors of integer indexed load / store.
570  if (!Subtarget->isThumb1Only()) {
571    for (unsigned im = (unsigned)ISD::PRE_INC;
572         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
573      setIndexedLoadAction(im,  MVT::i1,  Legal);
574      setIndexedLoadAction(im,  MVT::i8,  Legal);
575      setIndexedLoadAction(im,  MVT::i16, Legal);
576      setIndexedLoadAction(im,  MVT::i32, Legal);
577      setIndexedStoreAction(im, MVT::i1,  Legal);
578      setIndexedStoreAction(im, MVT::i8,  Legal);
579      setIndexedStoreAction(im, MVT::i16, Legal);
580      setIndexedStoreAction(im, MVT::i32, Legal);
581    }
582  }
583
584  // i64 operation support.
585  setOperationAction(ISD::MUL,     MVT::i64, Expand);
586  setOperationAction(ISD::MULHU,   MVT::i32, Expand);
587  if (Subtarget->isThumb1Only()) {
588    setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
589    setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
590  }
591  if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
592      || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
593    setOperationAction(ISD::MULHS, MVT::i32, Expand);
594
595  setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
596  setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
597  setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
598  setOperationAction(ISD::SRL,       MVT::i64, Custom);
599  setOperationAction(ISD::SRA,       MVT::i64, Custom);
600
601  if (!Subtarget->isThumb1Only()) {
602    // FIXME: We should do this for Thumb1 as well.
603    setOperationAction(ISD::ADDC,    MVT::i32, Custom);
604    setOperationAction(ISD::ADDE,    MVT::i32, Custom);
605    setOperationAction(ISD::SUBC,    MVT::i32, Custom);
606    setOperationAction(ISD::SUBE,    MVT::i32, Custom);
607  }
608
609  // ARM does not have ROTL.
610  setOperationAction(ISD::ROTL,  MVT::i32, Expand);
611  setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
612  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
613  if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
614    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
615
616  // These just redirect to CTTZ and CTLZ on ARM.
617  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
618  setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
619
620  // Only ARMv6 has BSWAP.
621  if (!Subtarget->hasV6Ops())
622    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
623
624  // These are expanded into libcalls.
625  if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
626    // v7M has a hardware divider
627    setOperationAction(ISD::SDIV,  MVT::i32, Expand);
628    setOperationAction(ISD::UDIV,  MVT::i32, Expand);
629  }
630  setOperationAction(ISD::SREM,  MVT::i32, Expand);
631  setOperationAction(ISD::UREM,  MVT::i32, Expand);
632  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
633  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
634
635  setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
636  setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
637  setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
638  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
639  setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
640
641  setOperationAction(ISD::TRAP, MVT::Other, Legal);
642
643  // Use the default implementation.
644  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
645  setOperationAction(ISD::VAARG,              MVT::Other, Expand);
646  setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
647  setOperationAction(ISD::VAEND,              MVT::Other, Expand);
648  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
649  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
650  setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
651  setOperationAction(ISD::EXCEPTIONADDR,      MVT::i32,   Expand);
652  setExceptionPointerRegister(ARM::R0);
653  setExceptionSelectorRegister(ARM::R1);
654
655  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
656  // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
657  // the default expansion.
658  // FIXME: This should be checking for v6k, not just v6.
659  if (Subtarget->hasDataBarrier() ||
660      (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
661    // membarrier needs custom lowering; the rest are legal and handled
662    // normally.
663    setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
664    setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
665    // Custom lowering for 64-bit ops
666    setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
667    setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
668    setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
669    setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
670    setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
671    setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
672    setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
673    // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
674    setInsertFencesForAtomic(true);
675  } else {
676    // Set them all for expansion, which will force libcalls.
677    setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
678    setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
679    setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
680    setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
681    setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
682    setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
683    setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
684    setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
685    setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
686    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
687    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
688    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
689    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
690    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
691    // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
692    // Unordered/Monotonic case.
693    setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
694    setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
695    // Since the libcalls include locking, fold in the fences
696    setShouldFoldAtomicFences(true);
697  }
698
699  setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
700
701  // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
702  if (!Subtarget->hasV6Ops()) {
703    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
704    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
705  }
706  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
707
708  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
709      !Subtarget->isThumb1Only()) {
710    // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
711    // iff target supports vfp2.
712    setOperationAction(ISD::BITCAST, MVT::i64, Custom);
713    setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
714  }
715
716  // We want to custom lower some of our intrinsics.
717  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
718  if (Subtarget->isTargetDarwin()) {
719    setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
720    setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
721    setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
722  }
723
724  setOperationAction(ISD::SETCC,     MVT::i32, Expand);
725  setOperationAction(ISD::SETCC,     MVT::f32, Expand);
726  setOperationAction(ISD::SETCC,     MVT::f64, Expand);
727  setOperationAction(ISD::SELECT,    MVT::i32, Custom);
728  setOperationAction(ISD::SELECT,    MVT::f32, Custom);
729  setOperationAction(ISD::SELECT,    MVT::f64, Custom);
730  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
731  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
732  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
733
734  setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
735  setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
736  setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
737  setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
738  setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
739
740  // We don't support sin/cos/fmod/copysign/pow
741  setOperationAction(ISD::FSIN,      MVT::f64, Expand);
742  setOperationAction(ISD::FSIN,      MVT::f32, Expand);
743  setOperationAction(ISD::FCOS,      MVT::f32, Expand);
744  setOperationAction(ISD::FCOS,      MVT::f64, Expand);
745  setOperationAction(ISD::FREM,      MVT::f64, Expand);
746  setOperationAction(ISD::FREM,      MVT::f32, Expand);
747  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
748      !Subtarget->isThumb1Only()) {
749    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
750    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
751  }
752  setOperationAction(ISD::FPOW,      MVT::f64, Expand);
753  setOperationAction(ISD::FPOW,      MVT::f32, Expand);
754
755  setOperationAction(ISD::FMA, MVT::f64, Expand);
756  setOperationAction(ISD::FMA, MVT::f32, Expand);
757
758  // Various VFP goodness
759  if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
760    // int <-> fp are custom expanded into bit_convert + ARMISD ops.
761    if (Subtarget->hasVFP2()) {
762      setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
763      setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
764      setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
765      setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
766    }
767    // Special handling for half-precision FP.
768    if (!Subtarget->hasFP16()) {
769      setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
770      setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
771    }
772  }
773
774  // We have target-specific dag combine patterns for the following nodes:
775  // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
776  setTargetDAGCombine(ISD::ADD);
777  setTargetDAGCombine(ISD::SUB);
778  setTargetDAGCombine(ISD::MUL);
779
780  if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON())
781    setTargetDAGCombine(ISD::OR);
782  if (Subtarget->hasNEON())
783    setTargetDAGCombine(ISD::AND);
784
785  setStackPointerRegisterToSaveRestore(ARM::SP);
786
787  if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
788      !Subtarget->hasVFP2())
789    setSchedulingPreference(Sched::RegPressure);
790  else
791    setSchedulingPreference(Sched::Hybrid);
792
793  //// temporary - rewrite interface to use type
794  maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
795  maxStoresPerMemset = 16;
796  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
797
798  // On ARM arguments smaller than 4 bytes are extended, so all arguments
799  // are at least 4 bytes aligned.
800  setMinStackArgumentAlignment(4);
801
802  benefitFromCodePlacementOpt = true;
803
804  setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
805}
806
807// FIXME: It might make sense to define the representative register class as the
808// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
809// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
810// SPR's representative would be DPR_VFP2. This should work well if register
811// pressure tracking were modified such that a register use would increment the
812// pressure of the register class's representative and all of it's super
813// classes' representatives transitively. We have not implemented this because
814// of the difficulty prior to coalescing of modeling operand register classes
815// due to the common occurrence of cross class copies and subregister insertions
816// and extractions.
817std::pair<const TargetRegisterClass*, uint8_t>
818ARMTargetLowering::findRepresentativeClass(EVT VT) const{
819  const TargetRegisterClass *RRC = 0;
820  uint8_t Cost = 1;
821  switch (VT.getSimpleVT().SimpleTy) {
822  default:
823    return TargetLowering::findRepresentativeClass(VT);
824  // Use DPR as representative register class for all floating point
825  // and vector types. Since there are 32 SPR registers and 32 DPR registers so
826  // the cost is 1 for both f32 and f64.
827  case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
828  case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
829    RRC = ARM::DPRRegisterClass;
830    // When NEON is used for SP, only half of the register file is available
831    // because operations that define both SP and DP results will be constrained
832    // to the VFP2 class (D0-D15). We currently model this constraint prior to
833    // coalescing by double-counting the SP regs. See the FIXME above.
834    if (Subtarget->useNEONForSinglePrecisionFP())
835      Cost = 2;
836    break;
837  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
838  case MVT::v4f32: case MVT::v2f64:
839    RRC = ARM::DPRRegisterClass;
840    Cost = 2;
841    break;
842  case MVT::v4i64:
843    RRC = ARM::DPRRegisterClass;
844    Cost = 4;
845    break;
846  case MVT::v8i64:
847    RRC = ARM::DPRRegisterClass;
848    Cost = 8;
849    break;
850  }
851  return std::make_pair(RRC, Cost);
852}
853
854const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
855  switch (Opcode) {
856  default: return 0;
857  case ARMISD::Wrapper:       return "ARMISD::Wrapper";
858  case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
859  case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
860  case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
861  case ARMISD::CALL:          return "ARMISD::CALL";
862  case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
863  case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
864  case ARMISD::tCALL:         return "ARMISD::tCALL";
865  case ARMISD::BRCOND:        return "ARMISD::BRCOND";
866  case ARMISD::BR_JT:         return "ARMISD::BR_JT";
867  case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
868  case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
869  case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
870  case ARMISD::CMP:           return "ARMISD::CMP";
871  case ARMISD::CMPZ:          return "ARMISD::CMPZ";
872  case ARMISD::CMPFP:         return "ARMISD::CMPFP";
873  case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
874  case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
875  case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
876  case ARMISD::CMOV:          return "ARMISD::CMOV";
877
878  case ARMISD::RBIT:          return "ARMISD::RBIT";
879
880  case ARMISD::FTOSI:         return "ARMISD::FTOSI";
881  case ARMISD::FTOUI:         return "ARMISD::FTOUI";
882  case ARMISD::SITOF:         return "ARMISD::SITOF";
883  case ARMISD::UITOF:         return "ARMISD::UITOF";
884
885  case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
886  case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
887  case ARMISD::RRX:           return "ARMISD::RRX";
888
889  case ARMISD::ADDC:          return "ARMISD::ADDC";
890  case ARMISD::ADDE:          return "ARMISD::ADDE";
891  case ARMISD::SUBC:          return "ARMISD::SUBC";
892  case ARMISD::SUBE:          return "ARMISD::SUBE";
893
894  case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
895  case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
896
897  case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
898  case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
899
900  case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
901
902  case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
903
904  case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
905
906  case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
907  case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
908
909  case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
910
911  case ARMISD::VCEQ:          return "ARMISD::VCEQ";
912  case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
913  case ARMISD::VCGE:          return "ARMISD::VCGE";
914  case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
915  case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
916  case ARMISD::VCGEU:         return "ARMISD::VCGEU";
917  case ARMISD::VCGT:          return "ARMISD::VCGT";
918  case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
919  case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
920  case ARMISD::VCGTU:         return "ARMISD::VCGTU";
921  case ARMISD::VTST:          return "ARMISD::VTST";
922
923  case ARMISD::VSHL:          return "ARMISD::VSHL";
924  case ARMISD::VSHRs:         return "ARMISD::VSHRs";
925  case ARMISD::VSHRu:         return "ARMISD::VSHRu";
926  case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
927  case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
928  case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
929  case ARMISD::VSHRN:         return "ARMISD::VSHRN";
930  case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
931  case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
932  case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
933  case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
934  case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
935  case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
936  case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
937  case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
938  case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
939  case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
940  case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
941  case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
942  case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
943  case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
944  case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
945  case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
946  case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
947  case ARMISD::VDUP:          return "ARMISD::VDUP";
948  case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
949  case ARMISD::VEXT:          return "ARMISD::VEXT";
950  case ARMISD::VREV64:        return "ARMISD::VREV64";
951  case ARMISD::VREV32:        return "ARMISD::VREV32";
952  case ARMISD::VREV16:        return "ARMISD::VREV16";
953  case ARMISD::VZIP:          return "ARMISD::VZIP";
954  case ARMISD::VUZP:          return "ARMISD::VUZP";
955  case ARMISD::VTRN:          return "ARMISD::VTRN";
956  case ARMISD::VTBL1:         return "ARMISD::VTBL1";
957  case ARMISD::VTBL2:         return "ARMISD::VTBL2";
958  case ARMISD::VMULLs:        return "ARMISD::VMULLs";
959  case ARMISD::VMULLu:        return "ARMISD::VMULLu";
960  case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
961  case ARMISD::FMAX:          return "ARMISD::FMAX";
962  case ARMISD::FMIN:          return "ARMISD::FMIN";
963  case ARMISD::BFI:           return "ARMISD::BFI";
964  case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
965  case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
966  case ARMISD::VBSL:          return "ARMISD::VBSL";
967  case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
968  case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
969  case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
970  case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
971  case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
972  case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
973  case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
974  case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
975  case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
976  case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
977  case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
978  case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
979  case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
980  case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
981  case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
982  case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
983  case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
984  case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
985  case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
986  case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
987  }
988}
989
990EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
991  if (!VT.isVector()) return getPointerTy();
992  return VT.changeVectorElementTypeToInteger();
993}
994
995/// getRegClassFor - Return the register class that should be used for the
996/// specified value type.
997TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
998  // Map v4i64 to QQ registers but do not make the type legal. Similarly map
999  // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1000  // load / store 4 to 8 consecutive D registers.
1001  if (Subtarget->hasNEON()) {
1002    if (VT == MVT::v4i64)
1003      return ARM::QQPRRegisterClass;
1004    else if (VT == MVT::v8i64)
1005      return ARM::QQQQPRRegisterClass;
1006  }
1007  return TargetLowering::getRegClassFor(VT);
1008}
1009
1010// Create a fast isel object.
1011FastISel *
1012ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1013  return ARM::createFastISel(funcInfo);
1014}
1015
1016/// getMaximalGlobalOffset - Returns the maximal possible offset which can
1017/// be used for loads / stores from the global.
1018unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1019  return (Subtarget->isThumb1Only() ? 127 : 4095);
1020}
1021
1022Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1023  unsigned NumVals = N->getNumValues();
1024  if (!NumVals)
1025    return Sched::RegPressure;
1026
1027  for (unsigned i = 0; i != NumVals; ++i) {
1028    EVT VT = N->getValueType(i);
1029    if (VT == MVT::Glue || VT == MVT::Other)
1030      continue;
1031    if (VT.isFloatingPoint() || VT.isVector())
1032      return Sched::ILP;
1033  }
1034
1035  if (!N->isMachineOpcode())
1036    return Sched::RegPressure;
1037
1038  // Load are scheduled for latency even if there instruction itinerary
1039  // is not available.
1040  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1041  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1042
1043  if (MCID.getNumDefs() == 0)
1044    return Sched::RegPressure;
1045  if (!Itins->isEmpty() &&
1046      Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1047    return Sched::ILP;
1048
1049  return Sched::RegPressure;
1050}
1051
1052//===----------------------------------------------------------------------===//
1053// Lowering Code
1054//===----------------------------------------------------------------------===//
1055
1056/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1057static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1058  switch (CC) {
1059  default: llvm_unreachable("Unknown condition code!");
1060  case ISD::SETNE:  return ARMCC::NE;
1061  case ISD::SETEQ:  return ARMCC::EQ;
1062  case ISD::SETGT:  return ARMCC::GT;
1063  case ISD::SETGE:  return ARMCC::GE;
1064  case ISD::SETLT:  return ARMCC::LT;
1065  case ISD::SETLE:  return ARMCC::LE;
1066  case ISD::SETUGT: return ARMCC::HI;
1067  case ISD::SETUGE: return ARMCC::HS;
1068  case ISD::SETULT: return ARMCC::LO;
1069  case ISD::SETULE: return ARMCC::LS;
1070  }
1071}
1072
1073/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1074static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1075                        ARMCC::CondCodes &CondCode2) {
1076  CondCode2 = ARMCC::AL;
1077  switch (CC) {
1078  default: llvm_unreachable("Unknown FP condition!");
1079  case ISD::SETEQ:
1080  case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1081  case ISD::SETGT:
1082  case ISD::SETOGT: CondCode = ARMCC::GT; break;
1083  case ISD::SETGE:
1084  case ISD::SETOGE: CondCode = ARMCC::GE; break;
1085  case ISD::SETOLT: CondCode = ARMCC::MI; break;
1086  case ISD::SETOLE: CondCode = ARMCC::LS; break;
1087  case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1088  case ISD::SETO:   CondCode = ARMCC::VC; break;
1089  case ISD::SETUO:  CondCode = ARMCC::VS; break;
1090  case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1091  case ISD::SETUGT: CondCode = ARMCC::HI; break;
1092  case ISD::SETUGE: CondCode = ARMCC::PL; break;
1093  case ISD::SETLT:
1094  case ISD::SETULT: CondCode = ARMCC::LT; break;
1095  case ISD::SETLE:
1096  case ISD::SETULE: CondCode = ARMCC::LE; break;
1097  case ISD::SETNE:
1098  case ISD::SETUNE: CondCode = ARMCC::NE; break;
1099  }
1100}
1101
1102//===----------------------------------------------------------------------===//
1103//                      Calling Convention Implementation
1104//===----------------------------------------------------------------------===//
1105
1106#include "ARMGenCallingConv.inc"
1107
1108/// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1109/// given CallingConvention value.
1110CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1111                                                 bool Return,
1112                                                 bool isVarArg) const {
1113  switch (CC) {
1114  default:
1115    llvm_unreachable("Unsupported calling convention");
1116  case CallingConv::Fast:
1117    if (Subtarget->hasVFP2() && !isVarArg) {
1118      if (!Subtarget->isAAPCS_ABI())
1119        return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1120      // For AAPCS ABI targets, just use VFP variant of the calling convention.
1121      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1122    }
1123    // Fallthrough
1124  case CallingConv::C: {
1125    // Use target triple & subtarget features to do actual dispatch.
1126    if (!Subtarget->isAAPCS_ABI())
1127      return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1128    else if (Subtarget->hasVFP2() &&
1129             getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1130             !isVarArg)
1131      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1132    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1133  }
1134  case CallingConv::ARM_AAPCS_VFP:
1135    if (!isVarArg)
1136      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1137    // Fallthrough
1138  case CallingConv::ARM_AAPCS:
1139    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1140  case CallingConv::ARM_APCS:
1141    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1142  }
1143}
1144
1145/// LowerCallResult - Lower the result values of a call into the
1146/// appropriate copies out of appropriate physical registers.
1147SDValue
1148ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1149                                   CallingConv::ID CallConv, bool isVarArg,
1150                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1151                                   DebugLoc dl, SelectionDAG &DAG,
1152                                   SmallVectorImpl<SDValue> &InVals) const {
1153
1154  // Assign locations to each value returned by this call.
1155  SmallVector<CCValAssign, 16> RVLocs;
1156  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1157                    getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1158  CCInfo.AnalyzeCallResult(Ins,
1159                           CCAssignFnForNode(CallConv, /* Return*/ true,
1160                                             isVarArg));
1161
1162  // Copy all of the result registers out of their specified physreg.
1163  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1164    CCValAssign VA = RVLocs[i];
1165
1166    SDValue Val;
1167    if (VA.needsCustom()) {
1168      // Handle f64 or half of a v2f64.
1169      SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1170                                      InFlag);
1171      Chain = Lo.getValue(1);
1172      InFlag = Lo.getValue(2);
1173      VA = RVLocs[++i]; // skip ahead to next loc
1174      SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1175                                      InFlag);
1176      Chain = Hi.getValue(1);
1177      InFlag = Hi.getValue(2);
1178      Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1179
1180      if (VA.getLocVT() == MVT::v2f64) {
1181        SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1182        Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1183                          DAG.getConstant(0, MVT::i32));
1184
1185        VA = RVLocs[++i]; // skip ahead to next loc
1186        Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1187        Chain = Lo.getValue(1);
1188        InFlag = Lo.getValue(2);
1189        VA = RVLocs[++i]; // skip ahead to next loc
1190        Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1191        Chain = Hi.getValue(1);
1192        InFlag = Hi.getValue(2);
1193        Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1194        Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1195                          DAG.getConstant(1, MVT::i32));
1196      }
1197    } else {
1198      Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1199                               InFlag);
1200      Chain = Val.getValue(1);
1201      InFlag = Val.getValue(2);
1202    }
1203
1204    switch (VA.getLocInfo()) {
1205    default: llvm_unreachable("Unknown loc info!");
1206    case CCValAssign::Full: break;
1207    case CCValAssign::BCvt:
1208      Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1209      break;
1210    }
1211
1212    InVals.push_back(Val);
1213  }
1214
1215  return Chain;
1216}
1217
1218/// LowerMemOpCallTo - Store the argument to the stack.
1219SDValue
1220ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1221                                    SDValue StackPtr, SDValue Arg,
1222                                    DebugLoc dl, SelectionDAG &DAG,
1223                                    const CCValAssign &VA,
1224                                    ISD::ArgFlagsTy Flags) const {
1225  unsigned LocMemOffset = VA.getLocMemOffset();
1226  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1227  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1228  return DAG.getStore(Chain, dl, Arg, PtrOff,
1229                      MachinePointerInfo::getStack(LocMemOffset),
1230                      false, false, 0);
1231}
1232
1233void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1234                                         SDValue Chain, SDValue &Arg,
1235                                         RegsToPassVector &RegsToPass,
1236                                         CCValAssign &VA, CCValAssign &NextVA,
1237                                         SDValue &StackPtr,
1238                                         SmallVector<SDValue, 8> &MemOpChains,
1239                                         ISD::ArgFlagsTy Flags) const {
1240
1241  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1242                              DAG.getVTList(MVT::i32, MVT::i32), Arg);
1243  RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1244
1245  if (NextVA.isRegLoc())
1246    RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1247  else {
1248    assert(NextVA.isMemLoc());
1249    if (StackPtr.getNode() == 0)
1250      StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1251
1252    MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1253                                           dl, DAG, NextVA,
1254                                           Flags));
1255  }
1256}
1257
1258/// LowerCall - Lowering a call into a callseq_start <-
1259/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1260/// nodes.
1261SDValue
1262ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1263                             CallingConv::ID CallConv, bool isVarArg,
1264                             bool &isTailCall,
1265                             const SmallVectorImpl<ISD::OutputArg> &Outs,
1266                             const SmallVectorImpl<SDValue> &OutVals,
1267                             const SmallVectorImpl<ISD::InputArg> &Ins,
1268                             DebugLoc dl, SelectionDAG &DAG,
1269                             SmallVectorImpl<SDValue> &InVals) const {
1270  MachineFunction &MF = DAG.getMachineFunction();
1271  bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1272  bool IsSibCall = false;
1273  // Disable tail calls if they're not supported.
1274  if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1275    isTailCall = false;
1276  if (isTailCall) {
1277    // Check if it's really possible to do a tail call.
1278    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1279                    isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1280                                                   Outs, OutVals, Ins, DAG);
1281    // We don't support GuaranteedTailCallOpt for ARM, only automatically
1282    // detected sibcalls.
1283    if (isTailCall) {
1284      ++NumTailCalls;
1285      IsSibCall = true;
1286    }
1287  }
1288
1289  // Analyze operands of the call, assigning locations to each operand.
1290  SmallVector<CCValAssign, 16> ArgLocs;
1291  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1292                 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1293  CCInfo.AnalyzeCallOperands(Outs,
1294                             CCAssignFnForNode(CallConv, /* Return*/ false,
1295                                               isVarArg));
1296
1297  // Get a count of how many bytes are to be pushed on the stack.
1298  unsigned NumBytes = CCInfo.getNextStackOffset();
1299
1300  // For tail calls, memory operands are available in our caller's stack.
1301  if (IsSibCall)
1302    NumBytes = 0;
1303
1304  // Adjust the stack pointer for the new arguments...
1305  // These operations are automatically eliminated by the prolog/epilog pass
1306  if (!IsSibCall)
1307    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1308
1309  SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1310
1311  RegsToPassVector RegsToPass;
1312  SmallVector<SDValue, 8> MemOpChains;
1313
1314  // Walk the register/memloc assignments, inserting copies/loads.  In the case
1315  // of tail call optimization, arguments are handled later.
1316  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1317       i != e;
1318       ++i, ++realArgIdx) {
1319    CCValAssign &VA = ArgLocs[i];
1320    SDValue Arg = OutVals[realArgIdx];
1321    ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1322    bool isByVal = Flags.isByVal();
1323
1324    // Promote the value if needed.
1325    switch (VA.getLocInfo()) {
1326    default: llvm_unreachable("Unknown loc info!");
1327    case CCValAssign::Full: break;
1328    case CCValAssign::SExt:
1329      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1330      break;
1331    case CCValAssign::ZExt:
1332      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1333      break;
1334    case CCValAssign::AExt:
1335      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1336      break;
1337    case CCValAssign::BCvt:
1338      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1339      break;
1340    }
1341
1342    // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1343    if (VA.needsCustom()) {
1344      if (VA.getLocVT() == MVT::v2f64) {
1345        SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1346                                  DAG.getConstant(0, MVT::i32));
1347        SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1348                                  DAG.getConstant(1, MVT::i32));
1349
1350        PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1351                         VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1352
1353        VA = ArgLocs[++i]; // skip ahead to next loc
1354        if (VA.isRegLoc()) {
1355          PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1356                           VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1357        } else {
1358          assert(VA.isMemLoc());
1359
1360          MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1361                                                 dl, DAG, VA, Flags));
1362        }
1363      } else {
1364        PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1365                         StackPtr, MemOpChains, Flags);
1366      }
1367    } else if (VA.isRegLoc()) {
1368      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1369    } else if (isByVal) {
1370      assert(VA.isMemLoc());
1371      unsigned offset = 0;
1372
1373      // True if this byval aggregate will be split between registers
1374      // and memory.
1375      if (CCInfo.isFirstByValRegValid()) {
1376        EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1377        unsigned int i, j;
1378        for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1379          SDValue Const = DAG.getConstant(4*i, MVT::i32);
1380          SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1381          SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1382                                     MachinePointerInfo(),
1383                                     false, false, false, 0);
1384          MemOpChains.push_back(Load.getValue(1));
1385          RegsToPass.push_back(std::make_pair(j, Load));
1386        }
1387        offset = ARM::R4 - CCInfo.getFirstByValReg();
1388        CCInfo.clearFirstByValReg();
1389      }
1390
1391      unsigned LocMemOffset = VA.getLocMemOffset();
1392      SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1393      SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1394                                StkPtrOff);
1395      SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1396      SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1397      SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1398                                         MVT::i32);
1399      MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1400                                          Flags.getByValAlign(),
1401                                          /*isVolatile=*/false,
1402                                          /*AlwaysInline=*/false,
1403                                          MachinePointerInfo(0),
1404                                          MachinePointerInfo(0)));
1405
1406    } else if (!IsSibCall) {
1407      assert(VA.isMemLoc());
1408
1409      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1410                                             dl, DAG, VA, Flags));
1411    }
1412  }
1413
1414  if (!MemOpChains.empty())
1415    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1416                        &MemOpChains[0], MemOpChains.size());
1417
1418  // Build a sequence of copy-to-reg nodes chained together with token chain
1419  // and flag operands which copy the outgoing args into the appropriate regs.
1420  SDValue InFlag;
1421  // Tail call byval lowering might overwrite argument registers so in case of
1422  // tail call optimization the copies to registers are lowered later.
1423  if (!isTailCall)
1424    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1425      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1426                               RegsToPass[i].second, InFlag);
1427      InFlag = Chain.getValue(1);
1428    }
1429
1430  // For tail calls lower the arguments to the 'real' stack slot.
1431  if (isTailCall) {
1432    // Force all the incoming stack arguments to be loaded from the stack
1433    // before any new outgoing arguments are stored to the stack, because the
1434    // outgoing stack slots may alias the incoming argument stack slots, and
1435    // the alias isn't otherwise explicit. This is slightly more conservative
1436    // than necessary, because it means that each store effectively depends
1437    // on every argument instead of just those arguments it would clobber.
1438
1439    // Do not flag preceding copytoreg stuff together with the following stuff.
1440    InFlag = SDValue();
1441    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1442      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1443                               RegsToPass[i].second, InFlag);
1444      InFlag = Chain.getValue(1);
1445    }
1446    InFlag =SDValue();
1447  }
1448
1449  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1450  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1451  // node so that legalize doesn't hack it.
1452  bool isDirect = false;
1453  bool isARMFunc = false;
1454  bool isLocalARMFunc = false;
1455  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1456
1457  if (EnableARMLongCalls) {
1458    assert (getTargetMachine().getRelocationModel() == Reloc::Static
1459            && "long-calls with non-static relocation model!");
1460    // Handle a global address or an external symbol. If it's not one of
1461    // those, the target's already in a register, so we don't need to do
1462    // anything extra.
1463    if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1464      const GlobalValue *GV = G->getGlobal();
1465      // Create a constant pool entry for the callee address
1466      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1467      ARMConstantPoolValue *CPV =
1468        ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1469
1470      // Get the address of the callee into a register
1471      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1472      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1473      Callee = DAG.getLoad(getPointerTy(), dl,
1474                           DAG.getEntryNode(), CPAddr,
1475                           MachinePointerInfo::getConstantPool(),
1476                           false, false, false, 0);
1477    } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1478      const char *Sym = S->getSymbol();
1479
1480      // Create a constant pool entry for the callee address
1481      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1482      ARMConstantPoolValue *CPV =
1483        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1484                                      ARMPCLabelIndex, 0);
1485      // Get the address of the callee into a register
1486      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1487      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1488      Callee = DAG.getLoad(getPointerTy(), dl,
1489                           DAG.getEntryNode(), CPAddr,
1490                           MachinePointerInfo::getConstantPool(),
1491                           false, false, false, 0);
1492    }
1493  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1494    const GlobalValue *GV = G->getGlobal();
1495    isDirect = true;
1496    bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1497    bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1498                   getTargetMachine().getRelocationModel() != Reloc::Static;
1499    isARMFunc = !Subtarget->isThumb() || isStub;
1500    // ARM call to a local ARM function is predicable.
1501    isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1502    // tBX takes a register source operand.
1503    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1504      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1505      ARMConstantPoolValue *CPV =
1506        ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1507      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1508      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1509      Callee = DAG.getLoad(getPointerTy(), dl,
1510                           DAG.getEntryNode(), CPAddr,
1511                           MachinePointerInfo::getConstantPool(),
1512                           false, false, false, 0);
1513      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1514      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1515                           getPointerTy(), Callee, PICLabel);
1516    } else {
1517      // On ELF targets for PIC code, direct calls should go through the PLT
1518      unsigned OpFlags = 0;
1519      if (Subtarget->isTargetELF() &&
1520                  getTargetMachine().getRelocationModel() == Reloc::PIC_)
1521        OpFlags = ARMII::MO_PLT;
1522      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1523    }
1524  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1525    isDirect = true;
1526    bool isStub = Subtarget->isTargetDarwin() &&
1527                  getTargetMachine().getRelocationModel() != Reloc::Static;
1528    isARMFunc = !Subtarget->isThumb() || isStub;
1529    // tBX takes a register source operand.
1530    const char *Sym = S->getSymbol();
1531    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1532      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1533      ARMConstantPoolValue *CPV =
1534        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1535                                      ARMPCLabelIndex, 4);
1536      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1537      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1538      Callee = DAG.getLoad(getPointerTy(), dl,
1539                           DAG.getEntryNode(), CPAddr,
1540                           MachinePointerInfo::getConstantPool(),
1541                           false, false, false, 0);
1542      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1543      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1544                           getPointerTy(), Callee, PICLabel);
1545    } else {
1546      unsigned OpFlags = 0;
1547      // On ELF targets for PIC code, direct calls should go through the PLT
1548      if (Subtarget->isTargetELF() &&
1549                  getTargetMachine().getRelocationModel() == Reloc::PIC_)
1550        OpFlags = ARMII::MO_PLT;
1551      Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1552    }
1553  }
1554
1555  // FIXME: handle tail calls differently.
1556  unsigned CallOpc;
1557  if (Subtarget->isThumb()) {
1558    if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1559      CallOpc = ARMISD::CALL_NOLINK;
1560    else
1561      CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1562  } else {
1563    CallOpc = (isDirect || Subtarget->hasV5TOps())
1564      ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1565      : ARMISD::CALL_NOLINK;
1566  }
1567
1568  std::vector<SDValue> Ops;
1569  Ops.push_back(Chain);
1570  Ops.push_back(Callee);
1571
1572  // Add argument registers to the end of the list so that they are known live
1573  // into the call.
1574  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1575    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1576                                  RegsToPass[i].second.getValueType()));
1577
1578  if (InFlag.getNode())
1579    Ops.push_back(InFlag);
1580
1581  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1582  if (isTailCall)
1583    return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1584
1585  // Returns a chain and a flag for retval copy to use.
1586  Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1587  InFlag = Chain.getValue(1);
1588
1589  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1590                             DAG.getIntPtrConstant(0, true), InFlag);
1591  if (!Ins.empty())
1592    InFlag = Chain.getValue(1);
1593
1594  // Handle result values, copying them out of physregs into vregs that we
1595  // return.
1596  return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1597                         dl, DAG, InVals);
1598}
1599
1600/// HandleByVal - Every parameter *after* a byval parameter is passed
1601/// on the stack.  Remember the next parameter register to allocate,
1602/// and then confiscate the rest of the parameter registers to insure
1603/// this.
1604void
1605llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1606  unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1607  assert((State->getCallOrPrologue() == Prologue ||
1608          State->getCallOrPrologue() == Call) &&
1609         "unhandled ParmContext");
1610  if ((!State->isFirstByValRegValid()) &&
1611      (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1612    State->setFirstByValReg(reg);
1613    // At a call site, a byval parameter that is split between
1614    // registers and memory needs its size truncated here.  In a
1615    // function prologue, such byval parameters are reassembled in
1616    // memory, and are not truncated.
1617    if (State->getCallOrPrologue() == Call) {
1618      unsigned excess = 4 * (ARM::R4 - reg);
1619      assert(size >= excess && "expected larger existing stack allocation");
1620      size -= excess;
1621    }
1622  }
1623  // Confiscate any remaining parameter registers to preclude their
1624  // assignment to subsequent parameters.
1625  while (State->AllocateReg(GPRArgRegs, 4))
1626    ;
1627}
1628
1629/// MatchingStackOffset - Return true if the given stack call argument is
1630/// already available in the same position (relatively) of the caller's
1631/// incoming argument stack.
1632static
1633bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1634                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1635                         const ARMInstrInfo *TII) {
1636  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1637  int FI = INT_MAX;
1638  if (Arg.getOpcode() == ISD::CopyFromReg) {
1639    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1640    if (!TargetRegisterInfo::isVirtualRegister(VR))
1641      return false;
1642    MachineInstr *Def = MRI->getVRegDef(VR);
1643    if (!Def)
1644      return false;
1645    if (!Flags.isByVal()) {
1646      if (!TII->isLoadFromStackSlot(Def, FI))
1647        return false;
1648    } else {
1649      return false;
1650    }
1651  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1652    if (Flags.isByVal())
1653      // ByVal argument is passed in as a pointer but it's now being
1654      // dereferenced. e.g.
1655      // define @foo(%struct.X* %A) {
1656      //   tail call @bar(%struct.X* byval %A)
1657      // }
1658      return false;
1659    SDValue Ptr = Ld->getBasePtr();
1660    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1661    if (!FINode)
1662      return false;
1663    FI = FINode->getIndex();
1664  } else
1665    return false;
1666
1667  assert(FI != INT_MAX);
1668  if (!MFI->isFixedObjectIndex(FI))
1669    return false;
1670  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1671}
1672
1673/// IsEligibleForTailCallOptimization - Check whether the call is eligible
1674/// for tail call optimization. Targets which want to do tail call
1675/// optimization should implement this function.
1676bool
1677ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1678                                                     CallingConv::ID CalleeCC,
1679                                                     bool isVarArg,
1680                                                     bool isCalleeStructRet,
1681                                                     bool isCallerStructRet,
1682                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1683                                    const SmallVectorImpl<SDValue> &OutVals,
1684                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1685                                                     SelectionDAG& DAG) const {
1686  const Function *CallerF = DAG.getMachineFunction().getFunction();
1687  CallingConv::ID CallerCC = CallerF->getCallingConv();
1688  bool CCMatch = CallerCC == CalleeCC;
1689
1690  // Look for obvious safe cases to perform tail call optimization that do not
1691  // require ABI changes. This is what gcc calls sibcall.
1692
1693  // Do not sibcall optimize vararg calls unless the call site is not passing
1694  // any arguments.
1695  if (isVarArg && !Outs.empty())
1696    return false;
1697
1698  // Also avoid sibcall optimization if either caller or callee uses struct
1699  // return semantics.
1700  if (isCalleeStructRet || isCallerStructRet)
1701    return false;
1702
1703  // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1704  // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1705  // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1706  // support in the assembler and linker to be used. This would need to be
1707  // fixed to fully support tail calls in Thumb1.
1708  //
1709  // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1710  // LR.  This means if we need to reload LR, it takes an extra instructions,
1711  // which outweighs the value of the tail call; but here we don't know yet
1712  // whether LR is going to be used.  Probably the right approach is to
1713  // generate the tail call here and turn it back into CALL/RET in
1714  // emitEpilogue if LR is used.
1715
1716  // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1717  // but we need to make sure there are enough registers; the only valid
1718  // registers are the 4 used for parameters.  We don't currently do this
1719  // case.
1720  if (Subtarget->isThumb1Only())
1721    return false;
1722
1723  // If the calling conventions do not match, then we'd better make sure the
1724  // results are returned in the same way as what the caller expects.
1725  if (!CCMatch) {
1726    SmallVector<CCValAssign, 16> RVLocs1;
1727    ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1728                       getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1729    CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1730
1731    SmallVector<CCValAssign, 16> RVLocs2;
1732    ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1733                       getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1734    CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1735
1736    if (RVLocs1.size() != RVLocs2.size())
1737      return false;
1738    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1739      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1740        return false;
1741      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1742        return false;
1743      if (RVLocs1[i].isRegLoc()) {
1744        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1745          return false;
1746      } else {
1747        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1748          return false;
1749      }
1750    }
1751  }
1752
1753  // If the callee takes no arguments then go on to check the results of the
1754  // call.
1755  if (!Outs.empty()) {
1756    // Check if stack adjustment is needed. For now, do not do this if any
1757    // argument is passed on the stack.
1758    SmallVector<CCValAssign, 16> ArgLocs;
1759    ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1760                      getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1761    CCInfo.AnalyzeCallOperands(Outs,
1762                               CCAssignFnForNode(CalleeCC, false, isVarArg));
1763    if (CCInfo.getNextStackOffset()) {
1764      MachineFunction &MF = DAG.getMachineFunction();
1765
1766      // Check if the arguments are already laid out in the right way as
1767      // the caller's fixed stack objects.
1768      MachineFrameInfo *MFI = MF.getFrameInfo();
1769      const MachineRegisterInfo *MRI = &MF.getRegInfo();
1770      const ARMInstrInfo *TII =
1771        ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1772      for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1773           i != e;
1774           ++i, ++realArgIdx) {
1775        CCValAssign &VA = ArgLocs[i];
1776        EVT RegVT = VA.getLocVT();
1777        SDValue Arg = OutVals[realArgIdx];
1778        ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1779        if (VA.getLocInfo() == CCValAssign::Indirect)
1780          return false;
1781        if (VA.needsCustom()) {
1782          // f64 and vector types are split into multiple registers or
1783          // register/stack-slot combinations.  The types will not match
1784          // the registers; give up on memory f64 refs until we figure
1785          // out what to do about this.
1786          if (!VA.isRegLoc())
1787            return false;
1788          if (!ArgLocs[++i].isRegLoc())
1789            return false;
1790          if (RegVT == MVT::v2f64) {
1791            if (!ArgLocs[++i].isRegLoc())
1792              return false;
1793            if (!ArgLocs[++i].isRegLoc())
1794              return false;
1795          }
1796        } else if (!VA.isRegLoc()) {
1797          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1798                                   MFI, MRI, TII))
1799            return false;
1800        }
1801      }
1802    }
1803  }
1804
1805  return true;
1806}
1807
1808SDValue
1809ARMTargetLowering::LowerReturn(SDValue Chain,
1810                               CallingConv::ID CallConv, bool isVarArg,
1811                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1812                               const SmallVectorImpl<SDValue> &OutVals,
1813                               DebugLoc dl, SelectionDAG &DAG) const {
1814
1815  // CCValAssign - represent the assignment of the return value to a location.
1816  SmallVector<CCValAssign, 16> RVLocs;
1817
1818  // CCState - Info about the registers and stack slots.
1819  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1820                    getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1821
1822  // Analyze outgoing return values.
1823  CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1824                                               isVarArg));
1825
1826  // If this is the first return lowered for this function, add
1827  // the regs to the liveout set for the function.
1828  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1829    for (unsigned i = 0; i != RVLocs.size(); ++i)
1830      if (RVLocs[i].isRegLoc())
1831        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1832  }
1833
1834  SDValue Flag;
1835
1836  // Copy the result values into the output registers.
1837  for (unsigned i = 0, realRVLocIdx = 0;
1838       i != RVLocs.size();
1839       ++i, ++realRVLocIdx) {
1840    CCValAssign &VA = RVLocs[i];
1841    assert(VA.isRegLoc() && "Can only return in registers!");
1842
1843    SDValue Arg = OutVals[realRVLocIdx];
1844
1845    switch (VA.getLocInfo()) {
1846    default: llvm_unreachable("Unknown loc info!");
1847    case CCValAssign::Full: break;
1848    case CCValAssign::BCvt:
1849      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1850      break;
1851    }
1852
1853    if (VA.needsCustom()) {
1854      if (VA.getLocVT() == MVT::v2f64) {
1855        // Extract the first half and return it in two registers.
1856        SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1857                                   DAG.getConstant(0, MVT::i32));
1858        SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1859                                       DAG.getVTList(MVT::i32, MVT::i32), Half);
1860
1861        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1862        Flag = Chain.getValue(1);
1863        VA = RVLocs[++i]; // skip ahead to next loc
1864        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1865                                 HalfGPRs.getValue(1), Flag);
1866        Flag = Chain.getValue(1);
1867        VA = RVLocs[++i]; // skip ahead to next loc
1868
1869        // Extract the 2nd half and fall through to handle it as an f64 value.
1870        Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1871                          DAG.getConstant(1, MVT::i32));
1872      }
1873      // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1874      // available.
1875      SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1876                                  DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1877      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1878      Flag = Chain.getValue(1);
1879      VA = RVLocs[++i]; // skip ahead to next loc
1880      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1881                               Flag);
1882    } else
1883      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1884
1885    // Guarantee that all emitted copies are
1886    // stuck together, avoiding something bad.
1887    Flag = Chain.getValue(1);
1888  }
1889
1890  SDValue result;
1891  if (Flag.getNode())
1892    result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1893  else // Return Void
1894    result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1895
1896  return result;
1897}
1898
1899bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1900  if (N->getNumValues() != 1)
1901    return false;
1902  if (!N->hasNUsesOfValue(1, 0))
1903    return false;
1904
1905  unsigned NumCopies = 0;
1906  SDNode* Copies[2];
1907  SDNode *Use = *N->use_begin();
1908  if (Use->getOpcode() == ISD::CopyToReg) {
1909    Copies[NumCopies++] = Use;
1910  } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1911    // f64 returned in a pair of GPRs.
1912    for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1913         UI != UE; ++UI) {
1914      if (UI->getOpcode() != ISD::CopyToReg)
1915        return false;
1916      Copies[UI.getUse().getResNo()] = *UI;
1917      ++NumCopies;
1918    }
1919  } else if (Use->getOpcode() == ISD::BITCAST) {
1920    // f32 returned in a single GPR.
1921    if (!Use->hasNUsesOfValue(1, 0))
1922      return false;
1923    Use = *Use->use_begin();
1924    if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1925      return false;
1926    Copies[NumCopies++] = Use;
1927  } else {
1928    return false;
1929  }
1930
1931  if (NumCopies != 1 && NumCopies != 2)
1932    return false;
1933
1934  bool HasRet = false;
1935  for (unsigned i = 0; i < NumCopies; ++i) {
1936    SDNode *Copy = Copies[i];
1937    for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1938         UI != UE; ++UI) {
1939      if (UI->getOpcode() == ISD::CopyToReg) {
1940        SDNode *Use = *UI;
1941        if (Use == Copies[0] || Use == Copies[1])
1942          continue;
1943        return false;
1944      }
1945      if (UI->getOpcode() != ARMISD::RET_FLAG)
1946        return false;
1947      HasRet = true;
1948    }
1949  }
1950
1951  return HasRet;
1952}
1953
1954bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1955  if (!EnableARMTailCalls)
1956    return false;
1957
1958  if (!CI->isTailCall())
1959    return false;
1960
1961  return !Subtarget->isThumb1Only();
1962}
1963
1964// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1965// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1966// one of the above mentioned nodes. It has to be wrapped because otherwise
1967// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1968// be used to form addressing mode. These wrapped nodes will be selected
1969// into MOVi.
1970static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1971  EVT PtrVT = Op.getValueType();
1972  // FIXME there is no actual debug info here
1973  DebugLoc dl = Op.getDebugLoc();
1974  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1975  SDValue Res;
1976  if (CP->isMachineConstantPoolEntry())
1977    Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1978                                    CP->getAlignment());
1979  else
1980    Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1981                                    CP->getAlignment());
1982  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1983}
1984
1985unsigned ARMTargetLowering::getJumpTableEncoding() const {
1986  return MachineJumpTableInfo::EK_Inline;
1987}
1988
1989SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
1990                                             SelectionDAG &DAG) const {
1991  MachineFunction &MF = DAG.getMachineFunction();
1992  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1993  unsigned ARMPCLabelIndex = 0;
1994  DebugLoc DL = Op.getDebugLoc();
1995  EVT PtrVT = getPointerTy();
1996  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1997  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1998  SDValue CPAddr;
1999  if (RelocM == Reloc::Static) {
2000    CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2001  } else {
2002    unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2003    ARMPCLabelIndex = AFI->createPICLabelUId();
2004    ARMConstantPoolValue *CPV =
2005      ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2006                                      ARMCP::CPBlockAddress, PCAdj);
2007    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2008  }
2009  CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2010  SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2011                               MachinePointerInfo::getConstantPool(),
2012                               false, false, false, 0);
2013  if (RelocM == Reloc::Static)
2014    return Result;
2015  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2016  return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2017}
2018
2019// Lower ISD::GlobalTLSAddress using the "general dynamic" model
2020SDValue
2021ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2022                                                 SelectionDAG &DAG) const {
2023  DebugLoc dl = GA->getDebugLoc();
2024  EVT PtrVT = getPointerTy();
2025  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2026  MachineFunction &MF = DAG.getMachineFunction();
2027  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2028  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2029  ARMConstantPoolValue *CPV =
2030    ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2031                                    ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2032  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2033  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2034  Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2035                         MachinePointerInfo::getConstantPool(),
2036                         false, false, false, 0);
2037  SDValue Chain = Argument.getValue(1);
2038
2039  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2040  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2041
2042  // call __tls_get_addr.
2043  ArgListTy Args;
2044  ArgListEntry Entry;
2045  Entry.Node = Argument;
2046  Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2047  Args.push_back(Entry);
2048  // FIXME: is there useful debug info available here?
2049  std::pair<SDValue, SDValue> CallResult =
2050    LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
2051                false, false, false, false,
2052                0, CallingConv::C, false, /*isReturnValueUsed=*/true,
2053                DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2054  return CallResult.first;
2055}
2056
2057// Lower ISD::GlobalTLSAddress using the "initial exec" or
2058// "local exec" model.
2059SDValue
2060ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2061                                        SelectionDAG &DAG) const {
2062  const GlobalValue *GV = GA->getGlobal();
2063  DebugLoc dl = GA->getDebugLoc();
2064  SDValue Offset;
2065  SDValue Chain = DAG.getEntryNode();
2066  EVT PtrVT = getPointerTy();
2067  // Get the Thread Pointer
2068  SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2069
2070  if (GV->isDeclaration()) {
2071    MachineFunction &MF = DAG.getMachineFunction();
2072    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2073    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2074    // Initial exec model.
2075    unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2076    ARMConstantPoolValue *CPV =
2077      ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2078                                      ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2079                                      true);
2080    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2081    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2082    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2083                         MachinePointerInfo::getConstantPool(),
2084                         false, false, false, 0);
2085    Chain = Offset.getValue(1);
2086
2087    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2088    Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2089
2090    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2091                         MachinePointerInfo::getConstantPool(),
2092                         false, false, false, 0);
2093  } else {
2094    // local exec model
2095    ARMConstantPoolValue *CPV =
2096      ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2097    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2098    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2099    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2100                         MachinePointerInfo::getConstantPool(),
2101                         false, false, false, 0);
2102  }
2103
2104  // The address of the thread local variable is the add of the thread
2105  // pointer with the offset of the variable.
2106  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2107}
2108
2109SDValue
2110ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2111  // TODO: implement the "local dynamic" model
2112  assert(Subtarget->isTargetELF() &&
2113         "TLS not implemented for non-ELF targets");
2114  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2115  // If the relocation model is PIC, use the "General Dynamic" TLS Model,
2116  // otherwise use the "Local Exec" TLS Model
2117  if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
2118    return LowerToTLSGeneralDynamicModel(GA, DAG);
2119  else
2120    return LowerToTLSExecModels(GA, DAG);
2121}
2122
2123SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2124                                                 SelectionDAG &DAG) const {
2125  EVT PtrVT = getPointerTy();
2126  DebugLoc dl = Op.getDebugLoc();
2127  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2128  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2129  if (RelocM == Reloc::PIC_) {
2130    bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2131    ARMConstantPoolValue *CPV =
2132      ARMConstantPoolConstant::Create(GV,
2133                                      UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2134    SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2135    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2136    SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2137                                 CPAddr,
2138                                 MachinePointerInfo::getConstantPool(),
2139                                 false, false, false, 0);
2140    SDValue Chain = Result.getValue(1);
2141    SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2142    Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2143    if (!UseGOTOFF)
2144      Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2145                           MachinePointerInfo::getGOT(),
2146                           false, false, false, 0);
2147    return Result;
2148  }
2149
2150  // If we have T2 ops, we can materialize the address directly via movt/movw
2151  // pair. This is always cheaper.
2152  if (Subtarget->useMovt()) {
2153    ++NumMovwMovt;
2154    // FIXME: Once remat is capable of dealing with instructions with register
2155    // operands, expand this into two nodes.
2156    return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2157                       DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2158  } else {
2159    SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2160    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2161    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2162                       MachinePointerInfo::getConstantPool(),
2163                       false, false, false, 0);
2164  }
2165}
2166
2167SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2168                                                    SelectionDAG &DAG) const {
2169  EVT PtrVT = getPointerTy();
2170  DebugLoc dl = Op.getDebugLoc();
2171  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2172  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2173  MachineFunction &MF = DAG.getMachineFunction();
2174  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2175
2176  // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2177  // update ARMFastISel::ARMMaterializeGV.
2178  if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2179    ++NumMovwMovt;
2180    // FIXME: Once remat is capable of dealing with instructions with register
2181    // operands, expand this into two nodes.
2182    if (RelocM == Reloc::Static)
2183      return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2184                                 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2185
2186    unsigned Wrapper = (RelocM == Reloc::PIC_)
2187      ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2188    SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2189                                 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2190    if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2191      Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2192                           MachinePointerInfo::getGOT(),
2193                           false, false, false, 0);
2194    return Result;
2195  }
2196
2197  unsigned ARMPCLabelIndex = 0;
2198  SDValue CPAddr;
2199  if (RelocM == Reloc::Static) {
2200    CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2201  } else {
2202    ARMPCLabelIndex = AFI->createPICLabelUId();
2203    unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2204    ARMConstantPoolValue *CPV =
2205      ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2206                                      PCAdj);
2207    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2208  }
2209  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2210
2211  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2212                               MachinePointerInfo::getConstantPool(),
2213                               false, false, false, 0);
2214  SDValue Chain = Result.getValue(1);
2215
2216  if (RelocM == Reloc::PIC_) {
2217    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2218    Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2219  }
2220
2221  if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2222    Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2223                         false, false, false, 0);
2224
2225  return Result;
2226}
2227
2228SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2229                                                    SelectionDAG &DAG) const {
2230  assert(Subtarget->isTargetELF() &&
2231         "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2232  MachineFunction &MF = DAG.getMachineFunction();
2233  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2234  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2235  EVT PtrVT = getPointerTy();
2236  DebugLoc dl = Op.getDebugLoc();
2237  unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2238  ARMConstantPoolValue *CPV =
2239    ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2240                                  ARMPCLabelIndex, PCAdj);
2241  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2242  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2243  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2244                               MachinePointerInfo::getConstantPool(),
2245                               false, false, false, 0);
2246  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2247  return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2248}
2249
2250SDValue
2251ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2252  DebugLoc dl = Op.getDebugLoc();
2253  SDValue Val = DAG.getConstant(0, MVT::i32);
2254  return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2255                     DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2256                     Op.getOperand(1), Val);
2257}
2258
2259SDValue
2260ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2261  DebugLoc dl = Op.getDebugLoc();
2262  return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2263                     Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2264}
2265
2266SDValue
2267ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2268                                          const ARMSubtarget *Subtarget) const {
2269  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2270  DebugLoc dl = Op.getDebugLoc();
2271  switch (IntNo) {
2272  default: return SDValue();    // Don't custom lower most intrinsics.
2273  case Intrinsic::arm_thread_pointer: {
2274    EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2275    return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2276  }
2277  case Intrinsic::eh_sjlj_lsda: {
2278    MachineFunction &MF = DAG.getMachineFunction();
2279    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2280    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2281    EVT PtrVT = getPointerTy();
2282    DebugLoc dl = Op.getDebugLoc();
2283    Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2284    SDValue CPAddr;
2285    unsigned PCAdj = (RelocM != Reloc::PIC_)
2286      ? 0 : (Subtarget->isThumb() ? 4 : 8);
2287    ARMConstantPoolValue *CPV =
2288      ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2289                                      ARMCP::CPLSDA, PCAdj);
2290    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2291    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2292    SDValue Result =
2293      DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2294                  MachinePointerInfo::getConstantPool(),
2295                  false, false, false, 0);
2296
2297    if (RelocM == Reloc::PIC_) {
2298      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2299      Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2300    }
2301    return Result;
2302  }
2303  case Intrinsic::arm_neon_vmulls:
2304  case Intrinsic::arm_neon_vmullu: {
2305    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2306      ? ARMISD::VMULLs : ARMISD::VMULLu;
2307    return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2308                       Op.getOperand(1), Op.getOperand(2));
2309  }
2310  }
2311}
2312
2313static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2314                               const ARMSubtarget *Subtarget) {
2315  DebugLoc dl = Op.getDebugLoc();
2316  if (!Subtarget->hasDataBarrier()) {
2317    // Some ARMv6 cpus can support data barriers with an mcr instruction.
2318    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2319    // here.
2320    assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2321           "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2322    return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2323                       DAG.getConstant(0, MVT::i32));
2324  }
2325
2326  SDValue Op5 = Op.getOperand(5);
2327  bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2328  unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2329  unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2330  bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2331
2332  ARM_MB::MemBOpt DMBOpt;
2333  if (isDeviceBarrier)
2334    DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2335  else
2336    DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2337  return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2338                     DAG.getConstant(DMBOpt, MVT::i32));
2339}
2340
2341
2342static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2343                                 const ARMSubtarget *Subtarget) {
2344  // FIXME: handle "fence singlethread" more efficiently.
2345  DebugLoc dl = Op.getDebugLoc();
2346  if (!Subtarget->hasDataBarrier()) {
2347    // Some ARMv6 cpus can support data barriers with an mcr instruction.
2348    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2349    // here.
2350    assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2351           "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2352    return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2353                       DAG.getConstant(0, MVT::i32));
2354  }
2355
2356  return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2357                     DAG.getConstant(ARM_MB::ISH, MVT::i32));
2358}
2359
2360static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2361                             const ARMSubtarget *Subtarget) {
2362  // ARM pre v5TE and Thumb1 does not have preload instructions.
2363  if (!(Subtarget->isThumb2() ||
2364        (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2365    // Just preserve the chain.
2366    return Op.getOperand(0);
2367
2368  DebugLoc dl = Op.getDebugLoc();
2369  unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2370  if (!isRead &&
2371      (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2372    // ARMv7 with MP extension has PLDW.
2373    return Op.getOperand(0);
2374
2375  unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2376  if (Subtarget->isThumb()) {
2377    // Invert the bits.
2378    isRead = ~isRead & 1;
2379    isData = ~isData & 1;
2380  }
2381
2382  return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2383                     Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2384                     DAG.getConstant(isData, MVT::i32));
2385}
2386
2387static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2388  MachineFunction &MF = DAG.getMachineFunction();
2389  ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2390
2391  // vastart just stores the address of the VarArgsFrameIndex slot into the
2392  // memory location argument.
2393  DebugLoc dl = Op.getDebugLoc();
2394  EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2395  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2396  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2397  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2398                      MachinePointerInfo(SV), false, false, 0);
2399}
2400
2401SDValue
2402ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2403                                        SDValue &Root, SelectionDAG &DAG,
2404                                        DebugLoc dl) const {
2405  MachineFunction &MF = DAG.getMachineFunction();
2406  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2407
2408  TargetRegisterClass *RC;
2409  if (AFI->isThumb1OnlyFunction())
2410    RC = ARM::tGPRRegisterClass;
2411  else
2412    RC = ARM::GPRRegisterClass;
2413
2414  // Transform the arguments stored in physical registers into virtual ones.
2415  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2416  SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2417
2418  SDValue ArgValue2;
2419  if (NextVA.isMemLoc()) {
2420    MachineFrameInfo *MFI = MF.getFrameInfo();
2421    int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2422
2423    // Create load node to retrieve arguments from the stack.
2424    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2425    ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2426                            MachinePointerInfo::getFixedStack(FI),
2427                            false, false, false, 0);
2428  } else {
2429    Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2430    ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2431  }
2432
2433  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2434}
2435
2436void
2437ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2438                                  unsigned &VARegSize, unsigned &VARegSaveSize)
2439  const {
2440  unsigned NumGPRs;
2441  if (CCInfo.isFirstByValRegValid())
2442    NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2443  else {
2444    unsigned int firstUnalloced;
2445    firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2446                                                sizeof(GPRArgRegs) /
2447                                                sizeof(GPRArgRegs[0]));
2448    NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2449  }
2450
2451  unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2452  VARegSize = NumGPRs * 4;
2453  VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2454}
2455
2456// The remaining GPRs hold either the beginning of variable-argument
2457// data, or the beginning of an aggregate passed by value (usuall
2458// byval).  Either way, we allocate stack slots adjacent to the data
2459// provided by our caller, and store the unallocated registers there.
2460// If this is a variadic function, the va_list pointer will begin with
2461// these values; otherwise, this reassembles a (byval) structure that
2462// was split between registers and memory.
2463void
2464ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2465                                        DebugLoc dl, SDValue &Chain,
2466                                        unsigned ArgOffset) const {
2467  MachineFunction &MF = DAG.getMachineFunction();
2468  MachineFrameInfo *MFI = MF.getFrameInfo();
2469  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2470  unsigned firstRegToSaveIndex;
2471  if (CCInfo.isFirstByValRegValid())
2472    firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2473  else {
2474    firstRegToSaveIndex = CCInfo.getFirstUnallocated
2475      (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2476  }
2477
2478  unsigned VARegSize, VARegSaveSize;
2479  computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2480  if (VARegSaveSize) {
2481    // If this function is vararg, store any remaining integer argument regs
2482    // to their spots on the stack so that they may be loaded by deferencing
2483    // the result of va_next.
2484    AFI->setVarArgsRegSaveSize(VARegSaveSize);
2485    AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2486                                                     ArgOffset + VARegSaveSize
2487                                                     - VARegSize,
2488                                                     false));
2489    SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2490                                    getPointerTy());
2491
2492    SmallVector<SDValue, 4> MemOps;
2493    for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2494      TargetRegisterClass *RC;
2495      if (AFI->isThumb1OnlyFunction())
2496        RC = ARM::tGPRRegisterClass;
2497      else
2498        RC = ARM::GPRRegisterClass;
2499
2500      unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2501      SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2502      SDValue Store =
2503        DAG.getStore(Val.getValue(1), dl, Val, FIN,
2504                 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2505                     false, false, 0);
2506      MemOps.push_back(Store);
2507      FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2508                        DAG.getConstant(4, getPointerTy()));
2509    }
2510    if (!MemOps.empty())
2511      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2512                          &MemOps[0], MemOps.size());
2513  } else
2514    // This will point to the next argument passed via stack.
2515    AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2516}
2517
2518SDValue
2519ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2520                                        CallingConv::ID CallConv, bool isVarArg,
2521                                        const SmallVectorImpl<ISD::InputArg>
2522                                          &Ins,
2523                                        DebugLoc dl, SelectionDAG &DAG,
2524                                        SmallVectorImpl<SDValue> &InVals)
2525                                          const {
2526  MachineFunction &MF = DAG.getMachineFunction();
2527  MachineFrameInfo *MFI = MF.getFrameInfo();
2528
2529  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2530
2531  // Assign locations to all of the incoming arguments.
2532  SmallVector<CCValAssign, 16> ArgLocs;
2533  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2534                    getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2535  CCInfo.AnalyzeFormalArguments(Ins,
2536                                CCAssignFnForNode(CallConv, /* Return*/ false,
2537                                                  isVarArg));
2538
2539  SmallVector<SDValue, 16> ArgValues;
2540  int lastInsIndex = -1;
2541
2542  SDValue ArgValue;
2543  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2544    CCValAssign &VA = ArgLocs[i];
2545
2546    // Arguments stored in registers.
2547    if (VA.isRegLoc()) {
2548      EVT RegVT = VA.getLocVT();
2549
2550      if (VA.needsCustom()) {
2551        // f64 and vector types are split up into multiple registers or
2552        // combinations of registers and stack slots.
2553        if (VA.getLocVT() == MVT::v2f64) {
2554          SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2555                                                   Chain, DAG, dl);
2556          VA = ArgLocs[++i]; // skip ahead to next loc
2557          SDValue ArgValue2;
2558          if (VA.isMemLoc()) {
2559            int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2560            SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2561            ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2562                                    MachinePointerInfo::getFixedStack(FI),
2563                                    false, false, false, 0);
2564          } else {
2565            ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2566                                             Chain, DAG, dl);
2567          }
2568          ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2569          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2570                                 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2571          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2572                                 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2573        } else
2574          ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2575
2576      } else {
2577        TargetRegisterClass *RC;
2578
2579        if (RegVT == MVT::f32)
2580          RC = ARM::SPRRegisterClass;
2581        else if (RegVT == MVT::f64)
2582          RC = ARM::DPRRegisterClass;
2583        else if (RegVT == MVT::v2f64)
2584          RC = ARM::QPRRegisterClass;
2585        else if (RegVT == MVT::i32)
2586          RC = (AFI->isThumb1OnlyFunction() ?
2587                ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2588        else
2589          llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2590
2591        // Transform the arguments in physical registers into virtual ones.
2592        unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2593        ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2594      }
2595
2596      // If this is an 8 or 16-bit value, it is really passed promoted
2597      // to 32 bits.  Insert an assert[sz]ext to capture this, then
2598      // truncate to the right size.
2599      switch (VA.getLocInfo()) {
2600      default: llvm_unreachable("Unknown loc info!");
2601      case CCValAssign::Full: break;
2602      case CCValAssign::BCvt:
2603        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2604        break;
2605      case CCValAssign::SExt:
2606        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2607                               DAG.getValueType(VA.getValVT()));
2608        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2609        break;
2610      case CCValAssign::ZExt:
2611        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2612                               DAG.getValueType(VA.getValVT()));
2613        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2614        break;
2615      }
2616
2617      InVals.push_back(ArgValue);
2618
2619    } else { // VA.isRegLoc()
2620
2621      // sanity check
2622      assert(VA.isMemLoc());
2623      assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2624
2625      int index = ArgLocs[i].getValNo();
2626
2627      // Some Ins[] entries become multiple ArgLoc[] entries.
2628      // Process them only once.
2629      if (index != lastInsIndex)
2630        {
2631          ISD::ArgFlagsTy Flags = Ins[index].Flags;
2632          // FIXME: For now, all byval parameter objects are marked mutable.
2633          // This can be changed with more analysis.
2634          // In case of tail call optimization mark all arguments mutable.
2635          // Since they could be overwritten by lowering of arguments in case of
2636          // a tail call.
2637          if (Flags.isByVal()) {
2638            unsigned VARegSize, VARegSaveSize;
2639            computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2640            VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2641            unsigned Bytes = Flags.getByValSize() - VARegSize;
2642            if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2643            int FI = MFI->CreateFixedObject(Bytes,
2644                                            VA.getLocMemOffset(), false);
2645            InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2646          } else {
2647            int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2648                                            VA.getLocMemOffset(), true);
2649
2650            // Create load nodes to retrieve arguments from the stack.
2651            SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2652            InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2653                                         MachinePointerInfo::getFixedStack(FI),
2654                                         false, false, false, 0));
2655          }
2656          lastInsIndex = index;
2657        }
2658    }
2659  }
2660
2661  // varargs
2662  if (isVarArg)
2663    VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2664
2665  return Chain;
2666}
2667
2668/// isFloatingPointZero - Return true if this is +0.0.
2669static bool isFloatingPointZero(SDValue Op) {
2670  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2671    return CFP->getValueAPF().isPosZero();
2672  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2673    // Maybe this has already been legalized into the constant pool?
2674    if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2675      SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2676      if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2677        if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2678          return CFP->getValueAPF().isPosZero();
2679    }
2680  }
2681  return false;
2682}
2683
2684/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2685/// the given operands.
2686SDValue
2687ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2688                             SDValue &ARMcc, SelectionDAG &DAG,
2689                             DebugLoc dl) const {
2690  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2691    unsigned C = RHSC->getZExtValue();
2692    if (!isLegalICmpImmediate(C)) {
2693      // Constant does not fit, try adjusting it by one?
2694      switch (CC) {
2695      default: break;
2696      case ISD::SETLT:
2697      case ISD::SETGE:
2698        if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2699          CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2700          RHS = DAG.getConstant(C-1, MVT::i32);
2701        }
2702        break;
2703      case ISD::SETULT:
2704      case ISD::SETUGE:
2705        if (C != 0 && isLegalICmpImmediate(C-1)) {
2706          CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2707          RHS = DAG.getConstant(C-1, MVT::i32);
2708        }
2709        break;
2710      case ISD::SETLE:
2711      case ISD::SETGT:
2712        if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2713          CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2714          RHS = DAG.getConstant(C+1, MVT::i32);
2715        }
2716        break;
2717      case ISD::SETULE:
2718      case ISD::SETUGT:
2719        if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2720          CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2721          RHS = DAG.getConstant(C+1, MVT::i32);
2722        }
2723        break;
2724      }
2725    }
2726  }
2727
2728  ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2729  ARMISD::NodeType CompareType;
2730  switch (CondCode) {
2731  default:
2732    CompareType = ARMISD::CMP;
2733    break;
2734  case ARMCC::EQ:
2735  case ARMCC::NE:
2736    // Uses only Z Flag
2737    CompareType = ARMISD::CMPZ;
2738    break;
2739  }
2740  ARMcc = DAG.getConstant(CondCode, MVT::i32);
2741  return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2742}
2743
2744/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2745SDValue
2746ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2747                             DebugLoc dl) const {
2748  SDValue Cmp;
2749  if (!isFloatingPointZero(RHS))
2750    Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2751  else
2752    Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2753  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2754}
2755
2756/// duplicateCmp - Glue values can have only one use, so this function
2757/// duplicates a comparison node.
2758SDValue
2759ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2760  unsigned Opc = Cmp.getOpcode();
2761  DebugLoc DL = Cmp.getDebugLoc();
2762  if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2763    return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2764
2765  assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2766  Cmp = Cmp.getOperand(0);
2767  Opc = Cmp.getOpcode();
2768  if (Opc == ARMISD::CMPFP)
2769    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2770  else {
2771    assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2772    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2773  }
2774  return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2775}
2776
2777SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2778  SDValue Cond = Op.getOperand(0);
2779  SDValue SelectTrue = Op.getOperand(1);
2780  SDValue SelectFalse = Op.getOperand(2);
2781  DebugLoc dl = Op.getDebugLoc();
2782
2783  // Convert:
2784  //
2785  //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2786  //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2787  //
2788  if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2789    const ConstantSDNode *CMOVTrue =
2790      dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2791    const ConstantSDNode *CMOVFalse =
2792      dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2793
2794    if (CMOVTrue && CMOVFalse) {
2795      unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2796      unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2797
2798      SDValue True;
2799      SDValue False;
2800      if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2801        True = SelectTrue;
2802        False = SelectFalse;
2803      } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2804        True = SelectFalse;
2805        False = SelectTrue;
2806      }
2807
2808      if (True.getNode() && False.getNode()) {
2809        EVT VT = Op.getValueType();
2810        SDValue ARMcc = Cond.getOperand(2);
2811        SDValue CCR = Cond.getOperand(3);
2812        SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2813        assert(True.getValueType() == VT);
2814        return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2815      }
2816    }
2817  }
2818
2819  return DAG.getSelectCC(dl, Cond,
2820                         DAG.getConstant(0, Cond.getValueType()),
2821                         SelectTrue, SelectFalse, ISD::SETNE);
2822}
2823
2824SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2825  EVT VT = Op.getValueType();
2826  SDValue LHS = Op.getOperand(0);
2827  SDValue RHS = Op.getOperand(1);
2828  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2829  SDValue TrueVal = Op.getOperand(2);
2830  SDValue FalseVal = Op.getOperand(3);
2831  DebugLoc dl = Op.getDebugLoc();
2832
2833  if (LHS.getValueType() == MVT::i32) {
2834    SDValue ARMcc;
2835    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2836    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2837    return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2838  }
2839
2840  ARMCC::CondCodes CondCode, CondCode2;
2841  FPCCToARMCC(CC, CondCode, CondCode2);
2842
2843  SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2844  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2845  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2846  SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2847                               ARMcc, CCR, Cmp);
2848  if (CondCode2 != ARMCC::AL) {
2849    SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2850    // FIXME: Needs another CMP because flag can have but one use.
2851    SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2852    Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2853                         Result, TrueVal, ARMcc2, CCR, Cmp2);
2854  }
2855  return Result;
2856}
2857
2858/// canChangeToInt - Given the fp compare operand, return true if it is suitable
2859/// to morph to an integer compare sequence.
2860static bool canChangeToInt(SDValue Op, bool &SeenZero,
2861                           const ARMSubtarget *Subtarget) {
2862  SDNode *N = Op.getNode();
2863  if (!N->hasOneUse())
2864    // Otherwise it requires moving the value from fp to integer registers.
2865    return false;
2866  if (!N->getNumValues())
2867    return false;
2868  EVT VT = Op.getValueType();
2869  if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2870    // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2871    // vmrs are very slow, e.g. cortex-a8.
2872    return false;
2873
2874  if (isFloatingPointZero(Op)) {
2875    SeenZero = true;
2876    return true;
2877  }
2878  return ISD::isNormalLoad(N);
2879}
2880
2881static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2882  if (isFloatingPointZero(Op))
2883    return DAG.getConstant(0, MVT::i32);
2884
2885  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2886    return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2887                       Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2888                       Ld->isVolatile(), Ld->isNonTemporal(),
2889                       Ld->isInvariant(), Ld->getAlignment());
2890
2891  llvm_unreachable("Unknown VFP cmp argument!");
2892}
2893
2894static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2895                           SDValue &RetVal1, SDValue &RetVal2) {
2896  if (isFloatingPointZero(Op)) {
2897    RetVal1 = DAG.getConstant(0, MVT::i32);
2898    RetVal2 = DAG.getConstant(0, MVT::i32);
2899    return;
2900  }
2901
2902  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2903    SDValue Ptr = Ld->getBasePtr();
2904    RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2905                          Ld->getChain(), Ptr,
2906                          Ld->getPointerInfo(),
2907                          Ld->isVolatile(), Ld->isNonTemporal(),
2908                          Ld->isInvariant(), Ld->getAlignment());
2909
2910    EVT PtrType = Ptr.getValueType();
2911    unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2912    SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2913                                 PtrType, Ptr, DAG.getConstant(4, PtrType));
2914    RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2915                          Ld->getChain(), NewPtr,
2916                          Ld->getPointerInfo().getWithOffset(4),
2917                          Ld->isVolatile(), Ld->isNonTemporal(),
2918                          Ld->isInvariant(), NewAlign);
2919    return;
2920  }
2921
2922  llvm_unreachable("Unknown VFP cmp argument!");
2923}
2924
2925/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2926/// f32 and even f64 comparisons to integer ones.
2927SDValue
2928ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2929  SDValue Chain = Op.getOperand(0);
2930  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2931  SDValue LHS = Op.getOperand(2);
2932  SDValue RHS = Op.getOperand(3);
2933  SDValue Dest = Op.getOperand(4);
2934  DebugLoc dl = Op.getDebugLoc();
2935
2936  bool SeenZero = false;
2937  if (canChangeToInt(LHS, SeenZero, Subtarget) &&
2938      canChangeToInt(RHS, SeenZero, Subtarget) &&
2939      // If one of the operand is zero, it's safe to ignore the NaN case since
2940      // we only care about equality comparisons.
2941      (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))) {
2942    // If unsafe fp math optimization is enabled and there are no other uses of
2943    // the CMP operands, and the condition code is EQ or NE, we can optimize it
2944    // to an integer comparison.
2945    if (CC == ISD::SETOEQ)
2946      CC = ISD::SETEQ;
2947    else if (CC == ISD::SETUNE)
2948      CC = ISD::SETNE;
2949
2950    SDValue ARMcc;
2951    if (LHS.getValueType() == MVT::f32) {
2952      LHS = bitcastf32Toi32(LHS, DAG);
2953      RHS = bitcastf32Toi32(RHS, DAG);
2954      SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2955      SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2956      return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2957                         Chain, Dest, ARMcc, CCR, Cmp);
2958    }
2959
2960    SDValue LHS1, LHS2;
2961    SDValue RHS1, RHS2;
2962    expandf64Toi32(LHS, DAG, LHS1, LHS2);
2963    expandf64Toi32(RHS, DAG, RHS1, RHS2);
2964    ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2965    ARMcc = DAG.getConstant(CondCode, MVT::i32);
2966    SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2967    SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
2968    return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
2969  }
2970
2971  return SDValue();
2972}
2973
2974SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2975  SDValue Chain = Op.getOperand(0);
2976  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2977  SDValue LHS = Op.getOperand(2);
2978  SDValue RHS = Op.getOperand(3);
2979  SDValue Dest = Op.getOperand(4);
2980  DebugLoc dl = Op.getDebugLoc();
2981
2982  if (LHS.getValueType() == MVT::i32) {
2983    SDValue ARMcc;
2984    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2985    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2986    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2987                       Chain, Dest, ARMcc, CCR, Cmp);
2988  }
2989
2990  assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2991
2992  if (getTargetMachine().Options.UnsafeFPMath &&
2993      (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
2994       CC == ISD::SETNE || CC == ISD::SETUNE)) {
2995    SDValue Result = OptimizeVFPBrcond(Op, DAG);
2996    if (Result.getNode())
2997      return Result;
2998  }
2999
3000  ARMCC::CondCodes CondCode, CondCode2;
3001  FPCCToARMCC(CC, CondCode, CondCode2);
3002
3003  SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3004  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3005  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3006  SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3007  SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3008  SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3009  if (CondCode2 != ARMCC::AL) {
3010    ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3011    SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3012    Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3013  }
3014  return Res;
3015}
3016
3017SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3018  SDValue Chain = Op.getOperand(0);
3019  SDValue Table = Op.getOperand(1);
3020  SDValue Index = Op.getOperand(2);
3021  DebugLoc dl = Op.getDebugLoc();
3022
3023  EVT PTy = getPointerTy();
3024  JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3025  ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3026  SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3027  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3028  Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3029  Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3030  SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3031  if (Subtarget->isThumb2()) {
3032    // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3033    // which does another jump to the destination. This also makes it easier
3034    // to translate it to TBB / TBH later.
3035    // FIXME: This might not work if the function is extremely large.
3036    return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3037                       Addr, Op.getOperand(2), JTI, UId);
3038  }
3039  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3040    Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3041                       MachinePointerInfo::getJumpTable(),
3042                       false, false, false, 0);
3043    Chain = Addr.getValue(1);
3044    Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3045    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3046  } else {
3047    Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3048                       MachinePointerInfo::getJumpTable(),
3049                       false, false, false, 0);
3050    Chain = Addr.getValue(1);
3051    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3052  }
3053}
3054
3055static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3056  assert(Op.getValueType().getVectorElementType() == MVT::i32
3057         && "Unexpected custom lowering");
3058
3059  if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3060    return Op;
3061  return DAG.UnrollVectorOp(Op.getNode());
3062}
3063
3064static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3065  EVT VT = Op.getValueType();
3066  if (VT.isVector())
3067    return LowerVectorFP_TO_INT(Op, DAG);
3068
3069  DebugLoc dl = Op.getDebugLoc();
3070  unsigned Opc;
3071
3072  switch (Op.getOpcode()) {
3073  default:
3074    assert(0 && "Invalid opcode!");
3075  case ISD::FP_TO_SINT:
3076    Opc = ARMISD::FTOSI;
3077    break;
3078  case ISD::FP_TO_UINT:
3079    Opc = ARMISD::FTOUI;
3080    break;
3081  }
3082  Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3083  return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3084}
3085
3086static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3087  EVT VT = Op.getValueType();
3088  DebugLoc dl = Op.getDebugLoc();
3089
3090  if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3091    if (VT.getVectorElementType() == MVT::f32)
3092      return Op;
3093    return DAG.UnrollVectorOp(Op.getNode());
3094  }
3095
3096  assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3097         "Invalid type for custom lowering!");
3098  if (VT != MVT::v4f32)
3099    return DAG.UnrollVectorOp(Op.getNode());
3100
3101  unsigned CastOpc;
3102  unsigned Opc;
3103  switch (Op.getOpcode()) {
3104  default:
3105    assert(0 && "Invalid opcode!");
3106  case ISD::SINT_TO_FP:
3107    CastOpc = ISD::SIGN_EXTEND;
3108    Opc = ISD::SINT_TO_FP;
3109    break;
3110  case ISD::UINT_TO_FP:
3111    CastOpc = ISD::ZERO_EXTEND;
3112    Opc = ISD::UINT_TO_FP;
3113    break;
3114  }
3115
3116  Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3117  return DAG.getNode(Opc, dl, VT, Op);
3118}
3119
3120static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3121  EVT VT = Op.getValueType();
3122  if (VT.isVector())
3123    return LowerVectorINT_TO_FP(Op, DAG);
3124
3125  DebugLoc dl = Op.getDebugLoc();
3126  unsigned Opc;
3127
3128  switch (Op.getOpcode()) {
3129  default:
3130    assert(0 && "Invalid opcode!");
3131  case ISD::SINT_TO_FP:
3132    Opc = ARMISD::SITOF;
3133    break;
3134  case ISD::UINT_TO_FP:
3135    Opc = ARMISD::UITOF;
3136    break;
3137  }
3138
3139  Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3140  return DAG.getNode(Opc, dl, VT, Op);
3141}
3142
3143SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3144  // Implement fcopysign with a fabs and a conditional fneg.
3145  SDValue Tmp0 = Op.getOperand(0);
3146  SDValue Tmp1 = Op.getOperand(1);
3147  DebugLoc dl = Op.getDebugLoc();
3148  EVT VT = Op.getValueType();
3149  EVT SrcVT = Tmp1.getValueType();
3150  bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3151    Tmp0.getOpcode() == ARMISD::VMOVDRR;
3152  bool UseNEON = !InGPR && Subtarget->hasNEON();
3153
3154  if (UseNEON) {
3155    // Use VBSL to copy the sign bit.
3156    unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3157    SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3158                               DAG.getTargetConstant(EncodedVal, MVT::i32));
3159    EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3160    if (VT == MVT::f64)
3161      Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3162                         DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3163                         DAG.getConstant(32, MVT::i32));
3164    else /*if (VT == MVT::f32)*/
3165      Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3166    if (SrcVT == MVT::f32) {
3167      Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3168      if (VT == MVT::f64)
3169        Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3170                           DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3171                           DAG.getConstant(32, MVT::i32));
3172    } else if (VT == MVT::f32)
3173      Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3174                         DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3175                         DAG.getConstant(32, MVT::i32));
3176    Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3177    Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3178
3179    SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3180                                            MVT::i32);
3181    AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3182    SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3183                                  DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3184
3185    SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3186                              DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3187                              DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3188    if (VT == MVT::f32) {
3189      Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3190      Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3191                        DAG.getConstant(0, MVT::i32));
3192    } else {
3193      Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3194    }
3195
3196    return Res;
3197  }
3198
3199  // Bitcast operand 1 to i32.
3200  if (SrcVT == MVT::f64)
3201    Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3202                       &Tmp1, 1).getValue(1);
3203  Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3204
3205  // Or in the signbit with integer operations.
3206  SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3207  SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3208  Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3209  if (VT == MVT::f32) {
3210    Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3211                       DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3212    return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3213                       DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3214  }
3215
3216  // f64: Or the high part with signbit and then combine two parts.
3217  Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3218                     &Tmp0, 1);
3219  SDValue Lo = Tmp0.getValue(0);
3220  SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3221  Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3222  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3223}
3224
3225SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3226  MachineFunction &MF = DAG.getMachineFunction();
3227  MachineFrameInfo *MFI = MF.getFrameInfo();
3228  MFI->setReturnAddressIsTaken(true);
3229
3230  EVT VT = Op.getValueType();
3231  DebugLoc dl = Op.getDebugLoc();
3232  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3233  if (Depth) {
3234    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3235    SDValue Offset = DAG.getConstant(4, MVT::i32);
3236    return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3237                       DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3238                       MachinePointerInfo(), false, false, false, 0);
3239  }
3240
3241  // Return LR, which contains the return address. Mark it an implicit live-in.
3242  unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3243  return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3244}
3245
3246SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3247  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3248  MFI->setFrameAddressIsTaken(true);
3249
3250  EVT VT = Op.getValueType();
3251  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3252  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3253  unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3254    ? ARM::R7 : ARM::R11;
3255  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3256  while (Depth--)
3257    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3258                            MachinePointerInfo(),
3259                            false, false, false, 0);
3260  return FrameAddr;
3261}
3262
3263/// ExpandBITCAST - If the target supports VFP, this function is called to
3264/// expand a bit convert where either the source or destination type is i64 to
3265/// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3266/// operand type is illegal (e.g., v2f32 for a target that doesn't support
3267/// vectors), since the legalizer won't know what to do with that.
3268static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3269  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3270  DebugLoc dl = N->getDebugLoc();
3271  SDValue Op = N->getOperand(0);
3272
3273  // This function is only supposed to be called for i64 types, either as the
3274  // source or destination of the bit convert.
3275  EVT SrcVT = Op.getValueType();
3276  EVT DstVT = N->getValueType(0);
3277  assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3278         "ExpandBITCAST called for non-i64 type");
3279
3280  // Turn i64->f64 into VMOVDRR.
3281  if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3282    SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3283                             DAG.getConstant(0, MVT::i32));
3284    SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3285                             DAG.getConstant(1, MVT::i32));
3286    return DAG.getNode(ISD::BITCAST, dl, DstVT,
3287                       DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3288  }
3289
3290  // Turn f64->i64 into VMOVRRD.
3291  if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3292    SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3293                              DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3294    // Merge the pieces into a single i64 value.
3295    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3296  }
3297
3298  return SDValue();
3299}
3300
3301/// getZeroVector - Returns a vector of specified type with all zero elements.
3302/// Zero vectors are used to represent vector negation and in those cases
3303/// will be implemented with the NEON VNEG instruction.  However, VNEG does
3304/// not support i64 elements, so sometimes the zero vectors will need to be
3305/// explicitly constructed.  Regardless, use a canonical VMOV to create the
3306/// zero vector.
3307static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3308  assert(VT.isVector() && "Expected a vector type");
3309  // The canonical modified immediate encoding of a zero vector is....0!
3310  SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3311  EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3312  SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3313  return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3314}
3315
3316/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3317/// i32 values and take a 2 x i32 value to shift plus a shift amount.
3318SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3319                                                SelectionDAG &DAG) const {
3320  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3321  EVT VT = Op.getValueType();
3322  unsigned VTBits = VT.getSizeInBits();
3323  DebugLoc dl = Op.getDebugLoc();
3324  SDValue ShOpLo = Op.getOperand(0);
3325  SDValue ShOpHi = Op.getOperand(1);
3326  SDValue ShAmt  = Op.getOperand(2);
3327  SDValue ARMcc;
3328  unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3329
3330  assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3331
3332  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3333                                 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3334  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3335  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3336                                   DAG.getConstant(VTBits, MVT::i32));
3337  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3338  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3339  SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3340
3341  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3342  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3343                          ARMcc, DAG, dl);
3344  SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3345  SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3346                           CCR, Cmp);
3347
3348  SDValue Ops[2] = { Lo, Hi };
3349  return DAG.getMergeValues(Ops, 2, dl);
3350}
3351
3352/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3353/// i32 values and take a 2 x i32 value to shift plus a shift amount.
3354SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3355                                               SelectionDAG &DAG) const {
3356  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3357  EVT VT = Op.getValueType();
3358  unsigned VTBits = VT.getSizeInBits();
3359  DebugLoc dl = Op.getDebugLoc();
3360  SDValue ShOpLo = Op.getOperand(0);
3361  SDValue ShOpHi = Op.getOperand(1);
3362  SDValue ShAmt  = Op.getOperand(2);
3363  SDValue ARMcc;
3364
3365  assert(Op.getOpcode() == ISD::SHL_PARTS);
3366  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3367                                 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3368  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3369  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3370                                   DAG.getConstant(VTBits, MVT::i32));
3371  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3372  SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3373
3374  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3375  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3376  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3377                          ARMcc, DAG, dl);
3378  SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3379  SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3380                           CCR, Cmp);
3381
3382  SDValue Ops[2] = { Lo, Hi };
3383  return DAG.getMergeValues(Ops, 2, dl);
3384}
3385
3386SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3387                                            SelectionDAG &DAG) const {
3388  // The rounding mode is in bits 23:22 of the FPSCR.
3389  // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3390  // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3391  // so that the shift + and get folded into a bitfield extract.
3392  DebugLoc dl = Op.getDebugLoc();
3393  SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3394                              DAG.getConstant(Intrinsic::arm_get_fpscr,
3395                                              MVT::i32));
3396  SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3397                                  DAG.getConstant(1U << 22, MVT::i32));
3398  SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3399                              DAG.getConstant(22, MVT::i32));
3400  return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3401                     DAG.getConstant(3, MVT::i32));
3402}
3403
3404static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3405                         const ARMSubtarget *ST) {
3406  EVT VT = N->getValueType(0);
3407  DebugLoc dl = N->getDebugLoc();
3408
3409  if (!ST->hasV6T2Ops())
3410    return SDValue();
3411
3412  SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3413  return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3414}
3415
3416static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3417                          const ARMSubtarget *ST) {
3418  EVT VT = N->getValueType(0);
3419  DebugLoc dl = N->getDebugLoc();
3420
3421  if (!VT.isVector())
3422    return SDValue();
3423
3424  // Lower vector shifts on NEON to use VSHL.
3425  assert(ST->hasNEON() && "unexpected vector shift");
3426
3427  // Left shifts translate directly to the vshiftu intrinsic.
3428  if (N->getOpcode() == ISD::SHL)
3429    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3430                       DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3431                       N->getOperand(0), N->getOperand(1));
3432
3433  assert((N->getOpcode() == ISD::SRA ||
3434          N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3435
3436  // NEON uses the same intrinsics for both left and right shifts.  For
3437  // right shifts, the shift amounts are negative, so negate the vector of
3438  // shift amounts.
3439  EVT ShiftVT = N->getOperand(1).getValueType();
3440  SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3441                                     getZeroVector(ShiftVT, DAG, dl),
3442                                     N->getOperand(1));
3443  Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3444                             Intrinsic::arm_neon_vshifts :
3445                             Intrinsic::arm_neon_vshiftu);
3446  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3447                     DAG.getConstant(vshiftInt, MVT::i32),
3448                     N->getOperand(0), NegatedCount);
3449}
3450
3451static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3452                                const ARMSubtarget *ST) {
3453  EVT VT = N->getValueType(0);
3454  DebugLoc dl = N->getDebugLoc();
3455
3456  // We can get here for a node like i32 = ISD::SHL i32, i64
3457  if (VT != MVT::i64)
3458    return SDValue();
3459
3460  assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3461         "Unknown shift to lower!");
3462
3463  // We only lower SRA, SRL of 1 here, all others use generic lowering.
3464  if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3465      cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3466    return SDValue();
3467
3468  // If we are in thumb mode, we don't have RRX.
3469  if (ST->isThumb1Only()) return SDValue();
3470
3471  // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3472  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3473                           DAG.getConstant(0, MVT::i32));
3474  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3475                           DAG.getConstant(1, MVT::i32));
3476
3477  // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3478  // captures the result into a carry flag.
3479  unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3480  Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3481
3482  // The low part is an ARMISD::RRX operand, which shifts the carry in.
3483  Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3484
3485  // Merge the pieces into a single i64 value.
3486 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3487}
3488
3489static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3490  SDValue TmpOp0, TmpOp1;
3491  bool Invert = false;
3492  bool Swap = false;
3493  unsigned Opc = 0;
3494
3495  SDValue Op0 = Op.getOperand(0);
3496  SDValue Op1 = Op.getOperand(1);
3497  SDValue CC = Op.getOperand(2);
3498  EVT VT = Op.getValueType();
3499  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3500  DebugLoc dl = Op.getDebugLoc();
3501
3502  if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3503    switch (SetCCOpcode) {
3504    default: llvm_unreachable("Illegal FP comparison");
3505    case ISD::SETUNE:
3506    case ISD::SETNE:  Invert = true; // Fallthrough
3507    case ISD::SETOEQ:
3508    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3509    case ISD::SETOLT:
3510    case ISD::SETLT: Swap = true; // Fallthrough
3511    case ISD::SETOGT:
3512    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3513    case ISD::SETOLE:
3514    case ISD::SETLE:  Swap = true; // Fallthrough
3515    case ISD::SETOGE:
3516    case ISD::SETGE: Opc = ARMISD::VCGE; break;
3517    case ISD::SETUGE: Swap = true; // Fallthrough
3518    case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3519    case ISD::SETUGT: Swap = true; // Fallthrough
3520    case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3521    case ISD::SETUEQ: Invert = true; // Fallthrough
3522    case ISD::SETONE:
3523      // Expand this to (OLT | OGT).
3524      TmpOp0 = Op0;
3525      TmpOp1 = Op1;
3526      Opc = ISD::OR;
3527      Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3528      Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3529      break;
3530    case ISD::SETUO: Invert = true; // Fallthrough
3531    case ISD::SETO:
3532      // Expand this to (OLT | OGE).
3533      TmpOp0 = Op0;
3534      TmpOp1 = Op1;
3535      Opc = ISD::OR;
3536      Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3537      Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3538      break;
3539    }
3540  } else {
3541    // Integer comparisons.
3542    switch (SetCCOpcode) {
3543    default: llvm_unreachable("Illegal integer comparison");
3544    case ISD::SETNE:  Invert = true;
3545    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3546    case ISD::SETLT:  Swap = true;
3547    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3548    case ISD::SETLE:  Swap = true;
3549    case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3550    case ISD::SETULT: Swap = true;
3551    case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3552    case ISD::SETULE: Swap = true;
3553    case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3554    }
3555
3556    // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3557    if (Opc == ARMISD::VCEQ) {
3558
3559      SDValue AndOp;
3560      if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3561        AndOp = Op0;
3562      else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3563        AndOp = Op1;
3564
3565      // Ignore bitconvert.
3566      if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3567        AndOp = AndOp.getOperand(0);
3568
3569      if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3570        Opc = ARMISD::VTST;
3571        Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3572        Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3573        Invert = !Invert;
3574      }
3575    }
3576  }
3577
3578  if (Swap)
3579    std::swap(Op0, Op1);
3580
3581  // If one of the operands is a constant vector zero, attempt to fold the
3582  // comparison to a specialized compare-against-zero form.
3583  SDValue SingleOp;
3584  if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3585    SingleOp = Op0;
3586  else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3587    if (Opc == ARMISD::VCGE)
3588      Opc = ARMISD::VCLEZ;
3589    else if (Opc == ARMISD::VCGT)
3590      Opc = ARMISD::VCLTZ;
3591    SingleOp = Op1;
3592  }
3593
3594  SDValue Result;
3595  if (SingleOp.getNode()) {
3596    switch (Opc) {
3597    case ARMISD::VCEQ:
3598      Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3599    case ARMISD::VCGE:
3600      Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3601    case ARMISD::VCLEZ:
3602      Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3603    case ARMISD::VCGT:
3604      Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3605    case ARMISD::VCLTZ:
3606      Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3607    default:
3608      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3609    }
3610  } else {
3611     Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3612  }
3613
3614  if (Invert)
3615    Result = DAG.getNOT(dl, Result, VT);
3616
3617  return Result;
3618}
3619
3620/// isNEONModifiedImm - Check if the specified splat value corresponds to a
3621/// valid vector constant for a NEON instruction with a "modified immediate"
3622/// operand (e.g., VMOV).  If so, return the encoded value.
3623static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3624                                 unsigned SplatBitSize, SelectionDAG &DAG,
3625                                 EVT &VT, bool is128Bits, NEONModImmType type) {
3626  unsigned OpCmode, Imm;
3627
3628  // SplatBitSize is set to the smallest size that splats the vector, so a
3629  // zero vector will always have SplatBitSize == 8.  However, NEON modified
3630  // immediate instructions others than VMOV do not support the 8-bit encoding
3631  // of a zero vector, and the default encoding of zero is supposed to be the
3632  // 32-bit version.
3633  if (SplatBits == 0)
3634    SplatBitSize = 32;
3635
3636  switch (SplatBitSize) {
3637  case 8:
3638    if (type != VMOVModImm)
3639      return SDValue();
3640    // Any 1-byte value is OK.  Op=0, Cmode=1110.
3641    assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3642    OpCmode = 0xe;
3643    Imm = SplatBits;
3644    VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3645    break;
3646
3647  case 16:
3648    // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3649    VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3650    if ((SplatBits & ~0xff) == 0) {
3651      // Value = 0x00nn: Op=x, Cmode=100x.
3652      OpCmode = 0x8;
3653      Imm = SplatBits;
3654      break;
3655    }
3656    if ((SplatBits & ~0xff00) == 0) {
3657      // Value = 0xnn00: Op=x, Cmode=101x.
3658      OpCmode = 0xa;
3659      Imm = SplatBits >> 8;
3660      break;
3661    }
3662    return SDValue();
3663
3664  case 32:
3665    // NEON's 32-bit VMOV supports splat values where:
3666    // * only one byte is nonzero, or
3667    // * the least significant byte is 0xff and the second byte is nonzero, or
3668    // * the least significant 2 bytes are 0xff and the third is nonzero.
3669    VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3670    if ((SplatBits & ~0xff) == 0) {
3671      // Value = 0x000000nn: Op=x, Cmode=000x.
3672      OpCmode = 0;
3673      Imm = SplatBits;
3674      break;
3675    }
3676    if ((SplatBits & ~0xff00) == 0) {
3677      // Value = 0x0000nn00: Op=x, Cmode=001x.
3678      OpCmode = 0x2;
3679      Imm = SplatBits >> 8;
3680      break;
3681    }
3682    if ((SplatBits & ~0xff0000) == 0) {
3683      // Value = 0x00nn0000: Op=x, Cmode=010x.
3684      OpCmode = 0x4;
3685      Imm = SplatBits >> 16;
3686      break;
3687    }
3688    if ((SplatBits & ~0xff000000) == 0) {
3689      // Value = 0xnn000000: Op=x, Cmode=011x.
3690      OpCmode = 0x6;
3691      Imm = SplatBits >> 24;
3692      break;
3693    }
3694
3695    // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3696    if (type == OtherModImm) return SDValue();
3697
3698    if ((SplatBits & ~0xffff) == 0 &&
3699        ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3700      // Value = 0x0000nnff: Op=x, Cmode=1100.
3701      OpCmode = 0xc;
3702      Imm = SplatBits >> 8;
3703      SplatBits |= 0xff;
3704      break;
3705    }
3706
3707    if ((SplatBits & ~0xffffff) == 0 &&
3708        ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3709      // Value = 0x00nnffff: Op=x, Cmode=1101.
3710      OpCmode = 0xd;
3711      Imm = SplatBits >> 16;
3712      SplatBits |= 0xffff;
3713      break;
3714    }
3715
3716    // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3717    // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3718    // VMOV.I32.  A (very) minor optimization would be to replicate the value
3719    // and fall through here to test for a valid 64-bit splat.  But, then the
3720    // caller would also need to check and handle the change in size.
3721    return SDValue();
3722
3723  case 64: {
3724    if (type != VMOVModImm)
3725      return SDValue();
3726    // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3727    uint64_t BitMask = 0xff;
3728    uint64_t Val = 0;
3729    unsigned ImmMask = 1;
3730    Imm = 0;
3731    for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3732      if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3733        Val |= BitMask;
3734        Imm |= ImmMask;
3735      } else if ((SplatBits & BitMask) != 0) {
3736        return SDValue();
3737      }
3738      BitMask <<= 8;
3739      ImmMask <<= 1;
3740    }
3741    // Op=1, Cmode=1110.
3742    OpCmode = 0x1e;
3743    SplatBits = Val;
3744    VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3745    break;
3746  }
3747
3748  default:
3749    llvm_unreachable("unexpected size for isNEONModifiedImm");
3750  }
3751
3752  unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3753  return DAG.getTargetConstant(EncodedVal, MVT::i32);
3754}
3755
3756static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3757                       bool &ReverseVEXT, unsigned &Imm) {
3758  unsigned NumElts = VT.getVectorNumElements();
3759  ReverseVEXT = false;
3760
3761  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3762  if (M[0] < 0)
3763    return false;
3764
3765  Imm = M[0];
3766
3767  // If this is a VEXT shuffle, the immediate value is the index of the first
3768  // element.  The other shuffle indices must be the successive elements after
3769  // the first one.
3770  unsigned ExpectedElt = Imm;
3771  for (unsigned i = 1; i < NumElts; ++i) {
3772    // Increment the expected index.  If it wraps around, it may still be
3773    // a VEXT but the source vectors must be swapped.
3774    ExpectedElt += 1;
3775    if (ExpectedElt == NumElts * 2) {
3776      ExpectedElt = 0;
3777      ReverseVEXT = true;
3778    }
3779
3780    if (M[i] < 0) continue; // ignore UNDEF indices
3781    if (ExpectedElt != static_cast<unsigned>(M[i]))
3782      return false;
3783  }
3784
3785  // Adjust the index value if the source operands will be swapped.
3786  if (ReverseVEXT)
3787    Imm -= NumElts;
3788
3789  return true;
3790}
3791
3792/// isVREVMask - Check if a vector shuffle corresponds to a VREV
3793/// instruction with the specified blocksize.  (The order of the elements
3794/// within each block of the vector is reversed.)
3795static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3796  assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3797         "Only possible block sizes for VREV are: 16, 32, 64");
3798
3799  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3800  if (EltSz == 64)
3801    return false;
3802
3803  unsigned NumElts = VT.getVectorNumElements();
3804  unsigned BlockElts = M[0] + 1;
3805  // If the first shuffle index is UNDEF, be optimistic.
3806  if (M[0] < 0)
3807    BlockElts = BlockSize / EltSz;
3808
3809  if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3810    return false;
3811
3812  for (unsigned i = 0; i < NumElts; ++i) {
3813    if (M[i] < 0) continue; // ignore UNDEF indices
3814    if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3815      return false;
3816  }
3817
3818  return true;
3819}
3820
3821static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3822  // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3823  // range, then 0 is placed into the resulting vector. So pretty much any mask
3824  // of 8 elements can work here.
3825  return VT == MVT::v8i8 && M.size() == 8;
3826}
3827
3828static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3829  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3830  if (EltSz == 64)
3831    return false;
3832
3833  unsigned NumElts = VT.getVectorNumElements();
3834  WhichResult = (M[0] == 0 ? 0 : 1);
3835  for (unsigned i = 0; i < NumElts; i += 2) {
3836    if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3837        (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3838      return false;
3839  }
3840  return true;
3841}
3842
3843/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3844/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3845/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3846static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3847  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3848  if (EltSz == 64)
3849    return false;
3850
3851  unsigned NumElts = VT.getVectorNumElements();
3852  WhichResult = (M[0] == 0 ? 0 : 1);
3853  for (unsigned i = 0; i < NumElts; i += 2) {
3854    if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3855        (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3856      return false;
3857  }
3858  return true;
3859}
3860
3861static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3862  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3863  if (EltSz == 64)
3864    return false;
3865
3866  unsigned NumElts = VT.getVectorNumElements();
3867  WhichResult = (M[0] == 0 ? 0 : 1);
3868  for (unsigned i = 0; i != NumElts; ++i) {
3869    if (M[i] < 0) continue; // ignore UNDEF indices
3870    if ((unsigned) M[i] != 2 * i + WhichResult)
3871      return false;
3872  }
3873
3874  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3875  if (VT.is64BitVector() && EltSz == 32)
3876    return false;
3877
3878  return true;
3879}
3880
3881/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3882/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3883/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3884static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3885  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3886  if (EltSz == 64)
3887    return false;
3888
3889  unsigned Half = VT.getVectorNumElements() / 2;
3890  WhichResult = (M[0] == 0 ? 0 : 1);
3891  for (unsigned j = 0; j != 2; ++j) {
3892    unsigned Idx = WhichResult;
3893    for (unsigned i = 0; i != Half; ++i) {
3894      int MIdx = M[i + j * Half];
3895      if (MIdx >= 0 && (unsigned) MIdx != Idx)
3896        return false;
3897      Idx += 2;
3898    }
3899  }
3900
3901  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3902  if (VT.is64BitVector() && EltSz == 32)
3903    return false;
3904
3905  return true;
3906}
3907
3908static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3909  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3910  if (EltSz == 64)
3911    return false;
3912
3913  unsigned NumElts = VT.getVectorNumElements();
3914  WhichResult = (M[0] == 0 ? 0 : 1);
3915  unsigned Idx = WhichResult * NumElts / 2;
3916  for (unsigned i = 0; i != NumElts; i += 2) {
3917    if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3918        (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3919      return false;
3920    Idx += 1;
3921  }
3922
3923  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3924  if (VT.is64BitVector() && EltSz == 32)
3925    return false;
3926
3927  return true;
3928}
3929
3930/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3931/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3932/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3933static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3934  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3935  if (EltSz == 64)
3936    return false;
3937
3938  unsigned NumElts = VT.getVectorNumElements();
3939  WhichResult = (M[0] == 0 ? 0 : 1);
3940  unsigned Idx = WhichResult * NumElts / 2;
3941  for (unsigned i = 0; i != NumElts; i += 2) {
3942    if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3943        (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
3944      return false;
3945    Idx += 1;
3946  }
3947
3948  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3949  if (VT.is64BitVector() && EltSz == 32)
3950    return false;
3951
3952  return true;
3953}
3954
3955// If N is an integer constant that can be moved into a register in one
3956// instruction, return an SDValue of such a constant (will become a MOV
3957// instruction).  Otherwise return null.
3958static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
3959                                     const ARMSubtarget *ST, DebugLoc dl) {
3960  uint64_t Val;
3961  if (!isa<ConstantSDNode>(N))
3962    return SDValue();
3963  Val = cast<ConstantSDNode>(N)->getZExtValue();
3964
3965  if (ST->isThumb1Only()) {
3966    if (Val <= 255 || ~Val <= 255)
3967      return DAG.getConstant(Val, MVT::i32);
3968  } else {
3969    if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
3970      return DAG.getConstant(Val, MVT::i32);
3971  }
3972  return SDValue();
3973}
3974
3975// If this is a case we can't handle, return null and let the default
3976// expansion code take care of it.
3977SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3978                                             const ARMSubtarget *ST) const {
3979  BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3980  DebugLoc dl = Op.getDebugLoc();
3981  EVT VT = Op.getValueType();
3982
3983  APInt SplatBits, SplatUndef;
3984  unsigned SplatBitSize;
3985  bool HasAnyUndefs;
3986  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3987    if (SplatBitSize <= 64) {
3988      // Check if an immediate VMOV works.
3989      EVT VmovVT;
3990      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
3991                                      SplatUndef.getZExtValue(), SplatBitSize,
3992                                      DAG, VmovVT, VT.is128BitVector(),
3993                                      VMOVModImm);
3994      if (Val.getNode()) {
3995        SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
3996        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3997      }
3998
3999      // Try an immediate VMVN.
4000      uint64_t NegatedImm = (~SplatBits).getZExtValue();
4001      Val = isNEONModifiedImm(NegatedImm,
4002                                      SplatUndef.getZExtValue(), SplatBitSize,
4003                                      DAG, VmovVT, VT.is128BitVector(),
4004                                      VMVNModImm);
4005      if (Val.getNode()) {
4006        SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4007        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4008      }
4009
4010      // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4011      if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4012        int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4013        if (ImmVal != -1) {
4014          SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4015          return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4016        }
4017      }
4018    }
4019  }
4020
4021  // Scan through the operands to see if only one value is used.
4022  unsigned NumElts = VT.getVectorNumElements();
4023  bool isOnlyLowElement = true;
4024  bool usesOnlyOneValue = true;
4025  bool isConstant = true;
4026  SDValue Value;
4027  for (unsigned i = 0; i < NumElts; ++i) {
4028    SDValue V = Op.getOperand(i);
4029    if (V.getOpcode() == ISD::UNDEF)
4030      continue;
4031    if (i > 0)
4032      isOnlyLowElement = false;
4033    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4034      isConstant = false;
4035
4036    if (!Value.getNode())
4037      Value = V;
4038    else if (V != Value)
4039      usesOnlyOneValue = false;
4040  }
4041
4042  if (!Value.getNode())
4043    return DAG.getUNDEF(VT);
4044
4045  if (isOnlyLowElement)
4046    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4047
4048  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4049
4050  // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4051  // i32 and try again.
4052  if (usesOnlyOneValue && EltSize <= 32) {
4053    if (!isConstant)
4054      return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4055    if (VT.getVectorElementType().isFloatingPoint()) {
4056      SmallVector<SDValue, 8> Ops;
4057      for (unsigned i = 0; i < NumElts; ++i)
4058        Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4059                                  Op.getOperand(i)));
4060      EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4061      SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4062      Val = LowerBUILD_VECTOR(Val, DAG, ST);
4063      if (Val.getNode())
4064        return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4065    }
4066    SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4067    if (Val.getNode())
4068      return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4069  }
4070
4071  // If all elements are constants and the case above didn't get hit, fall back
4072  // to the default expansion, which will generate a load from the constant
4073  // pool.
4074  if (isConstant)
4075    return SDValue();
4076
4077  // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4078  if (NumElts >= 4) {
4079    SDValue shuffle = ReconstructShuffle(Op, DAG);
4080    if (shuffle != SDValue())
4081      return shuffle;
4082  }
4083
4084  // Vectors with 32- or 64-bit elements can be built by directly assigning
4085  // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4086  // will be legalized.
4087  if (EltSize >= 32) {
4088    // Do the expansion with floating-point types, since that is what the VFP
4089    // registers are defined to use, and since i64 is not legal.
4090    EVT EltVT = EVT::getFloatingPointVT(EltSize);
4091    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4092    SmallVector<SDValue, 8> Ops;
4093    for (unsigned i = 0; i < NumElts; ++i)
4094      Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4095    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4096    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4097  }
4098
4099  return SDValue();
4100}
4101
4102// Gather data to see if the operation can be modelled as a
4103// shuffle in combination with VEXTs.
4104SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4105                                              SelectionDAG &DAG) const {
4106  DebugLoc dl = Op.getDebugLoc();
4107  EVT VT = Op.getValueType();
4108  unsigned NumElts = VT.getVectorNumElements();
4109
4110  SmallVector<SDValue, 2> SourceVecs;
4111  SmallVector<unsigned, 2> MinElts;
4112  SmallVector<unsigned, 2> MaxElts;
4113
4114  for (unsigned i = 0; i < NumElts; ++i) {
4115    SDValue V = Op.getOperand(i);
4116    if (V.getOpcode() == ISD::UNDEF)
4117      continue;
4118    else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4119      // A shuffle can only come from building a vector from various
4120      // elements of other vectors.
4121      return SDValue();
4122    } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4123               VT.getVectorElementType()) {
4124      // This code doesn't know how to handle shuffles where the vector
4125      // element types do not match (this happens because type legalization
4126      // promotes the return type of EXTRACT_VECTOR_ELT).
4127      // FIXME: It might be appropriate to extend this code to handle
4128      // mismatched types.
4129      return SDValue();
4130    }
4131
4132    // Record this extraction against the appropriate vector if possible...
4133    SDValue SourceVec = V.getOperand(0);
4134    unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4135    bool FoundSource = false;
4136    for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4137      if (SourceVecs[j] == SourceVec) {
4138        if (MinElts[j] > EltNo)
4139          MinElts[j] = EltNo;
4140        if (MaxElts[j] < EltNo)
4141          MaxElts[j] = EltNo;
4142        FoundSource = true;
4143        break;
4144      }
4145    }
4146
4147    // Or record a new source if not...
4148    if (!FoundSource) {
4149      SourceVecs.push_back(SourceVec);
4150      MinElts.push_back(EltNo);
4151      MaxElts.push_back(EltNo);
4152    }
4153  }
4154
4155  // Currently only do something sane when at most two source vectors
4156  // involved.
4157  if (SourceVecs.size() > 2)
4158    return SDValue();
4159
4160  SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4161  int VEXTOffsets[2] = {0, 0};
4162
4163  // This loop extracts the usage patterns of the source vectors
4164  // and prepares appropriate SDValues for a shuffle if possible.
4165  for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4166    if (SourceVecs[i].getValueType() == VT) {
4167      // No VEXT necessary
4168      ShuffleSrcs[i] = SourceVecs[i];
4169      VEXTOffsets[i] = 0;
4170      continue;
4171    } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4172      // It probably isn't worth padding out a smaller vector just to
4173      // break it down again in a shuffle.
4174      return SDValue();
4175    }
4176
4177    // Since only 64-bit and 128-bit vectors are legal on ARM and
4178    // we've eliminated the other cases...
4179    assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4180           "unexpected vector sizes in ReconstructShuffle");
4181
4182    if (MaxElts[i] - MinElts[i] >= NumElts) {
4183      // Span too large for a VEXT to cope
4184      return SDValue();
4185    }
4186
4187    if (MinElts[i] >= NumElts) {
4188      // The extraction can just take the second half
4189      VEXTOffsets[i] = NumElts;
4190      ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4191                                   SourceVecs[i],
4192                                   DAG.getIntPtrConstant(NumElts));
4193    } else if (MaxElts[i] < NumElts) {
4194      // The extraction can just take the first half
4195      VEXTOffsets[i] = 0;
4196      ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4197                                   SourceVecs[i],
4198                                   DAG.getIntPtrConstant(0));
4199    } else {
4200      // An actual VEXT is needed
4201      VEXTOffsets[i] = MinElts[i];
4202      SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4203                                     SourceVecs[i],
4204                                     DAG.getIntPtrConstant(0));
4205      SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4206                                     SourceVecs[i],
4207                                     DAG.getIntPtrConstant(NumElts));
4208      ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4209                                   DAG.getConstant(VEXTOffsets[i], MVT::i32));
4210    }
4211  }
4212
4213  SmallVector<int, 8> Mask;
4214
4215  for (unsigned i = 0; i < NumElts; ++i) {
4216    SDValue Entry = Op.getOperand(i);
4217    if (Entry.getOpcode() == ISD::UNDEF) {
4218      Mask.push_back(-1);
4219      continue;
4220    }
4221
4222    SDValue ExtractVec = Entry.getOperand(0);
4223    int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4224                                          .getOperand(1))->getSExtValue();
4225    if (ExtractVec == SourceVecs[0]) {
4226      Mask.push_back(ExtractElt - VEXTOffsets[0]);
4227    } else {
4228      Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4229    }
4230  }
4231
4232  // Final check before we try to produce nonsense...
4233  if (isShuffleMaskLegal(Mask, VT))
4234    return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4235                                &Mask[0]);
4236
4237  return SDValue();
4238}
4239
4240/// isShuffleMaskLegal - Targets can use this to indicate that they only
4241/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4242/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4243/// are assumed to be legal.
4244bool
4245ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4246                                      EVT VT) const {
4247  if (VT.getVectorNumElements() == 4 &&
4248      (VT.is128BitVector() || VT.is64BitVector())) {
4249    unsigned PFIndexes[4];
4250    for (unsigned i = 0; i != 4; ++i) {
4251      if (M[i] < 0)
4252        PFIndexes[i] = 8;
4253      else
4254        PFIndexes[i] = M[i];
4255    }
4256
4257    // Compute the index in the perfect shuffle table.
4258    unsigned PFTableIndex =
4259      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4260    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4261    unsigned Cost = (PFEntry >> 30);
4262
4263    if (Cost <= 4)
4264      return true;
4265  }
4266
4267  bool ReverseVEXT;
4268  unsigned Imm, WhichResult;
4269
4270  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4271  return (EltSize >= 32 ||
4272          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4273          isVREVMask(M, VT, 64) ||
4274          isVREVMask(M, VT, 32) ||
4275          isVREVMask(M, VT, 16) ||
4276          isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4277          isVTBLMask(M, VT) ||
4278          isVTRNMask(M, VT, WhichResult) ||
4279          isVUZPMask(M, VT, WhichResult) ||
4280          isVZIPMask(M, VT, WhichResult) ||
4281          isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4282          isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4283          isVZIP_v_undef_Mask(M, VT, WhichResult));
4284}
4285
4286/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4287/// the specified operations to build the shuffle.
4288static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4289                                      SDValue RHS, SelectionDAG &DAG,
4290                                      DebugLoc dl) {
4291  unsigned OpNum = (PFEntry >> 26) & 0x0F;
4292  unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4293  unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4294
4295  enum {
4296    OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4297    OP_VREV,
4298    OP_VDUP0,
4299    OP_VDUP1,
4300    OP_VDUP2,
4301    OP_VDUP3,
4302    OP_VEXT1,
4303    OP_VEXT2,
4304    OP_VEXT3,
4305    OP_VUZPL, // VUZP, left result
4306    OP_VUZPR, // VUZP, right result
4307    OP_VZIPL, // VZIP, left result
4308    OP_VZIPR, // VZIP, right result
4309    OP_VTRNL, // VTRN, left result
4310    OP_VTRNR  // VTRN, right result
4311  };
4312
4313  if (OpNum == OP_COPY) {
4314    if (LHSID == (1*9+2)*9+3) return LHS;
4315    assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4316    return RHS;
4317  }
4318
4319  SDValue OpLHS, OpRHS;
4320  OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4321  OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4322  EVT VT = OpLHS.getValueType();
4323
4324  switch (OpNum) {
4325  default: llvm_unreachable("Unknown shuffle opcode!");
4326  case OP_VREV:
4327    // VREV divides the vector in half and swaps within the half.
4328    if (VT.getVectorElementType() == MVT::i32 ||
4329        VT.getVectorElementType() == MVT::f32)
4330      return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4331    // vrev <4 x i16> -> VREV32
4332    if (VT.getVectorElementType() == MVT::i16)
4333      return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4334    // vrev <4 x i8> -> VREV16
4335    assert(VT.getVectorElementType() == MVT::i8);
4336    return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4337  case OP_VDUP0:
4338  case OP_VDUP1:
4339  case OP_VDUP2:
4340  case OP_VDUP3:
4341    return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4342                       OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4343  case OP_VEXT1:
4344  case OP_VEXT2:
4345  case OP_VEXT3:
4346    return DAG.getNode(ARMISD::VEXT, dl, VT,
4347                       OpLHS, OpRHS,
4348                       DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4349  case OP_VUZPL:
4350  case OP_VUZPR:
4351    return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4352                       OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4353  case OP_VZIPL:
4354  case OP_VZIPR:
4355    return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4356                       OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4357  case OP_VTRNL:
4358  case OP_VTRNR:
4359    return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4360                       OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4361  }
4362}
4363
4364static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4365                                       ArrayRef<int> ShuffleMask,
4366                                       SelectionDAG &DAG) {
4367  // Check to see if we can use the VTBL instruction.
4368  SDValue V1 = Op.getOperand(0);
4369  SDValue V2 = Op.getOperand(1);
4370  DebugLoc DL = Op.getDebugLoc();
4371
4372  SmallVector<SDValue, 8> VTBLMask;
4373  for (ArrayRef<int>::iterator
4374         I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4375    VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4376
4377  if (V2.getNode()->getOpcode() == ISD::UNDEF)
4378    return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4379                       DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4380                                   &VTBLMask[0], 8));
4381
4382  return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4383                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4384                                 &VTBLMask[0], 8));
4385}
4386
4387static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4388  SDValue V1 = Op.getOperand(0);
4389  SDValue V2 = Op.getOperand(1);
4390  DebugLoc dl = Op.getDebugLoc();
4391  EVT VT = Op.getValueType();
4392  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4393
4394  // Convert shuffles that are directly supported on NEON to target-specific
4395  // DAG nodes, instead of keeping them as shuffles and matching them again
4396  // during code selection.  This is more efficient and avoids the possibility
4397  // of inconsistencies between legalization and selection.
4398  // FIXME: floating-point vectors should be canonicalized to integer vectors
4399  // of the same time so that they get CSEd properly.
4400  ArrayRef<int> ShuffleMask = SVN->getMask();
4401
4402  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4403  if (EltSize <= 32) {
4404    if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4405      int Lane = SVN->getSplatIndex();
4406      // If this is undef splat, generate it via "just" vdup, if possible.
4407      if (Lane == -1) Lane = 0;
4408
4409      // Test if V1 is a SCALAR_TO_VECTOR.
4410      if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4411        return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4412      }
4413      // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4414      // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4415      // reaches it).
4416      if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4417          !isa<ConstantSDNode>(V1.getOperand(0))) {
4418        bool IsScalarToVector = true;
4419        for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4420          if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4421            IsScalarToVector = false;
4422            break;
4423          }
4424        if (IsScalarToVector)
4425          return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4426      }
4427      return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4428                         DAG.getConstant(Lane, MVT::i32));
4429    }
4430
4431    bool ReverseVEXT;
4432    unsigned Imm;
4433    if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4434      if (ReverseVEXT)
4435        std::swap(V1, V2);
4436      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4437                         DAG.getConstant(Imm, MVT::i32));
4438    }
4439
4440    if (isVREVMask(ShuffleMask, VT, 64))
4441      return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4442    if (isVREVMask(ShuffleMask, VT, 32))
4443      return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4444    if (isVREVMask(ShuffleMask, VT, 16))
4445      return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4446
4447    // Check for Neon shuffles that modify both input vectors in place.
4448    // If both results are used, i.e., if there are two shuffles with the same
4449    // source operands and with masks corresponding to both results of one of
4450    // these operations, DAG memoization will ensure that a single node is
4451    // used for both shuffles.
4452    unsigned WhichResult;
4453    if (isVTRNMask(ShuffleMask, VT, WhichResult))
4454      return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4455                         V1, V2).getValue(WhichResult);
4456    if (isVUZPMask(ShuffleMask, VT, WhichResult))
4457      return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4458                         V1, V2).getValue(WhichResult);
4459    if (isVZIPMask(ShuffleMask, VT, WhichResult))
4460      return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4461                         V1, V2).getValue(WhichResult);
4462
4463    if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4464      return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4465                         V1, V1).getValue(WhichResult);
4466    if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4467      return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4468                         V1, V1).getValue(WhichResult);
4469    if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4470      return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4471                         V1, V1).getValue(WhichResult);
4472  }
4473
4474  // If the shuffle is not directly supported and it has 4 elements, use
4475  // the PerfectShuffle-generated table to synthesize it from other shuffles.
4476  unsigned NumElts = VT.getVectorNumElements();
4477  if (NumElts == 4) {
4478    unsigned PFIndexes[4];
4479    for (unsigned i = 0; i != 4; ++i) {
4480      if (ShuffleMask[i] < 0)
4481        PFIndexes[i] = 8;
4482      else
4483        PFIndexes[i] = ShuffleMask[i];
4484    }
4485
4486    // Compute the index in the perfect shuffle table.
4487    unsigned PFTableIndex =
4488      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4489    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4490    unsigned Cost = (PFEntry >> 30);
4491
4492    if (Cost <= 4)
4493      return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4494  }
4495
4496  // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4497  if (EltSize >= 32) {
4498    // Do the expansion with floating-point types, since that is what the VFP
4499    // registers are defined to use, and since i64 is not legal.
4500    EVT EltVT = EVT::getFloatingPointVT(EltSize);
4501    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4502    V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4503    V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4504    SmallVector<SDValue, 8> Ops;
4505    for (unsigned i = 0; i < NumElts; ++i) {
4506      if (ShuffleMask[i] < 0)
4507        Ops.push_back(DAG.getUNDEF(EltVT));
4508      else
4509        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4510                                  ShuffleMask[i] < (int)NumElts ? V1 : V2,
4511                                  DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4512                                                  MVT::i32)));
4513    }
4514    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4515    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4516  }
4517
4518  if (VT == MVT::v8i8) {
4519    SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4520    if (NewOp.getNode())
4521      return NewOp;
4522  }
4523
4524  return SDValue();
4525}
4526
4527static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4528  // INSERT_VECTOR_ELT is legal only for immediate indexes.
4529  SDValue Lane = Op.getOperand(2);
4530  if (!isa<ConstantSDNode>(Lane))
4531    return SDValue();
4532
4533  return Op;
4534}
4535
4536static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4537  // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4538  SDValue Lane = Op.getOperand(1);
4539  if (!isa<ConstantSDNode>(Lane))
4540    return SDValue();
4541
4542  SDValue Vec = Op.getOperand(0);
4543  if (Op.getValueType() == MVT::i32 &&
4544      Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4545    DebugLoc dl = Op.getDebugLoc();
4546    return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4547  }
4548
4549  return Op;
4550}
4551
4552static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4553  // The only time a CONCAT_VECTORS operation can have legal types is when
4554  // two 64-bit vectors are concatenated to a 128-bit vector.
4555  assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4556         "unexpected CONCAT_VECTORS");
4557  DebugLoc dl = Op.getDebugLoc();
4558  SDValue Val = DAG.getUNDEF(MVT::v2f64);
4559  SDValue Op0 = Op.getOperand(0);
4560  SDValue Op1 = Op.getOperand(1);
4561  if (Op0.getOpcode() != ISD::UNDEF)
4562    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4563                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4564                      DAG.getIntPtrConstant(0));
4565  if (Op1.getOpcode() != ISD::UNDEF)
4566    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4567                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4568                      DAG.getIntPtrConstant(1));
4569  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4570}
4571
4572/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4573/// element has been zero/sign-extended, depending on the isSigned parameter,
4574/// from an integer type half its size.
4575static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4576                                   bool isSigned) {
4577  // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4578  EVT VT = N->getValueType(0);
4579  if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4580    SDNode *BVN = N->getOperand(0).getNode();
4581    if (BVN->getValueType(0) != MVT::v4i32 ||
4582        BVN->getOpcode() != ISD::BUILD_VECTOR)
4583      return false;
4584    unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4585    unsigned HiElt = 1 - LoElt;
4586    ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4587    ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4588    ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4589    ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4590    if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4591      return false;
4592    if (isSigned) {
4593      if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4594          Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4595        return true;
4596    } else {
4597      if (Hi0->isNullValue() && Hi1->isNullValue())
4598        return true;
4599    }
4600    return false;
4601  }
4602
4603  if (N->getOpcode() != ISD::BUILD_VECTOR)
4604    return false;
4605
4606  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4607    SDNode *Elt = N->getOperand(i).getNode();
4608    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4609      unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4610      unsigned HalfSize = EltSize / 2;
4611      if (isSigned) {
4612        if (!isIntN(HalfSize, C->getSExtValue()))
4613          return false;
4614      } else {
4615        if (!isUIntN(HalfSize, C->getZExtValue()))
4616          return false;
4617      }
4618      continue;
4619    }
4620    return false;
4621  }
4622
4623  return true;
4624}
4625
4626/// isSignExtended - Check if a node is a vector value that is sign-extended
4627/// or a constant BUILD_VECTOR with sign-extended elements.
4628static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4629  if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4630    return true;
4631  if (isExtendedBUILD_VECTOR(N, DAG, true))
4632    return true;
4633  return false;
4634}
4635
4636/// isZeroExtended - Check if a node is a vector value that is zero-extended
4637/// or a constant BUILD_VECTOR with zero-extended elements.
4638static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4639  if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4640    return true;
4641  if (isExtendedBUILD_VECTOR(N, DAG, false))
4642    return true;
4643  return false;
4644}
4645
4646/// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4647/// load, or BUILD_VECTOR with extended elements, return the unextended value.
4648static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4649  if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4650    return N->getOperand(0);
4651  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4652    return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4653                       LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4654                       LD->isNonTemporal(), LD->isInvariant(),
4655                       LD->getAlignment());
4656  // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4657  // have been legalized as a BITCAST from v4i32.
4658  if (N->getOpcode() == ISD::BITCAST) {
4659    SDNode *BVN = N->getOperand(0).getNode();
4660    assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4661           BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4662    unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4663    return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4664                       BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4665  }
4666  // Construct a new BUILD_VECTOR with elements truncated to half the size.
4667  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4668  EVT VT = N->getValueType(0);
4669  unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4670  unsigned NumElts = VT.getVectorNumElements();
4671  MVT TruncVT = MVT::getIntegerVT(EltSize);
4672  SmallVector<SDValue, 8> Ops;
4673  for (unsigned i = 0; i != NumElts; ++i) {
4674    ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4675    const APInt &CInt = C->getAPIntValue();
4676    Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4677  }
4678  return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4679                     MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4680}
4681
4682static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4683  unsigned Opcode = N->getOpcode();
4684  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4685    SDNode *N0 = N->getOperand(0).getNode();
4686    SDNode *N1 = N->getOperand(1).getNode();
4687    return N0->hasOneUse() && N1->hasOneUse() &&
4688      isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4689  }
4690  return false;
4691}
4692
4693static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4694  unsigned Opcode = N->getOpcode();
4695  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4696    SDNode *N0 = N->getOperand(0).getNode();
4697    SDNode *N1 = N->getOperand(1).getNode();
4698    return N0->hasOneUse() && N1->hasOneUse() &&
4699      isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4700  }
4701  return false;
4702}
4703
4704static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4705  // Multiplications are only custom-lowered for 128-bit vectors so that
4706  // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4707  EVT VT = Op.getValueType();
4708  assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4709  SDNode *N0 = Op.getOperand(0).getNode();
4710  SDNode *N1 = Op.getOperand(1).getNode();
4711  unsigned NewOpc = 0;
4712  bool isMLA = false;
4713  bool isN0SExt = isSignExtended(N0, DAG);
4714  bool isN1SExt = isSignExtended(N1, DAG);
4715  if (isN0SExt && isN1SExt)
4716    NewOpc = ARMISD::VMULLs;
4717  else {
4718    bool isN0ZExt = isZeroExtended(N0, DAG);
4719    bool isN1ZExt = isZeroExtended(N1, DAG);
4720    if (isN0ZExt && isN1ZExt)
4721      NewOpc = ARMISD::VMULLu;
4722    else if (isN1SExt || isN1ZExt) {
4723      // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4724      // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4725      if (isN1SExt && isAddSubSExt(N0, DAG)) {
4726        NewOpc = ARMISD::VMULLs;
4727        isMLA = true;
4728      } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4729        NewOpc = ARMISD::VMULLu;
4730        isMLA = true;
4731      } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4732        std::swap(N0, N1);
4733        NewOpc = ARMISD::VMULLu;
4734        isMLA = true;
4735      }
4736    }
4737
4738    if (!NewOpc) {
4739      if (VT == MVT::v2i64)
4740        // Fall through to expand this.  It is not legal.
4741        return SDValue();
4742      else
4743        // Other vector multiplications are legal.
4744        return Op;
4745    }
4746  }
4747
4748  // Legalize to a VMULL instruction.
4749  DebugLoc DL = Op.getDebugLoc();
4750  SDValue Op0;
4751  SDValue Op1 = SkipExtension(N1, DAG);
4752  if (!isMLA) {
4753    Op0 = SkipExtension(N0, DAG);
4754    assert(Op0.getValueType().is64BitVector() &&
4755           Op1.getValueType().is64BitVector() &&
4756           "unexpected types for extended operands to VMULL");
4757    return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4758  }
4759
4760  // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4761  // isel lowering to take advantage of no-stall back to back vmul + vmla.
4762  //   vmull q0, d4, d6
4763  //   vmlal q0, d5, d6
4764  // is faster than
4765  //   vaddl q0, d4, d5
4766  //   vmovl q1, d6
4767  //   vmul  q0, q0, q1
4768  SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4769  SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4770  EVT Op1VT = Op1.getValueType();
4771  return DAG.getNode(N0->getOpcode(), DL, VT,
4772                     DAG.getNode(NewOpc, DL, VT,
4773                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4774                     DAG.getNode(NewOpc, DL, VT,
4775                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4776}
4777
4778static SDValue
4779LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4780  // Convert to float
4781  // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4782  // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4783  X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4784  Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4785  X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4786  Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4787  // Get reciprocal estimate.
4788  // float4 recip = vrecpeq_f32(yf);
4789  Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4790                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4791  // Because char has a smaller range than uchar, we can actually get away
4792  // without any newton steps.  This requires that we use a weird bias
4793  // of 0xb000, however (again, this has been exhaustively tested).
4794  // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4795  X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4796  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4797  Y = DAG.getConstant(0xb000, MVT::i32);
4798  Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4799  X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4800  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4801  // Convert back to short.
4802  X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4803  X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4804  return X;
4805}
4806
4807static SDValue
4808LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4809  SDValue N2;
4810  // Convert to float.
4811  // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4812  // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4813  N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4814  N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4815  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4816  N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4817
4818  // Use reciprocal estimate and one refinement step.
4819  // float4 recip = vrecpeq_f32(yf);
4820  // recip *= vrecpsq_f32(yf, recip);
4821  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4822                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4823  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4824                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4825                   N1, N2);
4826  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4827  // Because short has a smaller range than ushort, we can actually get away
4828  // with only a single newton step.  This requires that we use a weird bias
4829  // of 89, however (again, this has been exhaustively tested).
4830  // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4831  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4832  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4833  N1 = DAG.getConstant(0x89, MVT::i32);
4834  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4835  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4836  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4837  // Convert back to integer and return.
4838  // return vmovn_s32(vcvt_s32_f32(result));
4839  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4840  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4841  return N0;
4842}
4843
4844static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4845  EVT VT = Op.getValueType();
4846  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4847         "unexpected type for custom-lowering ISD::SDIV");
4848
4849  DebugLoc dl = Op.getDebugLoc();
4850  SDValue N0 = Op.getOperand(0);
4851  SDValue N1 = Op.getOperand(1);
4852  SDValue N2, N3;
4853
4854  if (VT == MVT::v8i8) {
4855    N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4856    N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4857
4858    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4859                     DAG.getIntPtrConstant(4));
4860    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4861                     DAG.getIntPtrConstant(4));
4862    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4863                     DAG.getIntPtrConstant(0));
4864    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4865                     DAG.getIntPtrConstant(0));
4866
4867    N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4868    N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4869
4870    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4871    N0 = LowerCONCAT_VECTORS(N0, DAG);
4872
4873    N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4874    return N0;
4875  }
4876  return LowerSDIV_v4i16(N0, N1, dl, DAG);
4877}
4878
4879static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4880  EVT VT = Op.getValueType();
4881  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4882         "unexpected type for custom-lowering ISD::UDIV");
4883
4884  DebugLoc dl = Op.getDebugLoc();
4885  SDValue N0 = Op.getOperand(0);
4886  SDValue N1 = Op.getOperand(1);
4887  SDValue N2, N3;
4888
4889  if (VT == MVT::v8i8) {
4890    N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4891    N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4892
4893    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4894                     DAG.getIntPtrConstant(4));
4895    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4896                     DAG.getIntPtrConstant(4));
4897    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4898                     DAG.getIntPtrConstant(0));
4899    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4900                     DAG.getIntPtrConstant(0));
4901
4902    N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4903    N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4904
4905    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4906    N0 = LowerCONCAT_VECTORS(N0, DAG);
4907
4908    N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4909                     DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4910                     N0);
4911    return N0;
4912  }
4913
4914  // v4i16 sdiv ... Convert to float.
4915  // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4916  // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4917  N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4918  N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4919  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4920  SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4921
4922  // Use reciprocal estimate and two refinement steps.
4923  // float4 recip = vrecpeq_f32(yf);
4924  // recip *= vrecpsq_f32(yf, recip);
4925  // recip *= vrecpsq_f32(yf, recip);
4926  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4927                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
4928  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4929                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4930                   BN1, N2);
4931  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4932  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4933                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4934                   BN1, N2);
4935  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4936  // Simply multiplying by the reciprocal estimate can leave us a few ulps
4937  // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
4938  // and that it will never cause us to return an answer too large).
4939  // float4 result = as_float4(as_int4(xf*recip) + 2);
4940  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4941  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4942  N1 = DAG.getConstant(2, MVT::i32);
4943  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4944  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4945  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4946  // Convert back to integer and return.
4947  // return vmovn_u32(vcvt_s32_f32(result));
4948  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4949  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4950  return N0;
4951}
4952
4953static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
4954  EVT VT = Op.getNode()->getValueType(0);
4955  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4956
4957  unsigned Opc;
4958  bool ExtraOp = false;
4959  switch (Op.getOpcode()) {
4960  default: assert(0 && "Invalid code");
4961  case ISD::ADDC: Opc = ARMISD::ADDC; break;
4962  case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
4963  case ISD::SUBC: Opc = ARMISD::SUBC; break;
4964  case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
4965  }
4966
4967  if (!ExtraOp)
4968    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
4969                       Op.getOperand(1));
4970  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
4971                     Op.getOperand(1), Op.getOperand(2));
4972}
4973
4974static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
4975  // Monotonic load/store is legal for all targets
4976  if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
4977    return Op;
4978
4979  // Aquire/Release load/store is not legal for targets without a
4980  // dmb or equivalent available.
4981  return SDValue();
4982}
4983
4984
4985static void
4986ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
4987                    SelectionDAG &DAG, unsigned NewOp) {
4988  DebugLoc dl = Node->getDebugLoc();
4989  assert (Node->getValueType(0) == MVT::i64 &&
4990          "Only know how to expand i64 atomics");
4991
4992  SmallVector<SDValue, 6> Ops;
4993  Ops.push_back(Node->getOperand(0)); // Chain
4994  Ops.push_back(Node->getOperand(1)); // Ptr
4995  // Low part of Val1
4996  Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4997                            Node->getOperand(2), DAG.getIntPtrConstant(0)));
4998  // High part of Val1
4999  Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5000                            Node->getOperand(2), DAG.getIntPtrConstant(1)));
5001  if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5002    // High part of Val1
5003    Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5004                              Node->getOperand(3), DAG.getIntPtrConstant(0)));
5005    // High part of Val2
5006    Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5007                              Node->getOperand(3), DAG.getIntPtrConstant(1)));
5008  }
5009  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5010  SDValue Result =
5011    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5012                            cast<MemSDNode>(Node)->getMemOperand());
5013  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5014  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5015  Results.push_back(Result.getValue(2));
5016}
5017
5018SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5019  switch (Op.getOpcode()) {
5020  default: llvm_unreachable("Don't know how to custom lower this!");
5021  case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5022  case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5023  case ISD::GlobalAddress:
5024    return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5025      LowerGlobalAddressELF(Op, DAG);
5026  case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5027  case ISD::SELECT:        return LowerSELECT(Op, DAG);
5028  case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5029  case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5030  case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5031  case ISD::VASTART:       return LowerVASTART(Op, DAG);
5032  case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5033  case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5034  case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5035  case ISD::SINT_TO_FP:
5036  case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5037  case ISD::FP_TO_SINT:
5038  case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5039  case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5040  case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5041  case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5042  case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5043  case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5044  case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5045  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5046                                                               Subtarget);
5047  case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5048  case ISD::SHL:
5049  case ISD::SRL:
5050  case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5051  case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5052  case ISD::SRL_PARTS:
5053  case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5054  case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5055  case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5056  case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5057  case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5058  case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5059  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5060  case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5061  case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5062  case ISD::MUL:           return LowerMUL(Op, DAG);
5063  case ISD::SDIV:          return LowerSDIV(Op, DAG);
5064  case ISD::UDIV:          return LowerUDIV(Op, DAG);
5065  case ISD::ADDC:
5066  case ISD::ADDE:
5067  case ISD::SUBC:
5068  case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5069  case ISD::ATOMIC_LOAD:
5070  case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5071  }
5072}
5073
5074/// ReplaceNodeResults - Replace the results of node with an illegal result
5075/// type with new values built out of custom code.
5076void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5077                                           SmallVectorImpl<SDValue>&Results,
5078                                           SelectionDAG &DAG) const {
5079  SDValue Res;
5080  switch (N->getOpcode()) {
5081  default:
5082    llvm_unreachable("Don't know how to custom expand this!");
5083  case ISD::BITCAST:
5084    Res = ExpandBITCAST(N, DAG);
5085    break;
5086  case ISD::SRL:
5087  case ISD::SRA:
5088    Res = Expand64BitShift(N, DAG, Subtarget);
5089    break;
5090  case ISD::ATOMIC_LOAD_ADD:
5091    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5092    return;
5093  case ISD::ATOMIC_LOAD_AND:
5094    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5095    return;
5096  case ISD::ATOMIC_LOAD_NAND:
5097    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5098    return;
5099  case ISD::ATOMIC_LOAD_OR:
5100    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5101    return;
5102  case ISD::ATOMIC_LOAD_SUB:
5103    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5104    return;
5105  case ISD::ATOMIC_LOAD_XOR:
5106    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5107    return;
5108  case ISD::ATOMIC_SWAP:
5109    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5110    return;
5111  case ISD::ATOMIC_CMP_SWAP:
5112    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5113    return;
5114  }
5115  if (Res.getNode())
5116    Results.push_back(Res);
5117}
5118
5119//===----------------------------------------------------------------------===//
5120//                           ARM Scheduler Hooks
5121//===----------------------------------------------------------------------===//
5122
5123MachineBasicBlock *
5124ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5125                                     MachineBasicBlock *BB,
5126                                     unsigned Size) const {
5127  unsigned dest    = MI->getOperand(0).getReg();
5128  unsigned ptr     = MI->getOperand(1).getReg();
5129  unsigned oldval  = MI->getOperand(2).getReg();
5130  unsigned newval  = MI->getOperand(3).getReg();
5131  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5132  DebugLoc dl = MI->getDebugLoc();
5133  bool isThumb2 = Subtarget->isThumb2();
5134
5135  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5136  unsigned scratch =
5137    MRI.createVirtualRegister(isThumb2 ? ARM::rGPRRegisterClass
5138                                       : ARM::GPRRegisterClass);
5139
5140  if (isThumb2) {
5141    MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5142    MRI.constrainRegClass(oldval, ARM::rGPRRegisterClass);
5143    MRI.constrainRegClass(newval, ARM::rGPRRegisterClass);
5144  }
5145
5146  unsigned ldrOpc, strOpc;
5147  switch (Size) {
5148  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5149  case 1:
5150    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5151    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5152    break;
5153  case 2:
5154    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5155    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5156    break;
5157  case 4:
5158    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5159    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5160    break;
5161  }
5162
5163  MachineFunction *MF = BB->getParent();
5164  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5165  MachineFunction::iterator It = BB;
5166  ++It; // insert the new blocks after the current block
5167
5168  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5169  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5170  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5171  MF->insert(It, loop1MBB);
5172  MF->insert(It, loop2MBB);
5173  MF->insert(It, exitMBB);
5174
5175  // Transfer the remainder of BB and its successor edges to exitMBB.
5176  exitMBB->splice(exitMBB->begin(), BB,
5177                  llvm::next(MachineBasicBlock::iterator(MI)),
5178                  BB->end());
5179  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5180
5181  //  thisMBB:
5182  //   ...
5183  //   fallthrough --> loop1MBB
5184  BB->addSuccessor(loop1MBB);
5185
5186  // loop1MBB:
5187  //   ldrex dest, [ptr]
5188  //   cmp dest, oldval
5189  //   bne exitMBB
5190  BB = loop1MBB;
5191  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5192  if (ldrOpc == ARM::t2LDREX)
5193    MIB.addImm(0);
5194  AddDefaultPred(MIB);
5195  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5196                 .addReg(dest).addReg(oldval));
5197  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5198    .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5199  BB->addSuccessor(loop2MBB);
5200  BB->addSuccessor(exitMBB);
5201
5202  // loop2MBB:
5203  //   strex scratch, newval, [ptr]
5204  //   cmp scratch, #0
5205  //   bne loop1MBB
5206  BB = loop2MBB;
5207  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5208  if (strOpc == ARM::t2STREX)
5209    MIB.addImm(0);
5210  AddDefaultPred(MIB);
5211  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5212                 .addReg(scratch).addImm(0));
5213  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5214    .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5215  BB->addSuccessor(loop1MBB);
5216  BB->addSuccessor(exitMBB);
5217
5218  //  exitMBB:
5219  //   ...
5220  BB = exitMBB;
5221
5222  MI->eraseFromParent();   // The instruction is gone now.
5223
5224  return BB;
5225}
5226
5227MachineBasicBlock *
5228ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5229                                    unsigned Size, unsigned BinOpcode) const {
5230  // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5231  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5232
5233  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5234  MachineFunction *MF = BB->getParent();
5235  MachineFunction::iterator It = BB;
5236  ++It;
5237
5238  unsigned dest = MI->getOperand(0).getReg();
5239  unsigned ptr = MI->getOperand(1).getReg();
5240  unsigned incr = MI->getOperand(2).getReg();
5241  DebugLoc dl = MI->getDebugLoc();
5242  bool isThumb2 = Subtarget->isThumb2();
5243
5244  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5245  if (isThumb2) {
5246    MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5247    MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5248  }
5249
5250  unsigned ldrOpc, strOpc;
5251  switch (Size) {
5252  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5253  case 1:
5254    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5255    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5256    break;
5257  case 2:
5258    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5259    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5260    break;
5261  case 4:
5262    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5263    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5264    break;
5265  }
5266
5267  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5268  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5269  MF->insert(It, loopMBB);
5270  MF->insert(It, exitMBB);
5271
5272  // Transfer the remainder of BB and its successor edges to exitMBB.
5273  exitMBB->splice(exitMBB->begin(), BB,
5274                  llvm::next(MachineBasicBlock::iterator(MI)),
5275                  BB->end());
5276  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5277
5278  TargetRegisterClass *TRC =
5279    isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5280  unsigned scratch = MRI.createVirtualRegister(TRC);
5281  unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5282
5283  //  thisMBB:
5284  //   ...
5285  //   fallthrough --> loopMBB
5286  BB->addSuccessor(loopMBB);
5287
5288  //  loopMBB:
5289  //   ldrex dest, ptr
5290  //   <binop> scratch2, dest, incr
5291  //   strex scratch, scratch2, ptr
5292  //   cmp scratch, #0
5293  //   bne- loopMBB
5294  //   fallthrough --> exitMBB
5295  BB = loopMBB;
5296  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5297  if (ldrOpc == ARM::t2LDREX)
5298    MIB.addImm(0);
5299  AddDefaultPred(MIB);
5300  if (BinOpcode) {
5301    // operand order needs to go the other way for NAND
5302    if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5303      AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5304                     addReg(incr).addReg(dest)).addReg(0);
5305    else
5306      AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5307                     addReg(dest).addReg(incr)).addReg(0);
5308  }
5309
5310  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5311  if (strOpc == ARM::t2STREX)
5312    MIB.addImm(0);
5313  AddDefaultPred(MIB);
5314  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5315                 .addReg(scratch).addImm(0));
5316  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5317    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5318
5319  BB->addSuccessor(loopMBB);
5320  BB->addSuccessor(exitMBB);
5321
5322  //  exitMBB:
5323  //   ...
5324  BB = exitMBB;
5325
5326  MI->eraseFromParent();   // The instruction is gone now.
5327
5328  return BB;
5329}
5330
5331MachineBasicBlock *
5332ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5333                                          MachineBasicBlock *BB,
5334                                          unsigned Size,
5335                                          bool signExtend,
5336                                          ARMCC::CondCodes Cond) const {
5337  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5338
5339  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5340  MachineFunction *MF = BB->getParent();
5341  MachineFunction::iterator It = BB;
5342  ++It;
5343
5344  unsigned dest = MI->getOperand(0).getReg();
5345  unsigned ptr = MI->getOperand(1).getReg();
5346  unsigned incr = MI->getOperand(2).getReg();
5347  unsigned oldval = dest;
5348  DebugLoc dl = MI->getDebugLoc();
5349  bool isThumb2 = Subtarget->isThumb2();
5350
5351  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5352  if (isThumb2) {
5353    MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5354    MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5355  }
5356
5357  unsigned ldrOpc, strOpc, extendOpc;
5358  switch (Size) {
5359  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5360  case 1:
5361    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5362    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5363    extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5364    break;
5365  case 2:
5366    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5367    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5368    extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5369    break;
5370  case 4:
5371    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5372    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5373    extendOpc = 0;
5374    break;
5375  }
5376
5377  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5378  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5379  MF->insert(It, loopMBB);
5380  MF->insert(It, exitMBB);
5381
5382  // Transfer the remainder of BB and its successor edges to exitMBB.
5383  exitMBB->splice(exitMBB->begin(), BB,
5384                  llvm::next(MachineBasicBlock::iterator(MI)),
5385                  BB->end());
5386  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5387
5388  TargetRegisterClass *TRC =
5389    isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5390  unsigned scratch = MRI.createVirtualRegister(TRC);
5391  unsigned scratch2 = MRI.createVirtualRegister(TRC);
5392
5393  //  thisMBB:
5394  //   ...
5395  //   fallthrough --> loopMBB
5396  BB->addSuccessor(loopMBB);
5397
5398  //  loopMBB:
5399  //   ldrex dest, ptr
5400  //   (sign extend dest, if required)
5401  //   cmp dest, incr
5402  //   cmov.cond scratch2, dest, incr
5403  //   strex scratch, scratch2, ptr
5404  //   cmp scratch, #0
5405  //   bne- loopMBB
5406  //   fallthrough --> exitMBB
5407  BB = loopMBB;
5408  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5409  if (ldrOpc == ARM::t2LDREX)
5410    MIB.addImm(0);
5411  AddDefaultPred(MIB);
5412
5413  // Sign extend the value, if necessary.
5414  if (signExtend && extendOpc) {
5415    oldval = MRI.createVirtualRegister(ARM::GPRRegisterClass);
5416    AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5417                     .addReg(dest)
5418                     .addImm(0));
5419  }
5420
5421  // Build compare and cmov instructions.
5422  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5423                 .addReg(oldval).addReg(incr));
5424  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5425         .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5426
5427  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5428  if (strOpc == ARM::t2STREX)
5429    MIB.addImm(0);
5430  AddDefaultPred(MIB);
5431  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5432                 .addReg(scratch).addImm(0));
5433  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5434    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5435
5436  BB->addSuccessor(loopMBB);
5437  BB->addSuccessor(exitMBB);
5438
5439  //  exitMBB:
5440  //   ...
5441  BB = exitMBB;
5442
5443  MI->eraseFromParent();   // The instruction is gone now.
5444
5445  return BB;
5446}
5447
5448MachineBasicBlock *
5449ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5450                                      unsigned Op1, unsigned Op2,
5451                                      bool NeedsCarry, bool IsCmpxchg) const {
5452  // This also handles ATOMIC_SWAP, indicated by Op1==0.
5453  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5454
5455  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5456  MachineFunction *MF = BB->getParent();
5457  MachineFunction::iterator It = BB;
5458  ++It;
5459
5460  unsigned destlo = MI->getOperand(0).getReg();
5461  unsigned desthi = MI->getOperand(1).getReg();
5462  unsigned ptr = MI->getOperand(2).getReg();
5463  unsigned vallo = MI->getOperand(3).getReg();
5464  unsigned valhi = MI->getOperand(4).getReg();
5465  DebugLoc dl = MI->getDebugLoc();
5466  bool isThumb2 = Subtarget->isThumb2();
5467
5468  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5469  if (isThumb2) {
5470    MRI.constrainRegClass(destlo, ARM::rGPRRegisterClass);
5471    MRI.constrainRegClass(desthi, ARM::rGPRRegisterClass);
5472    MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5473  }
5474
5475  unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5476  unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5477
5478  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5479  MachineBasicBlock *contBB = 0, *cont2BB = 0;
5480  if (IsCmpxchg) {
5481    contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5482    cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5483  }
5484  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5485  MF->insert(It, loopMBB);
5486  if (IsCmpxchg) {
5487    MF->insert(It, contBB);
5488    MF->insert(It, cont2BB);
5489  }
5490  MF->insert(It, exitMBB);
5491
5492  // Transfer the remainder of BB and its successor edges to exitMBB.
5493  exitMBB->splice(exitMBB->begin(), BB,
5494                  llvm::next(MachineBasicBlock::iterator(MI)),
5495                  BB->end());
5496  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5497
5498  TargetRegisterClass *TRC =
5499    isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5500  unsigned storesuccess = MRI.createVirtualRegister(TRC);
5501
5502  //  thisMBB:
5503  //   ...
5504  //   fallthrough --> loopMBB
5505  BB->addSuccessor(loopMBB);
5506
5507  //  loopMBB:
5508  //   ldrexd r2, r3, ptr
5509  //   <binopa> r0, r2, incr
5510  //   <binopb> r1, r3, incr
5511  //   strexd storesuccess, r0, r1, ptr
5512  //   cmp storesuccess, #0
5513  //   bne- loopMBB
5514  //   fallthrough --> exitMBB
5515  //
5516  // Note that the registers are explicitly specified because there is not any
5517  // way to force the register allocator to allocate a register pair.
5518  //
5519  // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5520  // need to properly enforce the restriction that the two output registers
5521  // for ldrexd must be different.
5522  BB = loopMBB;
5523  // Load
5524  AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5525                 .addReg(ARM::R2, RegState::Define)
5526                 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5527  // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5528  BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5529  BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5530
5531  if (IsCmpxchg) {
5532    // Add early exit
5533    for (unsigned i = 0; i < 2; i++) {
5534      AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5535                                                         ARM::CMPrr))
5536                     .addReg(i == 0 ? destlo : desthi)
5537                     .addReg(i == 0 ? vallo : valhi));
5538      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5539        .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5540      BB->addSuccessor(exitMBB);
5541      BB->addSuccessor(i == 0 ? contBB : cont2BB);
5542      BB = (i == 0 ? contBB : cont2BB);
5543    }
5544
5545    // Copy to physregs for strexd
5546    unsigned setlo = MI->getOperand(5).getReg();
5547    unsigned sethi = MI->getOperand(6).getReg();
5548    BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5549    BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5550  } else if (Op1) {
5551    // Perform binary operation
5552    AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5553                   .addReg(destlo).addReg(vallo))
5554        .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5555    AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5556                   .addReg(desthi).addReg(valhi)).addReg(0);
5557  } else {
5558    // Copy to physregs for strexd
5559    BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5560    BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5561  }
5562
5563  // Store
5564  AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5565                 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5566  // Cmp+jump
5567  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5568                 .addReg(storesuccess).addImm(0));
5569  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5570    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5571
5572  BB->addSuccessor(loopMBB);
5573  BB->addSuccessor(exitMBB);
5574
5575  //  exitMBB:
5576  //   ...
5577  BB = exitMBB;
5578
5579  MI->eraseFromParent();   // The instruction is gone now.
5580
5581  return BB;
5582}
5583
5584/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5585/// registers the function context.
5586void ARMTargetLowering::
5587SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5588                       MachineBasicBlock *DispatchBB, int FI) const {
5589  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5590  DebugLoc dl = MI->getDebugLoc();
5591  MachineFunction *MF = MBB->getParent();
5592  MachineRegisterInfo *MRI = &MF->getRegInfo();
5593  MachineConstantPool *MCP = MF->getConstantPool();
5594  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5595  const Function *F = MF->getFunction();
5596
5597  bool isThumb = Subtarget->isThumb();
5598  bool isThumb2 = Subtarget->isThumb2();
5599
5600  unsigned PCLabelId = AFI->createPICLabelUId();
5601  unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5602  ARMConstantPoolValue *CPV =
5603    ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5604  unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5605
5606  const TargetRegisterClass *TRC =
5607    isThumb ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5608
5609  // Grab constant pool and fixed stack memory operands.
5610  MachineMemOperand *CPMMO =
5611    MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5612                             MachineMemOperand::MOLoad, 4, 4);
5613
5614  MachineMemOperand *FIMMOSt =
5615    MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5616                             MachineMemOperand::MOStore, 4, 4);
5617
5618  // Load the address of the dispatch MBB into the jump buffer.
5619  if (isThumb2) {
5620    // Incoming value: jbuf
5621    //   ldr.n  r5, LCPI1_1
5622    //   orr    r5, r5, #1
5623    //   add    r5, pc
5624    //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5625    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5626    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5627                   .addConstantPoolIndex(CPI)
5628                   .addMemOperand(CPMMO));
5629    // Set the low bit because of thumb mode.
5630    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5631    AddDefaultCC(
5632      AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5633                     .addReg(NewVReg1, RegState::Kill)
5634                     .addImm(0x01)));
5635    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5636    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5637      .addReg(NewVReg2, RegState::Kill)
5638      .addImm(PCLabelId);
5639    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5640                   .addReg(NewVReg3, RegState::Kill)
5641                   .addFrameIndex(FI)
5642                   .addImm(36)  // &jbuf[1] :: pc
5643                   .addMemOperand(FIMMOSt));
5644  } else if (isThumb) {
5645    // Incoming value: jbuf
5646    //   ldr.n  r1, LCPI1_4
5647    //   add    r1, pc
5648    //   mov    r2, #1
5649    //   orrs   r1, r2
5650    //   add    r2, $jbuf, #+4 ; &jbuf[1]
5651    //   str    r1, [r2]
5652    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5653    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5654                   .addConstantPoolIndex(CPI)
5655                   .addMemOperand(CPMMO));
5656    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5657    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5658      .addReg(NewVReg1, RegState::Kill)
5659      .addImm(PCLabelId);
5660    // Set the low bit because of thumb mode.
5661    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5662    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5663                   .addReg(ARM::CPSR, RegState::Define)
5664                   .addImm(1));
5665    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5666    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5667                   .addReg(ARM::CPSR, RegState::Define)
5668                   .addReg(NewVReg2, RegState::Kill)
5669                   .addReg(NewVReg3, RegState::Kill));
5670    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5671    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5672                   .addFrameIndex(FI)
5673                   .addImm(36)); // &jbuf[1] :: pc
5674    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5675                   .addReg(NewVReg4, RegState::Kill)
5676                   .addReg(NewVReg5, RegState::Kill)
5677                   .addImm(0)
5678                   .addMemOperand(FIMMOSt));
5679  } else {
5680    // Incoming value: jbuf
5681    //   ldr  r1, LCPI1_1
5682    //   add  r1, pc, r1
5683    //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5684    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5685    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5686                   .addConstantPoolIndex(CPI)
5687                   .addImm(0)
5688                   .addMemOperand(CPMMO));
5689    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5690    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5691                   .addReg(NewVReg1, RegState::Kill)
5692                   .addImm(PCLabelId));
5693    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5694                   .addReg(NewVReg2, RegState::Kill)
5695                   .addFrameIndex(FI)
5696                   .addImm(36)  // &jbuf[1] :: pc
5697                   .addMemOperand(FIMMOSt));
5698  }
5699}
5700
5701MachineBasicBlock *ARMTargetLowering::
5702EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5703  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5704  DebugLoc dl = MI->getDebugLoc();
5705  MachineFunction *MF = MBB->getParent();
5706  MachineRegisterInfo *MRI = &MF->getRegInfo();
5707  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5708  MachineFrameInfo *MFI = MF->getFrameInfo();
5709  int FI = MFI->getFunctionContextIndex();
5710
5711  const TargetRegisterClass *TRC =
5712    Subtarget->isThumb() ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5713
5714  // Get a mapping of the call site numbers to all of the landing pads they're
5715  // associated with.
5716  DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5717  unsigned MaxCSNum = 0;
5718  MachineModuleInfo &MMI = MF->getMMI();
5719  for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; ++BB) {
5720    if (!BB->isLandingPad()) continue;
5721
5722    // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5723    // pad.
5724    for (MachineBasicBlock::iterator
5725           II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5726      if (!II->isEHLabel()) continue;
5727
5728      MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5729      if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5730
5731      SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5732      for (SmallVectorImpl<unsigned>::iterator
5733             CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5734           CSI != CSE; ++CSI) {
5735        CallSiteNumToLPad[*CSI].push_back(BB);
5736        MaxCSNum = std::max(MaxCSNum, *CSI);
5737      }
5738      break;
5739    }
5740  }
5741
5742  // Get an ordered list of the machine basic blocks for the jump table.
5743  std::vector<MachineBasicBlock*> LPadList;
5744  SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5745  LPadList.reserve(CallSiteNumToLPad.size());
5746  for (unsigned I = 1; I <= MaxCSNum; ++I) {
5747    SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5748    for (SmallVectorImpl<MachineBasicBlock*>::iterator
5749           II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5750      LPadList.push_back(*II);
5751      InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5752    }
5753  }
5754
5755  assert(!LPadList.empty() &&
5756         "No landing pad destinations for the dispatch jump table!");
5757
5758  // Create the jump table and associated information.
5759  MachineJumpTableInfo *JTI =
5760    MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5761  unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5762  unsigned UId = AFI->createJumpTableUId();
5763
5764  // Create the MBBs for the dispatch code.
5765
5766  // Shove the dispatch's address into the return slot in the function context.
5767  MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5768  DispatchBB->setIsLandingPad();
5769
5770  MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5771  BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5772  DispatchBB->addSuccessor(TrapBB);
5773
5774  MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5775  DispatchBB->addSuccessor(DispContBB);
5776
5777  // Insert and MBBs.
5778  MF->insert(MF->end(), DispatchBB);
5779  MF->insert(MF->end(), DispContBB);
5780  MF->insert(MF->end(), TrapBB);
5781
5782  // Insert code into the entry block that creates and registers the function
5783  // context.
5784  SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5785
5786  MachineMemOperand *FIMMOLd =
5787    MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5788                             MachineMemOperand::MOLoad |
5789                             MachineMemOperand::MOVolatile, 4, 4);
5790
5791  if (AFI->isThumb1OnlyFunction())
5792    BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5793  else if (!Subtarget->hasVFP2())
5794    BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5795  else
5796    BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5797
5798  unsigned NumLPads = LPadList.size();
5799  if (Subtarget->isThumb2()) {
5800    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5801    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5802                   .addFrameIndex(FI)
5803                   .addImm(4)
5804                   .addMemOperand(FIMMOLd));
5805
5806    if (NumLPads < 256) {
5807      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5808                     .addReg(NewVReg1)
5809                     .addImm(LPadList.size()));
5810    } else {
5811      unsigned VReg1 = MRI->createVirtualRegister(TRC);
5812      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5813                     .addImm(NumLPads & 0xFFFF));
5814
5815      unsigned VReg2 = VReg1;
5816      if ((NumLPads & 0xFFFF0000) != 0) {
5817        VReg2 = MRI->createVirtualRegister(TRC);
5818        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5819                       .addReg(VReg1)
5820                       .addImm(NumLPads >> 16));
5821      }
5822
5823      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5824                     .addReg(NewVReg1)
5825                     .addReg(VReg2));
5826    }
5827
5828    BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5829      .addMBB(TrapBB)
5830      .addImm(ARMCC::HI)
5831      .addReg(ARM::CPSR);
5832
5833    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5834    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5835                   .addJumpTableIndex(MJTI)
5836                   .addImm(UId));
5837
5838    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5839    AddDefaultCC(
5840      AddDefaultPred(
5841        BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5842        .addReg(NewVReg3, RegState::Kill)
5843        .addReg(NewVReg1)
5844        .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5845
5846    BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5847      .addReg(NewVReg4, RegState::Kill)
5848      .addReg(NewVReg1)
5849      .addJumpTableIndex(MJTI)
5850      .addImm(UId);
5851  } else if (Subtarget->isThumb()) {
5852    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5853    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
5854                   .addFrameIndex(FI)
5855                   .addImm(1)
5856                   .addMemOperand(FIMMOLd));
5857
5858    if (NumLPads < 256) {
5859      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
5860                     .addReg(NewVReg1)
5861                     .addImm(NumLPads));
5862    } else {
5863      MachineConstantPool *ConstantPool = MF->getConstantPool();
5864      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5865      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5866
5867      // MachineConstantPool wants an explicit alignment.
5868      unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
5869      if (Align == 0)
5870        Align = getTargetData()->getTypeAllocSize(C->getType());
5871      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
5872
5873      unsigned VReg1 = MRI->createVirtualRegister(TRC);
5874      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
5875                     .addReg(VReg1, RegState::Define)
5876                     .addConstantPoolIndex(Idx));
5877      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
5878                     .addReg(NewVReg1)
5879                     .addReg(VReg1));
5880    }
5881
5882    BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
5883      .addMBB(TrapBB)
5884      .addImm(ARMCC::HI)
5885      .addReg(ARM::CPSR);
5886
5887    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5888    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
5889                   .addReg(ARM::CPSR, RegState::Define)
5890                   .addReg(NewVReg1)
5891                   .addImm(2));
5892
5893    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5894    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
5895                   .addJumpTableIndex(MJTI)
5896                   .addImm(UId));
5897
5898    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5899    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
5900                   .addReg(ARM::CPSR, RegState::Define)
5901                   .addReg(NewVReg2, RegState::Kill)
5902                   .addReg(NewVReg3));
5903
5904    MachineMemOperand *JTMMOLd =
5905      MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
5906                               MachineMemOperand::MOLoad, 4, 4);
5907
5908    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5909    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
5910                   .addReg(NewVReg4, RegState::Kill)
5911                   .addImm(0)
5912                   .addMemOperand(JTMMOLd));
5913
5914    unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
5915    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
5916                   .addReg(ARM::CPSR, RegState::Define)
5917                   .addReg(NewVReg5, RegState::Kill)
5918                   .addReg(NewVReg3));
5919
5920    BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
5921      .addReg(NewVReg6, RegState::Kill)
5922      .addJumpTableIndex(MJTI)
5923      .addImm(UId);
5924  } else {
5925    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5926    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
5927                   .addFrameIndex(FI)
5928                   .addImm(4)
5929                   .addMemOperand(FIMMOLd));
5930
5931    if (NumLPads < 256) {
5932      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
5933                     .addReg(NewVReg1)
5934                     .addImm(NumLPads));
5935    } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
5936      unsigned VReg1 = MRI->createVirtualRegister(TRC);
5937      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
5938                     .addImm(NumLPads & 0xFFFF));
5939
5940      unsigned VReg2 = VReg1;
5941      if ((NumLPads & 0xFFFF0000) != 0) {
5942        VReg2 = MRI->createVirtualRegister(TRC);
5943        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
5944                       .addReg(VReg1)
5945                       .addImm(NumLPads >> 16));
5946      }
5947
5948      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
5949                     .addReg(NewVReg1)
5950                     .addReg(VReg2));
5951    } else {
5952      MachineConstantPool *ConstantPool = MF->getConstantPool();
5953      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5954      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5955
5956      // MachineConstantPool wants an explicit alignment.
5957      unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
5958      if (Align == 0)
5959        Align = getTargetData()->getTypeAllocSize(C->getType());
5960      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
5961
5962      unsigned VReg1 = MRI->createVirtualRegister(TRC);
5963      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
5964                     .addReg(VReg1, RegState::Define)
5965                     .addConstantPoolIndex(Idx)
5966                     .addImm(0));
5967      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
5968                     .addReg(NewVReg1)
5969                     .addReg(VReg1, RegState::Kill));
5970    }
5971
5972    BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
5973      .addMBB(TrapBB)
5974      .addImm(ARMCC::HI)
5975      .addReg(ARM::CPSR);
5976
5977    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5978    AddDefaultCC(
5979      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
5980                     .addReg(NewVReg1)
5981                     .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5982    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5983    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
5984                   .addJumpTableIndex(MJTI)
5985                   .addImm(UId));
5986
5987    MachineMemOperand *JTMMOLd =
5988      MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
5989                               MachineMemOperand::MOLoad, 4, 4);
5990    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5991    AddDefaultPred(
5992      BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
5993      .addReg(NewVReg3, RegState::Kill)
5994      .addReg(NewVReg4)
5995      .addImm(0)
5996      .addMemOperand(JTMMOLd));
5997
5998    BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
5999      .addReg(NewVReg5, RegState::Kill)
6000      .addReg(NewVReg4)
6001      .addJumpTableIndex(MJTI)
6002      .addImm(UId);
6003  }
6004
6005  // Add the jump table entries as successors to the MBB.
6006  MachineBasicBlock *PrevMBB = 0;
6007  for (std::vector<MachineBasicBlock*>::iterator
6008         I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6009    MachineBasicBlock *CurMBB = *I;
6010    if (PrevMBB != CurMBB)
6011      DispContBB->addSuccessor(CurMBB);
6012    PrevMBB = CurMBB;
6013  }
6014
6015  // N.B. the order the invoke BBs are processed in doesn't matter here.
6016  const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6017  const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6018  const unsigned *SavedRegs = RI.getCalleeSavedRegs(MF);
6019  SmallVector<MachineBasicBlock*, 64> MBBLPads;
6020  for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6021         I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6022    MachineBasicBlock *BB = *I;
6023
6024    // Remove the landing pad successor from the invoke block and replace it
6025    // with the new dispatch block.
6026    SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6027                                                  BB->succ_end());
6028    while (!Successors.empty()) {
6029      MachineBasicBlock *SMBB = Successors.pop_back_val();
6030      if (SMBB->isLandingPad()) {
6031        BB->removeSuccessor(SMBB);
6032        MBBLPads.push_back(SMBB);
6033      }
6034    }
6035
6036    BB->addSuccessor(DispatchBB);
6037
6038    // Find the invoke call and mark all of the callee-saved registers as
6039    // 'implicit defined' so that they're spilled. This prevents code from
6040    // moving instructions to before the EH block, where they will never be
6041    // executed.
6042    for (MachineBasicBlock::reverse_iterator
6043           II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6044      if (!II->isCall()) continue;
6045
6046      DenseMap<unsigned, bool> DefRegs;
6047      for (MachineInstr::mop_iterator
6048             OI = II->operands_begin(), OE = II->operands_end();
6049           OI != OE; ++OI) {
6050        if (!OI->isReg()) continue;
6051        DefRegs[OI->getReg()] = true;
6052      }
6053
6054      MachineInstrBuilder MIB(&*II);
6055
6056      for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6057        unsigned Reg = SavedRegs[i];
6058        if (Subtarget->isThumb2() &&
6059            !ARM::tGPRRegisterClass->contains(Reg) &&
6060            !ARM::hGPRRegisterClass->contains(Reg))
6061          continue;
6062        else if (Subtarget->isThumb1Only() &&
6063                 !ARM::tGPRRegisterClass->contains(Reg))
6064          continue;
6065        else if (!Subtarget->isThumb() &&
6066                 !ARM::GPRRegisterClass->contains(Reg))
6067          continue;
6068        if (!DefRegs[Reg])
6069          MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6070      }
6071
6072      break;
6073    }
6074  }
6075
6076  // Mark all former landing pads as non-landing pads. The dispatch is the only
6077  // landing pad now.
6078  for (SmallVectorImpl<MachineBasicBlock*>::iterator
6079         I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6080    (*I)->setIsLandingPad(false);
6081
6082  // The instruction is gone now.
6083  MI->eraseFromParent();
6084
6085  return MBB;
6086}
6087
6088static
6089MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6090  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6091       E = MBB->succ_end(); I != E; ++I)
6092    if (*I != Succ)
6093      return *I;
6094  llvm_unreachable("Expecting a BB with two successors!");
6095}
6096
6097MachineBasicBlock *
6098ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6099                                               MachineBasicBlock *BB) const {
6100  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6101  DebugLoc dl = MI->getDebugLoc();
6102  bool isThumb2 = Subtarget->isThumb2();
6103  switch (MI->getOpcode()) {
6104  default: {
6105    MI->dump();
6106    llvm_unreachable("Unexpected instr type to insert");
6107  }
6108  // The Thumb2 pre-indexed stores have the same MI operands, they just
6109  // define them differently in the .td files from the isel patterns, so
6110  // they need pseudos.
6111  case ARM::t2STR_preidx:
6112    MI->setDesc(TII->get(ARM::t2STR_PRE));
6113    return BB;
6114  case ARM::t2STRB_preidx:
6115    MI->setDesc(TII->get(ARM::t2STRB_PRE));
6116    return BB;
6117  case ARM::t2STRH_preidx:
6118    MI->setDesc(TII->get(ARM::t2STRH_PRE));
6119    return BB;
6120
6121  case ARM::STRi_preidx:
6122  case ARM::STRBi_preidx: {
6123    unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6124      ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6125    // Decode the offset.
6126    unsigned Offset = MI->getOperand(4).getImm();
6127    bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6128    Offset = ARM_AM::getAM2Offset(Offset);
6129    if (isSub)
6130      Offset = -Offset;
6131
6132    MachineMemOperand *MMO = *MI->memoperands_begin();
6133    BuildMI(*BB, MI, dl, TII->get(NewOpc))
6134      .addOperand(MI->getOperand(0))  // Rn_wb
6135      .addOperand(MI->getOperand(1))  // Rt
6136      .addOperand(MI->getOperand(2))  // Rn
6137      .addImm(Offset)                 // offset (skip GPR==zero_reg)
6138      .addOperand(MI->getOperand(5))  // pred
6139      .addOperand(MI->getOperand(6))
6140      .addMemOperand(MMO);
6141    MI->eraseFromParent();
6142    return BB;
6143  }
6144  case ARM::STRr_preidx:
6145  case ARM::STRBr_preidx:
6146  case ARM::STRH_preidx: {
6147    unsigned NewOpc;
6148    switch (MI->getOpcode()) {
6149    default: llvm_unreachable("unexpected opcode!");
6150    case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6151    case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6152    case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6153    }
6154    MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6155    for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6156      MIB.addOperand(MI->getOperand(i));
6157    MI->eraseFromParent();
6158    return BB;
6159  }
6160  case ARM::ATOMIC_LOAD_ADD_I8:
6161     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6162  case ARM::ATOMIC_LOAD_ADD_I16:
6163     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6164  case ARM::ATOMIC_LOAD_ADD_I32:
6165     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6166
6167  case ARM::ATOMIC_LOAD_AND_I8:
6168     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6169  case ARM::ATOMIC_LOAD_AND_I16:
6170     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6171  case ARM::ATOMIC_LOAD_AND_I32:
6172     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6173
6174  case ARM::ATOMIC_LOAD_OR_I8:
6175     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6176  case ARM::ATOMIC_LOAD_OR_I16:
6177     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6178  case ARM::ATOMIC_LOAD_OR_I32:
6179     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6180
6181  case ARM::ATOMIC_LOAD_XOR_I8:
6182     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6183  case ARM::ATOMIC_LOAD_XOR_I16:
6184     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6185  case ARM::ATOMIC_LOAD_XOR_I32:
6186     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6187
6188  case ARM::ATOMIC_LOAD_NAND_I8:
6189     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6190  case ARM::ATOMIC_LOAD_NAND_I16:
6191     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6192  case ARM::ATOMIC_LOAD_NAND_I32:
6193     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6194
6195  case ARM::ATOMIC_LOAD_SUB_I8:
6196     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6197  case ARM::ATOMIC_LOAD_SUB_I16:
6198     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6199  case ARM::ATOMIC_LOAD_SUB_I32:
6200     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6201
6202  case ARM::ATOMIC_LOAD_MIN_I8:
6203     return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6204  case ARM::ATOMIC_LOAD_MIN_I16:
6205     return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6206  case ARM::ATOMIC_LOAD_MIN_I32:
6207     return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6208
6209  case ARM::ATOMIC_LOAD_MAX_I8:
6210     return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6211  case ARM::ATOMIC_LOAD_MAX_I16:
6212     return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6213  case ARM::ATOMIC_LOAD_MAX_I32:
6214     return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6215
6216  case ARM::ATOMIC_LOAD_UMIN_I8:
6217     return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6218  case ARM::ATOMIC_LOAD_UMIN_I16:
6219     return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6220  case ARM::ATOMIC_LOAD_UMIN_I32:
6221     return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6222
6223  case ARM::ATOMIC_LOAD_UMAX_I8:
6224     return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6225  case ARM::ATOMIC_LOAD_UMAX_I16:
6226     return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6227  case ARM::ATOMIC_LOAD_UMAX_I32:
6228     return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6229
6230  case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6231  case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6232  case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6233
6234  case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6235  case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6236  case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6237
6238
6239  case ARM::ATOMADD6432:
6240    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6241                              isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6242                              /*NeedsCarry*/ true);
6243  case ARM::ATOMSUB6432:
6244    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6245                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6246                              /*NeedsCarry*/ true);
6247  case ARM::ATOMOR6432:
6248    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6249                              isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6250  case ARM::ATOMXOR6432:
6251    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6252                              isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6253  case ARM::ATOMAND6432:
6254    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6255                              isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6256  case ARM::ATOMSWAP6432:
6257    return EmitAtomicBinary64(MI, BB, 0, 0, false);
6258  case ARM::ATOMCMPXCHG6432:
6259    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6260                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6261                              /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6262
6263  case ARM::tMOVCCr_pseudo: {
6264    // To "insert" a SELECT_CC instruction, we actually have to insert the
6265    // diamond control-flow pattern.  The incoming instruction knows the
6266    // destination vreg to set, the condition code register to branch on, the
6267    // true/false values to select between, and a branch opcode to use.
6268    const BasicBlock *LLVM_BB = BB->getBasicBlock();
6269    MachineFunction::iterator It = BB;
6270    ++It;
6271
6272    //  thisMBB:
6273    //  ...
6274    //   TrueVal = ...
6275    //   cmpTY ccX, r1, r2
6276    //   bCC copy1MBB
6277    //   fallthrough --> copy0MBB
6278    MachineBasicBlock *thisMBB  = BB;
6279    MachineFunction *F = BB->getParent();
6280    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6281    MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6282    F->insert(It, copy0MBB);
6283    F->insert(It, sinkMBB);
6284
6285    // Transfer the remainder of BB and its successor edges to sinkMBB.
6286    sinkMBB->splice(sinkMBB->begin(), BB,
6287                    llvm::next(MachineBasicBlock::iterator(MI)),
6288                    BB->end());
6289    sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6290
6291    BB->addSuccessor(copy0MBB);
6292    BB->addSuccessor(sinkMBB);
6293
6294    BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6295      .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6296
6297    //  copy0MBB:
6298    //   %FalseValue = ...
6299    //   # fallthrough to sinkMBB
6300    BB = copy0MBB;
6301
6302    // Update machine-CFG edges
6303    BB->addSuccessor(sinkMBB);
6304
6305    //  sinkMBB:
6306    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6307    //  ...
6308    BB = sinkMBB;
6309    BuildMI(*BB, BB->begin(), dl,
6310            TII->get(ARM::PHI), MI->getOperand(0).getReg())
6311      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6312      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6313
6314    MI->eraseFromParent();   // The pseudo instruction is gone now.
6315    return BB;
6316  }
6317
6318  case ARM::BCCi64:
6319  case ARM::BCCZi64: {
6320    // If there is an unconditional branch to the other successor, remove it.
6321    BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6322
6323    // Compare both parts that make up the double comparison separately for
6324    // equality.
6325    bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6326
6327    unsigned LHS1 = MI->getOperand(1).getReg();
6328    unsigned LHS2 = MI->getOperand(2).getReg();
6329    if (RHSisZero) {
6330      AddDefaultPred(BuildMI(BB, dl,
6331                             TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6332                     .addReg(LHS1).addImm(0));
6333      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6334        .addReg(LHS2).addImm(0)
6335        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6336    } else {
6337      unsigned RHS1 = MI->getOperand(3).getReg();
6338      unsigned RHS2 = MI->getOperand(4).getReg();
6339      AddDefaultPred(BuildMI(BB, dl,
6340                             TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6341                     .addReg(LHS1).addReg(RHS1));
6342      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6343        .addReg(LHS2).addReg(RHS2)
6344        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6345    }
6346
6347    MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6348    MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6349    if (MI->getOperand(0).getImm() == ARMCC::NE)
6350      std::swap(destMBB, exitMBB);
6351
6352    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6353      .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6354    if (isThumb2)
6355      AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6356    else
6357      BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6358
6359    MI->eraseFromParent();   // The pseudo instruction is gone now.
6360    return BB;
6361  }
6362
6363  case ARM::Int_eh_sjlj_setjmp:
6364  case ARM::Int_eh_sjlj_setjmp_nofp:
6365  case ARM::tInt_eh_sjlj_setjmp:
6366  case ARM::t2Int_eh_sjlj_setjmp:
6367  case ARM::t2Int_eh_sjlj_setjmp_nofp:
6368    EmitSjLjDispatchBlock(MI, BB);
6369    return BB;
6370
6371  case ARM::ABS:
6372  case ARM::t2ABS: {
6373    // To insert an ABS instruction, we have to insert the
6374    // diamond control-flow pattern.  The incoming instruction knows the
6375    // source vreg to test against 0, the destination vreg to set,
6376    // the condition code register to branch on, the
6377    // true/false values to select between, and a branch opcode to use.
6378    // It transforms
6379    //     V1 = ABS V0
6380    // into
6381    //     V2 = MOVS V0
6382    //     BCC                      (branch to SinkBB if V0 >= 0)
6383    //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6384    //     SinkBB: V1 = PHI(V2, V3)
6385    const BasicBlock *LLVM_BB = BB->getBasicBlock();
6386    MachineFunction::iterator BBI = BB;
6387    ++BBI;
6388    MachineFunction *Fn = BB->getParent();
6389    MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6390    MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6391    Fn->insert(BBI, RSBBB);
6392    Fn->insert(BBI, SinkBB);
6393
6394    unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6395    unsigned int ABSDstReg = MI->getOperand(0).getReg();
6396    bool isThumb2 = Subtarget->isThumb2();
6397    MachineRegisterInfo &MRI = Fn->getRegInfo();
6398    // In Thumb mode S must not be specified if source register is the SP or
6399    // PC and if destination register is the SP, so restrict register class
6400    unsigned NewMovDstReg = MRI.createVirtualRegister(
6401      isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6402    unsigned NewRsbDstReg = MRI.createVirtualRegister(
6403      isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6404
6405    // Transfer the remainder of BB and its successor edges to sinkMBB.
6406    SinkBB->splice(SinkBB->begin(), BB,
6407      llvm::next(MachineBasicBlock::iterator(MI)),
6408      BB->end());
6409    SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6410
6411    BB->addSuccessor(RSBBB);
6412    BB->addSuccessor(SinkBB);
6413
6414    // fall through to SinkMBB
6415    RSBBB->addSuccessor(SinkBB);
6416
6417    // insert a movs at the end of BB
6418    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6419      NewMovDstReg)
6420      .addReg(ABSSrcReg, RegState::Kill)
6421      .addImm((unsigned)ARMCC::AL).addReg(0)
6422      .addReg(ARM::CPSR, RegState::Define);
6423
6424    // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6425    BuildMI(BB, dl,
6426      TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6427      .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6428
6429    // insert rsbri in RSBBB
6430    // Note: BCC and rsbri will be converted into predicated rsbmi
6431    // by if-conversion pass
6432    BuildMI(*RSBBB, RSBBB->begin(), dl,
6433      TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6434      .addReg(NewMovDstReg, RegState::Kill)
6435      .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6436
6437    // insert PHI in SinkBB,
6438    // reuse ABSDstReg to not change uses of ABS instruction
6439    BuildMI(*SinkBB, SinkBB->begin(), dl,
6440      TII->get(ARM::PHI), ABSDstReg)
6441      .addReg(NewRsbDstReg).addMBB(RSBBB)
6442      .addReg(NewMovDstReg).addMBB(BB);
6443
6444    // remove ABS instruction
6445    MI->eraseFromParent();
6446
6447    // return last added BB
6448    return SinkBB;
6449  }
6450  }
6451}
6452
6453void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6454                                                      SDNode *Node) const {
6455  if (!MI->hasPostISelHook()) {
6456    assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6457           "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6458    return;
6459  }
6460
6461  const MCInstrDesc *MCID = &MI->getDesc();
6462  // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6463  // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6464  // operand is still set to noreg. If needed, set the optional operand's
6465  // register to CPSR, and remove the redundant implicit def.
6466  //
6467  // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6468
6469  // Rename pseudo opcodes.
6470  unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6471  if (NewOpc) {
6472    const ARMBaseInstrInfo *TII =
6473      static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6474    MCID = &TII->get(NewOpc);
6475
6476    assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6477           "converted opcode should be the same except for cc_out");
6478
6479    MI->setDesc(*MCID);
6480
6481    // Add the optional cc_out operand
6482    MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6483  }
6484  unsigned ccOutIdx = MCID->getNumOperands() - 1;
6485
6486  // Any ARM instruction that sets the 's' bit should specify an optional
6487  // "cc_out" operand in the last operand position.
6488  if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6489    assert(!NewOpc && "Optional cc_out operand required");
6490    return;
6491  }
6492  // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6493  // since we already have an optional CPSR def.
6494  bool definesCPSR = false;
6495  bool deadCPSR = false;
6496  for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6497       i != e; ++i) {
6498    const MachineOperand &MO = MI->getOperand(i);
6499    if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6500      definesCPSR = true;
6501      if (MO.isDead())
6502        deadCPSR = true;
6503      MI->RemoveOperand(i);
6504      break;
6505    }
6506  }
6507  if (!definesCPSR) {
6508    assert(!NewOpc && "Optional cc_out operand required");
6509    return;
6510  }
6511  assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6512  if (deadCPSR) {
6513    assert(!MI->getOperand(ccOutIdx).getReg() &&
6514           "expect uninitialized optional cc_out operand");
6515    return;
6516  }
6517
6518  // If this instruction was defined with an optional CPSR def and its dag node
6519  // had a live implicit CPSR def, then activate the optional CPSR def.
6520  MachineOperand &MO = MI->getOperand(ccOutIdx);
6521  MO.setReg(ARM::CPSR);
6522  MO.setIsDef(true);
6523}
6524
6525//===----------------------------------------------------------------------===//
6526//                           ARM Optimization Hooks
6527//===----------------------------------------------------------------------===//
6528
6529static
6530SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6531                            TargetLowering::DAGCombinerInfo &DCI) {
6532  SelectionDAG &DAG = DCI.DAG;
6533  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6534  EVT VT = N->getValueType(0);
6535  unsigned Opc = N->getOpcode();
6536  bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6537  SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6538  SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6539  ISD::CondCode CC = ISD::SETCC_INVALID;
6540
6541  if (isSlctCC) {
6542    CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6543  } else {
6544    SDValue CCOp = Slct.getOperand(0);
6545    if (CCOp.getOpcode() == ISD::SETCC)
6546      CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6547  }
6548
6549  bool DoXform = false;
6550  bool InvCC = false;
6551  assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6552          "Bad input!");
6553
6554  if (LHS.getOpcode() == ISD::Constant &&
6555      cast<ConstantSDNode>(LHS)->isNullValue()) {
6556    DoXform = true;
6557  } else if (CC != ISD::SETCC_INVALID &&
6558             RHS.getOpcode() == ISD::Constant &&
6559             cast<ConstantSDNode>(RHS)->isNullValue()) {
6560    std::swap(LHS, RHS);
6561    SDValue Op0 = Slct.getOperand(0);
6562    EVT OpVT = isSlctCC ? Op0.getValueType() :
6563                          Op0.getOperand(0).getValueType();
6564    bool isInt = OpVT.isInteger();
6565    CC = ISD::getSetCCInverse(CC, isInt);
6566
6567    if (!TLI.isCondCodeLegal(CC, OpVT))
6568      return SDValue();         // Inverse operator isn't legal.
6569
6570    DoXform = true;
6571    InvCC = true;
6572  }
6573
6574  if (DoXform) {
6575    SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6576    if (isSlctCC)
6577      return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6578                             Slct.getOperand(0), Slct.getOperand(1), CC);
6579    SDValue CCOp = Slct.getOperand(0);
6580    if (InvCC)
6581      CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6582                          CCOp.getOperand(0), CCOp.getOperand(1), CC);
6583    return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6584                       CCOp, OtherOp, Result);
6585  }
6586  return SDValue();
6587}
6588
6589// AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6590// (only after legalization).
6591static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6592                                 TargetLowering::DAGCombinerInfo &DCI,
6593                                 const ARMSubtarget *Subtarget) {
6594
6595  // Only perform optimization if after legalize, and if NEON is available. We
6596  // also expected both operands to be BUILD_VECTORs.
6597  if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6598      || N0.getOpcode() != ISD::BUILD_VECTOR
6599      || N1.getOpcode() != ISD::BUILD_VECTOR)
6600    return SDValue();
6601
6602  // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6603  EVT VT = N->getValueType(0);
6604  if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6605    return SDValue();
6606
6607  // Check that the vector operands are of the right form.
6608  // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6609  // operands, where N is the size of the formed vector.
6610  // Each EXTRACT_VECTOR should have the same input vector and odd or even
6611  // index such that we have a pair wise add pattern.
6612
6613  // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6614  if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6615    return SDValue();
6616  SDValue Vec = N0->getOperand(0)->getOperand(0);
6617  SDNode *V = Vec.getNode();
6618  unsigned nextIndex = 0;
6619
6620  // For each operands to the ADD which are BUILD_VECTORs,
6621  // check to see if each of their operands are an EXTRACT_VECTOR with
6622  // the same vector and appropriate index.
6623  for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6624    if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6625        && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6626
6627      SDValue ExtVec0 = N0->getOperand(i);
6628      SDValue ExtVec1 = N1->getOperand(i);
6629
6630      // First operand is the vector, verify its the same.
6631      if (V != ExtVec0->getOperand(0).getNode() ||
6632          V != ExtVec1->getOperand(0).getNode())
6633        return SDValue();
6634
6635      // Second is the constant, verify its correct.
6636      ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6637      ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6638
6639      // For the constant, we want to see all the even or all the odd.
6640      if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6641          || C1->getZExtValue() != nextIndex+1)
6642        return SDValue();
6643
6644      // Increment index.
6645      nextIndex+=2;
6646    } else
6647      return SDValue();
6648  }
6649
6650  // Create VPADDL node.
6651  SelectionDAG &DAG = DCI.DAG;
6652  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6653
6654  // Build operand list.
6655  SmallVector<SDValue, 8> Ops;
6656  Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6657                                TLI.getPointerTy()));
6658
6659  // Input is the vector.
6660  Ops.push_back(Vec);
6661
6662  // Get widened type and narrowed type.
6663  MVT widenType;
6664  unsigned numElem = VT.getVectorNumElements();
6665  switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6666    case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6667    case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6668    case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6669    default:
6670      assert(0 && "Invalid vector element type for padd optimization.");
6671  }
6672
6673  SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6674                            widenType, &Ops[0], Ops.size());
6675  return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6676}
6677
6678/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6679/// operands N0 and N1.  This is a helper for PerformADDCombine that is
6680/// called with the default operands, and if that fails, with commuted
6681/// operands.
6682static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6683                                          TargetLowering::DAGCombinerInfo &DCI,
6684                                          const ARMSubtarget *Subtarget){
6685
6686  // Attempt to create vpaddl for this add.
6687  SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6688  if (Result.getNode())
6689    return Result;
6690
6691  // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6692  if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6693    SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6694    if (Result.getNode()) return Result;
6695  }
6696  return SDValue();
6697}
6698
6699/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6700///
6701static SDValue PerformADDCombine(SDNode *N,
6702                                 TargetLowering::DAGCombinerInfo &DCI,
6703                                 const ARMSubtarget *Subtarget) {
6704  SDValue N0 = N->getOperand(0);
6705  SDValue N1 = N->getOperand(1);
6706
6707  // First try with the default operand order.
6708  SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6709  if (Result.getNode())
6710    return Result;
6711
6712  // If that didn't work, try again with the operands commuted.
6713  return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6714}
6715
6716/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6717///
6718static SDValue PerformSUBCombine(SDNode *N,
6719                                 TargetLowering::DAGCombinerInfo &DCI) {
6720  SDValue N0 = N->getOperand(0);
6721  SDValue N1 = N->getOperand(1);
6722
6723  // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6724  if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6725    SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6726    if (Result.getNode()) return Result;
6727  }
6728
6729  return SDValue();
6730}
6731
6732/// PerformVMULCombine
6733/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6734/// special multiplier accumulator forwarding.
6735///   vmul d3, d0, d2
6736///   vmla d3, d1, d2
6737/// is faster than
6738///   vadd d3, d0, d1
6739///   vmul d3, d3, d2
6740static SDValue PerformVMULCombine(SDNode *N,
6741                                  TargetLowering::DAGCombinerInfo &DCI,
6742                                  const ARMSubtarget *Subtarget) {
6743  if (!Subtarget->hasVMLxForwarding())
6744    return SDValue();
6745
6746  SelectionDAG &DAG = DCI.DAG;
6747  SDValue N0 = N->getOperand(0);
6748  SDValue N1 = N->getOperand(1);
6749  unsigned Opcode = N0.getOpcode();
6750  if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6751      Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6752    Opcode = N1.getOpcode();
6753    if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6754        Opcode != ISD::FADD && Opcode != ISD::FSUB)
6755      return SDValue();
6756    std::swap(N0, N1);
6757  }
6758
6759  EVT VT = N->getValueType(0);
6760  DebugLoc DL = N->getDebugLoc();
6761  SDValue N00 = N0->getOperand(0);
6762  SDValue N01 = N0->getOperand(1);
6763  return DAG.getNode(Opcode, DL, VT,
6764                     DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6765                     DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6766}
6767
6768static SDValue PerformMULCombine(SDNode *N,
6769                                 TargetLowering::DAGCombinerInfo &DCI,
6770                                 const ARMSubtarget *Subtarget) {
6771  SelectionDAG &DAG = DCI.DAG;
6772
6773  if (Subtarget->isThumb1Only())
6774    return SDValue();
6775
6776  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6777    return SDValue();
6778
6779  EVT VT = N->getValueType(0);
6780  if (VT.is64BitVector() || VT.is128BitVector())
6781    return PerformVMULCombine(N, DCI, Subtarget);
6782  if (VT != MVT::i32)
6783    return SDValue();
6784
6785  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6786  if (!C)
6787    return SDValue();
6788
6789  uint64_t MulAmt = C->getZExtValue();
6790  unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6791  ShiftAmt = ShiftAmt & (32 - 1);
6792  SDValue V = N->getOperand(0);
6793  DebugLoc DL = N->getDebugLoc();
6794
6795  SDValue Res;
6796  MulAmt >>= ShiftAmt;
6797  if (isPowerOf2_32(MulAmt - 1)) {
6798    // (mul x, 2^N + 1) => (add (shl x, N), x)
6799    Res = DAG.getNode(ISD::ADD, DL, VT,
6800                      V, DAG.getNode(ISD::SHL, DL, VT,
6801                                     V, DAG.getConstant(Log2_32(MulAmt-1),
6802                                                        MVT::i32)));
6803  } else if (isPowerOf2_32(MulAmt + 1)) {
6804    // (mul x, 2^N - 1) => (sub (shl x, N), x)
6805    Res = DAG.getNode(ISD::SUB, DL, VT,
6806                      DAG.getNode(ISD::SHL, DL, VT,
6807                                  V, DAG.getConstant(Log2_32(MulAmt+1),
6808                                                     MVT::i32)),
6809                                                     V);
6810  } else
6811    return SDValue();
6812
6813  if (ShiftAmt != 0)
6814    Res = DAG.getNode(ISD::SHL, DL, VT, Res,
6815                      DAG.getConstant(ShiftAmt, MVT::i32));
6816
6817  // Do not add new nodes to DAG combiner worklist.
6818  DCI.CombineTo(N, Res, false);
6819  return SDValue();
6820}
6821
6822static SDValue PerformANDCombine(SDNode *N,
6823                                TargetLowering::DAGCombinerInfo &DCI) {
6824
6825  // Attempt to use immediate-form VBIC
6826  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6827  DebugLoc dl = N->getDebugLoc();
6828  EVT VT = N->getValueType(0);
6829  SelectionDAG &DAG = DCI.DAG;
6830
6831  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6832    return SDValue();
6833
6834  APInt SplatBits, SplatUndef;
6835  unsigned SplatBitSize;
6836  bool HasAnyUndefs;
6837  if (BVN &&
6838      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6839    if (SplatBitSize <= 64) {
6840      EVT VbicVT;
6841      SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
6842                                      SplatUndef.getZExtValue(), SplatBitSize,
6843                                      DAG, VbicVT, VT.is128BitVector(),
6844                                      OtherModImm);
6845      if (Val.getNode()) {
6846        SDValue Input =
6847          DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
6848        SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
6849        return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
6850      }
6851    }
6852  }
6853
6854  return SDValue();
6855}
6856
6857/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
6858static SDValue PerformORCombine(SDNode *N,
6859                                TargetLowering::DAGCombinerInfo &DCI,
6860                                const ARMSubtarget *Subtarget) {
6861  // Attempt to use immediate-form VORR
6862  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6863  DebugLoc dl = N->getDebugLoc();
6864  EVT VT = N->getValueType(0);
6865  SelectionDAG &DAG = DCI.DAG;
6866
6867  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6868    return SDValue();
6869
6870  APInt SplatBits, SplatUndef;
6871  unsigned SplatBitSize;
6872  bool HasAnyUndefs;
6873  if (BVN && Subtarget->hasNEON() &&
6874      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6875    if (SplatBitSize <= 64) {
6876      EVT VorrVT;
6877      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6878                                      SplatUndef.getZExtValue(), SplatBitSize,
6879                                      DAG, VorrVT, VT.is128BitVector(),
6880                                      OtherModImm);
6881      if (Val.getNode()) {
6882        SDValue Input =
6883          DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
6884        SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
6885        return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
6886      }
6887    }
6888  }
6889
6890  SDValue N0 = N->getOperand(0);
6891  if (N0.getOpcode() != ISD::AND)
6892    return SDValue();
6893  SDValue N1 = N->getOperand(1);
6894
6895  // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
6896  if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
6897      DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
6898    APInt SplatUndef;
6899    unsigned SplatBitSize;
6900    bool HasAnyUndefs;
6901
6902    BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
6903    APInt SplatBits0;
6904    if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
6905                                  HasAnyUndefs) && !HasAnyUndefs) {
6906      BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
6907      APInt SplatBits1;
6908      if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
6909                                    HasAnyUndefs) && !HasAnyUndefs &&
6910          SplatBits0 == ~SplatBits1) {
6911        // Canonicalize the vector type to make instruction selection simpler.
6912        EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6913        SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
6914                                     N0->getOperand(1), N0->getOperand(0),
6915                                     N1->getOperand(0));
6916        return DAG.getNode(ISD::BITCAST, dl, VT, Result);
6917      }
6918    }
6919  }
6920
6921  // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
6922  // reasonable.
6923
6924  // BFI is only available on V6T2+
6925  if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
6926    return SDValue();
6927
6928  DebugLoc DL = N->getDebugLoc();
6929  // 1) or (and A, mask), val => ARMbfi A, val, mask
6930  //      iff (val & mask) == val
6931  //
6932  // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
6933  //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
6934  //          && mask == ~mask2
6935  //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
6936  //          && ~mask == mask2
6937  //  (i.e., copy a bitfield value into another bitfield of the same width)
6938
6939  if (VT != MVT::i32)
6940    return SDValue();
6941
6942  SDValue N00 = N0.getOperand(0);
6943
6944  // The value and the mask need to be constants so we can verify this is
6945  // actually a bitfield set. If the mask is 0xffff, we can do better
6946  // via a movt instruction, so don't use BFI in that case.
6947  SDValue MaskOp = N0.getOperand(1);
6948  ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
6949  if (!MaskC)
6950    return SDValue();
6951  unsigned Mask = MaskC->getZExtValue();
6952  if (Mask == 0xffff)
6953    return SDValue();
6954  SDValue Res;
6955  // Case (1): or (and A, mask), val => ARMbfi A, val, mask
6956  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
6957  if (N1C) {
6958    unsigned Val = N1C->getZExtValue();
6959    if ((Val & ~Mask) != Val)
6960      return SDValue();
6961
6962    if (ARM::isBitFieldInvertedMask(Mask)) {
6963      Val >>= CountTrailingZeros_32(~Mask);
6964
6965      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
6966                        DAG.getConstant(Val, MVT::i32),
6967                        DAG.getConstant(Mask, MVT::i32));
6968
6969      // Do not add new nodes to DAG combiner worklist.
6970      DCI.CombineTo(N, Res, false);
6971      return SDValue();
6972    }
6973  } else if (N1.getOpcode() == ISD::AND) {
6974    // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
6975    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
6976    if (!N11C)
6977      return SDValue();
6978    unsigned Mask2 = N11C->getZExtValue();
6979
6980    // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
6981    // as is to match.
6982    if (ARM::isBitFieldInvertedMask(Mask) &&
6983        (Mask == ~Mask2)) {
6984      // The pack halfword instruction works better for masks that fit it,
6985      // so use that when it's available.
6986      if (Subtarget->hasT2ExtractPack() &&
6987          (Mask == 0xffff || Mask == 0xffff0000))
6988        return SDValue();
6989      // 2a
6990      unsigned amt = CountTrailingZeros_32(Mask2);
6991      Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
6992                        DAG.getConstant(amt, MVT::i32));
6993      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
6994                        DAG.getConstant(Mask, MVT::i32));
6995      // Do not add new nodes to DAG combiner worklist.
6996      DCI.CombineTo(N, Res, false);
6997      return SDValue();
6998    } else if (ARM::isBitFieldInvertedMask(~Mask) &&
6999               (~Mask == Mask2)) {
7000      // The pack halfword instruction works better for masks that fit it,
7001      // so use that when it's available.
7002      if (Subtarget->hasT2ExtractPack() &&
7003          (Mask2 == 0xffff || Mask2 == 0xffff0000))
7004        return SDValue();
7005      // 2b
7006      unsigned lsb = CountTrailingZeros_32(Mask);
7007      Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7008                        DAG.getConstant(lsb, MVT::i32));
7009      Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7010                        DAG.getConstant(Mask2, MVT::i32));
7011      // Do not add new nodes to DAG combiner worklist.
7012      DCI.CombineTo(N, Res, false);
7013      return SDValue();
7014    }
7015  }
7016
7017  if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7018      N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7019      ARM::isBitFieldInvertedMask(~Mask)) {
7020    // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7021    // where lsb(mask) == #shamt and masked bits of B are known zero.
7022    SDValue ShAmt = N00.getOperand(1);
7023    unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7024    unsigned LSB = CountTrailingZeros_32(Mask);
7025    if (ShAmtC != LSB)
7026      return SDValue();
7027
7028    Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7029                      DAG.getConstant(~Mask, MVT::i32));
7030
7031    // Do not add new nodes to DAG combiner worklist.
7032    DCI.CombineTo(N, Res, false);
7033  }
7034
7035  return SDValue();
7036}
7037
7038/// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7039/// the bits being cleared by the AND are not demanded by the BFI.
7040static SDValue PerformBFICombine(SDNode *N,
7041                                 TargetLowering::DAGCombinerInfo &DCI) {
7042  SDValue N1 = N->getOperand(1);
7043  if (N1.getOpcode() == ISD::AND) {
7044    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7045    if (!N11C)
7046      return SDValue();
7047    unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7048    unsigned LSB = CountTrailingZeros_32(~InvMask);
7049    unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7050    unsigned Mask = (1 << Width)-1;
7051    unsigned Mask2 = N11C->getZExtValue();
7052    if ((Mask & (~Mask2)) == 0)
7053      return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7054                             N->getOperand(0), N1.getOperand(0),
7055                             N->getOperand(2));
7056  }
7057  return SDValue();
7058}
7059
7060/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7061/// ARMISD::VMOVRRD.
7062static SDValue PerformVMOVRRDCombine(SDNode *N,
7063                                     TargetLowering::DAGCombinerInfo &DCI) {
7064  // vmovrrd(vmovdrr x, y) -> x,y
7065  SDValue InDouble = N->getOperand(0);
7066  if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7067    return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7068
7069  // vmovrrd(load f64) -> (load i32), (load i32)
7070  SDNode *InNode = InDouble.getNode();
7071  if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7072      InNode->getValueType(0) == MVT::f64 &&
7073      InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7074      !cast<LoadSDNode>(InNode)->isVolatile()) {
7075    // TODO: Should this be done for non-FrameIndex operands?
7076    LoadSDNode *LD = cast<LoadSDNode>(InNode);
7077
7078    SelectionDAG &DAG = DCI.DAG;
7079    DebugLoc DL = LD->getDebugLoc();
7080    SDValue BasePtr = LD->getBasePtr();
7081    SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7082                                 LD->getPointerInfo(), LD->isVolatile(),
7083                                 LD->isNonTemporal(), LD->isInvariant(),
7084                                 LD->getAlignment());
7085
7086    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7087                                    DAG.getConstant(4, MVT::i32));
7088    SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7089                                 LD->getPointerInfo(), LD->isVolatile(),
7090                                 LD->isNonTemporal(), LD->isInvariant(),
7091                                 std::min(4U, LD->getAlignment() / 2));
7092
7093    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7094    SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7095    DCI.RemoveFromWorklist(LD);
7096    DAG.DeleteNode(LD);
7097    return Result;
7098  }
7099
7100  return SDValue();
7101}
7102
7103/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7104/// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7105static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7106  // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7107  SDValue Op0 = N->getOperand(0);
7108  SDValue Op1 = N->getOperand(1);
7109  if (Op0.getOpcode() == ISD::BITCAST)
7110    Op0 = Op0.getOperand(0);
7111  if (Op1.getOpcode() == ISD::BITCAST)
7112    Op1 = Op1.getOperand(0);
7113  if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7114      Op0.getNode() == Op1.getNode() &&
7115      Op0.getResNo() == 0 && Op1.getResNo() == 1)
7116    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7117                       N->getValueType(0), Op0.getOperand(0));
7118  return SDValue();
7119}
7120
7121/// PerformSTORECombine - Target-specific dag combine xforms for
7122/// ISD::STORE.
7123static SDValue PerformSTORECombine(SDNode *N,
7124                                   TargetLowering::DAGCombinerInfo &DCI) {
7125  // Bitcast an i64 store extracted from a vector to f64.
7126  // Otherwise, the i64 value will be legalized to a pair of i32 values.
7127  StoreSDNode *St = cast<StoreSDNode>(N);
7128  SDValue StVal = St->getValue();
7129  if (!ISD::isNormalStore(St) || St->isVolatile())
7130    return SDValue();
7131
7132  if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7133      StVal.getNode()->hasOneUse() && !St->isVolatile()) {
7134    SelectionDAG  &DAG = DCI.DAG;
7135    DebugLoc DL = St->getDebugLoc();
7136    SDValue BasePtr = St->getBasePtr();
7137    SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7138                                  StVal.getNode()->getOperand(0), BasePtr,
7139                                  St->getPointerInfo(), St->isVolatile(),
7140                                  St->isNonTemporal(), St->getAlignment());
7141
7142    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7143                                    DAG.getConstant(4, MVT::i32));
7144    return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7145                        OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7146                        St->isNonTemporal(),
7147                        std::min(4U, St->getAlignment() / 2));
7148  }
7149
7150  if (StVal.getValueType() != MVT::i64 ||
7151      StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7152    return SDValue();
7153
7154  SelectionDAG &DAG = DCI.DAG;
7155  DebugLoc dl = StVal.getDebugLoc();
7156  SDValue IntVec = StVal.getOperand(0);
7157  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7158                                 IntVec.getValueType().getVectorNumElements());
7159  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7160  SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7161                               Vec, StVal.getOperand(1));
7162  dl = N->getDebugLoc();
7163  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7164  // Make the DAGCombiner fold the bitcasts.
7165  DCI.AddToWorklist(Vec.getNode());
7166  DCI.AddToWorklist(ExtElt.getNode());
7167  DCI.AddToWorklist(V.getNode());
7168  return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7169                      St->getPointerInfo(), St->isVolatile(),
7170                      St->isNonTemporal(), St->getAlignment(),
7171                      St->getTBAAInfo());
7172}
7173
7174/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7175/// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7176/// i64 vector to have f64 elements, since the value can then be loaded
7177/// directly into a VFP register.
7178static bool hasNormalLoadOperand(SDNode *N) {
7179  unsigned NumElts = N->getValueType(0).getVectorNumElements();
7180  for (unsigned i = 0; i < NumElts; ++i) {
7181    SDNode *Elt = N->getOperand(i).getNode();
7182    if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7183      return true;
7184  }
7185  return false;
7186}
7187
7188/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7189/// ISD::BUILD_VECTOR.
7190static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7191                                          TargetLowering::DAGCombinerInfo &DCI){
7192  // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7193  // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7194  // into a pair of GPRs, which is fine when the value is used as a scalar,
7195  // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7196  SelectionDAG &DAG = DCI.DAG;
7197  if (N->getNumOperands() == 2) {
7198    SDValue RV = PerformVMOVDRRCombine(N, DAG);
7199    if (RV.getNode())
7200      return RV;
7201  }
7202
7203  // Load i64 elements as f64 values so that type legalization does not split
7204  // them up into i32 values.
7205  EVT VT = N->getValueType(0);
7206  if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7207    return SDValue();
7208  DebugLoc dl = N->getDebugLoc();
7209  SmallVector<SDValue, 8> Ops;
7210  unsigned NumElts = VT.getVectorNumElements();
7211  for (unsigned i = 0; i < NumElts; ++i) {
7212    SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7213    Ops.push_back(V);
7214    // Make the DAGCombiner fold the bitcast.
7215    DCI.AddToWorklist(V.getNode());
7216  }
7217  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7218  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7219  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7220}
7221
7222/// PerformInsertEltCombine - Target-specific dag combine xforms for
7223/// ISD::INSERT_VECTOR_ELT.
7224static SDValue PerformInsertEltCombine(SDNode *N,
7225                                       TargetLowering::DAGCombinerInfo &DCI) {
7226  // Bitcast an i64 load inserted into a vector to f64.
7227  // Otherwise, the i64 value will be legalized to a pair of i32 values.
7228  EVT VT = N->getValueType(0);
7229  SDNode *Elt = N->getOperand(1).getNode();
7230  if (VT.getVectorElementType() != MVT::i64 ||
7231      !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7232    return SDValue();
7233
7234  SelectionDAG &DAG = DCI.DAG;
7235  DebugLoc dl = N->getDebugLoc();
7236  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7237                                 VT.getVectorNumElements());
7238  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7239  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7240  // Make the DAGCombiner fold the bitcasts.
7241  DCI.AddToWorklist(Vec.getNode());
7242  DCI.AddToWorklist(V.getNode());
7243  SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7244                               Vec, V, N->getOperand(2));
7245  return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7246}
7247
7248/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7249/// ISD::VECTOR_SHUFFLE.
7250static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7251  // The LLVM shufflevector instruction does not require the shuffle mask
7252  // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7253  // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7254  // operands do not match the mask length, they are extended by concatenating
7255  // them with undef vectors.  That is probably the right thing for other
7256  // targets, but for NEON it is better to concatenate two double-register
7257  // size vector operands into a single quad-register size vector.  Do that
7258  // transformation here:
7259  //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7260  //   shuffle(concat(v1, v2), undef)
7261  SDValue Op0 = N->getOperand(0);
7262  SDValue Op1 = N->getOperand(1);
7263  if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7264      Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7265      Op0.getNumOperands() != 2 ||
7266      Op1.getNumOperands() != 2)
7267    return SDValue();
7268  SDValue Concat0Op1 = Op0.getOperand(1);
7269  SDValue Concat1Op1 = Op1.getOperand(1);
7270  if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7271      Concat1Op1.getOpcode() != ISD::UNDEF)
7272    return SDValue();
7273  // Skip the transformation if any of the types are illegal.
7274  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7275  EVT VT = N->getValueType(0);
7276  if (!TLI.isTypeLegal(VT) ||
7277      !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7278      !TLI.isTypeLegal(Concat1Op1.getValueType()))
7279    return SDValue();
7280
7281  SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7282                                  Op0.getOperand(0), Op1.getOperand(0));
7283  // Translate the shuffle mask.
7284  SmallVector<int, 16> NewMask;
7285  unsigned NumElts = VT.getVectorNumElements();
7286  unsigned HalfElts = NumElts/2;
7287  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7288  for (unsigned n = 0; n < NumElts; ++n) {
7289    int MaskElt = SVN->getMaskElt(n);
7290    int NewElt = -1;
7291    if (MaskElt < (int)HalfElts)
7292      NewElt = MaskElt;
7293    else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7294      NewElt = HalfElts + MaskElt - NumElts;
7295    NewMask.push_back(NewElt);
7296  }
7297  return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7298                              DAG.getUNDEF(VT), NewMask.data());
7299}
7300
7301/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7302/// NEON load/store intrinsics to merge base address updates.
7303static SDValue CombineBaseUpdate(SDNode *N,
7304                                 TargetLowering::DAGCombinerInfo &DCI) {
7305  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7306    return SDValue();
7307
7308  SelectionDAG &DAG = DCI.DAG;
7309  bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7310                      N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7311  unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7312  SDValue Addr = N->getOperand(AddrOpIdx);
7313
7314  // Search for a use of the address operand that is an increment.
7315  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7316         UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7317    SDNode *User = *UI;
7318    if (User->getOpcode() != ISD::ADD ||
7319        UI.getUse().getResNo() != Addr.getResNo())
7320      continue;
7321
7322    // Check that the add is independent of the load/store.  Otherwise, folding
7323    // it would create a cycle.
7324    if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7325      continue;
7326
7327    // Find the new opcode for the updating load/store.
7328    bool isLoad = true;
7329    bool isLaneOp = false;
7330    unsigned NewOpc = 0;
7331    unsigned NumVecs = 0;
7332    if (isIntrinsic) {
7333      unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7334      switch (IntNo) {
7335      default: assert(0 && "unexpected intrinsic for Neon base update");
7336      case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
7337        NumVecs = 1; break;
7338      case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
7339        NumVecs = 2; break;
7340      case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
7341        NumVecs = 3; break;
7342      case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
7343        NumVecs = 4; break;
7344      case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7345        NumVecs = 2; isLaneOp = true; break;
7346      case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7347        NumVecs = 3; isLaneOp = true; break;
7348      case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7349        NumVecs = 4; isLaneOp = true; break;
7350      case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
7351        NumVecs = 1; isLoad = false; break;
7352      case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
7353        NumVecs = 2; isLoad = false; break;
7354      case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
7355        NumVecs = 3; isLoad = false; break;
7356      case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
7357        NumVecs = 4; isLoad = false; break;
7358      case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7359        NumVecs = 2; isLoad = false; isLaneOp = true; break;
7360      case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7361        NumVecs = 3; isLoad = false; isLaneOp = true; break;
7362      case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7363        NumVecs = 4; isLoad = false; isLaneOp = true; break;
7364      }
7365    } else {
7366      isLaneOp = true;
7367      switch (N->getOpcode()) {
7368      default: assert(0 && "unexpected opcode for Neon base update");
7369      case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7370      case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7371      case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7372      }
7373    }
7374
7375    // Find the size of memory referenced by the load/store.
7376    EVT VecTy;
7377    if (isLoad)
7378      VecTy = N->getValueType(0);
7379    else
7380      VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7381    unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7382    if (isLaneOp)
7383      NumBytes /= VecTy.getVectorNumElements();
7384
7385    // If the increment is a constant, it must match the memory ref size.
7386    SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7387    if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7388      uint64_t IncVal = CInc->getZExtValue();
7389      if (IncVal != NumBytes)
7390        continue;
7391    } else if (NumBytes >= 3 * 16) {
7392      // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7393      // separate instructions that make it harder to use a non-constant update.
7394      continue;
7395    }
7396
7397    // Create the new updating load/store node.
7398    EVT Tys[6];
7399    unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7400    unsigned n;
7401    for (n = 0; n < NumResultVecs; ++n)
7402      Tys[n] = VecTy;
7403    Tys[n++] = MVT::i32;
7404    Tys[n] = MVT::Other;
7405    SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7406    SmallVector<SDValue, 8> Ops;
7407    Ops.push_back(N->getOperand(0)); // incoming chain
7408    Ops.push_back(N->getOperand(AddrOpIdx));
7409    Ops.push_back(Inc);
7410    for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7411      Ops.push_back(N->getOperand(i));
7412    }
7413    MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7414    SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7415                                           Ops.data(), Ops.size(),
7416                                           MemInt->getMemoryVT(),
7417                                           MemInt->getMemOperand());
7418
7419    // Update the uses.
7420    std::vector<SDValue> NewResults;
7421    for (unsigned i = 0; i < NumResultVecs; ++i) {
7422      NewResults.push_back(SDValue(UpdN.getNode(), i));
7423    }
7424    NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7425    DCI.CombineTo(N, NewResults);
7426    DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7427
7428    break;
7429  }
7430  return SDValue();
7431}
7432
7433/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7434/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7435/// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
7436/// return true.
7437static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7438  SelectionDAG &DAG = DCI.DAG;
7439  EVT VT = N->getValueType(0);
7440  // vldN-dup instructions only support 64-bit vectors for N > 1.
7441  if (!VT.is64BitVector())
7442    return false;
7443
7444  // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7445  SDNode *VLD = N->getOperand(0).getNode();
7446  if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7447    return false;
7448  unsigned NumVecs = 0;
7449  unsigned NewOpc = 0;
7450  unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7451  if (IntNo == Intrinsic::arm_neon_vld2lane) {
7452    NumVecs = 2;
7453    NewOpc = ARMISD::VLD2DUP;
7454  } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7455    NumVecs = 3;
7456    NewOpc = ARMISD::VLD3DUP;
7457  } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7458    NumVecs = 4;
7459    NewOpc = ARMISD::VLD4DUP;
7460  } else {
7461    return false;
7462  }
7463
7464  // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7465  // numbers match the load.
7466  unsigned VLDLaneNo =
7467    cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7468  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7469       UI != UE; ++UI) {
7470    // Ignore uses of the chain result.
7471    if (UI.getUse().getResNo() == NumVecs)
7472      continue;
7473    SDNode *User = *UI;
7474    if (User->getOpcode() != ARMISD::VDUPLANE ||
7475        VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7476      return false;
7477  }
7478
7479  // Create the vldN-dup node.
7480  EVT Tys[5];
7481  unsigned n;
7482  for (n = 0; n < NumVecs; ++n)
7483    Tys[n] = VT;
7484  Tys[n] = MVT::Other;
7485  SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7486  SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7487  MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7488  SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7489                                           Ops, 2, VLDMemInt->getMemoryVT(),
7490                                           VLDMemInt->getMemOperand());
7491
7492  // Update the uses.
7493  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7494       UI != UE; ++UI) {
7495    unsigned ResNo = UI.getUse().getResNo();
7496    // Ignore uses of the chain result.
7497    if (ResNo == NumVecs)
7498      continue;
7499    SDNode *User = *UI;
7500    DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7501  }
7502
7503  // Now the vldN-lane intrinsic is dead except for its chain result.
7504  // Update uses of the chain.
7505  std::vector<SDValue> VLDDupResults;
7506  for (unsigned n = 0; n < NumVecs; ++n)
7507    VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7508  VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7509  DCI.CombineTo(VLD, VLDDupResults);
7510
7511  return true;
7512}
7513
7514/// PerformVDUPLANECombine - Target-specific dag combine xforms for
7515/// ARMISD::VDUPLANE.
7516static SDValue PerformVDUPLANECombine(SDNode *N,
7517                                      TargetLowering::DAGCombinerInfo &DCI) {
7518  SDValue Op = N->getOperand(0);
7519
7520  // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7521  // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7522  if (CombineVLDDUP(N, DCI))
7523    return SDValue(N, 0);
7524
7525  // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7526  // redundant.  Ignore bit_converts for now; element sizes are checked below.
7527  while (Op.getOpcode() == ISD::BITCAST)
7528    Op = Op.getOperand(0);
7529  if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7530    return SDValue();
7531
7532  // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7533  unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7534  // The canonical VMOV for a zero vector uses a 32-bit element size.
7535  unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7536  unsigned EltBits;
7537  if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7538    EltSize = 8;
7539  EVT VT = N->getValueType(0);
7540  if (EltSize > VT.getVectorElementType().getSizeInBits())
7541    return SDValue();
7542
7543  return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7544}
7545
7546// isConstVecPow2 - Return true if each vector element is a power of 2, all
7547// elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7548static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7549{
7550  integerPart cN;
7551  integerPart c0 = 0;
7552  for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7553       I != E; I++) {
7554    ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7555    if (!C)
7556      return false;
7557
7558    bool isExact;
7559    APFloat APF = C->getValueAPF();
7560    if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7561        != APFloat::opOK || !isExact)
7562      return false;
7563
7564    c0 = (I == 0) ? cN : c0;
7565    if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7566      return false;
7567  }
7568  C = c0;
7569  return true;
7570}
7571
7572/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7573/// can replace combinations of VMUL and VCVT (floating-point to integer)
7574/// when the VMUL has a constant operand that is a power of 2.
7575///
7576/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7577///  vmul.f32        d16, d17, d16
7578///  vcvt.s32.f32    d16, d16
7579/// becomes:
7580///  vcvt.s32.f32    d16, d16, #3
7581static SDValue PerformVCVTCombine(SDNode *N,
7582                                  TargetLowering::DAGCombinerInfo &DCI,
7583                                  const ARMSubtarget *Subtarget) {
7584  SelectionDAG &DAG = DCI.DAG;
7585  SDValue Op = N->getOperand(0);
7586
7587  if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7588      Op.getOpcode() != ISD::FMUL)
7589    return SDValue();
7590
7591  uint64_t C;
7592  SDValue N0 = Op->getOperand(0);
7593  SDValue ConstVec = Op->getOperand(1);
7594  bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7595
7596  if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7597      !isConstVecPow2(ConstVec, isSigned, C))
7598    return SDValue();
7599
7600  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7601    Intrinsic::arm_neon_vcvtfp2fxu;
7602  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7603                     N->getValueType(0),
7604                     DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7605                     DAG.getConstant(Log2_64(C), MVT::i32));
7606}
7607
7608/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7609/// can replace combinations of VCVT (integer to floating-point) and VDIV
7610/// when the VDIV has a constant operand that is a power of 2.
7611///
7612/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7613///  vcvt.f32.s32    d16, d16
7614///  vdiv.f32        d16, d17, d16
7615/// becomes:
7616///  vcvt.f32.s32    d16, d16, #3
7617static SDValue PerformVDIVCombine(SDNode *N,
7618                                  TargetLowering::DAGCombinerInfo &DCI,
7619                                  const ARMSubtarget *Subtarget) {
7620  SelectionDAG &DAG = DCI.DAG;
7621  SDValue Op = N->getOperand(0);
7622  unsigned OpOpcode = Op.getNode()->getOpcode();
7623
7624  if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7625      (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7626    return SDValue();
7627
7628  uint64_t C;
7629  SDValue ConstVec = N->getOperand(1);
7630  bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7631
7632  if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7633      !isConstVecPow2(ConstVec, isSigned, C))
7634    return SDValue();
7635
7636  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7637    Intrinsic::arm_neon_vcvtfxu2fp;
7638  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7639                     Op.getValueType(),
7640                     DAG.getConstant(IntrinsicOpcode, MVT::i32),
7641                     Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7642}
7643
7644/// Getvshiftimm - Check if this is a valid build_vector for the immediate
7645/// operand of a vector shift operation, where all the elements of the
7646/// build_vector must have the same constant integer value.
7647static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7648  // Ignore bit_converts.
7649  while (Op.getOpcode() == ISD::BITCAST)
7650    Op = Op.getOperand(0);
7651  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7652  APInt SplatBits, SplatUndef;
7653  unsigned SplatBitSize;
7654  bool HasAnyUndefs;
7655  if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7656                                      HasAnyUndefs, ElementBits) ||
7657      SplatBitSize > ElementBits)
7658    return false;
7659  Cnt = SplatBits.getSExtValue();
7660  return true;
7661}
7662
7663/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7664/// operand of a vector shift left operation.  That value must be in the range:
7665///   0 <= Value < ElementBits for a left shift; or
7666///   0 <= Value <= ElementBits for a long left shift.
7667static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7668  assert(VT.isVector() && "vector shift count is not a vector type");
7669  unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7670  if (! getVShiftImm(Op, ElementBits, Cnt))
7671    return false;
7672  return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
7673}
7674
7675/// isVShiftRImm - Check if this is a valid build_vector for the immediate
7676/// operand of a vector shift right operation.  For a shift opcode, the value
7677/// is positive, but for an intrinsic the value count must be negative. The
7678/// absolute value must be in the range:
7679///   1 <= |Value| <= ElementBits for a right shift; or
7680///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
7681static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
7682                         int64_t &Cnt) {
7683  assert(VT.isVector() && "vector shift count is not a vector type");
7684  unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7685  if (! getVShiftImm(Op, ElementBits, Cnt))
7686    return false;
7687  if (isIntrinsic)
7688    Cnt = -Cnt;
7689  return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
7690}
7691
7692/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
7693static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
7694  unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7695  switch (IntNo) {
7696  default:
7697    // Don't do anything for most intrinsics.
7698    break;
7699
7700  // Vector shifts: check for immediate versions and lower them.
7701  // Note: This is done during DAG combining instead of DAG legalizing because
7702  // the build_vectors for 64-bit vector element shift counts are generally
7703  // not legal, and it is hard to see their values after they get legalized to
7704  // loads from a constant pool.
7705  case Intrinsic::arm_neon_vshifts:
7706  case Intrinsic::arm_neon_vshiftu:
7707  case Intrinsic::arm_neon_vshiftls:
7708  case Intrinsic::arm_neon_vshiftlu:
7709  case Intrinsic::arm_neon_vshiftn:
7710  case Intrinsic::arm_neon_vrshifts:
7711  case Intrinsic::arm_neon_vrshiftu:
7712  case Intrinsic::arm_neon_vrshiftn:
7713  case Intrinsic::arm_neon_vqshifts:
7714  case Intrinsic::arm_neon_vqshiftu:
7715  case Intrinsic::arm_neon_vqshiftsu:
7716  case Intrinsic::arm_neon_vqshiftns:
7717  case Intrinsic::arm_neon_vqshiftnu:
7718  case Intrinsic::arm_neon_vqshiftnsu:
7719  case Intrinsic::arm_neon_vqrshiftns:
7720  case Intrinsic::arm_neon_vqrshiftnu:
7721  case Intrinsic::arm_neon_vqrshiftnsu: {
7722    EVT VT = N->getOperand(1).getValueType();
7723    int64_t Cnt;
7724    unsigned VShiftOpc = 0;
7725
7726    switch (IntNo) {
7727    case Intrinsic::arm_neon_vshifts:
7728    case Intrinsic::arm_neon_vshiftu:
7729      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
7730        VShiftOpc = ARMISD::VSHL;
7731        break;
7732      }
7733      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
7734        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
7735                     ARMISD::VSHRs : ARMISD::VSHRu);
7736        break;
7737      }
7738      return SDValue();
7739
7740    case Intrinsic::arm_neon_vshiftls:
7741    case Intrinsic::arm_neon_vshiftlu:
7742      if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
7743        break;
7744      llvm_unreachable("invalid shift count for vshll intrinsic");
7745
7746    case Intrinsic::arm_neon_vrshifts:
7747    case Intrinsic::arm_neon_vrshiftu:
7748      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
7749        break;
7750      return SDValue();
7751
7752    case Intrinsic::arm_neon_vqshifts:
7753    case Intrinsic::arm_neon_vqshiftu:
7754      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7755        break;
7756      return SDValue();
7757
7758    case Intrinsic::arm_neon_vqshiftsu:
7759      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7760        break;
7761      llvm_unreachable("invalid shift count for vqshlu intrinsic");
7762
7763    case Intrinsic::arm_neon_vshiftn:
7764    case Intrinsic::arm_neon_vrshiftn:
7765    case Intrinsic::arm_neon_vqshiftns:
7766    case Intrinsic::arm_neon_vqshiftnu:
7767    case Intrinsic::arm_neon_vqshiftnsu:
7768    case Intrinsic::arm_neon_vqrshiftns:
7769    case Intrinsic::arm_neon_vqrshiftnu:
7770    case Intrinsic::arm_neon_vqrshiftnsu:
7771      // Narrowing shifts require an immediate right shift.
7772      if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
7773        break;
7774      llvm_unreachable("invalid shift count for narrowing vector shift "
7775                       "intrinsic");
7776
7777    default:
7778      llvm_unreachable("unhandled vector shift");
7779    }
7780
7781    switch (IntNo) {
7782    case Intrinsic::arm_neon_vshifts:
7783    case Intrinsic::arm_neon_vshiftu:
7784      // Opcode already set above.
7785      break;
7786    case Intrinsic::arm_neon_vshiftls:
7787    case Intrinsic::arm_neon_vshiftlu:
7788      if (Cnt == VT.getVectorElementType().getSizeInBits())
7789        VShiftOpc = ARMISD::VSHLLi;
7790      else
7791        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
7792                     ARMISD::VSHLLs : ARMISD::VSHLLu);
7793      break;
7794    case Intrinsic::arm_neon_vshiftn:
7795      VShiftOpc = ARMISD::VSHRN; break;
7796    case Intrinsic::arm_neon_vrshifts:
7797      VShiftOpc = ARMISD::VRSHRs; break;
7798    case Intrinsic::arm_neon_vrshiftu:
7799      VShiftOpc = ARMISD::VRSHRu; break;
7800    case Intrinsic::arm_neon_vrshiftn:
7801      VShiftOpc = ARMISD::VRSHRN; break;
7802    case Intrinsic::arm_neon_vqshifts:
7803      VShiftOpc = ARMISD::VQSHLs; break;
7804    case Intrinsic::arm_neon_vqshiftu:
7805      VShiftOpc = ARMISD::VQSHLu; break;
7806    case Intrinsic::arm_neon_vqshiftsu:
7807      VShiftOpc = ARMISD::VQSHLsu; break;
7808    case Intrinsic::arm_neon_vqshiftns:
7809      VShiftOpc = ARMISD::VQSHRNs; break;
7810    case Intrinsic::arm_neon_vqshiftnu:
7811      VShiftOpc = ARMISD::VQSHRNu; break;
7812    case Intrinsic::arm_neon_vqshiftnsu:
7813      VShiftOpc = ARMISD::VQSHRNsu; break;
7814    case Intrinsic::arm_neon_vqrshiftns:
7815      VShiftOpc = ARMISD::VQRSHRNs; break;
7816    case Intrinsic::arm_neon_vqrshiftnu:
7817      VShiftOpc = ARMISD::VQRSHRNu; break;
7818    case Intrinsic::arm_neon_vqrshiftnsu:
7819      VShiftOpc = ARMISD::VQRSHRNsu; break;
7820    }
7821
7822    return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7823                       N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
7824  }
7825
7826  case Intrinsic::arm_neon_vshiftins: {
7827    EVT VT = N->getOperand(1).getValueType();
7828    int64_t Cnt;
7829    unsigned VShiftOpc = 0;
7830
7831    if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
7832      VShiftOpc = ARMISD::VSLI;
7833    else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
7834      VShiftOpc = ARMISD::VSRI;
7835    else {
7836      llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
7837    }
7838
7839    return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7840                       N->getOperand(1), N->getOperand(2),
7841                       DAG.getConstant(Cnt, MVT::i32));
7842  }
7843
7844  case Intrinsic::arm_neon_vqrshifts:
7845  case Intrinsic::arm_neon_vqrshiftu:
7846    // No immediate versions of these to check for.
7847    break;
7848  }
7849
7850  return SDValue();
7851}
7852
7853/// PerformShiftCombine - Checks for immediate versions of vector shifts and
7854/// lowers them.  As with the vector shift intrinsics, this is done during DAG
7855/// combining instead of DAG legalizing because the build_vectors for 64-bit
7856/// vector element shift counts are generally not legal, and it is hard to see
7857/// their values after they get legalized to loads from a constant pool.
7858static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
7859                                   const ARMSubtarget *ST) {
7860  EVT VT = N->getValueType(0);
7861
7862  // Nothing to be done for scalar shifts.
7863  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7864  if (!VT.isVector() || !TLI.isTypeLegal(VT))
7865    return SDValue();
7866
7867  assert(ST->hasNEON() && "unexpected vector shift");
7868  int64_t Cnt;
7869
7870  switch (N->getOpcode()) {
7871  default: llvm_unreachable("unexpected shift opcode");
7872
7873  case ISD::SHL:
7874    if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
7875      return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
7876                         DAG.getConstant(Cnt, MVT::i32));
7877    break;
7878
7879  case ISD::SRA:
7880  case ISD::SRL:
7881    if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
7882      unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
7883                            ARMISD::VSHRs : ARMISD::VSHRu);
7884      return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
7885                         DAG.getConstant(Cnt, MVT::i32));
7886    }
7887  }
7888  return SDValue();
7889}
7890
7891/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
7892/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
7893static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
7894                                    const ARMSubtarget *ST) {
7895  SDValue N0 = N->getOperand(0);
7896
7897  // Check for sign- and zero-extensions of vector extract operations of 8-
7898  // and 16-bit vector elements.  NEON supports these directly.  They are
7899  // handled during DAG combining because type legalization will promote them
7900  // to 32-bit types and it is messy to recognize the operations after that.
7901  if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7902    SDValue Vec = N0.getOperand(0);
7903    SDValue Lane = N0.getOperand(1);
7904    EVT VT = N->getValueType(0);
7905    EVT EltVT = N0.getValueType();
7906    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7907
7908    if (VT == MVT::i32 &&
7909        (EltVT == MVT::i8 || EltVT == MVT::i16) &&
7910        TLI.isTypeLegal(Vec.getValueType()) &&
7911        isa<ConstantSDNode>(Lane)) {
7912
7913      unsigned Opc = 0;
7914      switch (N->getOpcode()) {
7915      default: llvm_unreachable("unexpected opcode");
7916      case ISD::SIGN_EXTEND:
7917        Opc = ARMISD::VGETLANEs;
7918        break;
7919      case ISD::ZERO_EXTEND:
7920      case ISD::ANY_EXTEND:
7921        Opc = ARMISD::VGETLANEu;
7922        break;
7923      }
7924      return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
7925    }
7926  }
7927
7928  return SDValue();
7929}
7930
7931/// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
7932/// to match f32 max/min patterns to use NEON vmax/vmin instructions.
7933static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
7934                                       const ARMSubtarget *ST) {
7935  // If the target supports NEON, try to use vmax/vmin instructions for f32
7936  // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
7937  // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
7938  // a NaN; only do the transformation when it matches that behavior.
7939
7940  // For now only do this when using NEON for FP operations; if using VFP, it
7941  // is not obvious that the benefit outweighs the cost of switching to the
7942  // NEON pipeline.
7943  if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
7944      N->getValueType(0) != MVT::f32)
7945    return SDValue();
7946
7947  SDValue CondLHS = N->getOperand(0);
7948  SDValue CondRHS = N->getOperand(1);
7949  SDValue LHS = N->getOperand(2);
7950  SDValue RHS = N->getOperand(3);
7951  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
7952
7953  unsigned Opcode = 0;
7954  bool IsReversed;
7955  if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
7956    IsReversed = false; // x CC y ? x : y
7957  } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
7958    IsReversed = true ; // x CC y ? y : x
7959  } else {
7960    return SDValue();
7961  }
7962
7963  bool IsUnordered;
7964  switch (CC) {
7965  default: break;
7966  case ISD::SETOLT:
7967  case ISD::SETOLE:
7968  case ISD::SETLT:
7969  case ISD::SETLE:
7970  case ISD::SETULT:
7971  case ISD::SETULE:
7972    // If LHS is NaN, an ordered comparison will be false and the result will
7973    // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
7974    // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
7975    IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
7976    if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
7977      break;
7978    // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
7979    // will return -0, so vmin can only be used for unsafe math or if one of
7980    // the operands is known to be nonzero.
7981    if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
7982        !DAG.getTarget().Options.UnsafeFPMath &&
7983        !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
7984      break;
7985    Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
7986    break;
7987
7988  case ISD::SETOGT:
7989  case ISD::SETOGE:
7990  case ISD::SETGT:
7991  case ISD::SETGE:
7992  case ISD::SETUGT:
7993  case ISD::SETUGE:
7994    // If LHS is NaN, an ordered comparison will be false and the result will
7995    // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
7996    // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
7997    IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
7998    if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
7999      break;
8000    // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8001    // will return +0, so vmax can only be used for unsafe math or if one of
8002    // the operands is known to be nonzero.
8003    if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8004        !DAG.getTarget().Options.UnsafeFPMath &&
8005        !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8006      break;
8007    Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8008    break;
8009  }
8010
8011  if (!Opcode)
8012    return SDValue();
8013  return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8014}
8015
8016/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8017SDValue
8018ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8019  SDValue Cmp = N->getOperand(4);
8020  if (Cmp.getOpcode() != ARMISD::CMPZ)
8021    // Only looking at EQ and NE cases.
8022    return SDValue();
8023
8024  EVT VT = N->getValueType(0);
8025  DebugLoc dl = N->getDebugLoc();
8026  SDValue LHS = Cmp.getOperand(0);
8027  SDValue RHS = Cmp.getOperand(1);
8028  SDValue FalseVal = N->getOperand(0);
8029  SDValue TrueVal = N->getOperand(1);
8030  SDValue ARMcc = N->getOperand(2);
8031  ARMCC::CondCodes CC =
8032    (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8033
8034  // Simplify
8035  //   mov     r1, r0
8036  //   cmp     r1, x
8037  //   mov     r0, y
8038  //   moveq   r0, x
8039  // to
8040  //   cmp     r0, x
8041  //   movne   r0, y
8042  //
8043  //   mov     r1, r0
8044  //   cmp     r1, x
8045  //   mov     r0, x
8046  //   movne   r0, y
8047  // to
8048  //   cmp     r0, x
8049  //   movne   r0, y
8050  /// FIXME: Turn this into a target neutral optimization?
8051  SDValue Res;
8052  if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8053    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8054                      N->getOperand(3), Cmp);
8055  } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8056    SDValue ARMcc;
8057    SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8058    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8059                      N->getOperand(3), NewCmp);
8060  }
8061
8062  if (Res.getNode()) {
8063    APInt KnownZero, KnownOne;
8064    APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
8065    DAG.ComputeMaskedBits(SDValue(N,0), Mask, KnownZero, KnownOne);
8066    // Capture demanded bits information that would be otherwise lost.
8067    if (KnownZero == 0xfffffffe)
8068      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8069                        DAG.getValueType(MVT::i1));
8070    else if (KnownZero == 0xffffff00)
8071      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8072                        DAG.getValueType(MVT::i8));
8073    else if (KnownZero == 0xffff0000)
8074      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8075                        DAG.getValueType(MVT::i16));
8076  }
8077
8078  return Res;
8079}
8080
8081SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8082                                             DAGCombinerInfo &DCI) const {
8083  switch (N->getOpcode()) {
8084  default: break;
8085  case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8086  case ISD::SUB:        return PerformSUBCombine(N, DCI);
8087  case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8088  case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8089  case ISD::AND:        return PerformANDCombine(N, DCI);
8090  case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8091  case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8092  case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8093  case ISD::STORE:      return PerformSTORECombine(N, DCI);
8094  case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8095  case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8096  case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8097  case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8098  case ISD::FP_TO_SINT:
8099  case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8100  case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8101  case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8102  case ISD::SHL:
8103  case ISD::SRA:
8104  case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8105  case ISD::SIGN_EXTEND:
8106  case ISD::ZERO_EXTEND:
8107  case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8108  case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8109  case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8110  case ARMISD::VLD2DUP:
8111  case ARMISD::VLD3DUP:
8112  case ARMISD::VLD4DUP:
8113    return CombineBaseUpdate(N, DCI);
8114  case ISD::INTRINSIC_VOID:
8115  case ISD::INTRINSIC_W_CHAIN:
8116    switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8117    case Intrinsic::arm_neon_vld1:
8118    case Intrinsic::arm_neon_vld2:
8119    case Intrinsic::arm_neon_vld3:
8120    case Intrinsic::arm_neon_vld4:
8121    case Intrinsic::arm_neon_vld2lane:
8122    case Intrinsic::arm_neon_vld3lane:
8123    case Intrinsic::arm_neon_vld4lane:
8124    case Intrinsic::arm_neon_vst1:
8125    case Intrinsic::arm_neon_vst2:
8126    case Intrinsic::arm_neon_vst3:
8127    case Intrinsic::arm_neon_vst4:
8128    case Intrinsic::arm_neon_vst2lane:
8129    case Intrinsic::arm_neon_vst3lane:
8130    case Intrinsic::arm_neon_vst4lane:
8131      return CombineBaseUpdate(N, DCI);
8132    default: break;
8133    }
8134    break;
8135  }
8136  return SDValue();
8137}
8138
8139bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8140                                                          EVT VT) const {
8141  return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8142}
8143
8144bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8145  if (!Subtarget->allowsUnalignedMem())
8146    return false;
8147
8148  switch (VT.getSimpleVT().SimpleTy) {
8149  default:
8150    return false;
8151  case MVT::i8:
8152  case MVT::i16:
8153  case MVT::i32:
8154    return true;
8155  // FIXME: VLD1 etc with standard alignment is legal.
8156  }
8157}
8158
8159static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8160                       unsigned AlignCheck) {
8161  return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8162          (DstAlign == 0 || DstAlign % AlignCheck == 0));
8163}
8164
8165EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8166                                           unsigned DstAlign, unsigned SrcAlign,
8167                                           bool IsZeroVal,
8168                                           bool MemcpyStrSrc,
8169                                           MachineFunction &MF) const {
8170  const Function *F = MF.getFunction();
8171
8172  // See if we can use NEON instructions for this...
8173  if (IsZeroVal &&
8174      !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8175      Subtarget->hasNEON()) {
8176    if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8177      return MVT::v4i32;
8178    } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8179      return MVT::v2i32;
8180    }
8181  }
8182
8183  // Lowering to i32/i16 if the size permits.
8184  if (Size >= 4) {
8185    return MVT::i32;
8186  } else if (Size >= 2) {
8187    return MVT::i16;
8188  }
8189
8190  // Let the target-independent logic figure it out.
8191  return MVT::Other;
8192}
8193
8194static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8195  if (V < 0)
8196    return false;
8197
8198  unsigned Scale = 1;
8199  switch (VT.getSimpleVT().SimpleTy) {
8200  default: return false;
8201  case MVT::i1:
8202  case MVT::i8:
8203    // Scale == 1;
8204    break;
8205  case MVT::i16:
8206    // Scale == 2;
8207    Scale = 2;
8208    break;
8209  case MVT::i32:
8210    // Scale == 4;
8211    Scale = 4;
8212    break;
8213  }
8214
8215  if ((V & (Scale - 1)) != 0)
8216    return false;
8217  V /= Scale;
8218  return V == (V & ((1LL << 5) - 1));
8219}
8220
8221static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8222                                      const ARMSubtarget *Subtarget) {
8223  bool isNeg = false;
8224  if (V < 0) {
8225    isNeg = true;
8226    V = - V;
8227  }
8228
8229  switch (VT.getSimpleVT().SimpleTy) {
8230  default: return false;
8231  case MVT::i1:
8232  case MVT::i8:
8233  case MVT::i16:
8234  case MVT::i32:
8235    // + imm12 or - imm8
8236    if (isNeg)
8237      return V == (V & ((1LL << 8) - 1));
8238    return V == (V & ((1LL << 12) - 1));
8239  case MVT::f32:
8240  case MVT::f64:
8241    // Same as ARM mode. FIXME: NEON?
8242    if (!Subtarget->hasVFP2())
8243      return false;
8244    if ((V & 3) != 0)
8245      return false;
8246    V >>= 2;
8247    return V == (V & ((1LL << 8) - 1));
8248  }
8249}
8250
8251/// isLegalAddressImmediate - Return true if the integer value can be used
8252/// as the offset of the target addressing mode for load / store of the
8253/// given type.
8254static bool isLegalAddressImmediate(int64_t V, EVT VT,
8255                                    const ARMSubtarget *Subtarget) {
8256  if (V == 0)
8257    return true;
8258
8259  if (!VT.isSimple())
8260    return false;
8261
8262  if (Subtarget->isThumb1Only())
8263    return isLegalT1AddressImmediate(V, VT);
8264  else if (Subtarget->isThumb2())
8265    return isLegalT2AddressImmediate(V, VT, Subtarget);
8266
8267  // ARM mode.
8268  if (V < 0)
8269    V = - V;
8270  switch (VT.getSimpleVT().SimpleTy) {
8271  default: return false;
8272  case MVT::i1:
8273  case MVT::i8:
8274  case MVT::i32:
8275    // +- imm12
8276    return V == (V & ((1LL << 12) - 1));
8277  case MVT::i16:
8278    // +- imm8
8279    return V == (V & ((1LL << 8) - 1));
8280  case MVT::f32:
8281  case MVT::f64:
8282    if (!Subtarget->hasVFP2()) // FIXME: NEON?
8283      return false;
8284    if ((V & 3) != 0)
8285      return false;
8286    V >>= 2;
8287    return V == (V & ((1LL << 8) - 1));
8288  }
8289}
8290
8291bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8292                                                      EVT VT) const {
8293  int Scale = AM.Scale;
8294  if (Scale < 0)
8295    return false;
8296
8297  switch (VT.getSimpleVT().SimpleTy) {
8298  default: return false;
8299  case MVT::i1:
8300  case MVT::i8:
8301  case MVT::i16:
8302  case MVT::i32:
8303    if (Scale == 1)
8304      return true;
8305    // r + r << imm
8306    Scale = Scale & ~1;
8307    return Scale == 2 || Scale == 4 || Scale == 8;
8308  case MVT::i64:
8309    // r + r
8310    if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8311      return true;
8312    return false;
8313  case MVT::isVoid:
8314    // Note, we allow "void" uses (basically, uses that aren't loads or
8315    // stores), because arm allows folding a scale into many arithmetic
8316    // operations.  This should be made more precise and revisited later.
8317
8318    // Allow r << imm, but the imm has to be a multiple of two.
8319    if (Scale & 1) return false;
8320    return isPowerOf2_32(Scale);
8321  }
8322}
8323
8324/// isLegalAddressingMode - Return true if the addressing mode represented
8325/// by AM is legal for this target, for a load/store of the specified type.
8326bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8327                                              Type *Ty) const {
8328  EVT VT = getValueType(Ty, true);
8329  if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8330    return false;
8331
8332  // Can never fold addr of global into load/store.
8333  if (AM.BaseGV)
8334    return false;
8335
8336  switch (AM.Scale) {
8337  case 0:  // no scale reg, must be "r+i" or "r", or "i".
8338    break;
8339  case 1:
8340    if (Subtarget->isThumb1Only())
8341      return false;
8342    // FALL THROUGH.
8343  default:
8344    // ARM doesn't support any R+R*scale+imm addr modes.
8345    if (AM.BaseOffs)
8346      return false;
8347
8348    if (!VT.isSimple())
8349      return false;
8350
8351    if (Subtarget->isThumb2())
8352      return isLegalT2ScaledAddressingMode(AM, VT);
8353
8354    int Scale = AM.Scale;
8355    switch (VT.getSimpleVT().SimpleTy) {
8356    default: return false;
8357    case MVT::i1:
8358    case MVT::i8:
8359    case MVT::i32:
8360      if (Scale < 0) Scale = -Scale;
8361      if (Scale == 1)
8362        return true;
8363      // r + r << imm
8364      return isPowerOf2_32(Scale & ~1);
8365    case MVT::i16:
8366    case MVT::i64:
8367      // r + r
8368      if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8369        return true;
8370      return false;
8371
8372    case MVT::isVoid:
8373      // Note, we allow "void" uses (basically, uses that aren't loads or
8374      // stores), because arm allows folding a scale into many arithmetic
8375      // operations.  This should be made more precise and revisited later.
8376
8377      // Allow r << imm, but the imm has to be a multiple of two.
8378      if (Scale & 1) return false;
8379      return isPowerOf2_32(Scale);
8380    }
8381  }
8382  return true;
8383}
8384
8385/// isLegalICmpImmediate - Return true if the specified immediate is legal
8386/// icmp immediate, that is the target has icmp instructions which can compare
8387/// a register against the immediate without having to materialize the
8388/// immediate into a register.
8389bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8390  if (!Subtarget->isThumb())
8391    return ARM_AM::getSOImmVal(Imm) != -1;
8392  if (Subtarget->isThumb2())
8393    return ARM_AM::getT2SOImmVal(Imm) != -1;
8394  return Imm >= 0 && Imm <= 255;
8395}
8396
8397/// isLegalAddImmediate - Return true if the specified immediate is legal
8398/// add immediate, that is the target has add instructions which can add
8399/// a register with the immediate without having to materialize the
8400/// immediate into a register.
8401bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8402  return ARM_AM::getSOImmVal(Imm) != -1;
8403}
8404
8405static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8406                                      bool isSEXTLoad, SDValue &Base,
8407                                      SDValue &Offset, bool &isInc,
8408                                      SelectionDAG &DAG) {
8409  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8410    return false;
8411
8412  if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8413    // AddressingMode 3
8414    Base = Ptr->getOperand(0);
8415    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8416      int RHSC = (int)RHS->getZExtValue();
8417      if (RHSC < 0 && RHSC > -256) {
8418        assert(Ptr->getOpcode() == ISD::ADD);
8419        isInc = false;
8420        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8421        return true;
8422      }
8423    }
8424    isInc = (Ptr->getOpcode() == ISD::ADD);
8425    Offset = Ptr->getOperand(1);
8426    return true;
8427  } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8428    // AddressingMode 2
8429    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8430      int RHSC = (int)RHS->getZExtValue();
8431      if (RHSC < 0 && RHSC > -0x1000) {
8432        assert(Ptr->getOpcode() == ISD::ADD);
8433        isInc = false;
8434        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8435        Base = Ptr->getOperand(0);
8436        return true;
8437      }
8438    }
8439
8440    if (Ptr->getOpcode() == ISD::ADD) {
8441      isInc = true;
8442      ARM_AM::ShiftOpc ShOpcVal=
8443        ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8444      if (ShOpcVal != ARM_AM::no_shift) {
8445        Base = Ptr->getOperand(1);
8446        Offset = Ptr->getOperand(0);
8447      } else {
8448        Base = Ptr->getOperand(0);
8449        Offset = Ptr->getOperand(1);
8450      }
8451      return true;
8452    }
8453
8454    isInc = (Ptr->getOpcode() == ISD::ADD);
8455    Base = Ptr->getOperand(0);
8456    Offset = Ptr->getOperand(1);
8457    return true;
8458  }
8459
8460  // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8461  return false;
8462}
8463
8464static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8465                                     bool isSEXTLoad, SDValue &Base,
8466                                     SDValue &Offset, bool &isInc,
8467                                     SelectionDAG &DAG) {
8468  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8469    return false;
8470
8471  Base = Ptr->getOperand(0);
8472  if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8473    int RHSC = (int)RHS->getZExtValue();
8474    if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8475      assert(Ptr->getOpcode() == ISD::ADD);
8476      isInc = false;
8477      Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8478      return true;
8479    } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8480      isInc = Ptr->getOpcode() == ISD::ADD;
8481      Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8482      return true;
8483    }
8484  }
8485
8486  return false;
8487}
8488
8489/// getPreIndexedAddressParts - returns true by value, base pointer and
8490/// offset pointer and addressing mode by reference if the node's address
8491/// can be legally represented as pre-indexed load / store address.
8492bool
8493ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8494                                             SDValue &Offset,
8495                                             ISD::MemIndexedMode &AM,
8496                                             SelectionDAG &DAG) const {
8497  if (Subtarget->isThumb1Only())
8498    return false;
8499
8500  EVT VT;
8501  SDValue Ptr;
8502  bool isSEXTLoad = false;
8503  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8504    Ptr = LD->getBasePtr();
8505    VT  = LD->getMemoryVT();
8506    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8507  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8508    Ptr = ST->getBasePtr();
8509    VT  = ST->getMemoryVT();
8510  } else
8511    return false;
8512
8513  bool isInc;
8514  bool isLegal = false;
8515  if (Subtarget->isThumb2())
8516    isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8517                                       Offset, isInc, DAG);
8518  else
8519    isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8520                                        Offset, isInc, DAG);
8521  if (!isLegal)
8522    return false;
8523
8524  AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8525  return true;
8526}
8527
8528/// getPostIndexedAddressParts - returns true by value, base pointer and
8529/// offset pointer and addressing mode by reference if this node can be
8530/// combined with a load / store to form a post-indexed load / store.
8531bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8532                                                   SDValue &Base,
8533                                                   SDValue &Offset,
8534                                                   ISD::MemIndexedMode &AM,
8535                                                   SelectionDAG &DAG) const {
8536  if (Subtarget->isThumb1Only())
8537    return false;
8538
8539  EVT VT;
8540  SDValue Ptr;
8541  bool isSEXTLoad = false;
8542  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8543    VT  = LD->getMemoryVT();
8544    Ptr = LD->getBasePtr();
8545    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8546  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8547    VT  = ST->getMemoryVT();
8548    Ptr = ST->getBasePtr();
8549  } else
8550    return false;
8551
8552  bool isInc;
8553  bool isLegal = false;
8554  if (Subtarget->isThumb2())
8555    isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8556                                       isInc, DAG);
8557  else
8558    isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8559                                        isInc, DAG);
8560  if (!isLegal)
8561    return false;
8562
8563  if (Ptr != Base) {
8564    // Swap base ptr and offset to catch more post-index load / store when
8565    // it's legal. In Thumb2 mode, offset must be an immediate.
8566    if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8567        !Subtarget->isThumb2())
8568      std::swap(Base, Offset);
8569
8570    // Post-indexed load / store update the base pointer.
8571    if (Ptr != Base)
8572      return false;
8573  }
8574
8575  AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8576  return true;
8577}
8578
8579void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8580                                                       const APInt &Mask,
8581                                                       APInt &KnownZero,
8582                                                       APInt &KnownOne,
8583                                                       const SelectionDAG &DAG,
8584                                                       unsigned Depth) const {
8585  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
8586  switch (Op.getOpcode()) {
8587  default: break;
8588  case ARMISD::CMOV: {
8589    // Bits are known zero/one if known on the LHS and RHS.
8590    DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
8591    if (KnownZero == 0 && KnownOne == 0) return;
8592
8593    APInt KnownZeroRHS, KnownOneRHS;
8594    DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
8595                          KnownZeroRHS, KnownOneRHS, Depth+1);
8596    KnownZero &= KnownZeroRHS;
8597    KnownOne  &= KnownOneRHS;
8598    return;
8599  }
8600  }
8601}
8602
8603//===----------------------------------------------------------------------===//
8604//                           ARM Inline Assembly Support
8605//===----------------------------------------------------------------------===//
8606
8607bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8608  // Looking for "rev" which is V6+.
8609  if (!Subtarget->hasV6Ops())
8610    return false;
8611
8612  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8613  std::string AsmStr = IA->getAsmString();
8614  SmallVector<StringRef, 4> AsmPieces;
8615  SplitString(AsmStr, AsmPieces, ";\n");
8616
8617  switch (AsmPieces.size()) {
8618  default: return false;
8619  case 1:
8620    AsmStr = AsmPieces[0];
8621    AsmPieces.clear();
8622    SplitString(AsmStr, AsmPieces, " \t,");
8623
8624    // rev $0, $1
8625    if (AsmPieces.size() == 3 &&
8626        AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8627        IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8628      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8629      if (Ty && Ty->getBitWidth() == 32)
8630        return IntrinsicLowering::LowerToByteSwap(CI);
8631    }
8632    break;
8633  }
8634
8635  return false;
8636}
8637
8638/// getConstraintType - Given a constraint letter, return the type of
8639/// constraint it is for this target.
8640ARMTargetLowering::ConstraintType
8641ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8642  if (Constraint.size() == 1) {
8643    switch (Constraint[0]) {
8644    default:  break;
8645    case 'l': return C_RegisterClass;
8646    case 'w': return C_RegisterClass;
8647    case 'h': return C_RegisterClass;
8648    case 'x': return C_RegisterClass;
8649    case 't': return C_RegisterClass;
8650    case 'j': return C_Other; // Constant for movw.
8651      // An address with a single base register. Due to the way we
8652      // currently handle addresses it is the same as an 'r' memory constraint.
8653    case 'Q': return C_Memory;
8654    }
8655  } else if (Constraint.size() == 2) {
8656    switch (Constraint[0]) {
8657    default: break;
8658    // All 'U+' constraints are addresses.
8659    case 'U': return C_Memory;
8660    }
8661  }
8662  return TargetLowering::getConstraintType(Constraint);
8663}
8664
8665/// Examine constraint type and operand type and determine a weight value.
8666/// This object must already have been set up with the operand type
8667/// and the current alternative constraint selected.
8668TargetLowering::ConstraintWeight
8669ARMTargetLowering::getSingleConstraintMatchWeight(
8670    AsmOperandInfo &info, const char *constraint) const {
8671  ConstraintWeight weight = CW_Invalid;
8672  Value *CallOperandVal = info.CallOperandVal;
8673    // If we don't have a value, we can't do a match,
8674    // but allow it at the lowest weight.
8675  if (CallOperandVal == NULL)
8676    return CW_Default;
8677  Type *type = CallOperandVal->getType();
8678  // Look at the constraint type.
8679  switch (*constraint) {
8680  default:
8681    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8682    break;
8683  case 'l':
8684    if (type->isIntegerTy()) {
8685      if (Subtarget->isThumb())
8686        weight = CW_SpecificReg;
8687      else
8688        weight = CW_Register;
8689    }
8690    break;
8691  case 'w':
8692    if (type->isFloatingPointTy())
8693      weight = CW_Register;
8694    break;
8695  }
8696  return weight;
8697}
8698
8699typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
8700RCPair
8701ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8702                                                EVT VT) const {
8703  if (Constraint.size() == 1) {
8704    // GCC ARM Constraint Letters
8705    switch (Constraint[0]) {
8706    case 'l': // Low regs or general regs.
8707      if (Subtarget->isThumb())
8708        return RCPair(0U, ARM::tGPRRegisterClass);
8709      else
8710        return RCPair(0U, ARM::GPRRegisterClass);
8711    case 'h': // High regs or no regs.
8712      if (Subtarget->isThumb())
8713        return RCPair(0U, ARM::hGPRRegisterClass);
8714      break;
8715    case 'r':
8716      return RCPair(0U, ARM::GPRRegisterClass);
8717    case 'w':
8718      if (VT == MVT::f32)
8719        return RCPair(0U, ARM::SPRRegisterClass);
8720      if (VT.getSizeInBits() == 64)
8721        return RCPair(0U, ARM::DPRRegisterClass);
8722      if (VT.getSizeInBits() == 128)
8723        return RCPair(0U, ARM::QPRRegisterClass);
8724      break;
8725    case 'x':
8726      if (VT == MVT::f32)
8727        return RCPair(0U, ARM::SPR_8RegisterClass);
8728      if (VT.getSizeInBits() == 64)
8729        return RCPair(0U, ARM::DPR_8RegisterClass);
8730      if (VT.getSizeInBits() == 128)
8731        return RCPair(0U, ARM::QPR_8RegisterClass);
8732      break;
8733    case 't':
8734      if (VT == MVT::f32)
8735        return RCPair(0U, ARM::SPRRegisterClass);
8736      break;
8737    }
8738  }
8739  if (StringRef("{cc}").equals_lower(Constraint))
8740    return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
8741
8742  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8743}
8744
8745/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8746/// vector.  If it is invalid, don't add anything to Ops.
8747void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8748                                                     std::string &Constraint,
8749                                                     std::vector<SDValue>&Ops,
8750                                                     SelectionDAG &DAG) const {
8751  SDValue Result(0, 0);
8752
8753  // Currently only support length 1 constraints.
8754  if (Constraint.length() != 1) return;
8755
8756  char ConstraintLetter = Constraint[0];
8757  switch (ConstraintLetter) {
8758  default: break;
8759  case 'j':
8760  case 'I': case 'J': case 'K': case 'L':
8761  case 'M': case 'N': case 'O':
8762    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8763    if (!C)
8764      return;
8765
8766    int64_t CVal64 = C->getSExtValue();
8767    int CVal = (int) CVal64;
8768    // None of these constraints allow values larger than 32 bits.  Check
8769    // that the value fits in an int.
8770    if (CVal != CVal64)
8771      return;
8772
8773    switch (ConstraintLetter) {
8774      case 'j':
8775        // Constant suitable for movw, must be between 0 and
8776        // 65535.
8777        if (Subtarget->hasV6T2Ops())
8778          if (CVal >= 0 && CVal <= 65535)
8779            break;
8780        return;
8781      case 'I':
8782        if (Subtarget->isThumb1Only()) {
8783          // This must be a constant between 0 and 255, for ADD
8784          // immediates.
8785          if (CVal >= 0 && CVal <= 255)
8786            break;
8787        } else if (Subtarget->isThumb2()) {
8788          // A constant that can be used as an immediate value in a
8789          // data-processing instruction.
8790          if (ARM_AM::getT2SOImmVal(CVal) != -1)
8791            break;
8792        } else {
8793          // A constant that can be used as an immediate value in a
8794          // data-processing instruction.
8795          if (ARM_AM::getSOImmVal(CVal) != -1)
8796            break;
8797        }
8798        return;
8799
8800      case 'J':
8801        if (Subtarget->isThumb()) {  // FIXME thumb2
8802          // This must be a constant between -255 and -1, for negated ADD
8803          // immediates. This can be used in GCC with an "n" modifier that
8804          // prints the negated value, for use with SUB instructions. It is
8805          // not useful otherwise but is implemented for compatibility.
8806          if (CVal >= -255 && CVal <= -1)
8807            break;
8808        } else {
8809          // This must be a constant between -4095 and 4095. It is not clear
8810          // what this constraint is intended for. Implemented for
8811          // compatibility with GCC.
8812          if (CVal >= -4095 && CVal <= 4095)
8813            break;
8814        }
8815        return;
8816
8817      case 'K':
8818        if (Subtarget->isThumb1Only()) {
8819          // A 32-bit value where only one byte has a nonzero value. Exclude
8820          // zero to match GCC. This constraint is used by GCC internally for
8821          // constants that can be loaded with a move/shift combination.
8822          // It is not useful otherwise but is implemented for compatibility.
8823          if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
8824            break;
8825        } else if (Subtarget->isThumb2()) {
8826          // A constant whose bitwise inverse can be used as an immediate
8827          // value in a data-processing instruction. This can be used in GCC
8828          // with a "B" modifier that prints the inverted value, for use with
8829          // BIC and MVN instructions. It is not useful otherwise but is
8830          // implemented for compatibility.
8831          if (ARM_AM::getT2SOImmVal(~CVal) != -1)
8832            break;
8833        } else {
8834          // A constant whose bitwise inverse can be used as an immediate
8835          // value in a data-processing instruction. This can be used in GCC
8836          // with a "B" modifier that prints the inverted value, for use with
8837          // BIC and MVN instructions. It is not useful otherwise but is
8838          // implemented for compatibility.
8839          if (ARM_AM::getSOImmVal(~CVal) != -1)
8840            break;
8841        }
8842        return;
8843
8844      case 'L':
8845        if (Subtarget->isThumb1Only()) {
8846          // This must be a constant between -7 and 7,
8847          // for 3-operand ADD/SUB immediate instructions.
8848          if (CVal >= -7 && CVal < 7)
8849            break;
8850        } else if (Subtarget->isThumb2()) {
8851          // A constant whose negation can be used as an immediate value in a
8852          // data-processing instruction. This can be used in GCC with an "n"
8853          // modifier that prints the negated value, for use with SUB
8854          // instructions. It is not useful otherwise but is implemented for
8855          // compatibility.
8856          if (ARM_AM::getT2SOImmVal(-CVal) != -1)
8857            break;
8858        } else {
8859          // A constant whose negation can be used as an immediate value in a
8860          // data-processing instruction. This can be used in GCC with an "n"
8861          // modifier that prints the negated value, for use with SUB
8862          // instructions. It is not useful otherwise but is implemented for
8863          // compatibility.
8864          if (ARM_AM::getSOImmVal(-CVal) != -1)
8865            break;
8866        }
8867        return;
8868
8869      case 'M':
8870        if (Subtarget->isThumb()) { // FIXME thumb2
8871          // This must be a multiple of 4 between 0 and 1020, for
8872          // ADD sp + immediate.
8873          if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
8874            break;
8875        } else {
8876          // A power of two or a constant between 0 and 32.  This is used in
8877          // GCC for the shift amount on shifted register operands, but it is
8878          // useful in general for any shift amounts.
8879          if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
8880            break;
8881        }
8882        return;
8883
8884      case 'N':
8885        if (Subtarget->isThumb()) {  // FIXME thumb2
8886          // This must be a constant between 0 and 31, for shift amounts.
8887          if (CVal >= 0 && CVal <= 31)
8888            break;
8889        }
8890        return;
8891
8892      case 'O':
8893        if (Subtarget->isThumb()) {  // FIXME thumb2
8894          // This must be a multiple of 4 between -508 and 508, for
8895          // ADD/SUB sp = sp + immediate.
8896          if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
8897            break;
8898        }
8899        return;
8900    }
8901    Result = DAG.getTargetConstant(CVal, Op.getValueType());
8902    break;
8903  }
8904
8905  if (Result.getNode()) {
8906    Ops.push_back(Result);
8907    return;
8908  }
8909  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8910}
8911
8912bool
8913ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8914  // The ARM target isn't yet aware of offsets.
8915  return false;
8916}
8917
8918bool ARM::isBitFieldInvertedMask(unsigned v) {
8919  if (v == 0xffffffff)
8920    return 0;
8921  // there can be 1's on either or both "outsides", all the "inside"
8922  // bits must be 0's
8923  unsigned int lsb = 0, msb = 31;
8924  while (v & (1 << msb)) --msb;
8925  while (v & (1 << lsb)) ++lsb;
8926  for (unsigned int i = lsb; i <= msb; ++i) {
8927    if (v & (1 << i))
8928      return 0;
8929  }
8930  return 1;
8931}
8932
8933/// isFPImmLegal - Returns true if the target can instruction select the
8934/// specified FP immediate natively. If false, the legalizer will
8935/// materialize the FP immediate as a load from a constant pool.
8936bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
8937  if (!Subtarget->hasVFP3())
8938    return false;
8939  if (VT == MVT::f32)
8940    return ARM_AM::getFP32Imm(Imm) != -1;
8941  if (VT == MVT::f64)
8942    return ARM_AM::getFP64Imm(Imm) != -1;
8943  return false;
8944}
8945
8946/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8947/// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8948/// specified in the intrinsic calls.
8949bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8950                                           const CallInst &I,
8951                                           unsigned Intrinsic) const {
8952  switch (Intrinsic) {
8953  case Intrinsic::arm_neon_vld1:
8954  case Intrinsic::arm_neon_vld2:
8955  case Intrinsic::arm_neon_vld3:
8956  case Intrinsic::arm_neon_vld4:
8957  case Intrinsic::arm_neon_vld2lane:
8958  case Intrinsic::arm_neon_vld3lane:
8959  case Intrinsic::arm_neon_vld4lane: {
8960    Info.opc = ISD::INTRINSIC_W_CHAIN;
8961    // Conservatively set memVT to the entire set of vectors loaded.
8962    uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
8963    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8964    Info.ptrVal = I.getArgOperand(0);
8965    Info.offset = 0;
8966    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
8967    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
8968    Info.vol = false; // volatile loads with NEON intrinsics not supported
8969    Info.readMem = true;
8970    Info.writeMem = false;
8971    return true;
8972  }
8973  case Intrinsic::arm_neon_vst1:
8974  case Intrinsic::arm_neon_vst2:
8975  case Intrinsic::arm_neon_vst3:
8976  case Intrinsic::arm_neon_vst4:
8977  case Intrinsic::arm_neon_vst2lane:
8978  case Intrinsic::arm_neon_vst3lane:
8979  case Intrinsic::arm_neon_vst4lane: {
8980    Info.opc = ISD::INTRINSIC_VOID;
8981    // Conservatively set memVT to the entire set of vectors stored.
8982    unsigned NumElts = 0;
8983    for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8984      Type *ArgTy = I.getArgOperand(ArgI)->getType();
8985      if (!ArgTy->isVectorTy())
8986        break;
8987      NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
8988    }
8989    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8990    Info.ptrVal = I.getArgOperand(0);
8991    Info.offset = 0;
8992    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
8993    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
8994    Info.vol = false; // volatile stores with NEON intrinsics not supported
8995    Info.readMem = false;
8996    Info.writeMem = true;
8997    return true;
8998  }
8999  case Intrinsic::arm_strexd: {
9000    Info.opc = ISD::INTRINSIC_W_CHAIN;
9001    Info.memVT = MVT::i64;
9002    Info.ptrVal = I.getArgOperand(2);
9003    Info.offset = 0;
9004    Info.align = 8;
9005    Info.vol = true;
9006    Info.readMem = false;
9007    Info.writeMem = true;
9008    return true;
9009  }
9010  case Intrinsic::arm_ldrexd: {
9011    Info.opc = ISD::INTRINSIC_W_CHAIN;
9012    Info.memVT = MVT::i64;
9013    Info.ptrVal = I.getArgOperand(0);
9014    Info.offset = 0;
9015    Info.align = 8;
9016    Info.vol = true;
9017    Info.readMem = true;
9018    Info.writeMem = false;
9019    return true;
9020  }
9021  default:
9022    break;
9023  }
9024
9025  return false;
9026}
9027