ARMISelLowering.cpp revision 81fef0267b6971b32a618a655d91f472cedfcaf2
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 "ARMISelLowering.h"
17#include "ARM.h"
18#include "ARMCallingConv.h"
19#include "ARMConstantPoolValue.h"
20#include "ARMMachineFunctionInfo.h"
21#include "ARMPerfectShuffle.h"
22#include "ARMSubtarget.h"
23#include "ARMTargetMachine.h"
24#include "ARMTargetObjectFile.h"
25#include "MCTargetDesc/ARMAddressingModes.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/CodeGen/CallingConvLower.h"
29#include "llvm/CodeGen/IntrinsicLowering.h"
30#include "llvm/CodeGen/MachineBasicBlock.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/Type.h"
45#include "llvm/MC/MCSectionMachO.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/raw_ostream.h"
50#include "llvm/Target/TargetOptions.h"
51using namespace llvm;
52
53STATISTIC(NumTailCalls, "Number of tail calls");
54STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57// This option should go away when tail calls fully work.
58static cl::opt<bool>
59EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60  cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61  cl::init(false));
62
63cl::opt<bool>
64EnableARMLongCalls("arm-long-calls", cl::Hidden,
65  cl::desc("Generate calls via indirect call instructions"),
66  cl::init(false));
67
68static cl::opt<bool>
69ARMInterworking("arm-interworking", cl::Hidden,
70  cl::desc("Enable / disable ARM interworking (for debugging only)"),
71  cl::init(true));
72
73namespace {
74  class ARMCCState : public CCState {
75  public:
76    ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77               const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78               LLVMContext &C, ParmContext PC)
79        : CCState(CC, isVarArg, MF, TM, locs, C) {
80      assert(((PC == Call) || (PC == Prologue)) &&
81             "ARMCCState users must specify whether their context is call"
82             "or prologue generation.");
83      CallOrPrologue = PC;
84    }
85  };
86}
87
88// The APCS parameter registers.
89static const uint16_t GPRArgRegs[] = {
90  ARM::R0, ARM::R1, ARM::R2, ARM::R3
91};
92
93void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                       MVT PromotedBitwiseVT) {
95  if (VT != PromotedLdStVT) {
96    setOperationAction(ISD::LOAD, VT, Promote);
97    AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99    setOperationAction(ISD::STORE, VT, Promote);
100    AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101  }
102
103  MVT ElemTy = VT.getVectorElementType();
104  if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105    setOperationAction(ISD::SETCC, VT, Custom);
106  setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108  if (ElemTy == MVT::i32) {
109    setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110    setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111    setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112    setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113  } else {
114    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118  }
119  setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120  setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121  setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123  setOperationAction(ISD::SELECT,            VT, Expand);
124  setOperationAction(ISD::SELECT_CC,         VT, Expand);
125  setOperationAction(ISD::VSELECT,           VT, Expand);
126  setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127  if (VT.isInteger()) {
128    setOperationAction(ISD::SHL, VT, Custom);
129    setOperationAction(ISD::SRA, VT, Custom);
130    setOperationAction(ISD::SRL, VT, Custom);
131  }
132
133  // Promote all bit-wise operations.
134  if (VT.isInteger() && VT != PromotedBitwiseVT) {
135    setOperationAction(ISD::AND, VT, Promote);
136    AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137    setOperationAction(ISD::OR,  VT, Promote);
138    AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139    setOperationAction(ISD::XOR, VT, Promote);
140    AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141  }
142
143  // Neon does not support vector divide/remainder operations.
144  setOperationAction(ISD::SDIV, VT, Expand);
145  setOperationAction(ISD::UDIV, VT, Expand);
146  setOperationAction(ISD::FDIV, VT, Expand);
147  setOperationAction(ISD::SREM, VT, Expand);
148  setOperationAction(ISD::UREM, VT, Expand);
149  setOperationAction(ISD::FREM, VT, Expand);
150}
151
152void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153  addRegisterClass(VT, &ARM::DPRRegClass);
154  addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155}
156
157void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158  addRegisterClass(VT, &ARM::QPRRegClass);
159  addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160}
161
162static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163  if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164    return new TargetLoweringObjectFileMachO();
165
166  return new ARMElfTargetObjectFile();
167}
168
169ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170    : TargetLowering(TM, createTLOF(TM)) {
171  Subtarget = &TM.getSubtarget<ARMSubtarget>();
172  RegInfo = TM.getRegisterInfo();
173  Itins = TM.getInstrItineraryData();
174
175  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177  if (Subtarget->isTargetDarwin()) {
178    // Uses VFP for Thumb libfuncs if available.
179    if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180      // Single-precision floating-point arithmetic.
181      setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182      setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183      setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184      setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186      // Double-precision floating-point arithmetic.
187      setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188      setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189      setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190      setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192      // Single-precision comparisons.
193      setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194      setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195      setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196      setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197      setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198      setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199      setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200      setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202      setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203      setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204      setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205      setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206      setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207      setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208      setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209      setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211      // Double-precision comparisons.
212      setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213      setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214      setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215      setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216      setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217      setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218      setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219      setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221      setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222      setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223      setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224      setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225      setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226      setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227      setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228      setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230      // Floating-point to integer conversions.
231      // i64 conversions are done via library routines even when generating VFP
232      // instructions, so use the same ones.
233      setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234      setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235      setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236      setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238      // Conversions between floating types.
239      setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240      setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242      // Integer to floating-point conversions.
243      // i64 conversions are done via library routines even when generating VFP
244      // instructions, so use the same ones.
245      // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246      // e.g., __floatunsidf vs. __floatunssidfvfp.
247      setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248      setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249      setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250      setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251    }
252  }
253
254  // These libcalls are not available in 32-bit.
255  setLibcallName(RTLIB::SHL_I128, 0);
256  setLibcallName(RTLIB::SRL_I128, 0);
257  setLibcallName(RTLIB::SRA_I128, 0);
258
259  if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260    // Double-precision floating-point arithmetic helper functions
261    // RTABI chapter 4.1.2, Table 2
262    setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263    setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264    setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265    setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266    setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267    setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268    setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269    setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271    // Double-precision floating-point comparison helper functions
272    // RTABI chapter 4.1.2, Table 3
273    setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274    setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275    setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276    setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277    setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278    setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279    setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280    setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281    setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282    setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283    setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284    setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285    setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286    setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287    setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288    setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289    setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290    setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291    setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292    setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293    setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294    setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295    setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296    setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298    // Single-precision floating-point arithmetic helper functions
299    // RTABI chapter 4.1.2, Table 4
300    setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301    setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302    setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303    setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304    setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305    setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306    setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307    setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309    // Single-precision floating-point comparison helper functions
310    // RTABI chapter 4.1.2, Table 5
311    setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312    setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313    setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314    setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315    setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316    setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317    setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318    setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319    setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320    setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321    setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322    setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323    setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324    setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325    setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326    setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327    setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328    setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329    setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330    setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331    setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332    setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333    setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334    setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336    // Floating-point to integer conversions.
337    // RTABI chapter 4.1.2, Table 6
338    setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339    setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340    setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341    setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342    setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343    setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344    setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345    setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346    setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348    setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350    setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352    setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355    // Conversions between floating types.
356    // RTABI chapter 4.1.2, Table 7
357    setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358    setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359    setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360    setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362    // Integer to floating-point conversions.
363    // RTABI chapter 4.1.2, Table 8
364    setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365    setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366    setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367    setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368    setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369    setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370    setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371    setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372    setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373    setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374    setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375    setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376    setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377    setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378    setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379    setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381    // Long long helper functions
382    // RTABI chapter 4.2, Table 9
383    setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384    setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385    setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386    setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390    setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391    setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392    setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394    // Integer division functions
395    // RTABI chapter 4.3.1
396    setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397    setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398    setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399    setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400    setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401    setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402    setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403    setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404    setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405    setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406    setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408    setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409    setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410    setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413    // Memory operations
414    // RTABI chapter 4.3.4
415    setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416    setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417    setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418    setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419    setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420    setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421  }
422
423  // Use divmod compiler-rt calls for iOS 5.0 and later.
424  if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425      !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426    setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427    setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428  }
429
430  if (Subtarget->isThumb1Only())
431    addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432  else
433    addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435      !Subtarget->isThumb1Only()) {
436    addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437    if (!Subtarget->isFPOnlySP())
438      addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441  }
442
443  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447      setTruncStoreAction((MVT::SimpleValueType)VT,
448                          (MVT::SimpleValueType)InnerVT, Expand);
449    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452  }
453
454  setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456  if (Subtarget->hasNEON()) {
457    addDRTypeForNEON(MVT::v2f32);
458    addDRTypeForNEON(MVT::v8i8);
459    addDRTypeForNEON(MVT::v4i16);
460    addDRTypeForNEON(MVT::v2i32);
461    addDRTypeForNEON(MVT::v1i64);
462
463    addQRTypeForNEON(MVT::v4f32);
464    addQRTypeForNEON(MVT::v2f64);
465    addQRTypeForNEON(MVT::v16i8);
466    addQRTypeForNEON(MVT::v8i16);
467    addQRTypeForNEON(MVT::v4i32);
468    addQRTypeForNEON(MVT::v2i64);
469
470    // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471    // neither Neon nor VFP support any arithmetic operations on it.
472    // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473    // supported for v4f32.
474    setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475    setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476    setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477    // FIXME: Code duplication: FDIV and FREM are expanded always, see
478    // ARMTargetLowering::addTypeForNEON method for details.
479    setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480    setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481    // FIXME: Create unittest.
482    // In another words, find a way when "copysign" appears in DAG with vector
483    // operands.
484    setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485    // FIXME: Code duplication: SETCC has custom operation action, see
486    // ARMTargetLowering::addTypeForNEON method for details.
487    setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488    // FIXME: Create unittest for FNEG and for FABS.
489    setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490    setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491    setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492    setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493    setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494    setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495    setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496    setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497    setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498    setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499    setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500    setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501    // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502    setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503    setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504    setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505    setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506    setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507    setOperationAction(ISD::FMA, MVT::v2f64, Expand);
508
509    setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510    setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511    setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512    setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513    setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514    setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515    setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516    setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517    setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518    setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519    setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520    setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521    setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522    setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523    setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525    // Mark v2f32 intrinsics.
526    setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527    setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528    setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529    setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530    setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531    setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532    setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533    setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534    setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535    setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536    setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537    setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538    setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539    setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540    setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
541
542    // Neon does not support some operations on v1i64 and v2i64 types.
543    setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544    // Custom handling for some quad-vector types to detect VMULL.
545    setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546    setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547    setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548    // Custom handling for some vector types to avoid expensive expansions
549    setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550    setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551    setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552    setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553    setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554    setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555    // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556    // a destination type that is wider than the source, and nor does
557    // it have a FP_TO_[SU]INT instruction with a narrower destination than
558    // source.
559    setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560    setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561    setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562    setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
563
564    setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
565    setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
566
567    // Custom expand long extensions to vectors.
568    setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
569    setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
570    setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
571    setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
572    setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573    setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574    setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
575    setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
576
577    // NEON does not have single instruction CTPOP for vectors with element
578    // types wider than 8-bits.  However, custom lowering can leverage the
579    // v8i8/v16i8 vcnt instruction.
580    setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581    setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582    setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583    setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585    // NEON only has FMA instructions as of VFP4.
586    if (!Subtarget->hasVFP4()) {
587      setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588      setOperationAction(ISD::FMA, MVT::v4f32, Expand);
589    }
590
591    setTargetDAGCombine(ISD::INTRINSIC_VOID);
592    setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593    setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594    setTargetDAGCombine(ISD::SHL);
595    setTargetDAGCombine(ISD::SRL);
596    setTargetDAGCombine(ISD::SRA);
597    setTargetDAGCombine(ISD::SIGN_EXTEND);
598    setTargetDAGCombine(ISD::ZERO_EXTEND);
599    setTargetDAGCombine(ISD::ANY_EXTEND);
600    setTargetDAGCombine(ISD::SELECT_CC);
601    setTargetDAGCombine(ISD::BUILD_VECTOR);
602    setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603    setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604    setTargetDAGCombine(ISD::STORE);
605    setTargetDAGCombine(ISD::FP_TO_SINT);
606    setTargetDAGCombine(ISD::FP_TO_UINT);
607    setTargetDAGCombine(ISD::FDIV);
608
609    // It is legal to extload from v4i8 to v4i16 or v4i32.
610    MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611                  MVT::v4i16, MVT::v2i16,
612                  MVT::v2i32};
613    for (unsigned i = 0; i < 6; ++i) {
614      setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615      setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616      setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
617    }
618  }
619
620  // ARM and Thumb2 support UMLAL/SMLAL.
621  if (!Subtarget->isThumb1Only())
622    setTargetDAGCombine(ISD::ADDC);
623
624
625  computeRegisterProperties();
626
627  // ARM does not have f32 extending load.
628  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
629
630  // ARM does not have i1 sign extending load.
631  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
632
633  // ARM supports all 4 flavors of integer indexed load / store.
634  if (!Subtarget->isThumb1Only()) {
635    for (unsigned im = (unsigned)ISD::PRE_INC;
636         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637      setIndexedLoadAction(im,  MVT::i1,  Legal);
638      setIndexedLoadAction(im,  MVT::i8,  Legal);
639      setIndexedLoadAction(im,  MVT::i16, Legal);
640      setIndexedLoadAction(im,  MVT::i32, Legal);
641      setIndexedStoreAction(im, MVT::i1,  Legal);
642      setIndexedStoreAction(im, MVT::i8,  Legal);
643      setIndexedStoreAction(im, MVT::i16, Legal);
644      setIndexedStoreAction(im, MVT::i32, Legal);
645    }
646  }
647
648  // i64 operation support.
649  setOperationAction(ISD::MUL,     MVT::i64, Expand);
650  setOperationAction(ISD::MULHU,   MVT::i32, Expand);
651  if (Subtarget->isThumb1Only()) {
652    setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653    setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
654  }
655  if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656      || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657    setOperationAction(ISD::MULHS, MVT::i32, Expand);
658
659  setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660  setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661  setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662  setOperationAction(ISD::SRL,       MVT::i64, Custom);
663  setOperationAction(ISD::SRA,       MVT::i64, Custom);
664
665  if (!Subtarget->isThumb1Only()) {
666    // FIXME: We should do this for Thumb1 as well.
667    setOperationAction(ISD::ADDC,    MVT::i32, Custom);
668    setOperationAction(ISD::ADDE,    MVT::i32, Custom);
669    setOperationAction(ISD::SUBC,    MVT::i32, Custom);
670    setOperationAction(ISD::SUBE,    MVT::i32, Custom);
671  }
672
673  // ARM does not have ROTL.
674  setOperationAction(ISD::ROTL,  MVT::i32, Expand);
675  setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
676  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677  if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
679
680  // These just redirect to CTTZ and CTLZ on ARM.
681  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
682  setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
683
684  // Only ARMv6 has BSWAP.
685  if (!Subtarget->hasV6Ops())
686    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
687
688  if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
689      !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
690    // These are expanded into libcalls if the cpu doesn't have HW divider.
691    setOperationAction(ISD::SDIV,  MVT::i32, Expand);
692    setOperationAction(ISD::UDIV,  MVT::i32, Expand);
693  }
694  setOperationAction(ISD::SREM,  MVT::i32, Expand);
695  setOperationAction(ISD::UREM,  MVT::i32, Expand);
696  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
697  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
698
699  setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
700  setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
701  setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
702  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
703  setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
704
705  setOperationAction(ISD::TRAP, MVT::Other, Legal);
706
707  // Use the default implementation.
708  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
709  setOperationAction(ISD::VAARG,              MVT::Other, Expand);
710  setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
711  setOperationAction(ISD::VAEND,              MVT::Other, Expand);
712  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
713  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
714
715  if (!Subtarget->isTargetDarwin()) {
716    // Non-Darwin platforms may return values in these registers via the
717    // personality function.
718    setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
719    setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
720    setExceptionPointerRegister(ARM::R0);
721    setExceptionSelectorRegister(ARM::R1);
722  }
723
724  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
725  // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
726  // the default expansion.
727  // FIXME: This should be checking for v6k, not just v6.
728  if (Subtarget->hasDataBarrier() ||
729      (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
730    // membarrier needs custom lowering; the rest are legal and handled
731    // normally.
732    setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
733    // Custom lowering for 64-bit ops
734    setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
735    setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
736    setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
737    setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
738    setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
739    setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
740    setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
741    setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
742    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
743    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
744    setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
745    // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
746    setInsertFencesForAtomic(true);
747  } else {
748    // Set them all for expansion, which will force libcalls.
749    setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
750    setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
751    setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
752    setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
753    setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
754    setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
755    setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
756    setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
757    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
758    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
759    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
760    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
761    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
762    // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
763    // Unordered/Monotonic case.
764    setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
765    setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
766  }
767
768  setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
769
770  // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
771  if (!Subtarget->hasV6Ops()) {
772    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
773    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
774  }
775  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
776
777  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
778      !Subtarget->isThumb1Only()) {
779    // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
780    // iff target supports vfp2.
781    setOperationAction(ISD::BITCAST, MVT::i64, Custom);
782    setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
783  }
784
785  // We want to custom lower some of our intrinsics.
786  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
787  if (Subtarget->isTargetDarwin()) {
788    setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
789    setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
790    setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
791  }
792
793  setOperationAction(ISD::SETCC,     MVT::i32, Expand);
794  setOperationAction(ISD::SETCC,     MVT::f32, Expand);
795  setOperationAction(ISD::SETCC,     MVT::f64, Expand);
796  setOperationAction(ISD::SELECT,    MVT::i32, Custom);
797  setOperationAction(ISD::SELECT,    MVT::f32, Custom);
798  setOperationAction(ISD::SELECT,    MVT::f64, Custom);
799  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
800  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
801  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
802
803  setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
804  setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
805  setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
806  setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
807  setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
808
809  // We don't support sin/cos/fmod/copysign/pow
810  setOperationAction(ISD::FSIN,      MVT::f64, Expand);
811  setOperationAction(ISD::FSIN,      MVT::f32, Expand);
812  setOperationAction(ISD::FCOS,      MVT::f32, Expand);
813  setOperationAction(ISD::FCOS,      MVT::f64, Expand);
814  setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
815  setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
816  setOperationAction(ISD::FREM,      MVT::f64, Expand);
817  setOperationAction(ISD::FREM,      MVT::f32, Expand);
818  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
819      !Subtarget->isThumb1Only()) {
820    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
821    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
822  }
823  setOperationAction(ISD::FPOW,      MVT::f64, Expand);
824  setOperationAction(ISD::FPOW,      MVT::f32, Expand);
825
826  if (!Subtarget->hasVFP4()) {
827    setOperationAction(ISD::FMA, MVT::f64, Expand);
828    setOperationAction(ISD::FMA, MVT::f32, Expand);
829  }
830
831  // Various VFP goodness
832  if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
833    // int <-> fp are custom expanded into bit_convert + ARMISD ops.
834    if (Subtarget->hasVFP2()) {
835      setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
836      setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
837      setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
838      setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
839    }
840    // Special handling for half-precision FP.
841    if (!Subtarget->hasFP16()) {
842      setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
843      setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
844    }
845  }
846
847  // We have target-specific dag combine patterns for the following nodes:
848  // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
849  setTargetDAGCombine(ISD::ADD);
850  setTargetDAGCombine(ISD::SUB);
851  setTargetDAGCombine(ISD::MUL);
852  setTargetDAGCombine(ISD::AND);
853  setTargetDAGCombine(ISD::OR);
854  setTargetDAGCombine(ISD::XOR);
855
856  if (Subtarget->hasV6Ops())
857    setTargetDAGCombine(ISD::SRL);
858
859  setStackPointerRegisterToSaveRestore(ARM::SP);
860
861  if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862      !Subtarget->hasVFP2())
863    setSchedulingPreference(Sched::RegPressure);
864  else
865    setSchedulingPreference(Sched::Hybrid);
866
867  //// temporary - rewrite interface to use type
868  MaxStoresPerMemset = 8;
869  MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870  MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871  MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872  MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873  MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874
875  // On ARM arguments smaller than 4 bytes are extended, so all arguments
876  // are at least 4 bytes aligned.
877  setMinStackArgumentAlignment(4);
878
879  // Prefer likely predicted branches to selects on out-of-order cores.
880  PredictableSelectIsExpensive = Subtarget->isLikeA9();
881
882  setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
883}
884
885// FIXME: It might make sense to define the representative register class as the
886// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888// SPR's representative would be DPR_VFP2. This should work well if register
889// pressure tracking were modified such that a register use would increment the
890// pressure of the register class's representative and all of it's super
891// classes' representatives transitively. We have not implemented this because
892// of the difficulty prior to coalescing of modeling operand register classes
893// due to the common occurrence of cross class copies and subregister insertions
894// and extractions.
895std::pair<const TargetRegisterClass*, uint8_t>
896ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897  const TargetRegisterClass *RRC = 0;
898  uint8_t Cost = 1;
899  switch (VT.SimpleTy) {
900  default:
901    return TargetLowering::findRepresentativeClass(VT);
902  // Use DPR as representative register class for all floating point
903  // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904  // the cost is 1 for both f32 and f64.
905  case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906  case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907    RRC = &ARM::DPRRegClass;
908    // When NEON is used for SP, only half of the register file is available
909    // because operations that define both SP and DP results will be constrained
910    // to the VFP2 class (D0-D15). We currently model this constraint prior to
911    // coalescing by double-counting the SP regs. See the FIXME above.
912    if (Subtarget->useNEONForSinglePrecisionFP())
913      Cost = 2;
914    break;
915  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916  case MVT::v4f32: case MVT::v2f64:
917    RRC = &ARM::DPRRegClass;
918    Cost = 2;
919    break;
920  case MVT::v4i64:
921    RRC = &ARM::DPRRegClass;
922    Cost = 4;
923    break;
924  case MVT::v8i64:
925    RRC = &ARM::DPRRegClass;
926    Cost = 8;
927    break;
928  }
929  return std::make_pair(RRC, Cost);
930}
931
932const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
933  switch (Opcode) {
934  default: return 0;
935  case ARMISD::Wrapper:       return "ARMISD::Wrapper";
936  case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
937  case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
938  case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
939  case ARMISD::CALL:          return "ARMISD::CALL";
940  case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
941  case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
942  case ARMISD::tCALL:         return "ARMISD::tCALL";
943  case ARMISD::BRCOND:        return "ARMISD::BRCOND";
944  case ARMISD::BR_JT:         return "ARMISD::BR_JT";
945  case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
946  case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
947  case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
948  case ARMISD::CMP:           return "ARMISD::CMP";
949  case ARMISD::CMN:           return "ARMISD::CMN";
950  case ARMISD::CMPZ:          return "ARMISD::CMPZ";
951  case ARMISD::CMPFP:         return "ARMISD::CMPFP";
952  case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
953  case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
954  case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
955
956  case ARMISD::CMOV:          return "ARMISD::CMOV";
957
958  case ARMISD::RBIT:          return "ARMISD::RBIT";
959
960  case ARMISD::FTOSI:         return "ARMISD::FTOSI";
961  case ARMISD::FTOUI:         return "ARMISD::FTOUI";
962  case ARMISD::SITOF:         return "ARMISD::SITOF";
963  case ARMISD::UITOF:         return "ARMISD::UITOF";
964
965  case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
966  case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
967  case ARMISD::RRX:           return "ARMISD::RRX";
968
969  case ARMISD::ADDC:          return "ARMISD::ADDC";
970  case ARMISD::ADDE:          return "ARMISD::ADDE";
971  case ARMISD::SUBC:          return "ARMISD::SUBC";
972  case ARMISD::SUBE:          return "ARMISD::SUBE";
973
974  case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
975  case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
976
977  case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978  case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
979
980  case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
981
982  case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
983
984  case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
985
986  case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
987  case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
988
989  case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
990
991  case ARMISD::VCEQ:          return "ARMISD::VCEQ";
992  case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
993  case ARMISD::VCGE:          return "ARMISD::VCGE";
994  case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
995  case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
996  case ARMISD::VCGEU:         return "ARMISD::VCGEU";
997  case ARMISD::VCGT:          return "ARMISD::VCGT";
998  case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
999  case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1000  case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1001  case ARMISD::VTST:          return "ARMISD::VTST";
1002
1003  case ARMISD::VSHL:          return "ARMISD::VSHL";
1004  case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1005  case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1006  case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1007  case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1008  case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1009  case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1010  case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1011  case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1012  case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1013  case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1014  case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1015  case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1016  case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1017  case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1018  case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1019  case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1020  case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1021  case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1022  case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1023  case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1024  case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1025  case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1026  case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1027  case ARMISD::VDUP:          return "ARMISD::VDUP";
1028  case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1029  case ARMISD::VEXT:          return "ARMISD::VEXT";
1030  case ARMISD::VREV64:        return "ARMISD::VREV64";
1031  case ARMISD::VREV32:        return "ARMISD::VREV32";
1032  case ARMISD::VREV16:        return "ARMISD::VREV16";
1033  case ARMISD::VZIP:          return "ARMISD::VZIP";
1034  case ARMISD::VUZP:          return "ARMISD::VUZP";
1035  case ARMISD::VTRN:          return "ARMISD::VTRN";
1036  case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1037  case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1038  case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1039  case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1040  case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1041  case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1042  case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1043  case ARMISD::FMAX:          return "ARMISD::FMAX";
1044  case ARMISD::FMIN:          return "ARMISD::FMIN";
1045  case ARMISD::BFI:           return "ARMISD::BFI";
1046  case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1047  case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1048  case ARMISD::VBSL:          return "ARMISD::VBSL";
1049  case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1050  case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1051  case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1052  case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1053  case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1054  case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1055  case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1056  case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1057  case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1058  case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1059  case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1060  case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1061  case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1062  case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1063  case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1064  case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1065  case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1066  case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1067  case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1068  case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1069  }
1070}
1071
1072EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1073  if (!VT.isVector()) return getPointerTy();
1074  return VT.changeVectorElementTypeToInteger();
1075}
1076
1077/// getRegClassFor - Return the register class that should be used for the
1078/// specified value type.
1079const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1080  // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1081  // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1082  // load / store 4 to 8 consecutive D registers.
1083  if (Subtarget->hasNEON()) {
1084    if (VT == MVT::v4i64)
1085      return &ARM::QQPRRegClass;
1086    if (VT == MVT::v8i64)
1087      return &ARM::QQQQPRRegClass;
1088  }
1089  return TargetLowering::getRegClassFor(VT);
1090}
1091
1092// Create a fast isel object.
1093FastISel *
1094ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1095                                  const TargetLibraryInfo *libInfo) const {
1096  return ARM::createFastISel(funcInfo, libInfo);
1097}
1098
1099/// getMaximalGlobalOffset - Returns the maximal possible offset which can
1100/// be used for loads / stores from the global.
1101unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1102  return (Subtarget->isThumb1Only() ? 127 : 4095);
1103}
1104
1105Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1106  unsigned NumVals = N->getNumValues();
1107  if (!NumVals)
1108    return Sched::RegPressure;
1109
1110  for (unsigned i = 0; i != NumVals; ++i) {
1111    EVT VT = N->getValueType(i);
1112    if (VT == MVT::Glue || VT == MVT::Other)
1113      continue;
1114    if (VT.isFloatingPoint() || VT.isVector())
1115      return Sched::ILP;
1116  }
1117
1118  if (!N->isMachineOpcode())
1119    return Sched::RegPressure;
1120
1121  // Load are scheduled for latency even if there instruction itinerary
1122  // is not available.
1123  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1124  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1125
1126  if (MCID.getNumDefs() == 0)
1127    return Sched::RegPressure;
1128  if (!Itins->isEmpty() &&
1129      Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1130    return Sched::ILP;
1131
1132  return Sched::RegPressure;
1133}
1134
1135//===----------------------------------------------------------------------===//
1136// Lowering Code
1137//===----------------------------------------------------------------------===//
1138
1139/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1140static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1141  switch (CC) {
1142  default: llvm_unreachable("Unknown condition code!");
1143  case ISD::SETNE:  return ARMCC::NE;
1144  case ISD::SETEQ:  return ARMCC::EQ;
1145  case ISD::SETGT:  return ARMCC::GT;
1146  case ISD::SETGE:  return ARMCC::GE;
1147  case ISD::SETLT:  return ARMCC::LT;
1148  case ISD::SETLE:  return ARMCC::LE;
1149  case ISD::SETUGT: return ARMCC::HI;
1150  case ISD::SETUGE: return ARMCC::HS;
1151  case ISD::SETULT: return ARMCC::LO;
1152  case ISD::SETULE: return ARMCC::LS;
1153  }
1154}
1155
1156/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1157static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1158                        ARMCC::CondCodes &CondCode2) {
1159  CondCode2 = ARMCC::AL;
1160  switch (CC) {
1161  default: llvm_unreachable("Unknown FP condition!");
1162  case ISD::SETEQ:
1163  case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1164  case ISD::SETGT:
1165  case ISD::SETOGT: CondCode = ARMCC::GT; break;
1166  case ISD::SETGE:
1167  case ISD::SETOGE: CondCode = ARMCC::GE; break;
1168  case ISD::SETOLT: CondCode = ARMCC::MI; break;
1169  case ISD::SETOLE: CondCode = ARMCC::LS; break;
1170  case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1171  case ISD::SETO:   CondCode = ARMCC::VC; break;
1172  case ISD::SETUO:  CondCode = ARMCC::VS; break;
1173  case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1174  case ISD::SETUGT: CondCode = ARMCC::HI; break;
1175  case ISD::SETUGE: CondCode = ARMCC::PL; break;
1176  case ISD::SETLT:
1177  case ISD::SETULT: CondCode = ARMCC::LT; break;
1178  case ISD::SETLE:
1179  case ISD::SETULE: CondCode = ARMCC::LE; break;
1180  case ISD::SETNE:
1181  case ISD::SETUNE: CondCode = ARMCC::NE; break;
1182  }
1183}
1184
1185//===----------------------------------------------------------------------===//
1186//                      Calling Convention Implementation
1187//===----------------------------------------------------------------------===//
1188
1189#include "ARMGenCallingConv.inc"
1190
1191/// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1192/// given CallingConvention value.
1193CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1194                                                 bool Return,
1195                                                 bool isVarArg) const {
1196  switch (CC) {
1197  default:
1198    llvm_unreachable("Unsupported calling convention");
1199  case CallingConv::Fast:
1200    if (Subtarget->hasVFP2() && !isVarArg) {
1201      if (!Subtarget->isAAPCS_ABI())
1202        return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1203      // For AAPCS ABI targets, just use VFP variant of the calling convention.
1204      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1205    }
1206    // Fallthrough
1207  case CallingConv::C: {
1208    // Use target triple & subtarget features to do actual dispatch.
1209    if (!Subtarget->isAAPCS_ABI())
1210      return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1211    else if (Subtarget->hasVFP2() &&
1212             getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1213             !isVarArg)
1214      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1215    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1216  }
1217  case CallingConv::ARM_AAPCS_VFP:
1218    if (!isVarArg)
1219      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1220    // Fallthrough
1221  case CallingConv::ARM_AAPCS:
1222    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1223  case CallingConv::ARM_APCS:
1224    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1225  case CallingConv::GHC:
1226    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1227  }
1228}
1229
1230/// LowerCallResult - Lower the result values of a call into the
1231/// appropriate copies out of appropriate physical registers.
1232SDValue
1233ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1234                                   CallingConv::ID CallConv, bool isVarArg,
1235                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1236                                   DebugLoc dl, SelectionDAG &DAG,
1237                                   SmallVectorImpl<SDValue> &InVals,
1238                                   bool isThisReturn, SDValue ThisVal) const {
1239
1240  // Assign locations to each value returned by this call.
1241  SmallVector<CCValAssign, 16> RVLocs;
1242  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1243                    getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1244  CCInfo.AnalyzeCallResult(Ins,
1245                           CCAssignFnForNode(CallConv, /* Return*/ true,
1246                                             isVarArg));
1247
1248  // Copy all of the result registers out of their specified physreg.
1249  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1250    CCValAssign VA = RVLocs[i];
1251
1252    // Pass 'this' value directly from the argument to return value, to avoid
1253    // reg unit interference
1254    if (i == 0 && isThisReturn) {
1255      assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1256             "unexpected return calling convention register assignment");
1257      InVals.push_back(ThisVal);
1258      continue;
1259    }
1260
1261    SDValue Val;
1262    if (VA.needsCustom()) {
1263      // Handle f64 or half of a v2f64.
1264      SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1265                                      InFlag);
1266      Chain = Lo.getValue(1);
1267      InFlag = Lo.getValue(2);
1268      VA = RVLocs[++i]; // skip ahead to next loc
1269      SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1270                                      InFlag);
1271      Chain = Hi.getValue(1);
1272      InFlag = Hi.getValue(2);
1273      Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1274
1275      if (VA.getLocVT() == MVT::v2f64) {
1276        SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1277        Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1278                          DAG.getConstant(0, MVT::i32));
1279
1280        VA = RVLocs[++i]; // skip ahead to next loc
1281        Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1282        Chain = Lo.getValue(1);
1283        InFlag = Lo.getValue(2);
1284        VA = RVLocs[++i]; // skip ahead to next loc
1285        Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1286        Chain = Hi.getValue(1);
1287        InFlag = Hi.getValue(2);
1288        Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1289        Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1290                          DAG.getConstant(1, MVT::i32));
1291      }
1292    } else {
1293      Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1294                               InFlag);
1295      Chain = Val.getValue(1);
1296      InFlag = Val.getValue(2);
1297    }
1298
1299    switch (VA.getLocInfo()) {
1300    default: llvm_unreachable("Unknown loc info!");
1301    case CCValAssign::Full: break;
1302    case CCValAssign::BCvt:
1303      Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1304      break;
1305    }
1306
1307    InVals.push_back(Val);
1308  }
1309
1310  return Chain;
1311}
1312
1313/// LowerMemOpCallTo - Store the argument to the stack.
1314SDValue
1315ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1316                                    SDValue StackPtr, SDValue Arg,
1317                                    DebugLoc dl, SelectionDAG &DAG,
1318                                    const CCValAssign &VA,
1319                                    ISD::ArgFlagsTy Flags) const {
1320  unsigned LocMemOffset = VA.getLocMemOffset();
1321  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1322  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1323  return DAG.getStore(Chain, dl, Arg, PtrOff,
1324                      MachinePointerInfo::getStack(LocMemOffset),
1325                      false, false, 0);
1326}
1327
1328void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1329                                         SDValue Chain, SDValue &Arg,
1330                                         RegsToPassVector &RegsToPass,
1331                                         CCValAssign &VA, CCValAssign &NextVA,
1332                                         SDValue &StackPtr,
1333                                         SmallVector<SDValue, 8> &MemOpChains,
1334                                         ISD::ArgFlagsTy Flags) const {
1335
1336  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1337                              DAG.getVTList(MVT::i32, MVT::i32), Arg);
1338  RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1339
1340  if (NextVA.isRegLoc())
1341    RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1342  else {
1343    assert(NextVA.isMemLoc());
1344    if (StackPtr.getNode() == 0)
1345      StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1346
1347    MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1348                                           dl, DAG, NextVA,
1349                                           Flags));
1350  }
1351}
1352
1353/// LowerCall - Lowering a call into a callseq_start <-
1354/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1355/// nodes.
1356SDValue
1357ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1358                             SmallVectorImpl<SDValue> &InVals) const {
1359  SelectionDAG &DAG                     = CLI.DAG;
1360  DebugLoc &dl                          = CLI.DL;
1361  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1362  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1363  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1364  SDValue Chain                         = CLI.Chain;
1365  SDValue Callee                        = CLI.Callee;
1366  bool &isTailCall                      = CLI.IsTailCall;
1367  CallingConv::ID CallConv              = CLI.CallConv;
1368  bool doesNotRet                       = CLI.DoesNotReturn;
1369  bool isVarArg                         = CLI.IsVarArg;
1370
1371  MachineFunction &MF = DAG.getMachineFunction();
1372  bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1373  bool isThisReturn   = false;
1374  bool isSibCall      = false;
1375  // Disable tail calls if they're not supported.
1376  if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1377    isTailCall = false;
1378  if (isTailCall) {
1379    // Check if it's really possible to do a tail call.
1380    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1381                    isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1382                                                   Outs, OutVals, Ins, DAG);
1383    // We don't support GuaranteedTailCallOpt for ARM, only automatically
1384    // detected sibcalls.
1385    if (isTailCall) {
1386      ++NumTailCalls;
1387      isSibCall = true;
1388    }
1389  }
1390
1391  // Analyze operands of the call, assigning locations to each operand.
1392  SmallVector<CCValAssign, 16> ArgLocs;
1393  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1394                 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1395  CCInfo.AnalyzeCallOperands(Outs,
1396                             CCAssignFnForNode(CallConv, /* Return*/ false,
1397                                               isVarArg));
1398
1399  // Get a count of how many bytes are to be pushed on the stack.
1400  unsigned NumBytes = CCInfo.getNextStackOffset();
1401
1402  // For tail calls, memory operands are available in our caller's stack.
1403  if (isSibCall)
1404    NumBytes = 0;
1405
1406  // Adjust the stack pointer for the new arguments...
1407  // These operations are automatically eliminated by the prolog/epilog pass
1408  if (!isSibCall)
1409    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1410
1411  SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1412
1413  RegsToPassVector RegsToPass;
1414  SmallVector<SDValue, 8> MemOpChains;
1415
1416  // Walk the register/memloc assignments, inserting copies/loads.  In the case
1417  // of tail call optimization, arguments are handled later.
1418  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1419       i != e;
1420       ++i, ++realArgIdx) {
1421    CCValAssign &VA = ArgLocs[i];
1422    SDValue Arg = OutVals[realArgIdx];
1423    ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1424    bool isByVal = Flags.isByVal();
1425
1426    // Promote the value if needed.
1427    switch (VA.getLocInfo()) {
1428    default: llvm_unreachable("Unknown loc info!");
1429    case CCValAssign::Full: break;
1430    case CCValAssign::SExt:
1431      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1432      break;
1433    case CCValAssign::ZExt:
1434      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1435      break;
1436    case CCValAssign::AExt:
1437      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1438      break;
1439    case CCValAssign::BCvt:
1440      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1441      break;
1442    }
1443
1444    // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1445    if (VA.needsCustom()) {
1446      if (VA.getLocVT() == MVT::v2f64) {
1447        SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1448                                  DAG.getConstant(0, MVT::i32));
1449        SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1450                                  DAG.getConstant(1, MVT::i32));
1451
1452        PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1453                         VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1454
1455        VA = ArgLocs[++i]; // skip ahead to next loc
1456        if (VA.isRegLoc()) {
1457          PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1458                           VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1459        } else {
1460          assert(VA.isMemLoc());
1461
1462          MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1463                                                 dl, DAG, VA, Flags));
1464        }
1465      } else {
1466        PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1467                         StackPtr, MemOpChains, Flags);
1468      }
1469    } else if (VA.isRegLoc()) {
1470      if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1471        assert(VA.getLocVT() == MVT::i32 &&
1472               "unexpected calling convention register assignment");
1473        assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1474               "unexpected use of 'returned'");
1475        isThisReturn = true;
1476      }
1477      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1478    } else if (isByVal) {
1479      assert(VA.isMemLoc());
1480      unsigned offset = 0;
1481
1482      // True if this byval aggregate will be split between registers
1483      // and memory.
1484      if (CCInfo.isFirstByValRegValid()) {
1485        EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1486        unsigned int i, j;
1487        for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1488          SDValue Const = DAG.getConstant(4*i, MVT::i32);
1489          SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1490          SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1491                                     MachinePointerInfo(),
1492                                     false, false, false, 0);
1493          MemOpChains.push_back(Load.getValue(1));
1494          RegsToPass.push_back(std::make_pair(j, Load));
1495        }
1496        offset = ARM::R4 - CCInfo.getFirstByValReg();
1497        CCInfo.clearFirstByValReg();
1498      }
1499
1500      if (Flags.getByValSize() - 4*offset > 0) {
1501        unsigned LocMemOffset = VA.getLocMemOffset();
1502        SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1503        SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1504                                  StkPtrOff);
1505        SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1506        SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1507        SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1508                                           MVT::i32);
1509        SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1510
1511        SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1512        SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1513        MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1514                                          Ops, array_lengthof(Ops)));
1515      }
1516    } else if (!isSibCall) {
1517      assert(VA.isMemLoc());
1518
1519      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1520                                             dl, DAG, VA, Flags));
1521    }
1522  }
1523
1524  if (!MemOpChains.empty())
1525    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1526                        &MemOpChains[0], MemOpChains.size());
1527
1528  // Build a sequence of copy-to-reg nodes chained together with token chain
1529  // and flag operands which copy the outgoing args into the appropriate regs.
1530  SDValue InFlag;
1531  // Tail call byval lowering might overwrite argument registers so in case of
1532  // tail call optimization the copies to registers are lowered later.
1533  if (!isTailCall)
1534    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1535      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1536                               RegsToPass[i].second, InFlag);
1537      InFlag = Chain.getValue(1);
1538    }
1539
1540  // For tail calls lower the arguments to the 'real' stack slot.
1541  if (isTailCall) {
1542    // Force all the incoming stack arguments to be loaded from the stack
1543    // before any new outgoing arguments are stored to the stack, because the
1544    // outgoing stack slots may alias the incoming argument stack slots, and
1545    // the alias isn't otherwise explicit. This is slightly more conservative
1546    // than necessary, because it means that each store effectively depends
1547    // on every argument instead of just those arguments it would clobber.
1548
1549    // Do not flag preceding copytoreg stuff together with the following stuff.
1550    InFlag = SDValue();
1551    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1552      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1553                               RegsToPass[i].second, InFlag);
1554      InFlag = Chain.getValue(1);
1555    }
1556    InFlag = SDValue();
1557  }
1558
1559  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1560  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1561  // node so that legalize doesn't hack it.
1562  bool isDirect = false;
1563  bool isARMFunc = false;
1564  bool isLocalARMFunc = false;
1565  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1566
1567  if (EnableARMLongCalls) {
1568    assert (getTargetMachine().getRelocationModel() == Reloc::Static
1569            && "long-calls with non-static relocation model!");
1570    // Handle a global address or an external symbol. If it's not one of
1571    // those, the target's already in a register, so we don't need to do
1572    // anything extra.
1573    if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1574      const GlobalValue *GV = G->getGlobal();
1575      // Create a constant pool entry for the callee address
1576      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1577      ARMConstantPoolValue *CPV =
1578        ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1579
1580      // Get the address of the callee into a register
1581      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1582      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1583      Callee = DAG.getLoad(getPointerTy(), dl,
1584                           DAG.getEntryNode(), CPAddr,
1585                           MachinePointerInfo::getConstantPool(),
1586                           false, false, false, 0);
1587    } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1588      const char *Sym = S->getSymbol();
1589
1590      // Create a constant pool entry for the callee address
1591      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1592      ARMConstantPoolValue *CPV =
1593        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1594                                      ARMPCLabelIndex, 0);
1595      // Get the address of the callee into a register
1596      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1597      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1598      Callee = DAG.getLoad(getPointerTy(), dl,
1599                           DAG.getEntryNode(), CPAddr,
1600                           MachinePointerInfo::getConstantPool(),
1601                           false, false, false, 0);
1602    }
1603  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1604    const GlobalValue *GV = G->getGlobal();
1605    isDirect = true;
1606    bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1607    bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1608                   getTargetMachine().getRelocationModel() != Reloc::Static;
1609    isARMFunc = !Subtarget->isThumb() || isStub;
1610    // ARM call to a local ARM function is predicable.
1611    isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1612    // tBX takes a register source operand.
1613    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1614      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1615      ARMConstantPoolValue *CPV =
1616        ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1617      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1618      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1619      Callee = DAG.getLoad(getPointerTy(), dl,
1620                           DAG.getEntryNode(), CPAddr,
1621                           MachinePointerInfo::getConstantPool(),
1622                           false, false, false, 0);
1623      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1624      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1625                           getPointerTy(), Callee, PICLabel);
1626    } else {
1627      // On ELF targets for PIC code, direct calls should go through the PLT
1628      unsigned OpFlags = 0;
1629      if (Subtarget->isTargetELF() &&
1630          getTargetMachine().getRelocationModel() == Reloc::PIC_)
1631        OpFlags = ARMII::MO_PLT;
1632      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1633    }
1634  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1635    isDirect = true;
1636    bool isStub = Subtarget->isTargetDarwin() &&
1637                  getTargetMachine().getRelocationModel() != Reloc::Static;
1638    isARMFunc = !Subtarget->isThumb() || isStub;
1639    // tBX takes a register source operand.
1640    const char *Sym = S->getSymbol();
1641    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1642      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1643      ARMConstantPoolValue *CPV =
1644        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1645                                      ARMPCLabelIndex, 4);
1646      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1647      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1648      Callee = DAG.getLoad(getPointerTy(), dl,
1649                           DAG.getEntryNode(), CPAddr,
1650                           MachinePointerInfo::getConstantPool(),
1651                           false, false, false, 0);
1652      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1653      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1654                           getPointerTy(), Callee, PICLabel);
1655    } else {
1656      unsigned OpFlags = 0;
1657      // On ELF targets for PIC code, direct calls should go through the PLT
1658      if (Subtarget->isTargetELF() &&
1659                  getTargetMachine().getRelocationModel() == Reloc::PIC_)
1660        OpFlags = ARMII::MO_PLT;
1661      Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1662    }
1663  }
1664
1665  // FIXME: handle tail calls differently.
1666  unsigned CallOpc;
1667  bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1668    hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1669  if (Subtarget->isThumb()) {
1670    if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1671      CallOpc = ARMISD::CALL_NOLINK;
1672    else
1673      CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1674  } else {
1675    if (!isDirect && !Subtarget->hasV5TOps())
1676      CallOpc = ARMISD::CALL_NOLINK;
1677    else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1678               // Emit regular call when code size is the priority
1679               !HasMinSizeAttr)
1680      // "mov lr, pc; b _foo" to avoid confusing the RSP
1681      CallOpc = ARMISD::CALL_NOLINK;
1682    else
1683      CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1684  }
1685
1686  std::vector<SDValue> Ops;
1687  Ops.push_back(Chain);
1688  Ops.push_back(Callee);
1689
1690  // Add argument registers to the end of the list so that they are known live
1691  // into the call.
1692  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1693    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1694                                  RegsToPass[i].second.getValueType()));
1695
1696  // Add a register mask operand representing the call-preserved registers.
1697  const uint32_t *Mask;
1698  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1699  const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1700  if (isThisReturn)
1701    // For 'this' returns, use the R0-preserving mask
1702    Mask = ARI->getThisReturnPreservedMask(CallConv);
1703  else
1704    Mask = ARI->getCallPreservedMask(CallConv);
1705
1706  assert(Mask && "Missing call preserved mask for calling convention");
1707  Ops.push_back(DAG.getRegisterMask(Mask));
1708
1709  if (InFlag.getNode())
1710    Ops.push_back(InFlag);
1711
1712  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1713  if (isTailCall)
1714    return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1715
1716  // Returns a chain and a flag for retval copy to use.
1717  Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1718  InFlag = Chain.getValue(1);
1719
1720  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1721                             DAG.getIntPtrConstant(0, true), InFlag);
1722  if (!Ins.empty())
1723    InFlag = Chain.getValue(1);
1724
1725  // Handle result values, copying them out of physregs into vregs that we
1726  // return.
1727  return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1728                         InVals, isThisReturn,
1729                         isThisReturn ? OutVals[0] : SDValue());
1730}
1731
1732/// HandleByVal - Every parameter *after* a byval parameter is passed
1733/// on the stack.  Remember the next parameter register to allocate,
1734/// and then confiscate the rest of the parameter registers to insure
1735/// this.
1736void
1737ARMTargetLowering::HandleByVal(
1738    CCState *State, unsigned &size, unsigned Align) const {
1739  unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1740  assert((State->getCallOrPrologue() == Prologue ||
1741          State->getCallOrPrologue() == Call) &&
1742         "unhandled ParmContext");
1743  if ((!State->isFirstByValRegValid()) &&
1744      (!Subtarget->isAAPCS_ABI() || State->getNextStackOffset() == 0) &&
1745      (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1746    if (Subtarget->isAAPCS_ABI() && Align > 4) {
1747      unsigned AlignInRegs = Align / 4;
1748      unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1749      for (unsigned i = 0; i < Waste; ++i)
1750        reg = State->AllocateReg(GPRArgRegs, 4);
1751    }
1752    if (reg != 0) {
1753      State->setFirstByValReg(reg);
1754      // At a call site, a byval parameter that is split between
1755      // registers and memory needs its size truncated here.  In a
1756      // function prologue, such byval parameters are reassembled in
1757      // memory, and are not truncated.
1758      if (State->getCallOrPrologue() == Call) {
1759        unsigned excess = 4 * (ARM::R4 - reg);
1760        assert(size >= excess && "expected larger existing stack allocation");
1761        size -= excess;
1762      }
1763    }
1764  }
1765  // Confiscate any remaining parameter registers to preclude their
1766  // assignment to subsequent parameters.
1767  while (State->AllocateReg(GPRArgRegs, 4))
1768    ;
1769}
1770
1771/// MatchingStackOffset - Return true if the given stack call argument is
1772/// already available in the same position (relatively) of the caller's
1773/// incoming argument stack.
1774static
1775bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1776                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1777                         const TargetInstrInfo *TII) {
1778  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1779  int FI = INT_MAX;
1780  if (Arg.getOpcode() == ISD::CopyFromReg) {
1781    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1782    if (!TargetRegisterInfo::isVirtualRegister(VR))
1783      return false;
1784    MachineInstr *Def = MRI->getVRegDef(VR);
1785    if (!Def)
1786      return false;
1787    if (!Flags.isByVal()) {
1788      if (!TII->isLoadFromStackSlot(Def, FI))
1789        return false;
1790    } else {
1791      return false;
1792    }
1793  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1794    if (Flags.isByVal())
1795      // ByVal argument is passed in as a pointer but it's now being
1796      // dereferenced. e.g.
1797      // define @foo(%struct.X* %A) {
1798      //   tail call @bar(%struct.X* byval %A)
1799      // }
1800      return false;
1801    SDValue Ptr = Ld->getBasePtr();
1802    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1803    if (!FINode)
1804      return false;
1805    FI = FINode->getIndex();
1806  } else
1807    return false;
1808
1809  assert(FI != INT_MAX);
1810  if (!MFI->isFixedObjectIndex(FI))
1811    return false;
1812  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1813}
1814
1815/// IsEligibleForTailCallOptimization - Check whether the call is eligible
1816/// for tail call optimization. Targets which want to do tail call
1817/// optimization should implement this function.
1818bool
1819ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1820                                                     CallingConv::ID CalleeCC,
1821                                                     bool isVarArg,
1822                                                     bool isCalleeStructRet,
1823                                                     bool isCallerStructRet,
1824                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1825                                    const SmallVectorImpl<SDValue> &OutVals,
1826                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1827                                                     SelectionDAG& DAG) const {
1828  const Function *CallerF = DAG.getMachineFunction().getFunction();
1829  CallingConv::ID CallerCC = CallerF->getCallingConv();
1830  bool CCMatch = CallerCC == CalleeCC;
1831
1832  // Look for obvious safe cases to perform tail call optimization that do not
1833  // require ABI changes. This is what gcc calls sibcall.
1834
1835  // Do not sibcall optimize vararg calls unless the call site is not passing
1836  // any arguments.
1837  if (isVarArg && !Outs.empty())
1838    return false;
1839
1840  // Also avoid sibcall optimization if either caller or callee uses struct
1841  // return semantics.
1842  if (isCalleeStructRet || isCallerStructRet)
1843    return false;
1844
1845  // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1846  // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1847  // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1848  // support in the assembler and linker to be used. This would need to be
1849  // fixed to fully support tail calls in Thumb1.
1850  //
1851  // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1852  // LR.  This means if we need to reload LR, it takes an extra instructions,
1853  // which outweighs the value of the tail call; but here we don't know yet
1854  // whether LR is going to be used.  Probably the right approach is to
1855  // generate the tail call here and turn it back into CALL/RET in
1856  // emitEpilogue if LR is used.
1857
1858  // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1859  // but we need to make sure there are enough registers; the only valid
1860  // registers are the 4 used for parameters.  We don't currently do this
1861  // case.
1862  if (Subtarget->isThumb1Only())
1863    return false;
1864
1865  // If the calling conventions do not match, then we'd better make sure the
1866  // results are returned in the same way as what the caller expects.
1867  if (!CCMatch) {
1868    SmallVector<CCValAssign, 16> RVLocs1;
1869    ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1870                       getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1871    CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1872
1873    SmallVector<CCValAssign, 16> RVLocs2;
1874    ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1875                       getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1876    CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1877
1878    if (RVLocs1.size() != RVLocs2.size())
1879      return false;
1880    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1881      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1882        return false;
1883      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1884        return false;
1885      if (RVLocs1[i].isRegLoc()) {
1886        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1887          return false;
1888      } else {
1889        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1890          return false;
1891      }
1892    }
1893  }
1894
1895  // If Caller's vararg or byval argument has been split between registers and
1896  // stack, do not perform tail call, since part of the argument is in caller's
1897  // local frame.
1898  const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1899                                      getInfo<ARMFunctionInfo>();
1900  if (AFI_Caller->getVarArgsRegSaveSize())
1901    return false;
1902
1903  // If the callee takes no arguments then go on to check the results of the
1904  // call.
1905  if (!Outs.empty()) {
1906    // Check if stack adjustment is needed. For now, do not do this if any
1907    // argument is passed on the stack.
1908    SmallVector<CCValAssign, 16> ArgLocs;
1909    ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1910                      getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1911    CCInfo.AnalyzeCallOperands(Outs,
1912                               CCAssignFnForNode(CalleeCC, false, isVarArg));
1913    if (CCInfo.getNextStackOffset()) {
1914      MachineFunction &MF = DAG.getMachineFunction();
1915
1916      // Check if the arguments are already laid out in the right way as
1917      // the caller's fixed stack objects.
1918      MachineFrameInfo *MFI = MF.getFrameInfo();
1919      const MachineRegisterInfo *MRI = &MF.getRegInfo();
1920      const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1921      for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1922           i != e;
1923           ++i, ++realArgIdx) {
1924        CCValAssign &VA = ArgLocs[i];
1925        EVT RegVT = VA.getLocVT();
1926        SDValue Arg = OutVals[realArgIdx];
1927        ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1928        if (VA.getLocInfo() == CCValAssign::Indirect)
1929          return false;
1930        if (VA.needsCustom()) {
1931          // f64 and vector types are split into multiple registers or
1932          // register/stack-slot combinations.  The types will not match
1933          // the registers; give up on memory f64 refs until we figure
1934          // out what to do about this.
1935          if (!VA.isRegLoc())
1936            return false;
1937          if (!ArgLocs[++i].isRegLoc())
1938            return false;
1939          if (RegVT == MVT::v2f64) {
1940            if (!ArgLocs[++i].isRegLoc())
1941              return false;
1942            if (!ArgLocs[++i].isRegLoc())
1943              return false;
1944          }
1945        } else if (!VA.isRegLoc()) {
1946          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1947                                   MFI, MRI, TII))
1948            return false;
1949        }
1950      }
1951    }
1952  }
1953
1954  return true;
1955}
1956
1957bool
1958ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1959                                  MachineFunction &MF, bool isVarArg,
1960                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1961                                  LLVMContext &Context) const {
1962  SmallVector<CCValAssign, 16> RVLocs;
1963  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1964  return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1965                                                    isVarArg));
1966}
1967
1968SDValue
1969ARMTargetLowering::LowerReturn(SDValue Chain,
1970                               CallingConv::ID CallConv, bool isVarArg,
1971                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1972                               const SmallVectorImpl<SDValue> &OutVals,
1973                               DebugLoc dl, SelectionDAG &DAG) const {
1974
1975  // CCValAssign - represent the assignment of the return value to a location.
1976  SmallVector<CCValAssign, 16> RVLocs;
1977
1978  // CCState - Info about the registers and stack slots.
1979  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1980                    getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1981
1982  // Analyze outgoing return values.
1983  CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1984                                               isVarArg));
1985
1986  SDValue Flag;
1987  SmallVector<SDValue, 4> RetOps;
1988  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1989
1990  // Copy the result values into the output registers.
1991  for (unsigned i = 0, realRVLocIdx = 0;
1992       i != RVLocs.size();
1993       ++i, ++realRVLocIdx) {
1994    CCValAssign &VA = RVLocs[i];
1995    assert(VA.isRegLoc() && "Can only return in registers!");
1996
1997    SDValue Arg = OutVals[realRVLocIdx];
1998
1999    switch (VA.getLocInfo()) {
2000    default: llvm_unreachable("Unknown loc info!");
2001    case CCValAssign::Full: break;
2002    case CCValAssign::BCvt:
2003      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2004      break;
2005    }
2006
2007    if (VA.needsCustom()) {
2008      if (VA.getLocVT() == MVT::v2f64) {
2009        // Extract the first half and return it in two registers.
2010        SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2011                                   DAG.getConstant(0, MVT::i32));
2012        SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2013                                       DAG.getVTList(MVT::i32, MVT::i32), Half);
2014
2015        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2016        Flag = Chain.getValue(1);
2017        RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2018        VA = RVLocs[++i]; // skip ahead to next loc
2019        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2020                                 HalfGPRs.getValue(1), Flag);
2021        Flag = Chain.getValue(1);
2022        RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2023        VA = RVLocs[++i]; // skip ahead to next loc
2024
2025        // Extract the 2nd half and fall through to handle it as an f64 value.
2026        Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2027                          DAG.getConstant(1, MVT::i32));
2028      }
2029      // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2030      // available.
2031      SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2032                                  DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2033      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2034      Flag = Chain.getValue(1);
2035      RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2036      VA = RVLocs[++i]; // skip ahead to next loc
2037      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2038                               Flag);
2039    } else
2040      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2041
2042    // Guarantee that all emitted copies are
2043    // stuck together, avoiding something bad.
2044    Flag = Chain.getValue(1);
2045    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2046  }
2047
2048  // Update chain and glue.
2049  RetOps[0] = Chain;
2050  if (Flag.getNode())
2051    RetOps.push_back(Flag);
2052
2053  return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2054                     RetOps.data(), RetOps.size());
2055}
2056
2057bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2058  if (N->getNumValues() != 1)
2059    return false;
2060  if (!N->hasNUsesOfValue(1, 0))
2061    return false;
2062
2063  SDValue TCChain = Chain;
2064  SDNode *Copy = *N->use_begin();
2065  if (Copy->getOpcode() == ISD::CopyToReg) {
2066    // If the copy has a glue operand, we conservatively assume it isn't safe to
2067    // perform a tail call.
2068    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2069      return false;
2070    TCChain = Copy->getOperand(0);
2071  } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2072    SDNode *VMov = Copy;
2073    // f64 returned in a pair of GPRs.
2074    SmallPtrSet<SDNode*, 2> Copies;
2075    for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2076         UI != UE; ++UI) {
2077      if (UI->getOpcode() != ISD::CopyToReg)
2078        return false;
2079      Copies.insert(*UI);
2080    }
2081    if (Copies.size() > 2)
2082      return false;
2083
2084    for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2085         UI != UE; ++UI) {
2086      SDValue UseChain = UI->getOperand(0);
2087      if (Copies.count(UseChain.getNode()))
2088        // Second CopyToReg
2089        Copy = *UI;
2090      else
2091        // First CopyToReg
2092        TCChain = UseChain;
2093    }
2094  } else if (Copy->getOpcode() == ISD::BITCAST) {
2095    // f32 returned in a single GPR.
2096    if (!Copy->hasOneUse())
2097      return false;
2098    Copy = *Copy->use_begin();
2099    if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2100      return false;
2101    Chain = Copy->getOperand(0);
2102  } else {
2103    return false;
2104  }
2105
2106  bool HasRet = false;
2107  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2108       UI != UE; ++UI) {
2109    if (UI->getOpcode() != ARMISD::RET_FLAG)
2110      return false;
2111    HasRet = true;
2112  }
2113
2114  if (!HasRet)
2115    return false;
2116
2117  Chain = TCChain;
2118  return true;
2119}
2120
2121bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2122  if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2123    return false;
2124
2125  if (!CI->isTailCall())
2126    return false;
2127
2128  return !Subtarget->isThumb1Only();
2129}
2130
2131// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2132// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2133// one of the above mentioned nodes. It has to be wrapped because otherwise
2134// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2135// be used to form addressing mode. These wrapped nodes will be selected
2136// into MOVi.
2137static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2138  EVT PtrVT = Op.getValueType();
2139  // FIXME there is no actual debug info here
2140  DebugLoc dl = Op.getDebugLoc();
2141  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2142  SDValue Res;
2143  if (CP->isMachineConstantPoolEntry())
2144    Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2145                                    CP->getAlignment());
2146  else
2147    Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2148                                    CP->getAlignment());
2149  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2150}
2151
2152unsigned ARMTargetLowering::getJumpTableEncoding() const {
2153  return MachineJumpTableInfo::EK_Inline;
2154}
2155
2156SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2157                                             SelectionDAG &DAG) const {
2158  MachineFunction &MF = DAG.getMachineFunction();
2159  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2160  unsigned ARMPCLabelIndex = 0;
2161  DebugLoc DL = Op.getDebugLoc();
2162  EVT PtrVT = getPointerTy();
2163  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2164  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2165  SDValue CPAddr;
2166  if (RelocM == Reloc::Static) {
2167    CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2168  } else {
2169    unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2170    ARMPCLabelIndex = AFI->createPICLabelUId();
2171    ARMConstantPoolValue *CPV =
2172      ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2173                                      ARMCP::CPBlockAddress, PCAdj);
2174    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2175  }
2176  CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2177  SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2178                               MachinePointerInfo::getConstantPool(),
2179                               false, false, false, 0);
2180  if (RelocM == Reloc::Static)
2181    return Result;
2182  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2183  return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2184}
2185
2186// Lower ISD::GlobalTLSAddress using the "general dynamic" model
2187SDValue
2188ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2189                                                 SelectionDAG &DAG) const {
2190  DebugLoc dl = GA->getDebugLoc();
2191  EVT PtrVT = getPointerTy();
2192  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2193  MachineFunction &MF = DAG.getMachineFunction();
2194  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2195  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2196  ARMConstantPoolValue *CPV =
2197    ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2198                                    ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2199  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2200  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2201  Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2202                         MachinePointerInfo::getConstantPool(),
2203                         false, false, false, 0);
2204  SDValue Chain = Argument.getValue(1);
2205
2206  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2207  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2208
2209  // call __tls_get_addr.
2210  ArgListTy Args;
2211  ArgListEntry Entry;
2212  Entry.Node = Argument;
2213  Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2214  Args.push_back(Entry);
2215  // FIXME: is there useful debug info available here?
2216  TargetLowering::CallLoweringInfo CLI(Chain,
2217                (Type *) Type::getInt32Ty(*DAG.getContext()),
2218                false, false, false, false,
2219                0, CallingConv::C, /*isTailCall=*/false,
2220                /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2221                DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2222  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2223  return CallResult.first;
2224}
2225
2226// Lower ISD::GlobalTLSAddress using the "initial exec" or
2227// "local exec" model.
2228SDValue
2229ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2230                                        SelectionDAG &DAG,
2231                                        TLSModel::Model model) const {
2232  const GlobalValue *GV = GA->getGlobal();
2233  DebugLoc dl = GA->getDebugLoc();
2234  SDValue Offset;
2235  SDValue Chain = DAG.getEntryNode();
2236  EVT PtrVT = getPointerTy();
2237  // Get the Thread Pointer
2238  SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2239
2240  if (model == TLSModel::InitialExec) {
2241    MachineFunction &MF = DAG.getMachineFunction();
2242    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2243    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2244    // Initial exec model.
2245    unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2246    ARMConstantPoolValue *CPV =
2247      ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2248                                      ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2249                                      true);
2250    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2251    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2252    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2253                         MachinePointerInfo::getConstantPool(),
2254                         false, false, false, 0);
2255    Chain = Offset.getValue(1);
2256
2257    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2258    Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2259
2260    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2261                         MachinePointerInfo::getConstantPool(),
2262                         false, false, false, 0);
2263  } else {
2264    // local exec model
2265    assert(model == TLSModel::LocalExec);
2266    ARMConstantPoolValue *CPV =
2267      ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2268    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2269    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2270    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2271                         MachinePointerInfo::getConstantPool(),
2272                         false, false, false, 0);
2273  }
2274
2275  // The address of the thread local variable is the add of the thread
2276  // pointer with the offset of the variable.
2277  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2278}
2279
2280SDValue
2281ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2282  // TODO: implement the "local dynamic" model
2283  assert(Subtarget->isTargetELF() &&
2284         "TLS not implemented for non-ELF targets");
2285  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2286
2287  TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2288
2289  switch (model) {
2290    case TLSModel::GeneralDynamic:
2291    case TLSModel::LocalDynamic:
2292      return LowerToTLSGeneralDynamicModel(GA, DAG);
2293    case TLSModel::InitialExec:
2294    case TLSModel::LocalExec:
2295      return LowerToTLSExecModels(GA, DAG, model);
2296  }
2297  llvm_unreachable("bogus TLS model");
2298}
2299
2300SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2301                                                 SelectionDAG &DAG) const {
2302  EVT PtrVT = getPointerTy();
2303  DebugLoc dl = Op.getDebugLoc();
2304  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2305  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2306    bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2307    ARMConstantPoolValue *CPV =
2308      ARMConstantPoolConstant::Create(GV,
2309                                      UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2310    SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2311    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2312    SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2313                                 CPAddr,
2314                                 MachinePointerInfo::getConstantPool(),
2315                                 false, false, false, 0);
2316    SDValue Chain = Result.getValue(1);
2317    SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2318    Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2319    if (!UseGOTOFF)
2320      Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2321                           MachinePointerInfo::getGOT(),
2322                           false, false, false, 0);
2323    return Result;
2324  }
2325
2326  // If we have T2 ops, we can materialize the address directly via movt/movw
2327  // pair. This is always cheaper.
2328  if (Subtarget->useMovt()) {
2329    ++NumMovwMovt;
2330    // FIXME: Once remat is capable of dealing with instructions with register
2331    // operands, expand this into two nodes.
2332    return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2333                       DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2334  } else {
2335    SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2336    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2337    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2338                       MachinePointerInfo::getConstantPool(),
2339                       false, false, false, 0);
2340  }
2341}
2342
2343SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2344                                                    SelectionDAG &DAG) const {
2345  EVT PtrVT = getPointerTy();
2346  DebugLoc dl = Op.getDebugLoc();
2347  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2348  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2349
2350  // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2351  // update ARMFastISel::ARMMaterializeGV.
2352  if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2353    ++NumMovwMovt;
2354    // FIXME: Once remat is capable of dealing with instructions with register
2355    // operands, expand this into two nodes.
2356    if (RelocM == Reloc::Static)
2357      return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2358                                 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2359
2360    unsigned Wrapper = (RelocM == Reloc::PIC_)
2361      ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2362    SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2363                                 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2364    if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2365      Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2366                           MachinePointerInfo::getGOT(),
2367                           false, false, false, 0);
2368    return Result;
2369  }
2370
2371  unsigned ARMPCLabelIndex = 0;
2372  SDValue CPAddr;
2373  if (RelocM == Reloc::Static) {
2374    CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2375  } else {
2376    ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2377    ARMPCLabelIndex = AFI->createPICLabelUId();
2378    unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2379    ARMConstantPoolValue *CPV =
2380      ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2381                                      PCAdj);
2382    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2383  }
2384  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2385
2386  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2387                               MachinePointerInfo::getConstantPool(),
2388                               false, false, false, 0);
2389  SDValue Chain = Result.getValue(1);
2390
2391  if (RelocM == Reloc::PIC_) {
2392    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2393    Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2394  }
2395
2396  if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2397    Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2398                         false, false, false, 0);
2399
2400  return Result;
2401}
2402
2403SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2404                                                    SelectionDAG &DAG) const {
2405  assert(Subtarget->isTargetELF() &&
2406         "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2407  MachineFunction &MF = DAG.getMachineFunction();
2408  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2409  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2410  EVT PtrVT = getPointerTy();
2411  DebugLoc dl = Op.getDebugLoc();
2412  unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2413  ARMConstantPoolValue *CPV =
2414    ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2415                                  ARMPCLabelIndex, PCAdj);
2416  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2417  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2418  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2419                               MachinePointerInfo::getConstantPool(),
2420                               false, false, false, 0);
2421  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2422  return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2423}
2424
2425SDValue
2426ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2427  DebugLoc dl = Op.getDebugLoc();
2428  SDValue Val = DAG.getConstant(0, MVT::i32);
2429  return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2430                     DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2431                     Op.getOperand(1), Val);
2432}
2433
2434SDValue
2435ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2436  DebugLoc dl = Op.getDebugLoc();
2437  return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2438                     Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2439}
2440
2441SDValue
2442ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2443                                          const ARMSubtarget *Subtarget) const {
2444  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2445  DebugLoc dl = Op.getDebugLoc();
2446  switch (IntNo) {
2447  default: return SDValue();    // Don't custom lower most intrinsics.
2448  case Intrinsic::arm_thread_pointer: {
2449    EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2450    return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2451  }
2452  case Intrinsic::eh_sjlj_lsda: {
2453    MachineFunction &MF = DAG.getMachineFunction();
2454    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2455    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2456    EVT PtrVT = getPointerTy();
2457    Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2458    SDValue CPAddr;
2459    unsigned PCAdj = (RelocM != Reloc::PIC_)
2460      ? 0 : (Subtarget->isThumb() ? 4 : 8);
2461    ARMConstantPoolValue *CPV =
2462      ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2463                                      ARMCP::CPLSDA, PCAdj);
2464    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2465    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2466    SDValue Result =
2467      DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2468                  MachinePointerInfo::getConstantPool(),
2469                  false, false, false, 0);
2470
2471    if (RelocM == Reloc::PIC_) {
2472      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2473      Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2474    }
2475    return Result;
2476  }
2477  case Intrinsic::arm_neon_vmulls:
2478  case Intrinsic::arm_neon_vmullu: {
2479    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2480      ? ARMISD::VMULLs : ARMISD::VMULLu;
2481    return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2482                       Op.getOperand(1), Op.getOperand(2));
2483  }
2484  }
2485}
2486
2487static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2488                                 const ARMSubtarget *Subtarget) {
2489  // FIXME: handle "fence singlethread" more efficiently.
2490  DebugLoc dl = Op.getDebugLoc();
2491  if (!Subtarget->hasDataBarrier()) {
2492    // Some ARMv6 cpus can support data barriers with an mcr instruction.
2493    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2494    // here.
2495    assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2496           "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2497    return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2498                       DAG.getConstant(0, MVT::i32));
2499  }
2500
2501  return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2502                     DAG.getConstant(ARM_MB::ISH, MVT::i32));
2503}
2504
2505static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2506                             const ARMSubtarget *Subtarget) {
2507  // ARM pre v5TE and Thumb1 does not have preload instructions.
2508  if (!(Subtarget->isThumb2() ||
2509        (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2510    // Just preserve the chain.
2511    return Op.getOperand(0);
2512
2513  DebugLoc dl = Op.getDebugLoc();
2514  unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2515  if (!isRead &&
2516      (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2517    // ARMv7 with MP extension has PLDW.
2518    return Op.getOperand(0);
2519
2520  unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2521  if (Subtarget->isThumb()) {
2522    // Invert the bits.
2523    isRead = ~isRead & 1;
2524    isData = ~isData & 1;
2525  }
2526
2527  return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2528                     Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2529                     DAG.getConstant(isData, MVT::i32));
2530}
2531
2532static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2533  MachineFunction &MF = DAG.getMachineFunction();
2534  ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2535
2536  // vastart just stores the address of the VarArgsFrameIndex slot into the
2537  // memory location argument.
2538  DebugLoc dl = Op.getDebugLoc();
2539  EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2540  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2541  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2542  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2543                      MachinePointerInfo(SV), false, false, 0);
2544}
2545
2546SDValue
2547ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2548                                        SDValue &Root, SelectionDAG &DAG,
2549                                        DebugLoc dl) const {
2550  MachineFunction &MF = DAG.getMachineFunction();
2551  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2552
2553  const TargetRegisterClass *RC;
2554  if (AFI->isThumb1OnlyFunction())
2555    RC = &ARM::tGPRRegClass;
2556  else
2557    RC = &ARM::GPRRegClass;
2558
2559  // Transform the arguments stored in physical registers into virtual ones.
2560  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2561  SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2562
2563  SDValue ArgValue2;
2564  if (NextVA.isMemLoc()) {
2565    MachineFrameInfo *MFI = MF.getFrameInfo();
2566    int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2567
2568    // Create load node to retrieve arguments from the stack.
2569    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2570    ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2571                            MachinePointerInfo::getFixedStack(FI),
2572                            false, false, false, 0);
2573  } else {
2574    Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2575    ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2576  }
2577
2578  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2579}
2580
2581void
2582ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2583                                  unsigned &VARegSize, unsigned &VARegSaveSize)
2584  const {
2585  unsigned NumGPRs;
2586  if (CCInfo.isFirstByValRegValid())
2587    NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2588  else {
2589    unsigned int firstUnalloced;
2590    firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2591                                                sizeof(GPRArgRegs) /
2592                                                sizeof(GPRArgRegs[0]));
2593    NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2594  }
2595
2596  unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2597  VARegSize = NumGPRs * 4;
2598  VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2599}
2600
2601// The remaining GPRs hold either the beginning of variable-argument
2602// data, or the beginning of an aggregate passed by value (usually
2603// byval).  Either way, we allocate stack slots adjacent to the data
2604// provided by our caller, and store the unallocated registers there.
2605// If this is a variadic function, the va_list pointer will begin with
2606// these values; otherwise, this reassembles a (byval) structure that
2607// was split between registers and memory.
2608void
2609ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2610                                        DebugLoc dl, SDValue &Chain,
2611                                        const Value *OrigArg,
2612                                        unsigned OffsetFromOrigArg,
2613                                        unsigned ArgOffset,
2614                                        bool ForceMutable) const {
2615  MachineFunction &MF = DAG.getMachineFunction();
2616  MachineFrameInfo *MFI = MF.getFrameInfo();
2617  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2618  unsigned firstRegToSaveIndex;
2619  if (CCInfo.isFirstByValRegValid())
2620    firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2621  else {
2622    firstRegToSaveIndex = CCInfo.getFirstUnallocated
2623      (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2624  }
2625
2626  unsigned VARegSize, VARegSaveSize;
2627  computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2628  if (VARegSaveSize) {
2629    // If this function is vararg, store any remaining integer argument regs
2630    // to their spots on the stack so that they may be loaded by deferencing
2631    // the result of va_next.
2632    AFI->setVarArgsRegSaveSize(VARegSaveSize);
2633    AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2634                                                     ArgOffset + VARegSaveSize
2635                                                     - VARegSize,
2636                                                     false));
2637    SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2638                                    getPointerTy());
2639
2640    SmallVector<SDValue, 4> MemOps;
2641    for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2642      const TargetRegisterClass *RC;
2643      if (AFI->isThumb1OnlyFunction())
2644        RC = &ARM::tGPRRegClass;
2645      else
2646        RC = &ARM::GPRRegClass;
2647
2648      unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2649      SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2650      SDValue Store =
2651        DAG.getStore(Val.getValue(1), dl, Val, FIN,
2652                     MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2653                     false, false, 0);
2654      MemOps.push_back(Store);
2655      FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2656                        DAG.getConstant(4, getPointerTy()));
2657    }
2658    if (!MemOps.empty())
2659      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2660                          &MemOps[0], MemOps.size());
2661  } else
2662    // This will point to the next argument passed via stack.
2663    AFI->setVarArgsFrameIndex(
2664        MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2665}
2666
2667SDValue
2668ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2669                                        CallingConv::ID CallConv, bool isVarArg,
2670                                        const SmallVectorImpl<ISD::InputArg>
2671                                          &Ins,
2672                                        DebugLoc dl, SelectionDAG &DAG,
2673                                        SmallVectorImpl<SDValue> &InVals)
2674                                          const {
2675  MachineFunction &MF = DAG.getMachineFunction();
2676  MachineFrameInfo *MFI = MF.getFrameInfo();
2677
2678  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2679
2680  // Assign locations to all of the incoming arguments.
2681  SmallVector<CCValAssign, 16> ArgLocs;
2682  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2683                    getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2684  CCInfo.AnalyzeFormalArguments(Ins,
2685                                CCAssignFnForNode(CallConv, /* Return*/ false,
2686                                                  isVarArg));
2687
2688  SmallVector<SDValue, 16> ArgValues;
2689  int lastInsIndex = -1;
2690  SDValue ArgValue;
2691  Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2692  unsigned CurArgIdx = 0;
2693  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2694    CCValAssign &VA = ArgLocs[i];
2695    std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2696    CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2697    // Arguments stored in registers.
2698    if (VA.isRegLoc()) {
2699      EVT RegVT = VA.getLocVT();
2700
2701      if (VA.needsCustom()) {
2702        // f64 and vector types are split up into multiple registers or
2703        // combinations of registers and stack slots.
2704        if (VA.getLocVT() == MVT::v2f64) {
2705          SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2706                                                   Chain, DAG, dl);
2707          VA = ArgLocs[++i]; // skip ahead to next loc
2708          SDValue ArgValue2;
2709          if (VA.isMemLoc()) {
2710            int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2711            SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2712            ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2713                                    MachinePointerInfo::getFixedStack(FI),
2714                                    false, false, false, 0);
2715          } else {
2716            ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2717                                             Chain, DAG, dl);
2718          }
2719          ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2720          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2721                                 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2722          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2723                                 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2724        } else
2725          ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2726
2727      } else {
2728        const TargetRegisterClass *RC;
2729
2730        if (RegVT == MVT::f32)
2731          RC = &ARM::SPRRegClass;
2732        else if (RegVT == MVT::f64)
2733          RC = &ARM::DPRRegClass;
2734        else if (RegVT == MVT::v2f64)
2735          RC = &ARM::QPRRegClass;
2736        else if (RegVT == MVT::i32)
2737          RC = AFI->isThumb1OnlyFunction() ?
2738            (const TargetRegisterClass*)&ARM::tGPRRegClass :
2739            (const TargetRegisterClass*)&ARM::GPRRegClass;
2740        else
2741          llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2742
2743        // Transform the arguments in physical registers into virtual ones.
2744        unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2745        ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2746      }
2747
2748      // If this is an 8 or 16-bit value, it is really passed promoted
2749      // to 32 bits.  Insert an assert[sz]ext to capture this, then
2750      // truncate to the right size.
2751      switch (VA.getLocInfo()) {
2752      default: llvm_unreachable("Unknown loc info!");
2753      case CCValAssign::Full: break;
2754      case CCValAssign::BCvt:
2755        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2756        break;
2757      case CCValAssign::SExt:
2758        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2759                               DAG.getValueType(VA.getValVT()));
2760        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2761        break;
2762      case CCValAssign::ZExt:
2763        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2764                               DAG.getValueType(VA.getValVT()));
2765        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2766        break;
2767      }
2768
2769      InVals.push_back(ArgValue);
2770
2771    } else { // VA.isRegLoc()
2772
2773      // sanity check
2774      assert(VA.isMemLoc());
2775      assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2776
2777      int index = ArgLocs[i].getValNo();
2778
2779      // Some Ins[] entries become multiple ArgLoc[] entries.
2780      // Process them only once.
2781      if (index != lastInsIndex)
2782        {
2783          ISD::ArgFlagsTy Flags = Ins[index].Flags;
2784          // FIXME: For now, all byval parameter objects are marked mutable.
2785          // This can be changed with more analysis.
2786          // In case of tail call optimization mark all arguments mutable.
2787          // Since they could be overwritten by lowering of arguments in case of
2788          // a tail call.
2789          if (Flags.isByVal()) {
2790            ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2791            if (!AFI->getVarArgsFrameIndex()) {
2792              VarArgStyleRegisters(CCInfo, DAG,
2793                                   dl, Chain, CurOrigArg,
2794                                   Ins[VA.getValNo()].PartOffset,
2795                                   VA.getLocMemOffset(),
2796                                   true /*force mutable frames*/);
2797              int VAFrameIndex = AFI->getVarArgsFrameIndex();
2798              InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2799            } else {
2800              int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2801                                              VA.getLocMemOffset(), false);
2802              InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2803            }
2804          } else {
2805            int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2806                                            VA.getLocMemOffset(), true);
2807
2808            // Create load nodes to retrieve arguments from the stack.
2809            SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2810            InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2811                                         MachinePointerInfo::getFixedStack(FI),
2812                                         false, false, false, 0));
2813          }
2814          lastInsIndex = index;
2815        }
2816    }
2817  }
2818
2819  // varargs
2820  if (isVarArg)
2821    VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2822                         CCInfo.getNextStackOffset());
2823
2824  return Chain;
2825}
2826
2827/// isFloatingPointZero - Return true if this is +0.0.
2828static bool isFloatingPointZero(SDValue Op) {
2829  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2830    return CFP->getValueAPF().isPosZero();
2831  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2832    // Maybe this has already been legalized into the constant pool?
2833    if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2834      SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2835      if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2836        if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2837          return CFP->getValueAPF().isPosZero();
2838    }
2839  }
2840  return false;
2841}
2842
2843/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2844/// the given operands.
2845SDValue
2846ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2847                             SDValue &ARMcc, SelectionDAG &DAG,
2848                             DebugLoc dl) const {
2849  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2850    unsigned C = RHSC->getZExtValue();
2851    if (!isLegalICmpImmediate(C)) {
2852      // Constant does not fit, try adjusting it by one?
2853      switch (CC) {
2854      default: break;
2855      case ISD::SETLT:
2856      case ISD::SETGE:
2857        if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2858          CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2859          RHS = DAG.getConstant(C-1, MVT::i32);
2860        }
2861        break;
2862      case ISD::SETULT:
2863      case ISD::SETUGE:
2864        if (C != 0 && isLegalICmpImmediate(C-1)) {
2865          CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2866          RHS = DAG.getConstant(C-1, MVT::i32);
2867        }
2868        break;
2869      case ISD::SETLE:
2870      case ISD::SETGT:
2871        if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2872          CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2873          RHS = DAG.getConstant(C+1, MVT::i32);
2874        }
2875        break;
2876      case ISD::SETULE:
2877      case ISD::SETUGT:
2878        if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2879          CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2880          RHS = DAG.getConstant(C+1, MVT::i32);
2881        }
2882        break;
2883      }
2884    }
2885  }
2886
2887  ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2888  ARMISD::NodeType CompareType;
2889  switch (CondCode) {
2890  default:
2891    CompareType = ARMISD::CMP;
2892    break;
2893  case ARMCC::EQ:
2894  case ARMCC::NE:
2895    // Uses only Z Flag
2896    CompareType = ARMISD::CMPZ;
2897    break;
2898  }
2899  ARMcc = DAG.getConstant(CondCode, MVT::i32);
2900  return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2901}
2902
2903/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2904SDValue
2905ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2906                             DebugLoc dl) const {
2907  SDValue Cmp;
2908  if (!isFloatingPointZero(RHS))
2909    Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2910  else
2911    Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2912  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2913}
2914
2915/// duplicateCmp - Glue values can have only one use, so this function
2916/// duplicates a comparison node.
2917SDValue
2918ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2919  unsigned Opc = Cmp.getOpcode();
2920  DebugLoc DL = Cmp.getDebugLoc();
2921  if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2922    return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2923
2924  assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2925  Cmp = Cmp.getOperand(0);
2926  Opc = Cmp.getOpcode();
2927  if (Opc == ARMISD::CMPFP)
2928    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2929  else {
2930    assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2931    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2932  }
2933  return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2934}
2935
2936SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2937  SDValue Cond = Op.getOperand(0);
2938  SDValue SelectTrue = Op.getOperand(1);
2939  SDValue SelectFalse = Op.getOperand(2);
2940  DebugLoc dl = Op.getDebugLoc();
2941
2942  // Convert:
2943  //
2944  //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2945  //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2946  //
2947  if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2948    const ConstantSDNode *CMOVTrue =
2949      dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2950    const ConstantSDNode *CMOVFalse =
2951      dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2952
2953    if (CMOVTrue && CMOVFalse) {
2954      unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2955      unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2956
2957      SDValue True;
2958      SDValue False;
2959      if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2960        True = SelectTrue;
2961        False = SelectFalse;
2962      } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2963        True = SelectFalse;
2964        False = SelectTrue;
2965      }
2966
2967      if (True.getNode() && False.getNode()) {
2968        EVT VT = Op.getValueType();
2969        SDValue ARMcc = Cond.getOperand(2);
2970        SDValue CCR = Cond.getOperand(3);
2971        SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2972        assert(True.getValueType() == VT);
2973        return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2974      }
2975    }
2976  }
2977
2978  // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2979  // undefined bits before doing a full-word comparison with zero.
2980  Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2981                     DAG.getConstant(1, Cond.getValueType()));
2982
2983  return DAG.getSelectCC(dl, Cond,
2984                         DAG.getConstant(0, Cond.getValueType()),
2985                         SelectTrue, SelectFalse, ISD::SETNE);
2986}
2987
2988SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2989  EVT VT = Op.getValueType();
2990  SDValue LHS = Op.getOperand(0);
2991  SDValue RHS = Op.getOperand(1);
2992  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2993  SDValue TrueVal = Op.getOperand(2);
2994  SDValue FalseVal = Op.getOperand(3);
2995  DebugLoc dl = Op.getDebugLoc();
2996
2997  if (LHS.getValueType() == MVT::i32) {
2998    SDValue ARMcc;
2999    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3000    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3001    return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3002  }
3003
3004  ARMCC::CondCodes CondCode, CondCode2;
3005  FPCCToARMCC(CC, CondCode, CondCode2);
3006
3007  SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3008  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3009  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3010  SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3011                               ARMcc, CCR, Cmp);
3012  if (CondCode2 != ARMCC::AL) {
3013    SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3014    // FIXME: Needs another CMP because flag can have but one use.
3015    SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3016    Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3017                         Result, TrueVal, ARMcc2, CCR, Cmp2);
3018  }
3019  return Result;
3020}
3021
3022/// canChangeToInt - Given the fp compare operand, return true if it is suitable
3023/// to morph to an integer compare sequence.
3024static bool canChangeToInt(SDValue Op, bool &SeenZero,
3025                           const ARMSubtarget *Subtarget) {
3026  SDNode *N = Op.getNode();
3027  if (!N->hasOneUse())
3028    // Otherwise it requires moving the value from fp to integer registers.
3029    return false;
3030  if (!N->getNumValues())
3031    return false;
3032  EVT VT = Op.getValueType();
3033  if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3034    // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3035    // vmrs are very slow, e.g. cortex-a8.
3036    return false;
3037
3038  if (isFloatingPointZero(Op)) {
3039    SeenZero = true;
3040    return true;
3041  }
3042  return ISD::isNormalLoad(N);
3043}
3044
3045static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3046  if (isFloatingPointZero(Op))
3047    return DAG.getConstant(0, MVT::i32);
3048
3049  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3050    return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3051                       Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3052                       Ld->isVolatile(), Ld->isNonTemporal(),
3053                       Ld->isInvariant(), Ld->getAlignment());
3054
3055  llvm_unreachable("Unknown VFP cmp argument!");
3056}
3057
3058static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3059                           SDValue &RetVal1, SDValue &RetVal2) {
3060  if (isFloatingPointZero(Op)) {
3061    RetVal1 = DAG.getConstant(0, MVT::i32);
3062    RetVal2 = DAG.getConstant(0, MVT::i32);
3063    return;
3064  }
3065
3066  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3067    SDValue Ptr = Ld->getBasePtr();
3068    RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3069                          Ld->getChain(), Ptr,
3070                          Ld->getPointerInfo(),
3071                          Ld->isVolatile(), Ld->isNonTemporal(),
3072                          Ld->isInvariant(), Ld->getAlignment());
3073
3074    EVT PtrType = Ptr.getValueType();
3075    unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3076    SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3077                                 PtrType, Ptr, DAG.getConstant(4, PtrType));
3078    RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3079                          Ld->getChain(), NewPtr,
3080                          Ld->getPointerInfo().getWithOffset(4),
3081                          Ld->isVolatile(), Ld->isNonTemporal(),
3082                          Ld->isInvariant(), NewAlign);
3083    return;
3084  }
3085
3086  llvm_unreachable("Unknown VFP cmp argument!");
3087}
3088
3089/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3090/// f32 and even f64 comparisons to integer ones.
3091SDValue
3092ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3093  SDValue Chain = Op.getOperand(0);
3094  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3095  SDValue LHS = Op.getOperand(2);
3096  SDValue RHS = Op.getOperand(3);
3097  SDValue Dest = Op.getOperand(4);
3098  DebugLoc dl = Op.getDebugLoc();
3099
3100  bool LHSSeenZero = false;
3101  bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3102  bool RHSSeenZero = false;
3103  bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3104  if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3105    // If unsafe fp math optimization is enabled and there are no other uses of
3106    // the CMP operands, and the condition code is EQ or NE, we can optimize it
3107    // to an integer comparison.
3108    if (CC == ISD::SETOEQ)
3109      CC = ISD::SETEQ;
3110    else if (CC == ISD::SETUNE)
3111      CC = ISD::SETNE;
3112
3113    SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3114    SDValue ARMcc;
3115    if (LHS.getValueType() == MVT::f32) {
3116      LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3117                        bitcastf32Toi32(LHS, DAG), Mask);
3118      RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3119                        bitcastf32Toi32(RHS, DAG), Mask);
3120      SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3121      SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3122      return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3123                         Chain, Dest, ARMcc, CCR, Cmp);
3124    }
3125
3126    SDValue LHS1, LHS2;
3127    SDValue RHS1, RHS2;
3128    expandf64Toi32(LHS, DAG, LHS1, LHS2);
3129    expandf64Toi32(RHS, DAG, RHS1, RHS2);
3130    LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3131    RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3132    ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3133    ARMcc = DAG.getConstant(CondCode, MVT::i32);
3134    SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3135    SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3136    return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3137  }
3138
3139  return SDValue();
3140}
3141
3142SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3143  SDValue Chain = Op.getOperand(0);
3144  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3145  SDValue LHS = Op.getOperand(2);
3146  SDValue RHS = Op.getOperand(3);
3147  SDValue Dest = Op.getOperand(4);
3148  DebugLoc dl = Op.getDebugLoc();
3149
3150  if (LHS.getValueType() == MVT::i32) {
3151    SDValue ARMcc;
3152    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3153    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3154    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3155                       Chain, Dest, ARMcc, CCR, Cmp);
3156  }
3157
3158  assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3159
3160  if (getTargetMachine().Options.UnsafeFPMath &&
3161      (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3162       CC == ISD::SETNE || CC == ISD::SETUNE)) {
3163    SDValue Result = OptimizeVFPBrcond(Op, DAG);
3164    if (Result.getNode())
3165      return Result;
3166  }
3167
3168  ARMCC::CondCodes CondCode, CondCode2;
3169  FPCCToARMCC(CC, CondCode, CondCode2);
3170
3171  SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3172  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3173  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3174  SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3175  SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3176  SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3177  if (CondCode2 != ARMCC::AL) {
3178    ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3179    SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3180    Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3181  }
3182  return Res;
3183}
3184
3185SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3186  SDValue Chain = Op.getOperand(0);
3187  SDValue Table = Op.getOperand(1);
3188  SDValue Index = Op.getOperand(2);
3189  DebugLoc dl = Op.getDebugLoc();
3190
3191  EVT PTy = getPointerTy();
3192  JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3193  ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3194  SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3195  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3196  Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3197  Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3198  SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3199  if (Subtarget->isThumb2()) {
3200    // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3201    // which does another jump to the destination. This also makes it easier
3202    // to translate it to TBB / TBH later.
3203    // FIXME: This might not work if the function is extremely large.
3204    return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3205                       Addr, Op.getOperand(2), JTI, UId);
3206  }
3207  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3208    Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3209                       MachinePointerInfo::getJumpTable(),
3210                       false, false, false, 0);
3211    Chain = Addr.getValue(1);
3212    Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3213    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3214  } else {
3215    Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3216                       MachinePointerInfo::getJumpTable(),
3217                       false, false, false, 0);
3218    Chain = Addr.getValue(1);
3219    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3220  }
3221}
3222
3223static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3224  EVT VT = Op.getValueType();
3225  DebugLoc dl = Op.getDebugLoc();
3226
3227  if (Op.getValueType().getVectorElementType() == MVT::i32) {
3228    if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3229      return Op;
3230    return DAG.UnrollVectorOp(Op.getNode());
3231  }
3232
3233  assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3234         "Invalid type for custom lowering!");
3235  if (VT != MVT::v4i16)
3236    return DAG.UnrollVectorOp(Op.getNode());
3237
3238  Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3239  return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3240}
3241
3242static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3243  EVT VT = Op.getValueType();
3244  if (VT.isVector())
3245    return LowerVectorFP_TO_INT(Op, DAG);
3246
3247  DebugLoc dl = Op.getDebugLoc();
3248  unsigned Opc;
3249
3250  switch (Op.getOpcode()) {
3251  default: llvm_unreachable("Invalid opcode!");
3252  case ISD::FP_TO_SINT:
3253    Opc = ARMISD::FTOSI;
3254    break;
3255  case ISD::FP_TO_UINT:
3256    Opc = ARMISD::FTOUI;
3257    break;
3258  }
3259  Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3260  return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3261}
3262
3263static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3264  EVT VT = Op.getValueType();
3265  DebugLoc dl = Op.getDebugLoc();
3266
3267  if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3268    if (VT.getVectorElementType() == MVT::f32)
3269      return Op;
3270    return DAG.UnrollVectorOp(Op.getNode());
3271  }
3272
3273  assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3274         "Invalid type for custom lowering!");
3275  if (VT != MVT::v4f32)
3276    return DAG.UnrollVectorOp(Op.getNode());
3277
3278  unsigned CastOpc;
3279  unsigned Opc;
3280  switch (Op.getOpcode()) {
3281  default: llvm_unreachable("Invalid opcode!");
3282  case ISD::SINT_TO_FP:
3283    CastOpc = ISD::SIGN_EXTEND;
3284    Opc = ISD::SINT_TO_FP;
3285    break;
3286  case ISD::UINT_TO_FP:
3287    CastOpc = ISD::ZERO_EXTEND;
3288    Opc = ISD::UINT_TO_FP;
3289    break;
3290  }
3291
3292  Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3293  return DAG.getNode(Opc, dl, VT, Op);
3294}
3295
3296static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3297  EVT VT = Op.getValueType();
3298  if (VT.isVector())
3299    return LowerVectorINT_TO_FP(Op, DAG);
3300
3301  DebugLoc dl = Op.getDebugLoc();
3302  unsigned Opc;
3303
3304  switch (Op.getOpcode()) {
3305  default: llvm_unreachable("Invalid opcode!");
3306  case ISD::SINT_TO_FP:
3307    Opc = ARMISD::SITOF;
3308    break;
3309  case ISD::UINT_TO_FP:
3310    Opc = ARMISD::UITOF;
3311    break;
3312  }
3313
3314  Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3315  return DAG.getNode(Opc, dl, VT, Op);
3316}
3317
3318SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3319  // Implement fcopysign with a fabs and a conditional fneg.
3320  SDValue Tmp0 = Op.getOperand(0);
3321  SDValue Tmp1 = Op.getOperand(1);
3322  DebugLoc dl = Op.getDebugLoc();
3323  EVT VT = Op.getValueType();
3324  EVT SrcVT = Tmp1.getValueType();
3325  bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3326    Tmp0.getOpcode() == ARMISD::VMOVDRR;
3327  bool UseNEON = !InGPR && Subtarget->hasNEON();
3328
3329  if (UseNEON) {
3330    // Use VBSL to copy the sign bit.
3331    unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3332    SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3333                               DAG.getTargetConstant(EncodedVal, MVT::i32));
3334    EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3335    if (VT == MVT::f64)
3336      Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3337                         DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3338                         DAG.getConstant(32, MVT::i32));
3339    else /*if (VT == MVT::f32)*/
3340      Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3341    if (SrcVT == MVT::f32) {
3342      Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3343      if (VT == MVT::f64)
3344        Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3345                           DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3346                           DAG.getConstant(32, MVT::i32));
3347    } else if (VT == MVT::f32)
3348      Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3349                         DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3350                         DAG.getConstant(32, MVT::i32));
3351    Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3352    Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3353
3354    SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3355                                            MVT::i32);
3356    AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3357    SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3358                                  DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3359
3360    SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3361                              DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3362                              DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3363    if (VT == MVT::f32) {
3364      Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3365      Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3366                        DAG.getConstant(0, MVT::i32));
3367    } else {
3368      Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3369    }
3370
3371    return Res;
3372  }
3373
3374  // Bitcast operand 1 to i32.
3375  if (SrcVT == MVT::f64)
3376    Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3377                       &Tmp1, 1).getValue(1);
3378  Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3379
3380  // Or in the signbit with integer operations.
3381  SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3382  SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3383  Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3384  if (VT == MVT::f32) {
3385    Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3386                       DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3387    return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3388                       DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3389  }
3390
3391  // f64: Or the high part with signbit and then combine two parts.
3392  Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3393                     &Tmp0, 1);
3394  SDValue Lo = Tmp0.getValue(0);
3395  SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3396  Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3397  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3398}
3399
3400SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3401  MachineFunction &MF = DAG.getMachineFunction();
3402  MachineFrameInfo *MFI = MF.getFrameInfo();
3403  MFI->setReturnAddressIsTaken(true);
3404
3405  EVT VT = Op.getValueType();
3406  DebugLoc dl = Op.getDebugLoc();
3407  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3408  if (Depth) {
3409    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3410    SDValue Offset = DAG.getConstant(4, MVT::i32);
3411    return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3412                       DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3413                       MachinePointerInfo(), false, false, false, 0);
3414  }
3415
3416  // Return LR, which contains the return address. Mark it an implicit live-in.
3417  unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3418  return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3419}
3420
3421SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3422  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3423  MFI->setFrameAddressIsTaken(true);
3424
3425  EVT VT = Op.getValueType();
3426  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3427  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3428  unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3429    ? ARM::R7 : ARM::R11;
3430  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3431  while (Depth--)
3432    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3433                            MachinePointerInfo(),
3434                            false, false, false, 0);
3435  return FrameAddr;
3436}
3437
3438/// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3439/// and size(DestVec) > 128-bits.
3440/// This is achieved by doing the one extension from the SrcVec, splitting the
3441/// result, extending these parts, and then concatenating these into the
3442/// destination.
3443static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3444  SDValue Op = N->getOperand(0);
3445  EVT SrcVT = Op.getValueType();
3446  EVT DestVT = N->getValueType(0);
3447
3448  assert(DestVT.getSizeInBits() > 128 &&
3449         "Custom sext/zext expansion needs >128-bit vector.");
3450  // If this is a normal length extension, use the default expansion.
3451  if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3452      SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3453    return SDValue();
3454
3455  DebugLoc dl = N->getDebugLoc();
3456  unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3457  unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3458  unsigned NumElts = SrcVT.getVectorNumElements();
3459  LLVMContext &Ctx = *DAG.getContext();
3460  SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3461
3462  EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3463                               NumElts);
3464  EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3465                                 NumElts/2);
3466  EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3467                               NumElts/2);
3468
3469  Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3470  SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3471                        DAG.getIntPtrConstant(0));
3472  SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3473                        DAG.getIntPtrConstant(NumElts/2));
3474  ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3475  ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3476  return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3477}
3478
3479/// ExpandBITCAST - If the target supports VFP, this function is called to
3480/// expand a bit convert where either the source or destination type is i64 to
3481/// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3482/// operand type is illegal (e.g., v2f32 for a target that doesn't support
3483/// vectors), since the legalizer won't know what to do with that.
3484static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3485  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3486  DebugLoc dl = N->getDebugLoc();
3487  SDValue Op = N->getOperand(0);
3488
3489  // This function is only supposed to be called for i64 types, either as the
3490  // source or destination of the bit convert.
3491  EVT SrcVT = Op.getValueType();
3492  EVT DstVT = N->getValueType(0);
3493  assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3494         "ExpandBITCAST called for non-i64 type");
3495
3496  // Turn i64->f64 into VMOVDRR.
3497  if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3498    SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3499                             DAG.getConstant(0, MVT::i32));
3500    SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3501                             DAG.getConstant(1, MVT::i32));
3502    return DAG.getNode(ISD::BITCAST, dl, DstVT,
3503                       DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3504  }
3505
3506  // Turn f64->i64 into VMOVRRD.
3507  if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3508    SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3509                              DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3510    // Merge the pieces into a single i64 value.
3511    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3512  }
3513
3514  return SDValue();
3515}
3516
3517/// getZeroVector - Returns a vector of specified type with all zero elements.
3518/// Zero vectors are used to represent vector negation and in those cases
3519/// will be implemented with the NEON VNEG instruction.  However, VNEG does
3520/// not support i64 elements, so sometimes the zero vectors will need to be
3521/// explicitly constructed.  Regardless, use a canonical VMOV to create the
3522/// zero vector.
3523static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3524  assert(VT.isVector() && "Expected a vector type");
3525  // The canonical modified immediate encoding of a zero vector is....0!
3526  SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3527  EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3528  SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3529  return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3530}
3531
3532/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3533/// i32 values and take a 2 x i32 value to shift plus a shift amount.
3534SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3535                                                SelectionDAG &DAG) const {
3536  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3537  EVT VT = Op.getValueType();
3538  unsigned VTBits = VT.getSizeInBits();
3539  DebugLoc dl = Op.getDebugLoc();
3540  SDValue ShOpLo = Op.getOperand(0);
3541  SDValue ShOpHi = Op.getOperand(1);
3542  SDValue ShAmt  = Op.getOperand(2);
3543  SDValue ARMcc;
3544  unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3545
3546  assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3547
3548  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3549                                 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3550  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3551  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3552                                   DAG.getConstant(VTBits, MVT::i32));
3553  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3554  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3555  SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3556
3557  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3558  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3559                          ARMcc, DAG, dl);
3560  SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3561  SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3562                           CCR, Cmp);
3563
3564  SDValue Ops[2] = { Lo, Hi };
3565  return DAG.getMergeValues(Ops, 2, dl);
3566}
3567
3568/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3569/// i32 values and take a 2 x i32 value to shift plus a shift amount.
3570SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3571                                               SelectionDAG &DAG) const {
3572  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3573  EVT VT = Op.getValueType();
3574  unsigned VTBits = VT.getSizeInBits();
3575  DebugLoc dl = Op.getDebugLoc();
3576  SDValue ShOpLo = Op.getOperand(0);
3577  SDValue ShOpHi = Op.getOperand(1);
3578  SDValue ShAmt  = Op.getOperand(2);
3579  SDValue ARMcc;
3580
3581  assert(Op.getOpcode() == ISD::SHL_PARTS);
3582  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3583                                 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3584  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3585  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3586                                   DAG.getConstant(VTBits, MVT::i32));
3587  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3588  SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3589
3590  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3591  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3592  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3593                          ARMcc, DAG, dl);
3594  SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3595  SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3596                           CCR, Cmp);
3597
3598  SDValue Ops[2] = { Lo, Hi };
3599  return DAG.getMergeValues(Ops, 2, dl);
3600}
3601
3602SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3603                                            SelectionDAG &DAG) const {
3604  // The rounding mode is in bits 23:22 of the FPSCR.
3605  // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3606  // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3607  // so that the shift + and get folded into a bitfield extract.
3608  DebugLoc dl = Op.getDebugLoc();
3609  SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3610                              DAG.getConstant(Intrinsic::arm_get_fpscr,
3611                                              MVT::i32));
3612  SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3613                                  DAG.getConstant(1U << 22, MVT::i32));
3614  SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3615                              DAG.getConstant(22, MVT::i32));
3616  return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3617                     DAG.getConstant(3, MVT::i32));
3618}
3619
3620static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3621                         const ARMSubtarget *ST) {
3622  EVT VT = N->getValueType(0);
3623  DebugLoc dl = N->getDebugLoc();
3624
3625  if (!ST->hasV6T2Ops())
3626    return SDValue();
3627
3628  SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3629  return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3630}
3631
3632/// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3633/// for each 16-bit element from operand, repeated.  The basic idea is to
3634/// leverage vcnt to get the 8-bit counts, gather and add the results.
3635///
3636/// Trace for v4i16:
3637/// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3638/// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3639/// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3640/// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3641///            [b0 b1 b2 b3 b4 b5 b6 b7]
3642///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3643/// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3644/// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3645static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3646  EVT VT = N->getValueType(0);
3647  DebugLoc DL = N->getDebugLoc();
3648
3649  EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3650  SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3651  SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3652  SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3653  SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3654  return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3655}
3656
3657/// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3658/// bit-count for each 16-bit element from the operand.  We need slightly
3659/// different sequencing for v4i16 and v8i16 to stay within NEON's available
3660/// 64/128-bit registers.
3661///
3662/// Trace for v4i16:
3663/// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3664/// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3665/// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3666/// v4i16:Extracted = [k0    k1    k2    k3    ]
3667static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3668  EVT VT = N->getValueType(0);
3669  DebugLoc DL = N->getDebugLoc();
3670
3671  SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3672  if (VT.is64BitVector()) {
3673    SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3674    return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3675                       DAG.getIntPtrConstant(0));
3676  } else {
3677    SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3678                                    BitCounts, DAG.getIntPtrConstant(0));
3679    return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3680  }
3681}
3682
3683/// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3684/// bit-count for each 32-bit element from the operand.  The idea here is
3685/// to split the vector into 16-bit elements, leverage the 16-bit count
3686/// routine, and then combine the results.
3687///
3688/// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3689/// input    = [v0    v1    ] (vi: 32-bit elements)
3690/// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3691/// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3692/// vrev: N0 = [k1 k0 k3 k2 ]
3693///            [k0 k1 k2 k3 ]
3694///       N1 =+[k1 k0 k3 k2 ]
3695///            [k0 k2 k1 k3 ]
3696///       N2 =+[k1 k3 k0 k2 ]
3697///            [k0    k2    k1    k3    ]
3698/// Extended =+[k1    k3    k0    k2    ]
3699///            [k0    k2    ]
3700/// Extracted=+[k1    k3    ]
3701///
3702static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3703  EVT VT = N->getValueType(0);
3704  DebugLoc DL = N->getDebugLoc();
3705
3706  EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3707
3708  SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3709  SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3710  SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3711  SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3712  SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3713
3714  if (VT.is64BitVector()) {
3715    SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3716    return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3717                       DAG.getIntPtrConstant(0));
3718  } else {
3719    SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3720                                    DAG.getIntPtrConstant(0));
3721    return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3722  }
3723}
3724
3725static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3726                          const ARMSubtarget *ST) {
3727  EVT VT = N->getValueType(0);
3728
3729  assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3730  assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3731          VT == MVT::v4i16 || VT == MVT::v8i16) &&
3732         "Unexpected type for custom ctpop lowering");
3733
3734  if (VT.getVectorElementType() == MVT::i32)
3735    return lowerCTPOP32BitElements(N, DAG);
3736  else
3737    return lowerCTPOP16BitElements(N, DAG);
3738}
3739
3740static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3741                          const ARMSubtarget *ST) {
3742  EVT VT = N->getValueType(0);
3743  DebugLoc dl = N->getDebugLoc();
3744
3745  if (!VT.isVector())
3746    return SDValue();
3747
3748  // Lower vector shifts on NEON to use VSHL.
3749  assert(ST->hasNEON() && "unexpected vector shift");
3750
3751  // Left shifts translate directly to the vshiftu intrinsic.
3752  if (N->getOpcode() == ISD::SHL)
3753    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3754                       DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3755                       N->getOperand(0), N->getOperand(1));
3756
3757  assert((N->getOpcode() == ISD::SRA ||
3758          N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3759
3760  // NEON uses the same intrinsics for both left and right shifts.  For
3761  // right shifts, the shift amounts are negative, so negate the vector of
3762  // shift amounts.
3763  EVT ShiftVT = N->getOperand(1).getValueType();
3764  SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3765                                     getZeroVector(ShiftVT, DAG, dl),
3766                                     N->getOperand(1));
3767  Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3768                             Intrinsic::arm_neon_vshifts :
3769                             Intrinsic::arm_neon_vshiftu);
3770  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3771                     DAG.getConstant(vshiftInt, MVT::i32),
3772                     N->getOperand(0), NegatedCount);
3773}
3774
3775static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3776                                const ARMSubtarget *ST) {
3777  EVT VT = N->getValueType(0);
3778  DebugLoc dl = N->getDebugLoc();
3779
3780  // We can get here for a node like i32 = ISD::SHL i32, i64
3781  if (VT != MVT::i64)
3782    return SDValue();
3783
3784  assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3785         "Unknown shift to lower!");
3786
3787  // We only lower SRA, SRL of 1 here, all others use generic lowering.
3788  if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3789      cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3790    return SDValue();
3791
3792  // If we are in thumb mode, we don't have RRX.
3793  if (ST->isThumb1Only()) return SDValue();
3794
3795  // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3796  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3797                           DAG.getConstant(0, MVT::i32));
3798  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3799                           DAG.getConstant(1, MVT::i32));
3800
3801  // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3802  // captures the result into a carry flag.
3803  unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3804  Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3805
3806  // The low part is an ARMISD::RRX operand, which shifts the carry in.
3807  Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3808
3809  // Merge the pieces into a single i64 value.
3810 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3811}
3812
3813static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3814  SDValue TmpOp0, TmpOp1;
3815  bool Invert = false;
3816  bool Swap = false;
3817  unsigned Opc = 0;
3818
3819  SDValue Op0 = Op.getOperand(0);
3820  SDValue Op1 = Op.getOperand(1);
3821  SDValue CC = Op.getOperand(2);
3822  EVT VT = Op.getValueType();
3823  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3824  DebugLoc dl = Op.getDebugLoc();
3825
3826  if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3827    switch (SetCCOpcode) {
3828    default: llvm_unreachable("Illegal FP comparison");
3829    case ISD::SETUNE:
3830    case ISD::SETNE:  Invert = true; // Fallthrough
3831    case ISD::SETOEQ:
3832    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3833    case ISD::SETOLT:
3834    case ISD::SETLT: Swap = true; // Fallthrough
3835    case ISD::SETOGT:
3836    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3837    case ISD::SETOLE:
3838    case ISD::SETLE:  Swap = true; // Fallthrough
3839    case ISD::SETOGE:
3840    case ISD::SETGE: Opc = ARMISD::VCGE; break;
3841    case ISD::SETUGE: Swap = true; // Fallthrough
3842    case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3843    case ISD::SETUGT: Swap = true; // Fallthrough
3844    case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3845    case ISD::SETUEQ: Invert = true; // Fallthrough
3846    case ISD::SETONE:
3847      // Expand this to (OLT | OGT).
3848      TmpOp0 = Op0;
3849      TmpOp1 = Op1;
3850      Opc = ISD::OR;
3851      Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3852      Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3853      break;
3854    case ISD::SETUO: Invert = true; // Fallthrough
3855    case ISD::SETO:
3856      // Expand this to (OLT | OGE).
3857      TmpOp0 = Op0;
3858      TmpOp1 = Op1;
3859      Opc = ISD::OR;
3860      Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3861      Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3862      break;
3863    }
3864  } else {
3865    // Integer comparisons.
3866    switch (SetCCOpcode) {
3867    default: llvm_unreachable("Illegal integer comparison");
3868    case ISD::SETNE:  Invert = true;
3869    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3870    case ISD::SETLT:  Swap = true;
3871    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3872    case ISD::SETLE:  Swap = true;
3873    case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3874    case ISD::SETULT: Swap = true;
3875    case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3876    case ISD::SETULE: Swap = true;
3877    case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3878    }
3879
3880    // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3881    if (Opc == ARMISD::VCEQ) {
3882
3883      SDValue AndOp;
3884      if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3885        AndOp = Op0;
3886      else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3887        AndOp = Op1;
3888
3889      // Ignore bitconvert.
3890      if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3891        AndOp = AndOp.getOperand(0);
3892
3893      if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3894        Opc = ARMISD::VTST;
3895        Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3896        Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3897        Invert = !Invert;
3898      }
3899    }
3900  }
3901
3902  if (Swap)
3903    std::swap(Op0, Op1);
3904
3905  // If one of the operands is a constant vector zero, attempt to fold the
3906  // comparison to a specialized compare-against-zero form.
3907  SDValue SingleOp;
3908  if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3909    SingleOp = Op0;
3910  else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3911    if (Opc == ARMISD::VCGE)
3912      Opc = ARMISD::VCLEZ;
3913    else if (Opc == ARMISD::VCGT)
3914      Opc = ARMISD::VCLTZ;
3915    SingleOp = Op1;
3916  }
3917
3918  SDValue Result;
3919  if (SingleOp.getNode()) {
3920    switch (Opc) {
3921    case ARMISD::VCEQ:
3922      Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3923    case ARMISD::VCGE:
3924      Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3925    case ARMISD::VCLEZ:
3926      Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3927    case ARMISD::VCGT:
3928      Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3929    case ARMISD::VCLTZ:
3930      Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3931    default:
3932      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3933    }
3934  } else {
3935     Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3936  }
3937
3938  if (Invert)
3939    Result = DAG.getNOT(dl, Result, VT);
3940
3941  return Result;
3942}
3943
3944/// isNEONModifiedImm - Check if the specified splat value corresponds to a
3945/// valid vector constant for a NEON instruction with a "modified immediate"
3946/// operand (e.g., VMOV).  If so, return the encoded value.
3947static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3948                                 unsigned SplatBitSize, SelectionDAG &DAG,
3949                                 EVT &VT, bool is128Bits, NEONModImmType type) {
3950  unsigned OpCmode, Imm;
3951
3952  // SplatBitSize is set to the smallest size that splats the vector, so a
3953  // zero vector will always have SplatBitSize == 8.  However, NEON modified
3954  // immediate instructions others than VMOV do not support the 8-bit encoding
3955  // of a zero vector, and the default encoding of zero is supposed to be the
3956  // 32-bit version.
3957  if (SplatBits == 0)
3958    SplatBitSize = 32;
3959
3960  switch (SplatBitSize) {
3961  case 8:
3962    if (type != VMOVModImm)
3963      return SDValue();
3964    // Any 1-byte value is OK.  Op=0, Cmode=1110.
3965    assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3966    OpCmode = 0xe;
3967    Imm = SplatBits;
3968    VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3969    break;
3970
3971  case 16:
3972    // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3973    VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3974    if ((SplatBits & ~0xff) == 0) {
3975      // Value = 0x00nn: Op=x, Cmode=100x.
3976      OpCmode = 0x8;
3977      Imm = SplatBits;
3978      break;
3979    }
3980    if ((SplatBits & ~0xff00) == 0) {
3981      // Value = 0xnn00: Op=x, Cmode=101x.
3982      OpCmode = 0xa;
3983      Imm = SplatBits >> 8;
3984      break;
3985    }
3986    return SDValue();
3987
3988  case 32:
3989    // NEON's 32-bit VMOV supports splat values where:
3990    // * only one byte is nonzero, or
3991    // * the least significant byte is 0xff and the second byte is nonzero, or
3992    // * the least significant 2 bytes are 0xff and the third is nonzero.
3993    VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3994    if ((SplatBits & ~0xff) == 0) {
3995      // Value = 0x000000nn: Op=x, Cmode=000x.
3996      OpCmode = 0;
3997      Imm = SplatBits;
3998      break;
3999    }
4000    if ((SplatBits & ~0xff00) == 0) {
4001      // Value = 0x0000nn00: Op=x, Cmode=001x.
4002      OpCmode = 0x2;
4003      Imm = SplatBits >> 8;
4004      break;
4005    }
4006    if ((SplatBits & ~0xff0000) == 0) {
4007      // Value = 0x00nn0000: Op=x, Cmode=010x.
4008      OpCmode = 0x4;
4009      Imm = SplatBits >> 16;
4010      break;
4011    }
4012    if ((SplatBits & ~0xff000000) == 0) {
4013      // Value = 0xnn000000: Op=x, Cmode=011x.
4014      OpCmode = 0x6;
4015      Imm = SplatBits >> 24;
4016      break;
4017    }
4018
4019    // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4020    if (type == OtherModImm) return SDValue();
4021
4022    if ((SplatBits & ~0xffff) == 0 &&
4023        ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4024      // Value = 0x0000nnff: Op=x, Cmode=1100.
4025      OpCmode = 0xc;
4026      Imm = SplatBits >> 8;
4027      SplatBits |= 0xff;
4028      break;
4029    }
4030
4031    if ((SplatBits & ~0xffffff) == 0 &&
4032        ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4033      // Value = 0x00nnffff: Op=x, Cmode=1101.
4034      OpCmode = 0xd;
4035      Imm = SplatBits >> 16;
4036      SplatBits |= 0xffff;
4037      break;
4038    }
4039
4040    // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4041    // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4042    // VMOV.I32.  A (very) minor optimization would be to replicate the value
4043    // and fall through here to test for a valid 64-bit splat.  But, then the
4044    // caller would also need to check and handle the change in size.
4045    return SDValue();
4046
4047  case 64: {
4048    if (type != VMOVModImm)
4049      return SDValue();
4050    // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4051    uint64_t BitMask = 0xff;
4052    uint64_t Val = 0;
4053    unsigned ImmMask = 1;
4054    Imm = 0;
4055    for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4056      if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4057        Val |= BitMask;
4058        Imm |= ImmMask;
4059      } else if ((SplatBits & BitMask) != 0) {
4060        return SDValue();
4061      }
4062      BitMask <<= 8;
4063      ImmMask <<= 1;
4064    }
4065    // Op=1, Cmode=1110.
4066    OpCmode = 0x1e;
4067    SplatBits = Val;
4068    VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4069    break;
4070  }
4071
4072  default:
4073    llvm_unreachable("unexpected size for isNEONModifiedImm");
4074  }
4075
4076  unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4077  return DAG.getTargetConstant(EncodedVal, MVT::i32);
4078}
4079
4080SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4081                                           const ARMSubtarget *ST) const {
4082  if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4083    return SDValue();
4084
4085  ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4086  assert(Op.getValueType() == MVT::f32 &&
4087         "ConstantFP custom lowering should only occur for f32.");
4088
4089  // Try splatting with a VMOV.f32...
4090  APFloat FPVal = CFP->getValueAPF();
4091  int ImmVal = ARM_AM::getFP32Imm(FPVal);
4092  if (ImmVal != -1) {
4093    DebugLoc DL = Op.getDebugLoc();
4094    SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4095    SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4096                                      NewVal);
4097    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4098                       DAG.getConstant(0, MVT::i32));
4099  }
4100
4101  // If that fails, try a VMOV.i32
4102  EVT VMovVT;
4103  unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4104  SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4105                                     VMOVModImm);
4106  if (NewVal != SDValue()) {
4107    DebugLoc DL = Op.getDebugLoc();
4108    SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4109                                      NewVal);
4110    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4111                                       VecConstant);
4112    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4113                       DAG.getConstant(0, MVT::i32));
4114  }
4115
4116  // Finally, try a VMVN.i32
4117  NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4118                             VMVNModImm);
4119  if (NewVal != SDValue()) {
4120    DebugLoc DL = Op.getDebugLoc();
4121    SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4122    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4123                                       VecConstant);
4124    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4125                       DAG.getConstant(0, MVT::i32));
4126  }
4127
4128  return SDValue();
4129}
4130
4131// check if an VEXT instruction can handle the shuffle mask when the
4132// vector sources of the shuffle are the same.
4133static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4134  unsigned NumElts = VT.getVectorNumElements();
4135
4136  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4137  if (M[0] < 0)
4138    return false;
4139
4140  Imm = M[0];
4141
4142  // If this is a VEXT shuffle, the immediate value is the index of the first
4143  // element.  The other shuffle indices must be the successive elements after
4144  // the first one.
4145  unsigned ExpectedElt = Imm;
4146  for (unsigned i = 1; i < NumElts; ++i) {
4147    // Increment the expected index.  If it wraps around, just follow it
4148    // back to index zero and keep going.
4149    ++ExpectedElt;
4150    if (ExpectedElt == NumElts)
4151      ExpectedElt = 0;
4152
4153    if (M[i] < 0) continue; // ignore UNDEF indices
4154    if (ExpectedElt != static_cast<unsigned>(M[i]))
4155      return false;
4156  }
4157
4158  return true;
4159}
4160
4161
4162static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4163                       bool &ReverseVEXT, unsigned &Imm) {
4164  unsigned NumElts = VT.getVectorNumElements();
4165  ReverseVEXT = false;
4166
4167  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4168  if (M[0] < 0)
4169    return false;
4170
4171  Imm = M[0];
4172
4173  // If this is a VEXT shuffle, the immediate value is the index of the first
4174  // element.  The other shuffle indices must be the successive elements after
4175  // the first one.
4176  unsigned ExpectedElt = Imm;
4177  for (unsigned i = 1; i < NumElts; ++i) {
4178    // Increment the expected index.  If it wraps around, it may still be
4179    // a VEXT but the source vectors must be swapped.
4180    ExpectedElt += 1;
4181    if (ExpectedElt == NumElts * 2) {
4182      ExpectedElt = 0;
4183      ReverseVEXT = true;
4184    }
4185
4186    if (M[i] < 0) continue; // ignore UNDEF indices
4187    if (ExpectedElt != static_cast<unsigned>(M[i]))
4188      return false;
4189  }
4190
4191  // Adjust the index value if the source operands will be swapped.
4192  if (ReverseVEXT)
4193    Imm -= NumElts;
4194
4195  return true;
4196}
4197
4198/// isVREVMask - Check if a vector shuffle corresponds to a VREV
4199/// instruction with the specified blocksize.  (The order of the elements
4200/// within each block of the vector is reversed.)
4201static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4202  assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4203         "Only possible block sizes for VREV are: 16, 32, 64");
4204
4205  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4206  if (EltSz == 64)
4207    return false;
4208
4209  unsigned NumElts = VT.getVectorNumElements();
4210  unsigned BlockElts = M[0] + 1;
4211  // If the first shuffle index is UNDEF, be optimistic.
4212  if (M[0] < 0)
4213    BlockElts = BlockSize / EltSz;
4214
4215  if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4216    return false;
4217
4218  for (unsigned i = 0; i < NumElts; ++i) {
4219    if (M[i] < 0) continue; // ignore UNDEF indices
4220    if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4221      return false;
4222  }
4223
4224  return true;
4225}
4226
4227static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4228  // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4229  // range, then 0 is placed into the resulting vector. So pretty much any mask
4230  // of 8 elements can work here.
4231  return VT == MVT::v8i8 && M.size() == 8;
4232}
4233
4234static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4235  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4236  if (EltSz == 64)
4237    return false;
4238
4239  unsigned NumElts = VT.getVectorNumElements();
4240  WhichResult = (M[0] == 0 ? 0 : 1);
4241  for (unsigned i = 0; i < NumElts; i += 2) {
4242    if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4243        (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4244      return false;
4245  }
4246  return true;
4247}
4248
4249/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4250/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4251/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4252static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4253  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4254  if (EltSz == 64)
4255    return false;
4256
4257  unsigned NumElts = VT.getVectorNumElements();
4258  WhichResult = (M[0] == 0 ? 0 : 1);
4259  for (unsigned i = 0; i < NumElts; i += 2) {
4260    if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4261        (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4262      return false;
4263  }
4264  return true;
4265}
4266
4267static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4268  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4269  if (EltSz == 64)
4270    return false;
4271
4272  unsigned NumElts = VT.getVectorNumElements();
4273  WhichResult = (M[0] == 0 ? 0 : 1);
4274  for (unsigned i = 0; i != NumElts; ++i) {
4275    if (M[i] < 0) continue; // ignore UNDEF indices
4276    if ((unsigned) M[i] != 2 * i + WhichResult)
4277      return false;
4278  }
4279
4280  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4281  if (VT.is64BitVector() && EltSz == 32)
4282    return false;
4283
4284  return true;
4285}
4286
4287/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4288/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4289/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4290static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4291  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4292  if (EltSz == 64)
4293    return false;
4294
4295  unsigned Half = VT.getVectorNumElements() / 2;
4296  WhichResult = (M[0] == 0 ? 0 : 1);
4297  for (unsigned j = 0; j != 2; ++j) {
4298    unsigned Idx = WhichResult;
4299    for (unsigned i = 0; i != Half; ++i) {
4300      int MIdx = M[i + j * Half];
4301      if (MIdx >= 0 && (unsigned) MIdx != Idx)
4302        return false;
4303      Idx += 2;
4304    }
4305  }
4306
4307  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4308  if (VT.is64BitVector() && EltSz == 32)
4309    return false;
4310
4311  return true;
4312}
4313
4314static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4315  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4316  if (EltSz == 64)
4317    return false;
4318
4319  unsigned NumElts = VT.getVectorNumElements();
4320  WhichResult = (M[0] == 0 ? 0 : 1);
4321  unsigned Idx = WhichResult * NumElts / 2;
4322  for (unsigned i = 0; i != NumElts; i += 2) {
4323    if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4324        (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4325      return false;
4326    Idx += 1;
4327  }
4328
4329  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4330  if (VT.is64BitVector() && EltSz == 32)
4331    return false;
4332
4333  return true;
4334}
4335
4336/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4337/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4338/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4339static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4340  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4341  if (EltSz == 64)
4342    return false;
4343
4344  unsigned NumElts = VT.getVectorNumElements();
4345  WhichResult = (M[0] == 0 ? 0 : 1);
4346  unsigned Idx = WhichResult * NumElts / 2;
4347  for (unsigned i = 0; i != NumElts; i += 2) {
4348    if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4349        (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4350      return false;
4351    Idx += 1;
4352  }
4353
4354  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4355  if (VT.is64BitVector() && EltSz == 32)
4356    return false;
4357
4358  return true;
4359}
4360
4361/// \return true if this is a reverse operation on an vector.
4362static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4363  unsigned NumElts = VT.getVectorNumElements();
4364  // Make sure the mask has the right size.
4365  if (NumElts != M.size())
4366      return false;
4367
4368  // Look for <15, ..., 3, -1, 1, 0>.
4369  for (unsigned i = 0; i != NumElts; ++i)
4370    if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4371      return false;
4372
4373  return true;
4374}
4375
4376// If N is an integer constant that can be moved into a register in one
4377// instruction, return an SDValue of such a constant (will become a MOV
4378// instruction).  Otherwise return null.
4379static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4380                                     const ARMSubtarget *ST, DebugLoc dl) {
4381  uint64_t Val;
4382  if (!isa<ConstantSDNode>(N))
4383    return SDValue();
4384  Val = cast<ConstantSDNode>(N)->getZExtValue();
4385
4386  if (ST->isThumb1Only()) {
4387    if (Val <= 255 || ~Val <= 255)
4388      return DAG.getConstant(Val, MVT::i32);
4389  } else {
4390    if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4391      return DAG.getConstant(Val, MVT::i32);
4392  }
4393  return SDValue();
4394}
4395
4396// If this is a case we can't handle, return null and let the default
4397// expansion code take care of it.
4398SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4399                                             const ARMSubtarget *ST) const {
4400  BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4401  DebugLoc dl = Op.getDebugLoc();
4402  EVT VT = Op.getValueType();
4403
4404  APInt SplatBits, SplatUndef;
4405  unsigned SplatBitSize;
4406  bool HasAnyUndefs;
4407  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4408    if (SplatBitSize <= 64) {
4409      // Check if an immediate VMOV works.
4410      EVT VmovVT;
4411      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4412                                      SplatUndef.getZExtValue(), SplatBitSize,
4413                                      DAG, VmovVT, VT.is128BitVector(),
4414                                      VMOVModImm);
4415      if (Val.getNode()) {
4416        SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4417        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4418      }
4419
4420      // Try an immediate VMVN.
4421      uint64_t NegatedImm = (~SplatBits).getZExtValue();
4422      Val = isNEONModifiedImm(NegatedImm,
4423                                      SplatUndef.getZExtValue(), SplatBitSize,
4424                                      DAG, VmovVT, VT.is128BitVector(),
4425                                      VMVNModImm);
4426      if (Val.getNode()) {
4427        SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4428        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4429      }
4430
4431      // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4432      if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4433        int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4434        if (ImmVal != -1) {
4435          SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4436          return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4437        }
4438      }
4439    }
4440  }
4441
4442  // Scan through the operands to see if only one value is used.
4443  //
4444  // As an optimisation, even if more than one value is used it may be more
4445  // profitable to splat with one value then change some lanes.
4446  //
4447  // Heuristically we decide to do this if the vector has a "dominant" value,
4448  // defined as splatted to more than half of the lanes.
4449  unsigned NumElts = VT.getVectorNumElements();
4450  bool isOnlyLowElement = true;
4451  bool usesOnlyOneValue = true;
4452  bool hasDominantValue = false;
4453  bool isConstant = true;
4454
4455  // Map of the number of times a particular SDValue appears in the
4456  // element list.
4457  DenseMap<SDValue, unsigned> ValueCounts;
4458  SDValue Value;
4459  for (unsigned i = 0; i < NumElts; ++i) {
4460    SDValue V = Op.getOperand(i);
4461    if (V.getOpcode() == ISD::UNDEF)
4462      continue;
4463    if (i > 0)
4464      isOnlyLowElement = false;
4465    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4466      isConstant = false;
4467
4468    ValueCounts.insert(std::make_pair(V, 0));
4469    unsigned &Count = ValueCounts[V];
4470
4471    // Is this value dominant? (takes up more than half of the lanes)
4472    if (++Count > (NumElts / 2)) {
4473      hasDominantValue = true;
4474      Value = V;
4475    }
4476  }
4477  if (ValueCounts.size() != 1)
4478    usesOnlyOneValue = false;
4479  if (!Value.getNode() && ValueCounts.size() > 0)
4480    Value = ValueCounts.begin()->first;
4481
4482  if (ValueCounts.size() == 0)
4483    return DAG.getUNDEF(VT);
4484
4485  if (isOnlyLowElement)
4486    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4487
4488  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4489
4490  // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4491  // i32 and try again.
4492  if (hasDominantValue && EltSize <= 32) {
4493    if (!isConstant) {
4494      SDValue N;
4495
4496      // If we are VDUPing a value that comes directly from a vector, that will
4497      // cause an unnecessary move to and from a GPR, where instead we could
4498      // just use VDUPLANE. We can only do this if the lane being extracted
4499      // is at a constant index, as the VDUP from lane instructions only have
4500      // constant-index forms.
4501      if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4502          isa<ConstantSDNode>(Value->getOperand(1))) {
4503        // We need to create a new undef vector to use for the VDUPLANE if the
4504        // size of the vector from which we get the value is different than the
4505        // size of the vector that we need to create. We will insert the element
4506        // such that the register coalescer will remove unnecessary copies.
4507        if (VT != Value->getOperand(0).getValueType()) {
4508          ConstantSDNode *constIndex;
4509          constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4510          assert(constIndex && "The index is not a constant!");
4511          unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4512                             VT.getVectorNumElements();
4513          N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4514                 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4515                        Value, DAG.getConstant(index, MVT::i32)),
4516                           DAG.getConstant(index, MVT::i32));
4517        } else
4518          N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4519                        Value->getOperand(0), Value->getOperand(1));
4520      } else
4521        N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4522
4523      if (!usesOnlyOneValue) {
4524        // The dominant value was splatted as 'N', but we now have to insert
4525        // all differing elements.
4526        for (unsigned I = 0; I < NumElts; ++I) {
4527          if (Op.getOperand(I) == Value)
4528            continue;
4529          SmallVector<SDValue, 3> Ops;
4530          Ops.push_back(N);
4531          Ops.push_back(Op.getOperand(I));
4532          Ops.push_back(DAG.getConstant(I, MVT::i32));
4533          N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4534        }
4535      }
4536      return N;
4537    }
4538    if (VT.getVectorElementType().isFloatingPoint()) {
4539      SmallVector<SDValue, 8> Ops;
4540      for (unsigned i = 0; i < NumElts; ++i)
4541        Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4542                                  Op.getOperand(i)));
4543      EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4544      SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4545      Val = LowerBUILD_VECTOR(Val, DAG, ST);
4546      if (Val.getNode())
4547        return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4548    }
4549    if (usesOnlyOneValue) {
4550      SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4551      if (isConstant && Val.getNode())
4552        return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4553    }
4554  }
4555
4556  // If all elements are constants and the case above didn't get hit, fall back
4557  // to the default expansion, which will generate a load from the constant
4558  // pool.
4559  if (isConstant)
4560    return SDValue();
4561
4562  // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4563  if (NumElts >= 4) {
4564    SDValue shuffle = ReconstructShuffle(Op, DAG);
4565    if (shuffle != SDValue())
4566      return shuffle;
4567  }
4568
4569  // Vectors with 32- or 64-bit elements can be built by directly assigning
4570  // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4571  // will be legalized.
4572  if (EltSize >= 32) {
4573    // Do the expansion with floating-point types, since that is what the VFP
4574    // registers are defined to use, and since i64 is not legal.
4575    EVT EltVT = EVT::getFloatingPointVT(EltSize);
4576    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4577    SmallVector<SDValue, 8> Ops;
4578    for (unsigned i = 0; i < NumElts; ++i)
4579      Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4580    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4581    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4582  }
4583
4584  return SDValue();
4585}
4586
4587// Gather data to see if the operation can be modelled as a
4588// shuffle in combination with VEXTs.
4589SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4590                                              SelectionDAG &DAG) const {
4591  DebugLoc dl = Op.getDebugLoc();
4592  EVT VT = Op.getValueType();
4593  unsigned NumElts = VT.getVectorNumElements();
4594
4595  SmallVector<SDValue, 2> SourceVecs;
4596  SmallVector<unsigned, 2> MinElts;
4597  SmallVector<unsigned, 2> MaxElts;
4598
4599  for (unsigned i = 0; i < NumElts; ++i) {
4600    SDValue V = Op.getOperand(i);
4601    if (V.getOpcode() == ISD::UNDEF)
4602      continue;
4603    else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4604      // A shuffle can only come from building a vector from various
4605      // elements of other vectors.
4606      return SDValue();
4607    } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4608               VT.getVectorElementType()) {
4609      // This code doesn't know how to handle shuffles where the vector
4610      // element types do not match (this happens because type legalization
4611      // promotes the return type of EXTRACT_VECTOR_ELT).
4612      // FIXME: It might be appropriate to extend this code to handle
4613      // mismatched types.
4614      return SDValue();
4615    }
4616
4617    // Record this extraction against the appropriate vector if possible...
4618    SDValue SourceVec = V.getOperand(0);
4619    // If the element number isn't a constant, we can't effectively
4620    // analyze what's going on.
4621    if (!isa<ConstantSDNode>(V.getOperand(1)))
4622      return SDValue();
4623    unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4624    bool FoundSource = false;
4625    for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4626      if (SourceVecs[j] == SourceVec) {
4627        if (MinElts[j] > EltNo)
4628          MinElts[j] = EltNo;
4629        if (MaxElts[j] < EltNo)
4630          MaxElts[j] = EltNo;
4631        FoundSource = true;
4632        break;
4633      }
4634    }
4635
4636    // Or record a new source if not...
4637    if (!FoundSource) {
4638      SourceVecs.push_back(SourceVec);
4639      MinElts.push_back(EltNo);
4640      MaxElts.push_back(EltNo);
4641    }
4642  }
4643
4644  // Currently only do something sane when at most two source vectors
4645  // involved.
4646  if (SourceVecs.size() > 2)
4647    return SDValue();
4648
4649  SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4650  int VEXTOffsets[2] = {0, 0};
4651
4652  // This loop extracts the usage patterns of the source vectors
4653  // and prepares appropriate SDValues for a shuffle if possible.
4654  for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4655    if (SourceVecs[i].getValueType() == VT) {
4656      // No VEXT necessary
4657      ShuffleSrcs[i] = SourceVecs[i];
4658      VEXTOffsets[i] = 0;
4659      continue;
4660    } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4661      // It probably isn't worth padding out a smaller vector just to
4662      // break it down again in a shuffle.
4663      return SDValue();
4664    }
4665
4666    // Since only 64-bit and 128-bit vectors are legal on ARM and
4667    // we've eliminated the other cases...
4668    assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4669           "unexpected vector sizes in ReconstructShuffle");
4670
4671    if (MaxElts[i] - MinElts[i] >= NumElts) {
4672      // Span too large for a VEXT to cope
4673      return SDValue();
4674    }
4675
4676    if (MinElts[i] >= NumElts) {
4677      // The extraction can just take the second half
4678      VEXTOffsets[i] = NumElts;
4679      ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4680                                   SourceVecs[i],
4681                                   DAG.getIntPtrConstant(NumElts));
4682    } else if (MaxElts[i] < NumElts) {
4683      // The extraction can just take the first half
4684      VEXTOffsets[i] = 0;
4685      ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4686                                   SourceVecs[i],
4687                                   DAG.getIntPtrConstant(0));
4688    } else {
4689      // An actual VEXT is needed
4690      VEXTOffsets[i] = MinElts[i];
4691      SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4692                                     SourceVecs[i],
4693                                     DAG.getIntPtrConstant(0));
4694      SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4695                                     SourceVecs[i],
4696                                     DAG.getIntPtrConstant(NumElts));
4697      ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4698                                   DAG.getConstant(VEXTOffsets[i], MVT::i32));
4699    }
4700  }
4701
4702  SmallVector<int, 8> Mask;
4703
4704  for (unsigned i = 0; i < NumElts; ++i) {
4705    SDValue Entry = Op.getOperand(i);
4706    if (Entry.getOpcode() == ISD::UNDEF) {
4707      Mask.push_back(-1);
4708      continue;
4709    }
4710
4711    SDValue ExtractVec = Entry.getOperand(0);
4712    int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4713                                          .getOperand(1))->getSExtValue();
4714    if (ExtractVec == SourceVecs[0]) {
4715      Mask.push_back(ExtractElt - VEXTOffsets[0]);
4716    } else {
4717      Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4718    }
4719  }
4720
4721  // Final check before we try to produce nonsense...
4722  if (isShuffleMaskLegal(Mask, VT))
4723    return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4724                                &Mask[0]);
4725
4726  return SDValue();
4727}
4728
4729/// isShuffleMaskLegal - Targets can use this to indicate that they only
4730/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4731/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4732/// are assumed to be legal.
4733bool
4734ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4735                                      EVT VT) const {
4736  if (VT.getVectorNumElements() == 4 &&
4737      (VT.is128BitVector() || VT.is64BitVector())) {
4738    unsigned PFIndexes[4];
4739    for (unsigned i = 0; i != 4; ++i) {
4740      if (M[i] < 0)
4741        PFIndexes[i] = 8;
4742      else
4743        PFIndexes[i] = M[i];
4744    }
4745
4746    // Compute the index in the perfect shuffle table.
4747    unsigned PFTableIndex =
4748      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4749    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4750    unsigned Cost = (PFEntry >> 30);
4751
4752    if (Cost <= 4)
4753      return true;
4754  }
4755
4756  bool ReverseVEXT;
4757  unsigned Imm, WhichResult;
4758
4759  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4760  return (EltSize >= 32 ||
4761          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4762          isVREVMask(M, VT, 64) ||
4763          isVREVMask(M, VT, 32) ||
4764          isVREVMask(M, VT, 16) ||
4765          isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4766          isVTBLMask(M, VT) ||
4767          isVTRNMask(M, VT, WhichResult) ||
4768          isVUZPMask(M, VT, WhichResult) ||
4769          isVZIPMask(M, VT, WhichResult) ||
4770          isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4771          isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4772          isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4773          ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4774}
4775
4776/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4777/// the specified operations to build the shuffle.
4778static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4779                                      SDValue RHS, SelectionDAG &DAG,
4780                                      DebugLoc dl) {
4781  unsigned OpNum = (PFEntry >> 26) & 0x0F;
4782  unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4783  unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4784
4785  enum {
4786    OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4787    OP_VREV,
4788    OP_VDUP0,
4789    OP_VDUP1,
4790    OP_VDUP2,
4791    OP_VDUP3,
4792    OP_VEXT1,
4793    OP_VEXT2,
4794    OP_VEXT3,
4795    OP_VUZPL, // VUZP, left result
4796    OP_VUZPR, // VUZP, right result
4797    OP_VZIPL, // VZIP, left result
4798    OP_VZIPR, // VZIP, right result
4799    OP_VTRNL, // VTRN, left result
4800    OP_VTRNR  // VTRN, right result
4801  };
4802
4803  if (OpNum == OP_COPY) {
4804    if (LHSID == (1*9+2)*9+3) return LHS;
4805    assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4806    return RHS;
4807  }
4808
4809  SDValue OpLHS, OpRHS;
4810  OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4811  OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4812  EVT VT = OpLHS.getValueType();
4813
4814  switch (OpNum) {
4815  default: llvm_unreachable("Unknown shuffle opcode!");
4816  case OP_VREV:
4817    // VREV divides the vector in half and swaps within the half.
4818    if (VT.getVectorElementType() == MVT::i32 ||
4819        VT.getVectorElementType() == MVT::f32)
4820      return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4821    // vrev <4 x i16> -> VREV32
4822    if (VT.getVectorElementType() == MVT::i16)
4823      return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4824    // vrev <4 x i8> -> VREV16
4825    assert(VT.getVectorElementType() == MVT::i8);
4826    return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4827  case OP_VDUP0:
4828  case OP_VDUP1:
4829  case OP_VDUP2:
4830  case OP_VDUP3:
4831    return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4832                       OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4833  case OP_VEXT1:
4834  case OP_VEXT2:
4835  case OP_VEXT3:
4836    return DAG.getNode(ARMISD::VEXT, dl, VT,
4837                       OpLHS, OpRHS,
4838                       DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4839  case OP_VUZPL:
4840  case OP_VUZPR:
4841    return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4842                       OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4843  case OP_VZIPL:
4844  case OP_VZIPR:
4845    return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4846                       OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4847  case OP_VTRNL:
4848  case OP_VTRNR:
4849    return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4850                       OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4851  }
4852}
4853
4854static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4855                                       ArrayRef<int> ShuffleMask,
4856                                       SelectionDAG &DAG) {
4857  // Check to see if we can use the VTBL instruction.
4858  SDValue V1 = Op.getOperand(0);
4859  SDValue V2 = Op.getOperand(1);
4860  DebugLoc DL = Op.getDebugLoc();
4861
4862  SmallVector<SDValue, 8> VTBLMask;
4863  for (ArrayRef<int>::iterator
4864         I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4865    VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4866
4867  if (V2.getNode()->getOpcode() == ISD::UNDEF)
4868    return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4869                       DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4870                                   &VTBLMask[0], 8));
4871
4872  return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4873                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4874                                 &VTBLMask[0], 8));
4875}
4876
4877static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4878                                                      SelectionDAG &DAG) {
4879  DebugLoc DL = Op.getDebugLoc();
4880  SDValue OpLHS = Op.getOperand(0);
4881  EVT VT = OpLHS.getValueType();
4882
4883  assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4884         "Expect an v8i16/v16i8 type");
4885  OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4886  // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4887  // extract the first 8 bytes into the top double word and the last 8 bytes
4888  // into the bottom double word. The v8i16 case is similar.
4889  unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4890  return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4891                     DAG.getConstant(ExtractNum, MVT::i32));
4892}
4893
4894static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4895  SDValue V1 = Op.getOperand(0);
4896  SDValue V2 = Op.getOperand(1);
4897  DebugLoc dl = Op.getDebugLoc();
4898  EVT VT = Op.getValueType();
4899  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4900
4901  // Convert shuffles that are directly supported on NEON to target-specific
4902  // DAG nodes, instead of keeping them as shuffles and matching them again
4903  // during code selection.  This is more efficient and avoids the possibility
4904  // of inconsistencies between legalization and selection.
4905  // FIXME: floating-point vectors should be canonicalized to integer vectors
4906  // of the same time so that they get CSEd properly.
4907  ArrayRef<int> ShuffleMask = SVN->getMask();
4908
4909  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4910  if (EltSize <= 32) {
4911    if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4912      int Lane = SVN->getSplatIndex();
4913      // If this is undef splat, generate it via "just" vdup, if possible.
4914      if (Lane == -1) Lane = 0;
4915
4916      // Test if V1 is a SCALAR_TO_VECTOR.
4917      if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4918        return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4919      }
4920      // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4921      // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4922      // reaches it).
4923      if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4924          !isa<ConstantSDNode>(V1.getOperand(0))) {
4925        bool IsScalarToVector = true;
4926        for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4927          if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4928            IsScalarToVector = false;
4929            break;
4930          }
4931        if (IsScalarToVector)
4932          return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4933      }
4934      return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4935                         DAG.getConstant(Lane, MVT::i32));
4936    }
4937
4938    bool ReverseVEXT;
4939    unsigned Imm;
4940    if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4941      if (ReverseVEXT)
4942        std::swap(V1, V2);
4943      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4944                         DAG.getConstant(Imm, MVT::i32));
4945    }
4946
4947    if (isVREVMask(ShuffleMask, VT, 64))
4948      return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4949    if (isVREVMask(ShuffleMask, VT, 32))
4950      return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4951    if (isVREVMask(ShuffleMask, VT, 16))
4952      return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4953
4954    if (V2->getOpcode() == ISD::UNDEF &&
4955        isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4956      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4957                         DAG.getConstant(Imm, MVT::i32));
4958    }
4959
4960    // Check for Neon shuffles that modify both input vectors in place.
4961    // If both results are used, i.e., if there are two shuffles with the same
4962    // source operands and with masks corresponding to both results of one of
4963    // these operations, DAG memoization will ensure that a single node is
4964    // used for both shuffles.
4965    unsigned WhichResult;
4966    if (isVTRNMask(ShuffleMask, VT, WhichResult))
4967      return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4968                         V1, V2).getValue(WhichResult);
4969    if (isVUZPMask(ShuffleMask, VT, WhichResult))
4970      return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4971                         V1, V2).getValue(WhichResult);
4972    if (isVZIPMask(ShuffleMask, VT, WhichResult))
4973      return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4974                         V1, V2).getValue(WhichResult);
4975
4976    if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4977      return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4978                         V1, V1).getValue(WhichResult);
4979    if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4980      return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4981                         V1, V1).getValue(WhichResult);
4982    if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4983      return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4984                         V1, V1).getValue(WhichResult);
4985  }
4986
4987  // If the shuffle is not directly supported and it has 4 elements, use
4988  // the PerfectShuffle-generated table to synthesize it from other shuffles.
4989  unsigned NumElts = VT.getVectorNumElements();
4990  if (NumElts == 4) {
4991    unsigned PFIndexes[4];
4992    for (unsigned i = 0; i != 4; ++i) {
4993      if (ShuffleMask[i] < 0)
4994        PFIndexes[i] = 8;
4995      else
4996        PFIndexes[i] = ShuffleMask[i];
4997    }
4998
4999    // Compute the index in the perfect shuffle table.
5000    unsigned PFTableIndex =
5001      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5002    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5003    unsigned Cost = (PFEntry >> 30);
5004
5005    if (Cost <= 4)
5006      return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5007  }
5008
5009  // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5010  if (EltSize >= 32) {
5011    // Do the expansion with floating-point types, since that is what the VFP
5012    // registers are defined to use, and since i64 is not legal.
5013    EVT EltVT = EVT::getFloatingPointVT(EltSize);
5014    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5015    V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5016    V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5017    SmallVector<SDValue, 8> Ops;
5018    for (unsigned i = 0; i < NumElts; ++i) {
5019      if (ShuffleMask[i] < 0)
5020        Ops.push_back(DAG.getUNDEF(EltVT));
5021      else
5022        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5023                                  ShuffleMask[i] < (int)NumElts ? V1 : V2,
5024                                  DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5025                                                  MVT::i32)));
5026    }
5027    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5028    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5029  }
5030
5031  if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5032    return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5033
5034  if (VT == MVT::v8i8) {
5035    SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5036    if (NewOp.getNode())
5037      return NewOp;
5038  }
5039
5040  return SDValue();
5041}
5042
5043static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5044  // INSERT_VECTOR_ELT is legal only for immediate indexes.
5045  SDValue Lane = Op.getOperand(2);
5046  if (!isa<ConstantSDNode>(Lane))
5047    return SDValue();
5048
5049  return Op;
5050}
5051
5052static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5053  // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5054  SDValue Lane = Op.getOperand(1);
5055  if (!isa<ConstantSDNode>(Lane))
5056    return SDValue();
5057
5058  SDValue Vec = Op.getOperand(0);
5059  if (Op.getValueType() == MVT::i32 &&
5060      Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5061    DebugLoc dl = Op.getDebugLoc();
5062    return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5063  }
5064
5065  return Op;
5066}
5067
5068static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5069  // The only time a CONCAT_VECTORS operation can have legal types is when
5070  // two 64-bit vectors are concatenated to a 128-bit vector.
5071  assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5072         "unexpected CONCAT_VECTORS");
5073  DebugLoc dl = Op.getDebugLoc();
5074  SDValue Val = DAG.getUNDEF(MVT::v2f64);
5075  SDValue Op0 = Op.getOperand(0);
5076  SDValue Op1 = Op.getOperand(1);
5077  if (Op0.getOpcode() != ISD::UNDEF)
5078    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5079                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5080                      DAG.getIntPtrConstant(0));
5081  if (Op1.getOpcode() != ISD::UNDEF)
5082    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5083                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5084                      DAG.getIntPtrConstant(1));
5085  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5086}
5087
5088/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5089/// element has been zero/sign-extended, depending on the isSigned parameter,
5090/// from an integer type half its size.
5091static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5092                                   bool isSigned) {
5093  // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5094  EVT VT = N->getValueType(0);
5095  if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5096    SDNode *BVN = N->getOperand(0).getNode();
5097    if (BVN->getValueType(0) != MVT::v4i32 ||
5098        BVN->getOpcode() != ISD::BUILD_VECTOR)
5099      return false;
5100    unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5101    unsigned HiElt = 1 - LoElt;
5102    ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5103    ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5104    ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5105    ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5106    if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5107      return false;
5108    if (isSigned) {
5109      if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5110          Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5111        return true;
5112    } else {
5113      if (Hi0->isNullValue() && Hi1->isNullValue())
5114        return true;
5115    }
5116    return false;
5117  }
5118
5119  if (N->getOpcode() != ISD::BUILD_VECTOR)
5120    return false;
5121
5122  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5123    SDNode *Elt = N->getOperand(i).getNode();
5124    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5125      unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5126      unsigned HalfSize = EltSize / 2;
5127      if (isSigned) {
5128        if (!isIntN(HalfSize, C->getSExtValue()))
5129          return false;
5130      } else {
5131        if (!isUIntN(HalfSize, C->getZExtValue()))
5132          return false;
5133      }
5134      continue;
5135    }
5136    return false;
5137  }
5138
5139  return true;
5140}
5141
5142/// isSignExtended - Check if a node is a vector value that is sign-extended
5143/// or a constant BUILD_VECTOR with sign-extended elements.
5144static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5145  if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5146    return true;
5147  if (isExtendedBUILD_VECTOR(N, DAG, true))
5148    return true;
5149  return false;
5150}
5151
5152/// isZeroExtended - Check if a node is a vector value that is zero-extended
5153/// or a constant BUILD_VECTOR with zero-extended elements.
5154static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5155  if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5156    return true;
5157  if (isExtendedBUILD_VECTOR(N, DAG, false))
5158    return true;
5159  return false;
5160}
5161
5162/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5163/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5164/// We insert the required extension here to get the vector to fill a D register.
5165static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5166                                            const EVT &OrigTy,
5167                                            const EVT &ExtTy,
5168                                            unsigned ExtOpcode) {
5169  // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5170  // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5171  // 64-bits we need to insert a new extension so that it will be 64-bits.
5172  assert(ExtTy.is128BitVector() && "Unexpected extension size");
5173  if (OrigTy.getSizeInBits() >= 64)
5174    return N;
5175
5176  // Must extend size to at least 64 bits to be used as an operand for VMULL.
5177  MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5178  EVT NewVT;
5179  switch (OrigSimpleTy) {
5180  default: llvm_unreachable("Unexpected Orig Vector Type");
5181  case MVT::v2i8:
5182  case MVT::v2i16:
5183    NewVT = MVT::v2i32;
5184    break;
5185  case MVT::v4i8:
5186    NewVT = MVT::v4i16;
5187    break;
5188  }
5189  return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5190}
5191
5192/// SkipLoadExtensionForVMULL - return a load of the original vector size that
5193/// does not do any sign/zero extension. If the original vector is less
5194/// than 64 bits, an appropriate extension will be added after the load to
5195/// reach a total size of 64 bits. We have to add the extension separately
5196/// because ARM does not have a sign/zero extending load for vectors.
5197static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5198  SDValue NonExtendingLoad =
5199    DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5200                LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5201                LD->isNonTemporal(), LD->isInvariant(),
5202                LD->getAlignment());
5203  unsigned ExtOp = 0;
5204  switch (LD->getExtensionType()) {
5205  default: llvm_unreachable("Unexpected LoadExtType");
5206  case ISD::EXTLOAD:
5207  case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5208  case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5209  }
5210  MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5211  MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5212  return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5213                                      MemType, ExtType, ExtOp);
5214}
5215
5216/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5217/// extending load, or BUILD_VECTOR with extended elements, return the
5218/// unextended value. The unextended vector should be 64 bits so that it can
5219/// be used as an operand to a VMULL instruction. If the original vector size
5220/// before extension is less than 64 bits we add a an extension to resize
5221/// the vector to 64 bits.
5222static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5223  if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5224    return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5225                                        N->getOperand(0)->getValueType(0),
5226                                        N->getValueType(0),
5227                                        N->getOpcode());
5228
5229  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5230    return SkipLoadExtensionForVMULL(LD, DAG);
5231
5232  // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5233  // have been legalized as a BITCAST from v4i32.
5234  if (N->getOpcode() == ISD::BITCAST) {
5235    SDNode *BVN = N->getOperand(0).getNode();
5236    assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5237           BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5238    unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5239    return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5240                       BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5241  }
5242  // Construct a new BUILD_VECTOR with elements truncated to half the size.
5243  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5244  EVT VT = N->getValueType(0);
5245  unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5246  unsigned NumElts = VT.getVectorNumElements();
5247  MVT TruncVT = MVT::getIntegerVT(EltSize);
5248  SmallVector<SDValue, 8> Ops;
5249  for (unsigned i = 0; i != NumElts; ++i) {
5250    ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5251    const APInt &CInt = C->getAPIntValue();
5252    // Element types smaller than 32 bits are not legal, so use i32 elements.
5253    // The values are implicitly truncated so sext vs. zext doesn't matter.
5254    Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5255  }
5256  return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5257                     MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5258}
5259
5260static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5261  unsigned Opcode = N->getOpcode();
5262  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5263    SDNode *N0 = N->getOperand(0).getNode();
5264    SDNode *N1 = N->getOperand(1).getNode();
5265    return N0->hasOneUse() && N1->hasOneUse() &&
5266      isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5267  }
5268  return false;
5269}
5270
5271static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5272  unsigned Opcode = N->getOpcode();
5273  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5274    SDNode *N0 = N->getOperand(0).getNode();
5275    SDNode *N1 = N->getOperand(1).getNode();
5276    return N0->hasOneUse() && N1->hasOneUse() &&
5277      isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5278  }
5279  return false;
5280}
5281
5282static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5283  // Multiplications are only custom-lowered for 128-bit vectors so that
5284  // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5285  EVT VT = Op.getValueType();
5286  assert(VT.is128BitVector() && VT.isInteger() &&
5287         "unexpected type for custom-lowering ISD::MUL");
5288  SDNode *N0 = Op.getOperand(0).getNode();
5289  SDNode *N1 = Op.getOperand(1).getNode();
5290  unsigned NewOpc = 0;
5291  bool isMLA = false;
5292  bool isN0SExt = isSignExtended(N0, DAG);
5293  bool isN1SExt = isSignExtended(N1, DAG);
5294  if (isN0SExt && isN1SExt)
5295    NewOpc = ARMISD::VMULLs;
5296  else {
5297    bool isN0ZExt = isZeroExtended(N0, DAG);
5298    bool isN1ZExt = isZeroExtended(N1, DAG);
5299    if (isN0ZExt && isN1ZExt)
5300      NewOpc = ARMISD::VMULLu;
5301    else if (isN1SExt || isN1ZExt) {
5302      // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5303      // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5304      if (isN1SExt && isAddSubSExt(N0, DAG)) {
5305        NewOpc = ARMISD::VMULLs;
5306        isMLA = true;
5307      } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5308        NewOpc = ARMISD::VMULLu;
5309        isMLA = true;
5310      } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5311        std::swap(N0, N1);
5312        NewOpc = ARMISD::VMULLu;
5313        isMLA = true;
5314      }
5315    }
5316
5317    if (!NewOpc) {
5318      if (VT == MVT::v2i64)
5319        // Fall through to expand this.  It is not legal.
5320        return SDValue();
5321      else
5322        // Other vector multiplications are legal.
5323        return Op;
5324    }
5325  }
5326
5327  // Legalize to a VMULL instruction.
5328  DebugLoc DL = Op.getDebugLoc();
5329  SDValue Op0;
5330  SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5331  if (!isMLA) {
5332    Op0 = SkipExtensionForVMULL(N0, DAG);
5333    assert(Op0.getValueType().is64BitVector() &&
5334           Op1.getValueType().is64BitVector() &&
5335           "unexpected types for extended operands to VMULL");
5336    return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5337  }
5338
5339  // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5340  // isel lowering to take advantage of no-stall back to back vmul + vmla.
5341  //   vmull q0, d4, d6
5342  //   vmlal q0, d5, d6
5343  // is faster than
5344  //   vaddl q0, d4, d5
5345  //   vmovl q1, d6
5346  //   vmul  q0, q0, q1
5347  SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5348  SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5349  EVT Op1VT = Op1.getValueType();
5350  return DAG.getNode(N0->getOpcode(), DL, VT,
5351                     DAG.getNode(NewOpc, DL, VT,
5352                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5353                     DAG.getNode(NewOpc, DL, VT,
5354                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5355}
5356
5357static SDValue
5358LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5359  // Convert to float
5360  // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5361  // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5362  X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5363  Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5364  X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5365  Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5366  // Get reciprocal estimate.
5367  // float4 recip = vrecpeq_f32(yf);
5368  Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5369                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5370  // Because char has a smaller range than uchar, we can actually get away
5371  // without any newton steps.  This requires that we use a weird bias
5372  // of 0xb000, however (again, this has been exhaustively tested).
5373  // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5374  X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5375  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5376  Y = DAG.getConstant(0xb000, MVT::i32);
5377  Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5378  X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5379  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5380  // Convert back to short.
5381  X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5382  X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5383  return X;
5384}
5385
5386static SDValue
5387LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5388  SDValue N2;
5389  // Convert to float.
5390  // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5391  // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5392  N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5393  N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5394  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5395  N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5396
5397  // Use reciprocal estimate and one refinement step.
5398  // float4 recip = vrecpeq_f32(yf);
5399  // recip *= vrecpsq_f32(yf, recip);
5400  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5401                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5402  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5403                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5404                   N1, N2);
5405  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5406  // Because short has a smaller range than ushort, we can actually get away
5407  // with only a single newton step.  This requires that we use a weird bias
5408  // of 89, however (again, this has been exhaustively tested).
5409  // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5410  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5411  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5412  N1 = DAG.getConstant(0x89, MVT::i32);
5413  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5414  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5415  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5416  // Convert back to integer and return.
5417  // return vmovn_s32(vcvt_s32_f32(result));
5418  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5419  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5420  return N0;
5421}
5422
5423static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5424  EVT VT = Op.getValueType();
5425  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5426         "unexpected type for custom-lowering ISD::SDIV");
5427
5428  DebugLoc dl = Op.getDebugLoc();
5429  SDValue N0 = Op.getOperand(0);
5430  SDValue N1 = Op.getOperand(1);
5431  SDValue N2, N3;
5432
5433  if (VT == MVT::v8i8) {
5434    N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5435    N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5436
5437    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5438                     DAG.getIntPtrConstant(4));
5439    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5440                     DAG.getIntPtrConstant(4));
5441    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5442                     DAG.getIntPtrConstant(0));
5443    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5444                     DAG.getIntPtrConstant(0));
5445
5446    N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5447    N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5448
5449    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5450    N0 = LowerCONCAT_VECTORS(N0, DAG);
5451
5452    N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5453    return N0;
5454  }
5455  return LowerSDIV_v4i16(N0, N1, dl, DAG);
5456}
5457
5458static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5459  EVT VT = Op.getValueType();
5460  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5461         "unexpected type for custom-lowering ISD::UDIV");
5462
5463  DebugLoc dl = Op.getDebugLoc();
5464  SDValue N0 = Op.getOperand(0);
5465  SDValue N1 = Op.getOperand(1);
5466  SDValue N2, N3;
5467
5468  if (VT == MVT::v8i8) {
5469    N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5470    N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5471
5472    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5473                     DAG.getIntPtrConstant(4));
5474    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5475                     DAG.getIntPtrConstant(4));
5476    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5477                     DAG.getIntPtrConstant(0));
5478    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5479                     DAG.getIntPtrConstant(0));
5480
5481    N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5482    N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5483
5484    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5485    N0 = LowerCONCAT_VECTORS(N0, DAG);
5486
5487    N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5488                     DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5489                     N0);
5490    return N0;
5491  }
5492
5493  // v4i16 sdiv ... Convert to float.
5494  // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5495  // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5496  N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5497  N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5498  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5499  SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5500
5501  // Use reciprocal estimate and two refinement steps.
5502  // float4 recip = vrecpeq_f32(yf);
5503  // recip *= vrecpsq_f32(yf, recip);
5504  // recip *= vrecpsq_f32(yf, recip);
5505  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5506                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5507  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5508                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5509                   BN1, N2);
5510  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5511  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5512                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5513                   BN1, N2);
5514  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5515  // Simply multiplying by the reciprocal estimate can leave us a few ulps
5516  // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5517  // and that it will never cause us to return an answer too large).
5518  // float4 result = as_float4(as_int4(xf*recip) + 2);
5519  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5520  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5521  N1 = DAG.getConstant(2, MVT::i32);
5522  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5523  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5524  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5525  // Convert back to integer and return.
5526  // return vmovn_u32(vcvt_s32_f32(result));
5527  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5528  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5529  return N0;
5530}
5531
5532static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5533  EVT VT = Op.getNode()->getValueType(0);
5534  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5535
5536  unsigned Opc;
5537  bool ExtraOp = false;
5538  switch (Op.getOpcode()) {
5539  default: llvm_unreachable("Invalid code");
5540  case ISD::ADDC: Opc = ARMISD::ADDC; break;
5541  case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5542  case ISD::SUBC: Opc = ARMISD::SUBC; break;
5543  case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5544  }
5545
5546  if (!ExtraOp)
5547    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5548                       Op.getOperand(1));
5549  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5550                     Op.getOperand(1), Op.getOperand(2));
5551}
5552
5553static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5554  // Monotonic load/store is legal for all targets
5555  if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5556    return Op;
5557
5558  // Aquire/Release load/store is not legal for targets without a
5559  // dmb or equivalent available.
5560  return SDValue();
5561}
5562
5563
5564static void
5565ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5566                    SelectionDAG &DAG, unsigned NewOp) {
5567  DebugLoc dl = Node->getDebugLoc();
5568  assert (Node->getValueType(0) == MVT::i64 &&
5569          "Only know how to expand i64 atomics");
5570
5571  SmallVector<SDValue, 6> Ops;
5572  Ops.push_back(Node->getOperand(0)); // Chain
5573  Ops.push_back(Node->getOperand(1)); // Ptr
5574  // Low part of Val1
5575  Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5576                            Node->getOperand(2), DAG.getIntPtrConstant(0)));
5577  // High part of Val1
5578  Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5579                            Node->getOperand(2), DAG.getIntPtrConstant(1)));
5580  if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5581    // High part of Val1
5582    Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5583                              Node->getOperand(3), DAG.getIntPtrConstant(0)));
5584    // High part of Val2
5585    Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5586                              Node->getOperand(3), DAG.getIntPtrConstant(1)));
5587  }
5588  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5589  SDValue Result =
5590    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5591                            cast<MemSDNode>(Node)->getMemOperand());
5592  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5593  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5594  Results.push_back(Result.getValue(2));
5595}
5596
5597SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5598  switch (Op.getOpcode()) {
5599  default: llvm_unreachable("Don't know how to custom lower this!");
5600  case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5601  case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5602  case ISD::GlobalAddress:
5603    return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5604      LowerGlobalAddressELF(Op, DAG);
5605  case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5606  case ISD::SELECT:        return LowerSELECT(Op, DAG);
5607  case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5608  case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5609  case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5610  case ISD::VASTART:       return LowerVASTART(Op, DAG);
5611  case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5612  case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5613  case ISD::SINT_TO_FP:
5614  case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5615  case ISD::FP_TO_SINT:
5616  case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5617  case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5618  case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5619  case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5620  case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5621  case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5622  case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5623  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5624                                                               Subtarget);
5625  case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5626  case ISD::SHL:
5627  case ISD::SRL:
5628  case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5629  case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5630  case ISD::SRL_PARTS:
5631  case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5632  case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5633  case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5634  case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5635  case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5636  case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5637  case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5638  case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5639  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5640  case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5641  case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5642  case ISD::MUL:           return LowerMUL(Op, DAG);
5643  case ISD::SDIV:          return LowerSDIV(Op, DAG);
5644  case ISD::UDIV:          return LowerUDIV(Op, DAG);
5645  case ISD::ADDC:
5646  case ISD::ADDE:
5647  case ISD::SUBC:
5648  case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5649  case ISD::ATOMIC_LOAD:
5650  case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5651  }
5652}
5653
5654/// ReplaceNodeResults - Replace the results of node with an illegal result
5655/// type with new values built out of custom code.
5656void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5657                                           SmallVectorImpl<SDValue>&Results,
5658                                           SelectionDAG &DAG) const {
5659  SDValue Res;
5660  switch (N->getOpcode()) {
5661  default:
5662    llvm_unreachable("Don't know how to custom expand this!");
5663  case ISD::BITCAST:
5664    Res = ExpandBITCAST(N, DAG);
5665    break;
5666  case ISD::SIGN_EXTEND:
5667  case ISD::ZERO_EXTEND:
5668    Res = ExpandVectorExtension(N, DAG);
5669    break;
5670  case ISD::SRL:
5671  case ISD::SRA:
5672    Res = Expand64BitShift(N, DAG, Subtarget);
5673    break;
5674  case ISD::ATOMIC_LOAD_ADD:
5675    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5676    return;
5677  case ISD::ATOMIC_LOAD_AND:
5678    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5679    return;
5680  case ISD::ATOMIC_LOAD_NAND:
5681    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5682    return;
5683  case ISD::ATOMIC_LOAD_OR:
5684    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5685    return;
5686  case ISD::ATOMIC_LOAD_SUB:
5687    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5688    return;
5689  case ISD::ATOMIC_LOAD_XOR:
5690    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5691    return;
5692  case ISD::ATOMIC_SWAP:
5693    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5694    return;
5695  case ISD::ATOMIC_CMP_SWAP:
5696    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5697    return;
5698  case ISD::ATOMIC_LOAD_MIN:
5699    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5700    return;
5701  case ISD::ATOMIC_LOAD_UMIN:
5702    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5703    return;
5704  case ISD::ATOMIC_LOAD_MAX:
5705    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5706    return;
5707  case ISD::ATOMIC_LOAD_UMAX:
5708    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5709    return;
5710  }
5711  if (Res.getNode())
5712    Results.push_back(Res);
5713}
5714
5715//===----------------------------------------------------------------------===//
5716//                           ARM Scheduler Hooks
5717//===----------------------------------------------------------------------===//
5718
5719MachineBasicBlock *
5720ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5721                                     MachineBasicBlock *BB,
5722                                     unsigned Size) const {
5723  unsigned dest    = MI->getOperand(0).getReg();
5724  unsigned ptr     = MI->getOperand(1).getReg();
5725  unsigned oldval  = MI->getOperand(2).getReg();
5726  unsigned newval  = MI->getOperand(3).getReg();
5727  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5728  DebugLoc dl = MI->getDebugLoc();
5729  bool isThumb2 = Subtarget->isThumb2();
5730
5731  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5732  unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5733    (const TargetRegisterClass*)&ARM::rGPRRegClass :
5734    (const TargetRegisterClass*)&ARM::GPRRegClass);
5735
5736  if (isThumb2) {
5737    MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5738    MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5739    MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5740  }
5741
5742  unsigned ldrOpc, strOpc;
5743  switch (Size) {
5744  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5745  case 1:
5746    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5747    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5748    break;
5749  case 2:
5750    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5751    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5752    break;
5753  case 4:
5754    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5755    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5756    break;
5757  }
5758
5759  MachineFunction *MF = BB->getParent();
5760  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5761  MachineFunction::iterator It = BB;
5762  ++It; // insert the new blocks after the current block
5763
5764  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5765  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5766  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5767  MF->insert(It, loop1MBB);
5768  MF->insert(It, loop2MBB);
5769  MF->insert(It, exitMBB);
5770
5771  // Transfer the remainder of BB and its successor edges to exitMBB.
5772  exitMBB->splice(exitMBB->begin(), BB,
5773                  llvm::next(MachineBasicBlock::iterator(MI)),
5774                  BB->end());
5775  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5776
5777  //  thisMBB:
5778  //   ...
5779  //   fallthrough --> loop1MBB
5780  BB->addSuccessor(loop1MBB);
5781
5782  // loop1MBB:
5783  //   ldrex dest, [ptr]
5784  //   cmp dest, oldval
5785  //   bne exitMBB
5786  BB = loop1MBB;
5787  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5788  if (ldrOpc == ARM::t2LDREX)
5789    MIB.addImm(0);
5790  AddDefaultPred(MIB);
5791  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5792                 .addReg(dest).addReg(oldval));
5793  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5794    .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5795  BB->addSuccessor(loop2MBB);
5796  BB->addSuccessor(exitMBB);
5797
5798  // loop2MBB:
5799  //   strex scratch, newval, [ptr]
5800  //   cmp scratch, #0
5801  //   bne loop1MBB
5802  BB = loop2MBB;
5803  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5804  if (strOpc == ARM::t2STREX)
5805    MIB.addImm(0);
5806  AddDefaultPred(MIB);
5807  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5808                 .addReg(scratch).addImm(0));
5809  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5810    .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5811  BB->addSuccessor(loop1MBB);
5812  BB->addSuccessor(exitMBB);
5813
5814  //  exitMBB:
5815  //   ...
5816  BB = exitMBB;
5817
5818  MI->eraseFromParent();   // The instruction is gone now.
5819
5820  return BB;
5821}
5822
5823MachineBasicBlock *
5824ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5825                                    unsigned Size, unsigned BinOpcode) const {
5826  // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5827  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5828
5829  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5830  MachineFunction *MF = BB->getParent();
5831  MachineFunction::iterator It = BB;
5832  ++It;
5833
5834  unsigned dest = MI->getOperand(0).getReg();
5835  unsigned ptr = MI->getOperand(1).getReg();
5836  unsigned incr = MI->getOperand(2).getReg();
5837  DebugLoc dl = MI->getDebugLoc();
5838  bool isThumb2 = Subtarget->isThumb2();
5839
5840  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5841  if (isThumb2) {
5842    MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5843    MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5844  }
5845
5846  unsigned ldrOpc, strOpc;
5847  switch (Size) {
5848  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5849  case 1:
5850    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5851    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5852    break;
5853  case 2:
5854    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5855    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5856    break;
5857  case 4:
5858    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5859    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5860    break;
5861  }
5862
5863  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5864  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5865  MF->insert(It, loopMBB);
5866  MF->insert(It, exitMBB);
5867
5868  // Transfer the remainder of BB and its successor edges to exitMBB.
5869  exitMBB->splice(exitMBB->begin(), BB,
5870                  llvm::next(MachineBasicBlock::iterator(MI)),
5871                  BB->end());
5872  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5873
5874  const TargetRegisterClass *TRC = isThumb2 ?
5875    (const TargetRegisterClass*)&ARM::rGPRRegClass :
5876    (const TargetRegisterClass*)&ARM::GPRRegClass;
5877  unsigned scratch = MRI.createVirtualRegister(TRC);
5878  unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5879
5880  //  thisMBB:
5881  //   ...
5882  //   fallthrough --> loopMBB
5883  BB->addSuccessor(loopMBB);
5884
5885  //  loopMBB:
5886  //   ldrex dest, ptr
5887  //   <binop> scratch2, dest, incr
5888  //   strex scratch, scratch2, ptr
5889  //   cmp scratch, #0
5890  //   bne- loopMBB
5891  //   fallthrough --> exitMBB
5892  BB = loopMBB;
5893  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5894  if (ldrOpc == ARM::t2LDREX)
5895    MIB.addImm(0);
5896  AddDefaultPred(MIB);
5897  if (BinOpcode) {
5898    // operand order needs to go the other way for NAND
5899    if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5900      AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5901                     addReg(incr).addReg(dest)).addReg(0);
5902    else
5903      AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5904                     addReg(dest).addReg(incr)).addReg(0);
5905  }
5906
5907  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5908  if (strOpc == ARM::t2STREX)
5909    MIB.addImm(0);
5910  AddDefaultPred(MIB);
5911  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5912                 .addReg(scratch).addImm(0));
5913  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5914    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5915
5916  BB->addSuccessor(loopMBB);
5917  BB->addSuccessor(exitMBB);
5918
5919  //  exitMBB:
5920  //   ...
5921  BB = exitMBB;
5922
5923  MI->eraseFromParent();   // The instruction is gone now.
5924
5925  return BB;
5926}
5927
5928MachineBasicBlock *
5929ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5930                                          MachineBasicBlock *BB,
5931                                          unsigned Size,
5932                                          bool signExtend,
5933                                          ARMCC::CondCodes Cond) const {
5934  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5935
5936  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5937  MachineFunction *MF = BB->getParent();
5938  MachineFunction::iterator It = BB;
5939  ++It;
5940
5941  unsigned dest = MI->getOperand(0).getReg();
5942  unsigned ptr = MI->getOperand(1).getReg();
5943  unsigned incr = MI->getOperand(2).getReg();
5944  unsigned oldval = dest;
5945  DebugLoc dl = MI->getDebugLoc();
5946  bool isThumb2 = Subtarget->isThumb2();
5947
5948  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5949  if (isThumb2) {
5950    MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5951    MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5952  }
5953
5954  unsigned ldrOpc, strOpc, extendOpc;
5955  switch (Size) {
5956  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5957  case 1:
5958    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5959    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5960    extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5961    break;
5962  case 2:
5963    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5964    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5965    extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5966    break;
5967  case 4:
5968    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5969    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5970    extendOpc = 0;
5971    break;
5972  }
5973
5974  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5975  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5976  MF->insert(It, loopMBB);
5977  MF->insert(It, exitMBB);
5978
5979  // Transfer the remainder of BB and its successor edges to exitMBB.
5980  exitMBB->splice(exitMBB->begin(), BB,
5981                  llvm::next(MachineBasicBlock::iterator(MI)),
5982                  BB->end());
5983  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5984
5985  const TargetRegisterClass *TRC = isThumb2 ?
5986    (const TargetRegisterClass*)&ARM::rGPRRegClass :
5987    (const TargetRegisterClass*)&ARM::GPRRegClass;
5988  unsigned scratch = MRI.createVirtualRegister(TRC);
5989  unsigned scratch2 = MRI.createVirtualRegister(TRC);
5990
5991  //  thisMBB:
5992  //   ...
5993  //   fallthrough --> loopMBB
5994  BB->addSuccessor(loopMBB);
5995
5996  //  loopMBB:
5997  //   ldrex dest, ptr
5998  //   (sign extend dest, if required)
5999  //   cmp dest, incr
6000  //   cmov.cond scratch2, incr, dest
6001  //   strex scratch, scratch2, ptr
6002  //   cmp scratch, #0
6003  //   bne- loopMBB
6004  //   fallthrough --> exitMBB
6005  BB = loopMBB;
6006  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6007  if (ldrOpc == ARM::t2LDREX)
6008    MIB.addImm(0);
6009  AddDefaultPred(MIB);
6010
6011  // Sign extend the value, if necessary.
6012  if (signExtend && extendOpc) {
6013    oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6014    AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6015                     .addReg(dest)
6016                     .addImm(0));
6017  }
6018
6019  // Build compare and cmov instructions.
6020  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6021                 .addReg(oldval).addReg(incr));
6022  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6023         .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6024
6025  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6026  if (strOpc == ARM::t2STREX)
6027    MIB.addImm(0);
6028  AddDefaultPred(MIB);
6029  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6030                 .addReg(scratch).addImm(0));
6031  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6032    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6033
6034  BB->addSuccessor(loopMBB);
6035  BB->addSuccessor(exitMBB);
6036
6037  //  exitMBB:
6038  //   ...
6039  BB = exitMBB;
6040
6041  MI->eraseFromParent();   // The instruction is gone now.
6042
6043  return BB;
6044}
6045
6046MachineBasicBlock *
6047ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6048                                      unsigned Op1, unsigned Op2,
6049                                      bool NeedsCarry, bool IsCmpxchg,
6050                                      bool IsMinMax, ARMCC::CondCodes CC) const {
6051  // This also handles ATOMIC_SWAP, indicated by Op1==0.
6052  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6053
6054  const BasicBlock *LLVM_BB = BB->getBasicBlock();
6055  MachineFunction *MF = BB->getParent();
6056  MachineFunction::iterator It = BB;
6057  ++It;
6058
6059  unsigned destlo = MI->getOperand(0).getReg();
6060  unsigned desthi = MI->getOperand(1).getReg();
6061  unsigned ptr = MI->getOperand(2).getReg();
6062  unsigned vallo = MI->getOperand(3).getReg();
6063  unsigned valhi = MI->getOperand(4).getReg();
6064  DebugLoc dl = MI->getDebugLoc();
6065  bool isThumb2 = Subtarget->isThumb2();
6066
6067  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6068  if (isThumb2) {
6069    MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6070    MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6071    MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6072  }
6073
6074  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6075  MachineBasicBlock *contBB = 0, *cont2BB = 0;
6076  if (IsCmpxchg || IsMinMax)
6077    contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6078  if (IsCmpxchg)
6079    cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6080  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6081
6082  MF->insert(It, loopMBB);
6083  if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6084  if (IsCmpxchg) MF->insert(It, cont2BB);
6085  MF->insert(It, exitMBB);
6086
6087  // Transfer the remainder of BB and its successor edges to exitMBB.
6088  exitMBB->splice(exitMBB->begin(), BB,
6089                  llvm::next(MachineBasicBlock::iterator(MI)),
6090                  BB->end());
6091  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6092
6093  const TargetRegisterClass *TRC = isThumb2 ?
6094    (const TargetRegisterClass*)&ARM::tGPRRegClass :
6095    (const TargetRegisterClass*)&ARM::GPRRegClass;
6096  unsigned storesuccess = MRI.createVirtualRegister(TRC);
6097
6098  //  thisMBB:
6099  //   ...
6100  //   fallthrough --> loopMBB
6101  BB->addSuccessor(loopMBB);
6102
6103  //  loopMBB:
6104  //   ldrexd r2, r3, ptr
6105  //   <binopa> r0, r2, incr
6106  //   <binopb> r1, r3, incr
6107  //   strexd storesuccess, r0, r1, ptr
6108  //   cmp storesuccess, #0
6109  //   bne- loopMBB
6110  //   fallthrough --> exitMBB
6111  BB = loopMBB;
6112
6113  // Load
6114  if (isThumb2) {
6115    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6116                   .addReg(destlo, RegState::Define)
6117                   .addReg(desthi, RegState::Define)
6118                   .addReg(ptr));
6119  } else {
6120    unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6121    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6122                   .addReg(GPRPair0, RegState::Define).addReg(ptr));
6123    // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6124    BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6125      .addReg(GPRPair0, 0, ARM::gsub_0);
6126    BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6127      .addReg(GPRPair0, 0, ARM::gsub_1);
6128  }
6129
6130  unsigned StoreLo, StoreHi;
6131  if (IsCmpxchg) {
6132    // Add early exit
6133    for (unsigned i = 0; i < 2; i++) {
6134      AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6135                                                         ARM::CMPrr))
6136                     .addReg(i == 0 ? destlo : desthi)
6137                     .addReg(i == 0 ? vallo : valhi));
6138      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6139        .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6140      BB->addSuccessor(exitMBB);
6141      BB->addSuccessor(i == 0 ? contBB : cont2BB);
6142      BB = (i == 0 ? contBB : cont2BB);
6143    }
6144
6145    // Copy to physregs for strexd
6146    StoreLo = MI->getOperand(5).getReg();
6147    StoreHi = MI->getOperand(6).getReg();
6148  } else if (Op1) {
6149    // Perform binary operation
6150    unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6151    AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6152                   .addReg(destlo).addReg(vallo))
6153        .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6154    unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6155    AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6156                   .addReg(desthi).addReg(valhi))
6157        .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6158
6159    StoreLo = tmpRegLo;
6160    StoreHi = tmpRegHi;
6161  } else {
6162    // Copy to physregs for strexd
6163    StoreLo = vallo;
6164    StoreHi = valhi;
6165  }
6166  if (IsMinMax) {
6167    // Compare and branch to exit block.
6168    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6169      .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6170    BB->addSuccessor(exitMBB);
6171    BB->addSuccessor(contBB);
6172    BB = contBB;
6173    StoreLo = vallo;
6174    StoreHi = valhi;
6175  }
6176
6177  // Store
6178  if (isThumb2) {
6179    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6180                   .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6181  } else {
6182    // Marshal a pair...
6183    unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6184    unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6185    unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6186    BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6187    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6188      .addReg(UndefPair)
6189      .addReg(StoreLo)
6190      .addImm(ARM::gsub_0);
6191    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6192      .addReg(r1)
6193      .addReg(StoreHi)
6194      .addImm(ARM::gsub_1);
6195
6196    // ...and store it
6197    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6198                   .addReg(StorePair).addReg(ptr));
6199  }
6200  // Cmp+jump
6201  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6202                 .addReg(storesuccess).addImm(0));
6203  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6204    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6205
6206  BB->addSuccessor(loopMBB);
6207  BB->addSuccessor(exitMBB);
6208
6209  //  exitMBB:
6210  //   ...
6211  BB = exitMBB;
6212
6213  MI->eraseFromParent();   // The instruction is gone now.
6214
6215  return BB;
6216}
6217
6218/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6219/// registers the function context.
6220void ARMTargetLowering::
6221SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6222                       MachineBasicBlock *DispatchBB, int FI) const {
6223  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6224  DebugLoc dl = MI->getDebugLoc();
6225  MachineFunction *MF = MBB->getParent();
6226  MachineRegisterInfo *MRI = &MF->getRegInfo();
6227  MachineConstantPool *MCP = MF->getConstantPool();
6228  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6229  const Function *F = MF->getFunction();
6230
6231  bool isThumb = Subtarget->isThumb();
6232  bool isThumb2 = Subtarget->isThumb2();
6233
6234  unsigned PCLabelId = AFI->createPICLabelUId();
6235  unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6236  ARMConstantPoolValue *CPV =
6237    ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6238  unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6239
6240  const TargetRegisterClass *TRC = isThumb ?
6241    (const TargetRegisterClass*)&ARM::tGPRRegClass :
6242    (const TargetRegisterClass*)&ARM::GPRRegClass;
6243
6244  // Grab constant pool and fixed stack memory operands.
6245  MachineMemOperand *CPMMO =
6246    MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6247                             MachineMemOperand::MOLoad, 4, 4);
6248
6249  MachineMemOperand *FIMMOSt =
6250    MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6251                             MachineMemOperand::MOStore, 4, 4);
6252
6253  // Load the address of the dispatch MBB into the jump buffer.
6254  if (isThumb2) {
6255    // Incoming value: jbuf
6256    //   ldr.n  r5, LCPI1_1
6257    //   orr    r5, r5, #1
6258    //   add    r5, pc
6259    //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6260    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6261    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6262                   .addConstantPoolIndex(CPI)
6263                   .addMemOperand(CPMMO));
6264    // Set the low bit because of thumb mode.
6265    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6266    AddDefaultCC(
6267      AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6268                     .addReg(NewVReg1, RegState::Kill)
6269                     .addImm(0x01)));
6270    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6271    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6272      .addReg(NewVReg2, RegState::Kill)
6273      .addImm(PCLabelId);
6274    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6275                   .addReg(NewVReg3, RegState::Kill)
6276                   .addFrameIndex(FI)
6277                   .addImm(36)  // &jbuf[1] :: pc
6278                   .addMemOperand(FIMMOSt));
6279  } else if (isThumb) {
6280    // Incoming value: jbuf
6281    //   ldr.n  r1, LCPI1_4
6282    //   add    r1, pc
6283    //   mov    r2, #1
6284    //   orrs   r1, r2
6285    //   add    r2, $jbuf, #+4 ; &jbuf[1]
6286    //   str    r1, [r2]
6287    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6288    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6289                   .addConstantPoolIndex(CPI)
6290                   .addMemOperand(CPMMO));
6291    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6292    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6293      .addReg(NewVReg1, RegState::Kill)
6294      .addImm(PCLabelId);
6295    // Set the low bit because of thumb mode.
6296    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6297    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6298                   .addReg(ARM::CPSR, RegState::Define)
6299                   .addImm(1));
6300    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6301    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6302                   .addReg(ARM::CPSR, RegState::Define)
6303                   .addReg(NewVReg2, RegState::Kill)
6304                   .addReg(NewVReg3, RegState::Kill));
6305    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6306    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6307                   .addFrameIndex(FI)
6308                   .addImm(36)); // &jbuf[1] :: pc
6309    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6310                   .addReg(NewVReg4, RegState::Kill)
6311                   .addReg(NewVReg5, RegState::Kill)
6312                   .addImm(0)
6313                   .addMemOperand(FIMMOSt));
6314  } else {
6315    // Incoming value: jbuf
6316    //   ldr  r1, LCPI1_1
6317    //   add  r1, pc, r1
6318    //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6319    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6320    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6321                   .addConstantPoolIndex(CPI)
6322                   .addImm(0)
6323                   .addMemOperand(CPMMO));
6324    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6325    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6326                   .addReg(NewVReg1, RegState::Kill)
6327                   .addImm(PCLabelId));
6328    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6329                   .addReg(NewVReg2, RegState::Kill)
6330                   .addFrameIndex(FI)
6331                   .addImm(36)  // &jbuf[1] :: pc
6332                   .addMemOperand(FIMMOSt));
6333  }
6334}
6335
6336MachineBasicBlock *ARMTargetLowering::
6337EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6338  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6339  DebugLoc dl = MI->getDebugLoc();
6340  MachineFunction *MF = MBB->getParent();
6341  MachineRegisterInfo *MRI = &MF->getRegInfo();
6342  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6343  MachineFrameInfo *MFI = MF->getFrameInfo();
6344  int FI = MFI->getFunctionContextIndex();
6345
6346  const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6347    (const TargetRegisterClass*)&ARM::tGPRRegClass :
6348    (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6349
6350  // Get a mapping of the call site numbers to all of the landing pads they're
6351  // associated with.
6352  DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6353  unsigned MaxCSNum = 0;
6354  MachineModuleInfo &MMI = MF->getMMI();
6355  for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6356       ++BB) {
6357    if (!BB->isLandingPad()) continue;
6358
6359    // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6360    // pad.
6361    for (MachineBasicBlock::iterator
6362           II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6363      if (!II->isEHLabel()) continue;
6364
6365      MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6366      if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6367
6368      SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6369      for (SmallVectorImpl<unsigned>::iterator
6370             CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6371           CSI != CSE; ++CSI) {
6372        CallSiteNumToLPad[*CSI].push_back(BB);
6373        MaxCSNum = std::max(MaxCSNum, *CSI);
6374      }
6375      break;
6376    }
6377  }
6378
6379  // Get an ordered list of the machine basic blocks for the jump table.
6380  std::vector<MachineBasicBlock*> LPadList;
6381  SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6382  LPadList.reserve(CallSiteNumToLPad.size());
6383  for (unsigned I = 1; I <= MaxCSNum; ++I) {
6384    SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6385    for (SmallVectorImpl<MachineBasicBlock*>::iterator
6386           II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6387      LPadList.push_back(*II);
6388      InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6389    }
6390  }
6391
6392  assert(!LPadList.empty() &&
6393         "No landing pad destinations for the dispatch jump table!");
6394
6395  // Create the jump table and associated information.
6396  MachineJumpTableInfo *JTI =
6397    MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6398  unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6399  unsigned UId = AFI->createJumpTableUId();
6400  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6401
6402  // Create the MBBs for the dispatch code.
6403
6404  // Shove the dispatch's address into the return slot in the function context.
6405  MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6406  DispatchBB->setIsLandingPad();
6407
6408  MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6409  unsigned trap_opcode;
6410  if (Subtarget->isThumb())
6411    trap_opcode = ARM::tTRAP;
6412  else
6413    trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6414
6415  BuildMI(TrapBB, dl, TII->get(trap_opcode));
6416  DispatchBB->addSuccessor(TrapBB);
6417
6418  MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6419  DispatchBB->addSuccessor(DispContBB);
6420
6421  // Insert and MBBs.
6422  MF->insert(MF->end(), DispatchBB);
6423  MF->insert(MF->end(), DispContBB);
6424  MF->insert(MF->end(), TrapBB);
6425
6426  // Insert code into the entry block that creates and registers the function
6427  // context.
6428  SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6429
6430  MachineMemOperand *FIMMOLd =
6431    MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6432                             MachineMemOperand::MOLoad |
6433                             MachineMemOperand::MOVolatile, 4, 4);
6434
6435  MachineInstrBuilder MIB;
6436  MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6437
6438  const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6439  const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6440
6441  // Add a register mask with no preserved registers.  This results in all
6442  // registers being marked as clobbered.
6443  MIB.addRegMask(RI.getNoPreservedMask());
6444
6445  unsigned NumLPads = LPadList.size();
6446  if (Subtarget->isThumb2()) {
6447    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6448    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6449                   .addFrameIndex(FI)
6450                   .addImm(4)
6451                   .addMemOperand(FIMMOLd));
6452
6453    if (NumLPads < 256) {
6454      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6455                     .addReg(NewVReg1)
6456                     .addImm(LPadList.size()));
6457    } else {
6458      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6459      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6460                     .addImm(NumLPads & 0xFFFF));
6461
6462      unsigned VReg2 = VReg1;
6463      if ((NumLPads & 0xFFFF0000) != 0) {
6464        VReg2 = MRI->createVirtualRegister(TRC);
6465        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6466                       .addReg(VReg1)
6467                       .addImm(NumLPads >> 16));
6468      }
6469
6470      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6471                     .addReg(NewVReg1)
6472                     .addReg(VReg2));
6473    }
6474
6475    BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6476      .addMBB(TrapBB)
6477      .addImm(ARMCC::HI)
6478      .addReg(ARM::CPSR);
6479
6480    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6481    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6482                   .addJumpTableIndex(MJTI)
6483                   .addImm(UId));
6484
6485    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6486    AddDefaultCC(
6487      AddDefaultPred(
6488        BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6489        .addReg(NewVReg3, RegState::Kill)
6490        .addReg(NewVReg1)
6491        .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6492
6493    BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6494      .addReg(NewVReg4, RegState::Kill)
6495      .addReg(NewVReg1)
6496      .addJumpTableIndex(MJTI)
6497      .addImm(UId);
6498  } else if (Subtarget->isThumb()) {
6499    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6500    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6501                   .addFrameIndex(FI)
6502                   .addImm(1)
6503                   .addMemOperand(FIMMOLd));
6504
6505    if (NumLPads < 256) {
6506      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6507                     .addReg(NewVReg1)
6508                     .addImm(NumLPads));
6509    } else {
6510      MachineConstantPool *ConstantPool = MF->getConstantPool();
6511      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6512      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6513
6514      // MachineConstantPool wants an explicit alignment.
6515      unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6516      if (Align == 0)
6517        Align = getDataLayout()->getTypeAllocSize(C->getType());
6518      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6519
6520      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6521      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6522                     .addReg(VReg1, RegState::Define)
6523                     .addConstantPoolIndex(Idx));
6524      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6525                     .addReg(NewVReg1)
6526                     .addReg(VReg1));
6527    }
6528
6529    BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6530      .addMBB(TrapBB)
6531      .addImm(ARMCC::HI)
6532      .addReg(ARM::CPSR);
6533
6534    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6535    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6536                   .addReg(ARM::CPSR, RegState::Define)
6537                   .addReg(NewVReg1)
6538                   .addImm(2));
6539
6540    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6541    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6542                   .addJumpTableIndex(MJTI)
6543                   .addImm(UId));
6544
6545    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6546    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6547                   .addReg(ARM::CPSR, RegState::Define)
6548                   .addReg(NewVReg2, RegState::Kill)
6549                   .addReg(NewVReg3));
6550
6551    MachineMemOperand *JTMMOLd =
6552      MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6553                               MachineMemOperand::MOLoad, 4, 4);
6554
6555    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6556    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6557                   .addReg(NewVReg4, RegState::Kill)
6558                   .addImm(0)
6559                   .addMemOperand(JTMMOLd));
6560
6561    unsigned NewVReg6 = NewVReg5;
6562    if (RelocM == Reloc::PIC_) {
6563      NewVReg6 = MRI->createVirtualRegister(TRC);
6564      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6565                     .addReg(ARM::CPSR, RegState::Define)
6566                     .addReg(NewVReg5, RegState::Kill)
6567                     .addReg(NewVReg3));
6568    }
6569
6570    BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6571      .addReg(NewVReg6, RegState::Kill)
6572      .addJumpTableIndex(MJTI)
6573      .addImm(UId);
6574  } else {
6575    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6576    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6577                   .addFrameIndex(FI)
6578                   .addImm(4)
6579                   .addMemOperand(FIMMOLd));
6580
6581    if (NumLPads < 256) {
6582      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6583                     .addReg(NewVReg1)
6584                     .addImm(NumLPads));
6585    } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6586      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6587      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6588                     .addImm(NumLPads & 0xFFFF));
6589
6590      unsigned VReg2 = VReg1;
6591      if ((NumLPads & 0xFFFF0000) != 0) {
6592        VReg2 = MRI->createVirtualRegister(TRC);
6593        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6594                       .addReg(VReg1)
6595                       .addImm(NumLPads >> 16));
6596      }
6597
6598      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6599                     .addReg(NewVReg1)
6600                     .addReg(VReg2));
6601    } else {
6602      MachineConstantPool *ConstantPool = MF->getConstantPool();
6603      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6604      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6605
6606      // MachineConstantPool wants an explicit alignment.
6607      unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6608      if (Align == 0)
6609        Align = getDataLayout()->getTypeAllocSize(C->getType());
6610      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6611
6612      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6613      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6614                     .addReg(VReg1, RegState::Define)
6615                     .addConstantPoolIndex(Idx)
6616                     .addImm(0));
6617      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6618                     .addReg(NewVReg1)
6619                     .addReg(VReg1, RegState::Kill));
6620    }
6621
6622    BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6623      .addMBB(TrapBB)
6624      .addImm(ARMCC::HI)
6625      .addReg(ARM::CPSR);
6626
6627    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6628    AddDefaultCC(
6629      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6630                     .addReg(NewVReg1)
6631                     .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6632    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6633    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6634                   .addJumpTableIndex(MJTI)
6635                   .addImm(UId));
6636
6637    MachineMemOperand *JTMMOLd =
6638      MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6639                               MachineMemOperand::MOLoad, 4, 4);
6640    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6641    AddDefaultPred(
6642      BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6643      .addReg(NewVReg3, RegState::Kill)
6644      .addReg(NewVReg4)
6645      .addImm(0)
6646      .addMemOperand(JTMMOLd));
6647
6648    if (RelocM == Reloc::PIC_) {
6649      BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6650        .addReg(NewVReg5, RegState::Kill)
6651        .addReg(NewVReg4)
6652        .addJumpTableIndex(MJTI)
6653        .addImm(UId);
6654    } else {
6655      BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6656        .addReg(NewVReg5, RegState::Kill)
6657        .addJumpTableIndex(MJTI)
6658        .addImm(UId);
6659    }
6660  }
6661
6662  // Add the jump table entries as successors to the MBB.
6663  SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6664  for (std::vector<MachineBasicBlock*>::iterator
6665         I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6666    MachineBasicBlock *CurMBB = *I;
6667    if (SeenMBBs.insert(CurMBB))
6668      DispContBB->addSuccessor(CurMBB);
6669  }
6670
6671  // N.B. the order the invoke BBs are processed in doesn't matter here.
6672  const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6673  SmallVector<MachineBasicBlock*, 64> MBBLPads;
6674  for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6675         I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6676    MachineBasicBlock *BB = *I;
6677
6678    // Remove the landing pad successor from the invoke block and replace it
6679    // with the new dispatch block.
6680    SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6681                                                  BB->succ_end());
6682    while (!Successors.empty()) {
6683      MachineBasicBlock *SMBB = Successors.pop_back_val();
6684      if (SMBB->isLandingPad()) {
6685        BB->removeSuccessor(SMBB);
6686        MBBLPads.push_back(SMBB);
6687      }
6688    }
6689
6690    BB->addSuccessor(DispatchBB);
6691
6692    // Find the invoke call and mark all of the callee-saved registers as
6693    // 'implicit defined' so that they're spilled. This prevents code from
6694    // moving instructions to before the EH block, where they will never be
6695    // executed.
6696    for (MachineBasicBlock::reverse_iterator
6697           II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6698      if (!II->isCall()) continue;
6699
6700      DenseMap<unsigned, bool> DefRegs;
6701      for (MachineInstr::mop_iterator
6702             OI = II->operands_begin(), OE = II->operands_end();
6703           OI != OE; ++OI) {
6704        if (!OI->isReg()) continue;
6705        DefRegs[OI->getReg()] = true;
6706      }
6707
6708      MachineInstrBuilder MIB(*MF, &*II);
6709
6710      for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6711        unsigned Reg = SavedRegs[i];
6712        if (Subtarget->isThumb2() &&
6713            !ARM::tGPRRegClass.contains(Reg) &&
6714            !ARM::hGPRRegClass.contains(Reg))
6715          continue;
6716        if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6717          continue;
6718        if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6719          continue;
6720        if (!DefRegs[Reg])
6721          MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6722      }
6723
6724      break;
6725    }
6726  }
6727
6728  // Mark all former landing pads as non-landing pads. The dispatch is the only
6729  // landing pad now.
6730  for (SmallVectorImpl<MachineBasicBlock*>::iterator
6731         I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6732    (*I)->setIsLandingPad(false);
6733
6734  // The instruction is gone now.
6735  MI->eraseFromParent();
6736
6737  return MBB;
6738}
6739
6740static
6741MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6742  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6743       E = MBB->succ_end(); I != E; ++I)
6744    if (*I != Succ)
6745      return *I;
6746  llvm_unreachable("Expecting a BB with two successors!");
6747}
6748
6749MachineBasicBlock *ARMTargetLowering::
6750EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6751  // This pseudo instruction has 3 operands: dst, src, size
6752  // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6753  // Otherwise, we will generate unrolled scalar copies.
6754  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6755  const BasicBlock *LLVM_BB = BB->getBasicBlock();
6756  MachineFunction::iterator It = BB;
6757  ++It;
6758
6759  unsigned dest = MI->getOperand(0).getReg();
6760  unsigned src = MI->getOperand(1).getReg();
6761  unsigned SizeVal = MI->getOperand(2).getImm();
6762  unsigned Align = MI->getOperand(3).getImm();
6763  DebugLoc dl = MI->getDebugLoc();
6764
6765  bool isThumb2 = Subtarget->isThumb2();
6766  MachineFunction *MF = BB->getParent();
6767  MachineRegisterInfo &MRI = MF->getRegInfo();
6768  unsigned ldrOpc, strOpc, UnitSize = 0;
6769
6770  const TargetRegisterClass *TRC = isThumb2 ?
6771    (const TargetRegisterClass*)&ARM::tGPRRegClass :
6772    (const TargetRegisterClass*)&ARM::GPRRegClass;
6773  const TargetRegisterClass *TRC_Vec = 0;
6774
6775  if (Align & 1) {
6776    ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6777    strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6778    UnitSize = 1;
6779  } else if (Align & 2) {
6780    ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6781    strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6782    UnitSize = 2;
6783  } else {
6784    // Check whether we can use NEON instructions.
6785    if (!MF->getFunction()->getAttributes().
6786          hasAttribute(AttributeSet::FunctionIndex,
6787                       Attribute::NoImplicitFloat) &&
6788        Subtarget->hasNEON()) {
6789      if ((Align % 16 == 0) && SizeVal >= 16) {
6790        ldrOpc = ARM::VLD1q32wb_fixed;
6791        strOpc = ARM::VST1q32wb_fixed;
6792        UnitSize = 16;
6793        TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6794      }
6795      else if ((Align % 8 == 0) && SizeVal >= 8) {
6796        ldrOpc = ARM::VLD1d32wb_fixed;
6797        strOpc = ARM::VST1d32wb_fixed;
6798        UnitSize = 8;
6799        TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6800      }
6801    }
6802    // Can't use NEON instructions.
6803    if (UnitSize == 0) {
6804      ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6805      strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6806      UnitSize = 4;
6807    }
6808  }
6809
6810  unsigned BytesLeft = SizeVal % UnitSize;
6811  unsigned LoopSize = SizeVal - BytesLeft;
6812
6813  if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6814    // Use LDR and STR to copy.
6815    // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6816    // [destOut] = STR_POST(scratch, destIn, UnitSize)
6817    unsigned srcIn = src;
6818    unsigned destIn = dest;
6819    for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6820      unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6821      unsigned srcOut = MRI.createVirtualRegister(TRC);
6822      unsigned destOut = MRI.createVirtualRegister(TRC);
6823      if (UnitSize >= 8) {
6824        AddDefaultPred(BuildMI(*BB, MI, dl,
6825          TII->get(ldrOpc), scratch)
6826          .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6827
6828        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6829          .addReg(destIn).addImm(0).addReg(scratch));
6830      } else if (isThumb2) {
6831        AddDefaultPred(BuildMI(*BB, MI, dl,
6832          TII->get(ldrOpc), scratch)
6833          .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6834
6835        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6836          .addReg(scratch).addReg(destIn)
6837          .addImm(UnitSize));
6838      } else {
6839        AddDefaultPred(BuildMI(*BB, MI, dl,
6840          TII->get(ldrOpc), scratch)
6841          .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6842          .addImm(UnitSize));
6843
6844        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6845          .addReg(scratch).addReg(destIn)
6846          .addReg(0).addImm(UnitSize));
6847      }
6848      srcIn = srcOut;
6849      destIn = destOut;
6850    }
6851
6852    // Handle the leftover bytes with LDRB and STRB.
6853    // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6854    // [destOut] = STRB_POST(scratch, destIn, 1)
6855    ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6856    strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6857    for (unsigned i = 0; i < BytesLeft; i++) {
6858      unsigned scratch = MRI.createVirtualRegister(TRC);
6859      unsigned srcOut = MRI.createVirtualRegister(TRC);
6860      unsigned destOut = MRI.createVirtualRegister(TRC);
6861      if (isThumb2) {
6862        AddDefaultPred(BuildMI(*BB, MI, dl,
6863          TII->get(ldrOpc),scratch)
6864          .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6865
6866        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6867          .addReg(scratch).addReg(destIn)
6868          .addReg(0).addImm(1));
6869      } else {
6870        AddDefaultPred(BuildMI(*BB, MI, dl,
6871          TII->get(ldrOpc),scratch)
6872          .addReg(srcOut, RegState::Define).addReg(srcIn)
6873          .addReg(0).addImm(1));
6874
6875        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6876          .addReg(scratch).addReg(destIn)
6877          .addReg(0).addImm(1));
6878      }
6879      srcIn = srcOut;
6880      destIn = destOut;
6881    }
6882    MI->eraseFromParent();   // The instruction is gone now.
6883    return BB;
6884  }
6885
6886  // Expand the pseudo op to a loop.
6887  // thisMBB:
6888  //   ...
6889  //   movw varEnd, # --> with thumb2
6890  //   movt varEnd, #
6891  //   ldrcp varEnd, idx --> without thumb2
6892  //   fallthrough --> loopMBB
6893  // loopMBB:
6894  //   PHI varPhi, varEnd, varLoop
6895  //   PHI srcPhi, src, srcLoop
6896  //   PHI destPhi, dst, destLoop
6897  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6898  //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6899  //   subs varLoop, varPhi, #UnitSize
6900  //   bne loopMBB
6901  //   fallthrough --> exitMBB
6902  // exitMBB:
6903  //   epilogue to handle left-over bytes
6904  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6905  //   [destOut] = STRB_POST(scratch, destLoop, 1)
6906  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6907  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6908  MF->insert(It, loopMBB);
6909  MF->insert(It, exitMBB);
6910
6911  // Transfer the remainder of BB and its successor edges to exitMBB.
6912  exitMBB->splice(exitMBB->begin(), BB,
6913                  llvm::next(MachineBasicBlock::iterator(MI)),
6914                  BB->end());
6915  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6916
6917  // Load an immediate to varEnd.
6918  unsigned varEnd = MRI.createVirtualRegister(TRC);
6919  if (isThumb2) {
6920    unsigned VReg1 = varEnd;
6921    if ((LoopSize & 0xFFFF0000) != 0)
6922      VReg1 = MRI.createVirtualRegister(TRC);
6923    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6924                   .addImm(LoopSize & 0xFFFF));
6925
6926    if ((LoopSize & 0xFFFF0000) != 0)
6927      AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6928                     .addReg(VReg1)
6929                     .addImm(LoopSize >> 16));
6930  } else {
6931    MachineConstantPool *ConstantPool = MF->getConstantPool();
6932    Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6933    const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6934
6935    // MachineConstantPool wants an explicit alignment.
6936    unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6937    if (Align == 0)
6938      Align = getDataLayout()->getTypeAllocSize(C->getType());
6939    unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6940
6941    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6942                   .addReg(varEnd, RegState::Define)
6943                   .addConstantPoolIndex(Idx)
6944                   .addImm(0));
6945  }
6946  BB->addSuccessor(loopMBB);
6947
6948  // Generate the loop body:
6949  //   varPhi = PHI(varLoop, varEnd)
6950  //   srcPhi = PHI(srcLoop, src)
6951  //   destPhi = PHI(destLoop, dst)
6952  MachineBasicBlock *entryBB = BB;
6953  BB = loopMBB;
6954  unsigned varLoop = MRI.createVirtualRegister(TRC);
6955  unsigned varPhi = MRI.createVirtualRegister(TRC);
6956  unsigned srcLoop = MRI.createVirtualRegister(TRC);
6957  unsigned srcPhi = MRI.createVirtualRegister(TRC);
6958  unsigned destLoop = MRI.createVirtualRegister(TRC);
6959  unsigned destPhi = MRI.createVirtualRegister(TRC);
6960
6961  BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6962    .addReg(varLoop).addMBB(loopMBB)
6963    .addReg(varEnd).addMBB(entryBB);
6964  BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6965    .addReg(srcLoop).addMBB(loopMBB)
6966    .addReg(src).addMBB(entryBB);
6967  BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6968    .addReg(destLoop).addMBB(loopMBB)
6969    .addReg(dest).addMBB(entryBB);
6970
6971  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6972  //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6973  unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6974  if (UnitSize >= 8) {
6975    AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6976      .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6977
6978    AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6979      .addReg(destPhi).addImm(0).addReg(scratch));
6980  } else if (isThumb2) {
6981    AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6982      .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6983
6984    AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6985      .addReg(scratch).addReg(destPhi)
6986      .addImm(UnitSize));
6987  } else {
6988    AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6989      .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6990      .addImm(UnitSize));
6991
6992    AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6993      .addReg(scratch).addReg(destPhi)
6994      .addReg(0).addImm(UnitSize));
6995  }
6996
6997  // Decrement loop variable by UnitSize.
6998  MachineInstrBuilder MIB = BuildMI(BB, dl,
6999    TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7000  AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7001  MIB->getOperand(5).setReg(ARM::CPSR);
7002  MIB->getOperand(5).setIsDef(true);
7003
7004  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7005    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7006
7007  // loopMBB can loop back to loopMBB or fall through to exitMBB.
7008  BB->addSuccessor(loopMBB);
7009  BB->addSuccessor(exitMBB);
7010
7011  // Add epilogue to handle BytesLeft.
7012  BB = exitMBB;
7013  MachineInstr *StartOfExit = exitMBB->begin();
7014  ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7015  strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7016
7017  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7018  //   [destOut] = STRB_POST(scratch, destLoop, 1)
7019  unsigned srcIn = srcLoop;
7020  unsigned destIn = destLoop;
7021  for (unsigned i = 0; i < BytesLeft; i++) {
7022    unsigned scratch = MRI.createVirtualRegister(TRC);
7023    unsigned srcOut = MRI.createVirtualRegister(TRC);
7024    unsigned destOut = MRI.createVirtualRegister(TRC);
7025    if (isThumb2) {
7026      AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7027        TII->get(ldrOpc),scratch)
7028        .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7029
7030      AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7031        .addReg(scratch).addReg(destIn)
7032        .addImm(1));
7033    } else {
7034      AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7035        TII->get(ldrOpc),scratch)
7036        .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7037
7038      AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7039        .addReg(scratch).addReg(destIn)
7040        .addReg(0).addImm(1));
7041    }
7042    srcIn = srcOut;
7043    destIn = destOut;
7044  }
7045
7046  MI->eraseFromParent();   // The instruction is gone now.
7047  return BB;
7048}
7049
7050MachineBasicBlock *
7051ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7052                                               MachineBasicBlock *BB) const {
7053  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7054  DebugLoc dl = MI->getDebugLoc();
7055  bool isThumb2 = Subtarget->isThumb2();
7056  switch (MI->getOpcode()) {
7057  default: {
7058    MI->dump();
7059    llvm_unreachable("Unexpected instr type to insert");
7060  }
7061  // The Thumb2 pre-indexed stores have the same MI operands, they just
7062  // define them differently in the .td files from the isel patterns, so
7063  // they need pseudos.
7064  case ARM::t2STR_preidx:
7065    MI->setDesc(TII->get(ARM::t2STR_PRE));
7066    return BB;
7067  case ARM::t2STRB_preidx:
7068    MI->setDesc(TII->get(ARM::t2STRB_PRE));
7069    return BB;
7070  case ARM::t2STRH_preidx:
7071    MI->setDesc(TII->get(ARM::t2STRH_PRE));
7072    return BB;
7073
7074  case ARM::STRi_preidx:
7075  case ARM::STRBi_preidx: {
7076    unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7077      ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7078    // Decode the offset.
7079    unsigned Offset = MI->getOperand(4).getImm();
7080    bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7081    Offset = ARM_AM::getAM2Offset(Offset);
7082    if (isSub)
7083      Offset = -Offset;
7084
7085    MachineMemOperand *MMO = *MI->memoperands_begin();
7086    BuildMI(*BB, MI, dl, TII->get(NewOpc))
7087      .addOperand(MI->getOperand(0))  // Rn_wb
7088      .addOperand(MI->getOperand(1))  // Rt
7089      .addOperand(MI->getOperand(2))  // Rn
7090      .addImm(Offset)                 // offset (skip GPR==zero_reg)
7091      .addOperand(MI->getOperand(5))  // pred
7092      .addOperand(MI->getOperand(6))
7093      .addMemOperand(MMO);
7094    MI->eraseFromParent();
7095    return BB;
7096  }
7097  case ARM::STRr_preidx:
7098  case ARM::STRBr_preidx:
7099  case ARM::STRH_preidx: {
7100    unsigned NewOpc;
7101    switch (MI->getOpcode()) {
7102    default: llvm_unreachable("unexpected opcode!");
7103    case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7104    case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7105    case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7106    }
7107    MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7108    for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7109      MIB.addOperand(MI->getOperand(i));
7110    MI->eraseFromParent();
7111    return BB;
7112  }
7113  case ARM::ATOMIC_LOAD_ADD_I8:
7114     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7115  case ARM::ATOMIC_LOAD_ADD_I16:
7116     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7117  case ARM::ATOMIC_LOAD_ADD_I32:
7118     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7119
7120  case ARM::ATOMIC_LOAD_AND_I8:
7121     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7122  case ARM::ATOMIC_LOAD_AND_I16:
7123     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7124  case ARM::ATOMIC_LOAD_AND_I32:
7125     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7126
7127  case ARM::ATOMIC_LOAD_OR_I8:
7128     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7129  case ARM::ATOMIC_LOAD_OR_I16:
7130     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7131  case ARM::ATOMIC_LOAD_OR_I32:
7132     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7133
7134  case ARM::ATOMIC_LOAD_XOR_I8:
7135     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7136  case ARM::ATOMIC_LOAD_XOR_I16:
7137     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7138  case ARM::ATOMIC_LOAD_XOR_I32:
7139     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7140
7141  case ARM::ATOMIC_LOAD_NAND_I8:
7142     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7143  case ARM::ATOMIC_LOAD_NAND_I16:
7144     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7145  case ARM::ATOMIC_LOAD_NAND_I32:
7146     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7147
7148  case ARM::ATOMIC_LOAD_SUB_I8:
7149     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7150  case ARM::ATOMIC_LOAD_SUB_I16:
7151     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7152  case ARM::ATOMIC_LOAD_SUB_I32:
7153     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7154
7155  case ARM::ATOMIC_LOAD_MIN_I8:
7156     return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7157  case ARM::ATOMIC_LOAD_MIN_I16:
7158     return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7159  case ARM::ATOMIC_LOAD_MIN_I32:
7160     return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7161
7162  case ARM::ATOMIC_LOAD_MAX_I8:
7163     return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7164  case ARM::ATOMIC_LOAD_MAX_I16:
7165     return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7166  case ARM::ATOMIC_LOAD_MAX_I32:
7167     return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7168
7169  case ARM::ATOMIC_LOAD_UMIN_I8:
7170     return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7171  case ARM::ATOMIC_LOAD_UMIN_I16:
7172     return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7173  case ARM::ATOMIC_LOAD_UMIN_I32:
7174     return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7175
7176  case ARM::ATOMIC_LOAD_UMAX_I8:
7177     return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7178  case ARM::ATOMIC_LOAD_UMAX_I16:
7179     return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7180  case ARM::ATOMIC_LOAD_UMAX_I32:
7181     return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7182
7183  case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7184  case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7185  case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7186
7187  case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7188  case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7189  case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7190
7191
7192  case ARM::ATOMADD6432:
7193    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7194                              isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7195                              /*NeedsCarry*/ true);
7196  case ARM::ATOMSUB6432:
7197    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7198                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7199                              /*NeedsCarry*/ true);
7200  case ARM::ATOMOR6432:
7201    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7202                              isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7203  case ARM::ATOMXOR6432:
7204    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7205                              isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7206  case ARM::ATOMAND6432:
7207    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7208                              isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7209  case ARM::ATOMSWAP6432:
7210    return EmitAtomicBinary64(MI, BB, 0, 0, false);
7211  case ARM::ATOMCMPXCHG6432:
7212    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7213                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7214                              /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7215  case ARM::ATOMMIN6432:
7216    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7217                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7218                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7219                              /*IsMinMax*/ true, ARMCC::LT);
7220  case ARM::ATOMMAX6432:
7221    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7222                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7223                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7224                              /*IsMinMax*/ true, ARMCC::GE);
7225  case ARM::ATOMUMIN6432:
7226    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7227                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7228                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7229                              /*IsMinMax*/ true, ARMCC::LO);
7230  case ARM::ATOMUMAX6432:
7231    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7232                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7233                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7234                              /*IsMinMax*/ true, ARMCC::HS);
7235
7236  case ARM::tMOVCCr_pseudo: {
7237    // To "insert" a SELECT_CC instruction, we actually have to insert the
7238    // diamond control-flow pattern.  The incoming instruction knows the
7239    // destination vreg to set, the condition code register to branch on, the
7240    // true/false values to select between, and a branch opcode to use.
7241    const BasicBlock *LLVM_BB = BB->getBasicBlock();
7242    MachineFunction::iterator It = BB;
7243    ++It;
7244
7245    //  thisMBB:
7246    //  ...
7247    //   TrueVal = ...
7248    //   cmpTY ccX, r1, r2
7249    //   bCC copy1MBB
7250    //   fallthrough --> copy0MBB
7251    MachineBasicBlock *thisMBB  = BB;
7252    MachineFunction *F = BB->getParent();
7253    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7254    MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7255    F->insert(It, copy0MBB);
7256    F->insert(It, sinkMBB);
7257
7258    // Transfer the remainder of BB and its successor edges to sinkMBB.
7259    sinkMBB->splice(sinkMBB->begin(), BB,
7260                    llvm::next(MachineBasicBlock::iterator(MI)),
7261                    BB->end());
7262    sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7263
7264    BB->addSuccessor(copy0MBB);
7265    BB->addSuccessor(sinkMBB);
7266
7267    BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7268      .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7269
7270    //  copy0MBB:
7271    //   %FalseValue = ...
7272    //   # fallthrough to sinkMBB
7273    BB = copy0MBB;
7274
7275    // Update machine-CFG edges
7276    BB->addSuccessor(sinkMBB);
7277
7278    //  sinkMBB:
7279    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7280    //  ...
7281    BB = sinkMBB;
7282    BuildMI(*BB, BB->begin(), dl,
7283            TII->get(ARM::PHI), MI->getOperand(0).getReg())
7284      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7285      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7286
7287    MI->eraseFromParent();   // The pseudo instruction is gone now.
7288    return BB;
7289  }
7290
7291  case ARM::BCCi64:
7292  case ARM::BCCZi64: {
7293    // If there is an unconditional branch to the other successor, remove it.
7294    BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7295
7296    // Compare both parts that make up the double comparison separately for
7297    // equality.
7298    bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7299
7300    unsigned LHS1 = MI->getOperand(1).getReg();
7301    unsigned LHS2 = MI->getOperand(2).getReg();
7302    if (RHSisZero) {
7303      AddDefaultPred(BuildMI(BB, dl,
7304                             TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7305                     .addReg(LHS1).addImm(0));
7306      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7307        .addReg(LHS2).addImm(0)
7308        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7309    } else {
7310      unsigned RHS1 = MI->getOperand(3).getReg();
7311      unsigned RHS2 = MI->getOperand(4).getReg();
7312      AddDefaultPred(BuildMI(BB, dl,
7313                             TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7314                     .addReg(LHS1).addReg(RHS1));
7315      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7316        .addReg(LHS2).addReg(RHS2)
7317        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7318    }
7319
7320    MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7321    MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7322    if (MI->getOperand(0).getImm() == ARMCC::NE)
7323      std::swap(destMBB, exitMBB);
7324
7325    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7326      .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7327    if (isThumb2)
7328      AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7329    else
7330      BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7331
7332    MI->eraseFromParent();   // The pseudo instruction is gone now.
7333    return BB;
7334  }
7335
7336  case ARM::Int_eh_sjlj_setjmp:
7337  case ARM::Int_eh_sjlj_setjmp_nofp:
7338  case ARM::tInt_eh_sjlj_setjmp:
7339  case ARM::t2Int_eh_sjlj_setjmp:
7340  case ARM::t2Int_eh_sjlj_setjmp_nofp:
7341    EmitSjLjDispatchBlock(MI, BB);
7342    return BB;
7343
7344  case ARM::ABS:
7345  case ARM::t2ABS: {
7346    // To insert an ABS instruction, we have to insert the
7347    // diamond control-flow pattern.  The incoming instruction knows the
7348    // source vreg to test against 0, the destination vreg to set,
7349    // the condition code register to branch on, the
7350    // true/false values to select between, and a branch opcode to use.
7351    // It transforms
7352    //     V1 = ABS V0
7353    // into
7354    //     V2 = MOVS V0
7355    //     BCC                      (branch to SinkBB if V0 >= 0)
7356    //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7357    //     SinkBB: V1 = PHI(V2, V3)
7358    const BasicBlock *LLVM_BB = BB->getBasicBlock();
7359    MachineFunction::iterator BBI = BB;
7360    ++BBI;
7361    MachineFunction *Fn = BB->getParent();
7362    MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7363    MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7364    Fn->insert(BBI, RSBBB);
7365    Fn->insert(BBI, SinkBB);
7366
7367    unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7368    unsigned int ABSDstReg = MI->getOperand(0).getReg();
7369    bool isThumb2 = Subtarget->isThumb2();
7370    MachineRegisterInfo &MRI = Fn->getRegInfo();
7371    // In Thumb mode S must not be specified if source register is the SP or
7372    // PC and if destination register is the SP, so restrict register class
7373    unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7374      (const TargetRegisterClass*)&ARM::rGPRRegClass :
7375      (const TargetRegisterClass*)&ARM::GPRRegClass);
7376
7377    // Transfer the remainder of BB and its successor edges to sinkMBB.
7378    SinkBB->splice(SinkBB->begin(), BB,
7379      llvm::next(MachineBasicBlock::iterator(MI)),
7380      BB->end());
7381    SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7382
7383    BB->addSuccessor(RSBBB);
7384    BB->addSuccessor(SinkBB);
7385
7386    // fall through to SinkMBB
7387    RSBBB->addSuccessor(SinkBB);
7388
7389    // insert a cmp at the end of BB
7390    AddDefaultPred(BuildMI(BB, dl,
7391                           TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7392                   .addReg(ABSSrcReg).addImm(0));
7393
7394    // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7395    BuildMI(BB, dl,
7396      TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7397      .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7398
7399    // insert rsbri in RSBBB
7400    // Note: BCC and rsbri will be converted into predicated rsbmi
7401    // by if-conversion pass
7402    BuildMI(*RSBBB, RSBBB->begin(), dl,
7403      TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7404      .addReg(ABSSrcReg, RegState::Kill)
7405      .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7406
7407    // insert PHI in SinkBB,
7408    // reuse ABSDstReg to not change uses of ABS instruction
7409    BuildMI(*SinkBB, SinkBB->begin(), dl,
7410      TII->get(ARM::PHI), ABSDstReg)
7411      .addReg(NewRsbDstReg).addMBB(RSBBB)
7412      .addReg(ABSSrcReg).addMBB(BB);
7413
7414    // remove ABS instruction
7415    MI->eraseFromParent();
7416
7417    // return last added BB
7418    return SinkBB;
7419  }
7420  case ARM::COPY_STRUCT_BYVAL_I32:
7421    ++NumLoopByVals;
7422    return EmitStructByval(MI, BB);
7423  }
7424}
7425
7426void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7427                                                      SDNode *Node) const {
7428  if (!MI->hasPostISelHook()) {
7429    assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7430           "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7431    return;
7432  }
7433
7434  const MCInstrDesc *MCID = &MI->getDesc();
7435  // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7436  // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7437  // operand is still set to noreg. If needed, set the optional operand's
7438  // register to CPSR, and remove the redundant implicit def.
7439  //
7440  // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7441
7442  // Rename pseudo opcodes.
7443  unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7444  if (NewOpc) {
7445    const ARMBaseInstrInfo *TII =
7446      static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7447    MCID = &TII->get(NewOpc);
7448
7449    assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7450           "converted opcode should be the same except for cc_out");
7451
7452    MI->setDesc(*MCID);
7453
7454    // Add the optional cc_out operand
7455    MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7456  }
7457  unsigned ccOutIdx = MCID->getNumOperands() - 1;
7458
7459  // Any ARM instruction that sets the 's' bit should specify an optional
7460  // "cc_out" operand in the last operand position.
7461  if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7462    assert(!NewOpc && "Optional cc_out operand required");
7463    return;
7464  }
7465  // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7466  // since we already have an optional CPSR def.
7467  bool definesCPSR = false;
7468  bool deadCPSR = false;
7469  for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7470       i != e; ++i) {
7471    const MachineOperand &MO = MI->getOperand(i);
7472    if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7473      definesCPSR = true;
7474      if (MO.isDead())
7475        deadCPSR = true;
7476      MI->RemoveOperand(i);
7477      break;
7478    }
7479  }
7480  if (!definesCPSR) {
7481    assert(!NewOpc && "Optional cc_out operand required");
7482    return;
7483  }
7484  assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7485  if (deadCPSR) {
7486    assert(!MI->getOperand(ccOutIdx).getReg() &&
7487           "expect uninitialized optional cc_out operand");
7488    return;
7489  }
7490
7491  // If this instruction was defined with an optional CPSR def and its dag node
7492  // had a live implicit CPSR def, then activate the optional CPSR def.
7493  MachineOperand &MO = MI->getOperand(ccOutIdx);
7494  MO.setReg(ARM::CPSR);
7495  MO.setIsDef(true);
7496}
7497
7498//===----------------------------------------------------------------------===//
7499//                           ARM Optimization Hooks
7500//===----------------------------------------------------------------------===//
7501
7502// Helper function that checks if N is a null or all ones constant.
7503static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7504  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7505  if (!C)
7506    return false;
7507  return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7508}
7509
7510// Return true if N is conditionally 0 or all ones.
7511// Detects these expressions where cc is an i1 value:
7512//
7513//   (select cc 0, y)   [AllOnes=0]
7514//   (select cc y, 0)   [AllOnes=0]
7515//   (zext cc)          [AllOnes=0]
7516//   (sext cc)          [AllOnes=0/1]
7517//   (select cc -1, y)  [AllOnes=1]
7518//   (select cc y, -1)  [AllOnes=1]
7519//
7520// Invert is set when N is the null/all ones constant when CC is false.
7521// OtherOp is set to the alternative value of N.
7522static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7523                                       SDValue &CC, bool &Invert,
7524                                       SDValue &OtherOp,
7525                                       SelectionDAG &DAG) {
7526  switch (N->getOpcode()) {
7527  default: return false;
7528  case ISD::SELECT: {
7529    CC = N->getOperand(0);
7530    SDValue N1 = N->getOperand(1);
7531    SDValue N2 = N->getOperand(2);
7532    if (isZeroOrAllOnes(N1, AllOnes)) {
7533      Invert = false;
7534      OtherOp = N2;
7535      return true;
7536    }
7537    if (isZeroOrAllOnes(N2, AllOnes)) {
7538      Invert = true;
7539      OtherOp = N1;
7540      return true;
7541    }
7542    return false;
7543  }
7544  case ISD::ZERO_EXTEND:
7545    // (zext cc) can never be the all ones value.
7546    if (AllOnes)
7547      return false;
7548    // Fall through.
7549  case ISD::SIGN_EXTEND: {
7550    EVT VT = N->getValueType(0);
7551    CC = N->getOperand(0);
7552    if (CC.getValueType() != MVT::i1)
7553      return false;
7554    Invert = !AllOnes;
7555    if (AllOnes)
7556      // When looking for an AllOnes constant, N is an sext, and the 'other'
7557      // value is 0.
7558      OtherOp = DAG.getConstant(0, VT);
7559    else if (N->getOpcode() == ISD::ZERO_EXTEND)
7560      // When looking for a 0 constant, N can be zext or sext.
7561      OtherOp = DAG.getConstant(1, VT);
7562    else
7563      OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7564    return true;
7565  }
7566  }
7567}
7568
7569// Combine a constant select operand into its use:
7570//
7571//   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7572//   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7573//   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7574//   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7575//   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7576//
7577// The transform is rejected if the select doesn't have a constant operand that
7578// is null, or all ones when AllOnes is set.
7579//
7580// Also recognize sext/zext from i1:
7581//
7582//   (add (zext cc), x) -> (select cc (add x, 1), x)
7583//   (add (sext cc), x) -> (select cc (add x, -1), x)
7584//
7585// These transformations eventually create predicated instructions.
7586//
7587// @param N       The node to transform.
7588// @param Slct    The N operand that is a select.
7589// @param OtherOp The other N operand (x above).
7590// @param DCI     Context.
7591// @param AllOnes Require the select constant to be all ones instead of null.
7592// @returns The new node, or SDValue() on failure.
7593static
7594SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7595                            TargetLowering::DAGCombinerInfo &DCI,
7596                            bool AllOnes = false) {
7597  SelectionDAG &DAG = DCI.DAG;
7598  EVT VT = N->getValueType(0);
7599  SDValue NonConstantVal;
7600  SDValue CCOp;
7601  bool SwapSelectOps;
7602  if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7603                                  NonConstantVal, DAG))
7604    return SDValue();
7605
7606  // Slct is now know to be the desired identity constant when CC is true.
7607  SDValue TrueVal = OtherOp;
7608  SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7609                                 OtherOp, NonConstantVal);
7610  // Unless SwapSelectOps says CC should be false.
7611  if (SwapSelectOps)
7612    std::swap(TrueVal, FalseVal);
7613
7614  return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7615                     CCOp, TrueVal, FalseVal);
7616}
7617
7618// Attempt combineSelectAndUse on each operand of a commutative operator N.
7619static
7620SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7621                                       TargetLowering::DAGCombinerInfo &DCI) {
7622  SDValue N0 = N->getOperand(0);
7623  SDValue N1 = N->getOperand(1);
7624  if (N0.getNode()->hasOneUse()) {
7625    SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7626    if (Result.getNode())
7627      return Result;
7628  }
7629  if (N1.getNode()->hasOneUse()) {
7630    SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7631    if (Result.getNode())
7632      return Result;
7633  }
7634  return SDValue();
7635}
7636
7637// AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7638// (only after legalization).
7639static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7640                                 TargetLowering::DAGCombinerInfo &DCI,
7641                                 const ARMSubtarget *Subtarget) {
7642
7643  // Only perform optimization if after legalize, and if NEON is available. We
7644  // also expected both operands to be BUILD_VECTORs.
7645  if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7646      || N0.getOpcode() != ISD::BUILD_VECTOR
7647      || N1.getOpcode() != ISD::BUILD_VECTOR)
7648    return SDValue();
7649
7650  // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7651  EVT VT = N->getValueType(0);
7652  if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7653    return SDValue();
7654
7655  // Check that the vector operands are of the right form.
7656  // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7657  // operands, where N is the size of the formed vector.
7658  // Each EXTRACT_VECTOR should have the same input vector and odd or even
7659  // index such that we have a pair wise add pattern.
7660
7661  // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7662  if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7663    return SDValue();
7664  SDValue Vec = N0->getOperand(0)->getOperand(0);
7665  SDNode *V = Vec.getNode();
7666  unsigned nextIndex = 0;
7667
7668  // For each operands to the ADD which are BUILD_VECTORs,
7669  // check to see if each of their operands are an EXTRACT_VECTOR with
7670  // the same vector and appropriate index.
7671  for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7672    if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7673        && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7674
7675      SDValue ExtVec0 = N0->getOperand(i);
7676      SDValue ExtVec1 = N1->getOperand(i);
7677
7678      // First operand is the vector, verify its the same.
7679      if (V != ExtVec0->getOperand(0).getNode() ||
7680          V != ExtVec1->getOperand(0).getNode())
7681        return SDValue();
7682
7683      // Second is the constant, verify its correct.
7684      ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7685      ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7686
7687      // For the constant, we want to see all the even or all the odd.
7688      if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7689          || C1->getZExtValue() != nextIndex+1)
7690        return SDValue();
7691
7692      // Increment index.
7693      nextIndex+=2;
7694    } else
7695      return SDValue();
7696  }
7697
7698  // Create VPADDL node.
7699  SelectionDAG &DAG = DCI.DAG;
7700  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7701
7702  // Build operand list.
7703  SmallVector<SDValue, 8> Ops;
7704  Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7705                                TLI.getPointerTy()));
7706
7707  // Input is the vector.
7708  Ops.push_back(Vec);
7709
7710  // Get widened type and narrowed type.
7711  MVT widenType;
7712  unsigned numElem = VT.getVectorNumElements();
7713  switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7714    case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7715    case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7716    case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7717    default:
7718      llvm_unreachable("Invalid vector element type for padd optimization.");
7719  }
7720
7721  SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7722                            widenType, &Ops[0], Ops.size());
7723  return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7724}
7725
7726static SDValue findMUL_LOHI(SDValue V) {
7727  if (V->getOpcode() == ISD::UMUL_LOHI ||
7728      V->getOpcode() == ISD::SMUL_LOHI)
7729    return V;
7730  return SDValue();
7731}
7732
7733static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7734                                     TargetLowering::DAGCombinerInfo &DCI,
7735                                     const ARMSubtarget *Subtarget) {
7736
7737  if (Subtarget->isThumb1Only()) return SDValue();
7738
7739  // Only perform the checks after legalize when the pattern is available.
7740  if (DCI.isBeforeLegalize()) return SDValue();
7741
7742  // Look for multiply add opportunities.
7743  // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7744  // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7745  // a glue link from the first add to the second add.
7746  // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7747  // a S/UMLAL instruction.
7748  //          loAdd   UMUL_LOHI
7749  //            \    / :lo    \ :hi
7750  //             \  /          \          [no multiline comment]
7751  //              ADDC         |  hiAdd
7752  //                 \ :glue  /  /
7753  //                  \      /  /
7754  //                    ADDE
7755  //
7756  assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7757  SDValue AddcOp0 = AddcNode->getOperand(0);
7758  SDValue AddcOp1 = AddcNode->getOperand(1);
7759
7760  // Check if the two operands are from the same mul_lohi node.
7761  if (AddcOp0.getNode() == AddcOp1.getNode())
7762    return SDValue();
7763
7764  assert(AddcNode->getNumValues() == 2 &&
7765         AddcNode->getValueType(0) == MVT::i32 &&
7766         AddcNode->getValueType(1) == MVT::Glue &&
7767         "Expect ADDC with two result values: i32, glue");
7768
7769  // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7770  if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7771      AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7772      AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7773      AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7774    return SDValue();
7775
7776  // Look for the glued ADDE.
7777  SDNode* AddeNode = AddcNode->getGluedUser();
7778  if (AddeNode == NULL)
7779    return SDValue();
7780
7781  // Make sure it is really an ADDE.
7782  if (AddeNode->getOpcode() != ISD::ADDE)
7783    return SDValue();
7784
7785  assert(AddeNode->getNumOperands() == 3 &&
7786         AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7787         "ADDE node has the wrong inputs");
7788
7789  // Check for the triangle shape.
7790  SDValue AddeOp0 = AddeNode->getOperand(0);
7791  SDValue AddeOp1 = AddeNode->getOperand(1);
7792
7793  // Make sure that the ADDE operands are not coming from the same node.
7794  if (AddeOp0.getNode() == AddeOp1.getNode())
7795    return SDValue();
7796
7797  // Find the MUL_LOHI node walking up ADDE's operands.
7798  bool IsLeftOperandMUL = false;
7799  SDValue MULOp = findMUL_LOHI(AddeOp0);
7800  if (MULOp == SDValue())
7801   MULOp = findMUL_LOHI(AddeOp1);
7802  else
7803    IsLeftOperandMUL = true;
7804  if (MULOp == SDValue())
7805     return SDValue();
7806
7807  // Figure out the right opcode.
7808  unsigned Opc = MULOp->getOpcode();
7809  unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7810
7811  // Figure out the high and low input values to the MLAL node.
7812  SDValue* HiMul = &MULOp;
7813  SDValue* HiAdd = NULL;
7814  SDValue* LoMul = NULL;
7815  SDValue* LowAdd = NULL;
7816
7817  if (IsLeftOperandMUL)
7818    HiAdd = &AddeOp1;
7819  else
7820    HiAdd = &AddeOp0;
7821
7822
7823  if (AddcOp0->getOpcode() == Opc) {
7824    LoMul = &AddcOp0;
7825    LowAdd = &AddcOp1;
7826  }
7827  if (AddcOp1->getOpcode() == Opc) {
7828    LoMul = &AddcOp1;
7829    LowAdd = &AddcOp0;
7830  }
7831
7832  if (LoMul == NULL)
7833    return SDValue();
7834
7835  if (LoMul->getNode() != HiMul->getNode())
7836    return SDValue();
7837
7838  // Create the merged node.
7839  SelectionDAG &DAG = DCI.DAG;
7840
7841  // Build operand list.
7842  SmallVector<SDValue, 8> Ops;
7843  Ops.push_back(LoMul->getOperand(0));
7844  Ops.push_back(LoMul->getOperand(1));
7845  Ops.push_back(*LowAdd);
7846  Ops.push_back(*HiAdd);
7847
7848  SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7849                                 DAG.getVTList(MVT::i32, MVT::i32),
7850                                 &Ops[0], Ops.size());
7851
7852  // Replace the ADDs' nodes uses by the MLA node's values.
7853  SDValue HiMLALResult(MLALNode.getNode(), 1);
7854  DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7855
7856  SDValue LoMLALResult(MLALNode.getNode(), 0);
7857  DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7858
7859  // Return original node to notify the driver to stop replacing.
7860  SDValue resNode(AddcNode, 0);
7861  return resNode;
7862}
7863
7864/// PerformADDCCombine - Target-specific dag combine transform from
7865/// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7866static SDValue PerformADDCCombine(SDNode *N,
7867                                 TargetLowering::DAGCombinerInfo &DCI,
7868                                 const ARMSubtarget *Subtarget) {
7869
7870  return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7871
7872}
7873
7874/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7875/// operands N0 and N1.  This is a helper for PerformADDCombine that is
7876/// called with the default operands, and if that fails, with commuted
7877/// operands.
7878static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7879                                          TargetLowering::DAGCombinerInfo &DCI,
7880                                          const ARMSubtarget *Subtarget){
7881
7882  // Attempt to create vpaddl for this add.
7883  SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7884  if (Result.getNode())
7885    return Result;
7886
7887  // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7888  if (N0.getNode()->hasOneUse()) {
7889    SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7890    if (Result.getNode()) return Result;
7891  }
7892  return SDValue();
7893}
7894
7895/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7896///
7897static SDValue PerformADDCombine(SDNode *N,
7898                                 TargetLowering::DAGCombinerInfo &DCI,
7899                                 const ARMSubtarget *Subtarget) {
7900  SDValue N0 = N->getOperand(0);
7901  SDValue N1 = N->getOperand(1);
7902
7903  // First try with the default operand order.
7904  SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7905  if (Result.getNode())
7906    return Result;
7907
7908  // If that didn't work, try again with the operands commuted.
7909  return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7910}
7911
7912/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7913///
7914static SDValue PerformSUBCombine(SDNode *N,
7915                                 TargetLowering::DAGCombinerInfo &DCI) {
7916  SDValue N0 = N->getOperand(0);
7917  SDValue N1 = N->getOperand(1);
7918
7919  // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7920  if (N1.getNode()->hasOneUse()) {
7921    SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7922    if (Result.getNode()) return Result;
7923  }
7924
7925  return SDValue();
7926}
7927
7928/// PerformVMULCombine
7929/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7930/// special multiplier accumulator forwarding.
7931///   vmul d3, d0, d2
7932///   vmla d3, d1, d2
7933/// is faster than
7934///   vadd d3, d0, d1
7935///   vmul d3, d3, d2
7936static SDValue PerformVMULCombine(SDNode *N,
7937                                  TargetLowering::DAGCombinerInfo &DCI,
7938                                  const ARMSubtarget *Subtarget) {
7939  if (!Subtarget->hasVMLxForwarding())
7940    return SDValue();
7941
7942  SelectionDAG &DAG = DCI.DAG;
7943  SDValue N0 = N->getOperand(0);
7944  SDValue N1 = N->getOperand(1);
7945  unsigned Opcode = N0.getOpcode();
7946  if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7947      Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7948    Opcode = N1.getOpcode();
7949    if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7950        Opcode != ISD::FADD && Opcode != ISD::FSUB)
7951      return SDValue();
7952    std::swap(N0, N1);
7953  }
7954
7955  EVT VT = N->getValueType(0);
7956  DebugLoc DL = N->getDebugLoc();
7957  SDValue N00 = N0->getOperand(0);
7958  SDValue N01 = N0->getOperand(1);
7959  return DAG.getNode(Opcode, DL, VT,
7960                     DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7961                     DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7962}
7963
7964static SDValue PerformMULCombine(SDNode *N,
7965                                 TargetLowering::DAGCombinerInfo &DCI,
7966                                 const ARMSubtarget *Subtarget) {
7967  SelectionDAG &DAG = DCI.DAG;
7968
7969  if (Subtarget->isThumb1Only())
7970    return SDValue();
7971
7972  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7973    return SDValue();
7974
7975  EVT VT = N->getValueType(0);
7976  if (VT.is64BitVector() || VT.is128BitVector())
7977    return PerformVMULCombine(N, DCI, Subtarget);
7978  if (VT != MVT::i32)
7979    return SDValue();
7980
7981  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7982  if (!C)
7983    return SDValue();
7984
7985  int64_t MulAmt = C->getSExtValue();
7986  unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7987
7988  ShiftAmt = ShiftAmt & (32 - 1);
7989  SDValue V = N->getOperand(0);
7990  DebugLoc DL = N->getDebugLoc();
7991
7992  SDValue Res;
7993  MulAmt >>= ShiftAmt;
7994
7995  if (MulAmt >= 0) {
7996    if (isPowerOf2_32(MulAmt - 1)) {
7997      // (mul x, 2^N + 1) => (add (shl x, N), x)
7998      Res = DAG.getNode(ISD::ADD, DL, VT,
7999                        V,
8000                        DAG.getNode(ISD::SHL, DL, VT,
8001                                    V,
8002                                    DAG.getConstant(Log2_32(MulAmt - 1),
8003                                                    MVT::i32)));
8004    } else if (isPowerOf2_32(MulAmt + 1)) {
8005      // (mul x, 2^N - 1) => (sub (shl x, N), x)
8006      Res = DAG.getNode(ISD::SUB, DL, VT,
8007                        DAG.getNode(ISD::SHL, DL, VT,
8008                                    V,
8009                                    DAG.getConstant(Log2_32(MulAmt + 1),
8010                                                    MVT::i32)),
8011                        V);
8012    } else
8013      return SDValue();
8014  } else {
8015    uint64_t MulAmtAbs = -MulAmt;
8016    if (isPowerOf2_32(MulAmtAbs + 1)) {
8017      // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8018      Res = DAG.getNode(ISD::SUB, DL, VT,
8019                        V,
8020                        DAG.getNode(ISD::SHL, DL, VT,
8021                                    V,
8022                                    DAG.getConstant(Log2_32(MulAmtAbs + 1),
8023                                                    MVT::i32)));
8024    } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8025      // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8026      Res = DAG.getNode(ISD::ADD, DL, VT,
8027                        V,
8028                        DAG.getNode(ISD::SHL, DL, VT,
8029                                    V,
8030                                    DAG.getConstant(Log2_32(MulAmtAbs-1),
8031                                                    MVT::i32)));
8032      Res = DAG.getNode(ISD::SUB, DL, VT,
8033                        DAG.getConstant(0, MVT::i32),Res);
8034
8035    } else
8036      return SDValue();
8037  }
8038
8039  if (ShiftAmt != 0)
8040    Res = DAG.getNode(ISD::SHL, DL, VT,
8041                      Res, DAG.getConstant(ShiftAmt, MVT::i32));
8042
8043  // Do not add new nodes to DAG combiner worklist.
8044  DCI.CombineTo(N, Res, false);
8045  return SDValue();
8046}
8047
8048static SDValue PerformANDCombine(SDNode *N,
8049                                 TargetLowering::DAGCombinerInfo &DCI,
8050                                 const ARMSubtarget *Subtarget) {
8051
8052  // Attempt to use immediate-form VBIC
8053  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8054  DebugLoc dl = N->getDebugLoc();
8055  EVT VT = N->getValueType(0);
8056  SelectionDAG &DAG = DCI.DAG;
8057
8058  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8059    return SDValue();
8060
8061  APInt SplatBits, SplatUndef;
8062  unsigned SplatBitSize;
8063  bool HasAnyUndefs;
8064  if (BVN &&
8065      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8066    if (SplatBitSize <= 64) {
8067      EVT VbicVT;
8068      SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8069                                      SplatUndef.getZExtValue(), SplatBitSize,
8070                                      DAG, VbicVT, VT.is128BitVector(),
8071                                      OtherModImm);
8072      if (Val.getNode()) {
8073        SDValue Input =
8074          DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8075        SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8076        return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8077      }
8078    }
8079  }
8080
8081  if (!Subtarget->isThumb1Only()) {
8082    // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8083    SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8084    if (Result.getNode())
8085      return Result;
8086  }
8087
8088  return SDValue();
8089}
8090
8091/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8092static SDValue PerformORCombine(SDNode *N,
8093                                TargetLowering::DAGCombinerInfo &DCI,
8094                                const ARMSubtarget *Subtarget) {
8095  // Attempt to use immediate-form VORR
8096  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8097  DebugLoc dl = N->getDebugLoc();
8098  EVT VT = N->getValueType(0);
8099  SelectionDAG &DAG = DCI.DAG;
8100
8101  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8102    return SDValue();
8103
8104  APInt SplatBits, SplatUndef;
8105  unsigned SplatBitSize;
8106  bool HasAnyUndefs;
8107  if (BVN && Subtarget->hasNEON() &&
8108      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8109    if (SplatBitSize <= 64) {
8110      EVT VorrVT;
8111      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8112                                      SplatUndef.getZExtValue(), SplatBitSize,
8113                                      DAG, VorrVT, VT.is128BitVector(),
8114                                      OtherModImm);
8115      if (Val.getNode()) {
8116        SDValue Input =
8117          DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8118        SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8119        return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8120      }
8121    }
8122  }
8123
8124  if (!Subtarget->isThumb1Only()) {
8125    // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8126    SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8127    if (Result.getNode())
8128      return Result;
8129  }
8130
8131  // The code below optimizes (or (and X, Y), Z).
8132  // The AND operand needs to have a single user to make these optimizations
8133  // profitable.
8134  SDValue N0 = N->getOperand(0);
8135  if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8136    return SDValue();
8137  SDValue N1 = N->getOperand(1);
8138
8139  // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8140  if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8141      DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8142    APInt SplatUndef;
8143    unsigned SplatBitSize;
8144    bool HasAnyUndefs;
8145
8146    BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8147    APInt SplatBits0;
8148    if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8149                                  HasAnyUndefs) && !HasAnyUndefs) {
8150      BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8151      APInt SplatBits1;
8152      if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8153                                    HasAnyUndefs) && !HasAnyUndefs &&
8154          SplatBits0 == ~SplatBits1) {
8155        // Canonicalize the vector type to make instruction selection simpler.
8156        EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8157        SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8158                                     N0->getOperand(1), N0->getOperand(0),
8159                                     N1->getOperand(0));
8160        return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8161      }
8162    }
8163  }
8164
8165  // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8166  // reasonable.
8167
8168  // BFI is only available on V6T2+
8169  if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8170    return SDValue();
8171
8172  DebugLoc DL = N->getDebugLoc();
8173  // 1) or (and A, mask), val => ARMbfi A, val, mask
8174  //      iff (val & mask) == val
8175  //
8176  // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8177  //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8178  //          && mask == ~mask2
8179  //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8180  //          && ~mask == mask2
8181  //  (i.e., copy a bitfield value into another bitfield of the same width)
8182
8183  if (VT != MVT::i32)
8184    return SDValue();
8185
8186  SDValue N00 = N0.getOperand(0);
8187
8188  // The value and the mask need to be constants so we can verify this is
8189  // actually a bitfield set. If the mask is 0xffff, we can do better
8190  // via a movt instruction, so don't use BFI in that case.
8191  SDValue MaskOp = N0.getOperand(1);
8192  ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8193  if (!MaskC)
8194    return SDValue();
8195  unsigned Mask = MaskC->getZExtValue();
8196  if (Mask == 0xffff)
8197    return SDValue();
8198  SDValue Res;
8199  // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8200  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8201  if (N1C) {
8202    unsigned Val = N1C->getZExtValue();
8203    if ((Val & ~Mask) != Val)
8204      return SDValue();
8205
8206    if (ARM::isBitFieldInvertedMask(Mask)) {
8207      Val >>= CountTrailingZeros_32(~Mask);
8208
8209      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8210                        DAG.getConstant(Val, MVT::i32),
8211                        DAG.getConstant(Mask, MVT::i32));
8212
8213      // Do not add new nodes to DAG combiner worklist.
8214      DCI.CombineTo(N, Res, false);
8215      return SDValue();
8216    }
8217  } else if (N1.getOpcode() == ISD::AND) {
8218    // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8219    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8220    if (!N11C)
8221      return SDValue();
8222    unsigned Mask2 = N11C->getZExtValue();
8223
8224    // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8225    // as is to match.
8226    if (ARM::isBitFieldInvertedMask(Mask) &&
8227        (Mask == ~Mask2)) {
8228      // The pack halfword instruction works better for masks that fit it,
8229      // so use that when it's available.
8230      if (Subtarget->hasT2ExtractPack() &&
8231          (Mask == 0xffff || Mask == 0xffff0000))
8232        return SDValue();
8233      // 2a
8234      unsigned amt = CountTrailingZeros_32(Mask2);
8235      Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8236                        DAG.getConstant(amt, MVT::i32));
8237      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8238                        DAG.getConstant(Mask, MVT::i32));
8239      // Do not add new nodes to DAG combiner worklist.
8240      DCI.CombineTo(N, Res, false);
8241      return SDValue();
8242    } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8243               (~Mask == Mask2)) {
8244      // The pack halfword instruction works better for masks that fit it,
8245      // so use that when it's available.
8246      if (Subtarget->hasT2ExtractPack() &&
8247          (Mask2 == 0xffff || Mask2 == 0xffff0000))
8248        return SDValue();
8249      // 2b
8250      unsigned lsb = CountTrailingZeros_32(Mask);
8251      Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8252                        DAG.getConstant(lsb, MVT::i32));
8253      Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8254                        DAG.getConstant(Mask2, MVT::i32));
8255      // Do not add new nodes to DAG combiner worklist.
8256      DCI.CombineTo(N, Res, false);
8257      return SDValue();
8258    }
8259  }
8260
8261  if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8262      N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8263      ARM::isBitFieldInvertedMask(~Mask)) {
8264    // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8265    // where lsb(mask) == #shamt and masked bits of B are known zero.
8266    SDValue ShAmt = N00.getOperand(1);
8267    unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8268    unsigned LSB = CountTrailingZeros_32(Mask);
8269    if (ShAmtC != LSB)
8270      return SDValue();
8271
8272    Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8273                      DAG.getConstant(~Mask, MVT::i32));
8274
8275    // Do not add new nodes to DAG combiner worklist.
8276    DCI.CombineTo(N, Res, false);
8277  }
8278
8279  return SDValue();
8280}
8281
8282static SDValue PerformXORCombine(SDNode *N,
8283                                 TargetLowering::DAGCombinerInfo &DCI,
8284                                 const ARMSubtarget *Subtarget) {
8285  EVT VT = N->getValueType(0);
8286  SelectionDAG &DAG = DCI.DAG;
8287
8288  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8289    return SDValue();
8290
8291  if (!Subtarget->isThumb1Only()) {
8292    // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8293    SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8294    if (Result.getNode())
8295      return Result;
8296  }
8297
8298  return SDValue();
8299}
8300
8301/// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8302/// the bits being cleared by the AND are not demanded by the BFI.
8303static SDValue PerformBFICombine(SDNode *N,
8304                                 TargetLowering::DAGCombinerInfo &DCI) {
8305  SDValue N1 = N->getOperand(1);
8306  if (N1.getOpcode() == ISD::AND) {
8307    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8308    if (!N11C)
8309      return SDValue();
8310    unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8311    unsigned LSB = CountTrailingZeros_32(~InvMask);
8312    unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8313    unsigned Mask = (1 << Width)-1;
8314    unsigned Mask2 = N11C->getZExtValue();
8315    if ((Mask & (~Mask2)) == 0)
8316      return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8317                             N->getOperand(0), N1.getOperand(0),
8318                             N->getOperand(2));
8319  }
8320  return SDValue();
8321}
8322
8323/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8324/// ARMISD::VMOVRRD.
8325static SDValue PerformVMOVRRDCombine(SDNode *N,
8326                                     TargetLowering::DAGCombinerInfo &DCI) {
8327  // vmovrrd(vmovdrr x, y) -> x,y
8328  SDValue InDouble = N->getOperand(0);
8329  if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8330    return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8331
8332  // vmovrrd(load f64) -> (load i32), (load i32)
8333  SDNode *InNode = InDouble.getNode();
8334  if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8335      InNode->getValueType(0) == MVT::f64 &&
8336      InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8337      !cast<LoadSDNode>(InNode)->isVolatile()) {
8338    // TODO: Should this be done for non-FrameIndex operands?
8339    LoadSDNode *LD = cast<LoadSDNode>(InNode);
8340
8341    SelectionDAG &DAG = DCI.DAG;
8342    DebugLoc DL = LD->getDebugLoc();
8343    SDValue BasePtr = LD->getBasePtr();
8344    SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8345                                 LD->getPointerInfo(), LD->isVolatile(),
8346                                 LD->isNonTemporal(), LD->isInvariant(),
8347                                 LD->getAlignment());
8348
8349    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8350                                    DAG.getConstant(4, MVT::i32));
8351    SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8352                                 LD->getPointerInfo(), LD->isVolatile(),
8353                                 LD->isNonTemporal(), LD->isInvariant(),
8354                                 std::min(4U, LD->getAlignment() / 2));
8355
8356    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8357    SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8358    DCI.RemoveFromWorklist(LD);
8359    DAG.DeleteNode(LD);
8360    return Result;
8361  }
8362
8363  return SDValue();
8364}
8365
8366/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8367/// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8368static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8369  // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8370  SDValue Op0 = N->getOperand(0);
8371  SDValue Op1 = N->getOperand(1);
8372  if (Op0.getOpcode() == ISD::BITCAST)
8373    Op0 = Op0.getOperand(0);
8374  if (Op1.getOpcode() == ISD::BITCAST)
8375    Op1 = Op1.getOperand(0);
8376  if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8377      Op0.getNode() == Op1.getNode() &&
8378      Op0.getResNo() == 0 && Op1.getResNo() == 1)
8379    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8380                       N->getValueType(0), Op0.getOperand(0));
8381  return SDValue();
8382}
8383
8384/// PerformSTORECombine - Target-specific dag combine xforms for
8385/// ISD::STORE.
8386static SDValue PerformSTORECombine(SDNode *N,
8387                                   TargetLowering::DAGCombinerInfo &DCI) {
8388  StoreSDNode *St = cast<StoreSDNode>(N);
8389  if (St->isVolatile())
8390    return SDValue();
8391
8392  // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8393  // pack all of the elements in one place.  Next, store to memory in fewer
8394  // chunks.
8395  SDValue StVal = St->getValue();
8396  EVT VT = StVal.getValueType();
8397  if (St->isTruncatingStore() && VT.isVector()) {
8398    SelectionDAG &DAG = DCI.DAG;
8399    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8400    EVT StVT = St->getMemoryVT();
8401    unsigned NumElems = VT.getVectorNumElements();
8402    assert(StVT != VT && "Cannot truncate to the same type");
8403    unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8404    unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8405
8406    // From, To sizes and ElemCount must be pow of two
8407    if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8408
8409    // We are going to use the original vector elt for storing.
8410    // Accumulated smaller vector elements must be a multiple of the store size.
8411    if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8412
8413    unsigned SizeRatio  = FromEltSz / ToEltSz;
8414    assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8415
8416    // Create a type on which we perform the shuffle.
8417    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8418                                     NumElems*SizeRatio);
8419    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8420
8421    DebugLoc DL = St->getDebugLoc();
8422    SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8423    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8424    for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8425
8426    // Can't shuffle using an illegal type.
8427    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8428
8429    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8430                                DAG.getUNDEF(WideVec.getValueType()),
8431                                ShuffleVec.data());
8432    // At this point all of the data is stored at the bottom of the
8433    // register. We now need to save it to mem.
8434
8435    // Find the largest store unit
8436    MVT StoreType = MVT::i8;
8437    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8438         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8439      MVT Tp = (MVT::SimpleValueType)tp;
8440      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8441        StoreType = Tp;
8442    }
8443    // Didn't find a legal store type.
8444    if (!TLI.isTypeLegal(StoreType))
8445      return SDValue();
8446
8447    // Bitcast the original vector into a vector of store-size units
8448    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8449            StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8450    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8451    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8452    SmallVector<SDValue, 8> Chains;
8453    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8454                                        TLI.getPointerTy());
8455    SDValue BasePtr = St->getBasePtr();
8456
8457    // Perform one or more big stores into memory.
8458    unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8459    for (unsigned I = 0; I < E; I++) {
8460      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8461                                   StoreType, ShuffWide,
8462                                   DAG.getIntPtrConstant(I));
8463      SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8464                                St->getPointerInfo(), St->isVolatile(),
8465                                St->isNonTemporal(), St->getAlignment());
8466      BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8467                            Increment);
8468      Chains.push_back(Ch);
8469    }
8470    return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8471                       Chains.size());
8472  }
8473
8474  if (!ISD::isNormalStore(St))
8475    return SDValue();
8476
8477  // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8478  // ARM stores of arguments in the same cache line.
8479  if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8480      StVal.getNode()->hasOneUse()) {
8481    SelectionDAG  &DAG = DCI.DAG;
8482    DebugLoc DL = St->getDebugLoc();
8483    SDValue BasePtr = St->getBasePtr();
8484    SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8485                                  StVal.getNode()->getOperand(0), BasePtr,
8486                                  St->getPointerInfo(), St->isVolatile(),
8487                                  St->isNonTemporal(), St->getAlignment());
8488
8489    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8490                                    DAG.getConstant(4, MVT::i32));
8491    return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8492                        OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8493                        St->isNonTemporal(),
8494                        std::min(4U, St->getAlignment() / 2));
8495  }
8496
8497  if (StVal.getValueType() != MVT::i64 ||
8498      StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8499    return SDValue();
8500
8501  // Bitcast an i64 store extracted from a vector to f64.
8502  // Otherwise, the i64 value will be legalized to a pair of i32 values.
8503  SelectionDAG &DAG = DCI.DAG;
8504  DebugLoc dl = StVal.getDebugLoc();
8505  SDValue IntVec = StVal.getOperand(0);
8506  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8507                                 IntVec.getValueType().getVectorNumElements());
8508  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8509  SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8510                               Vec, StVal.getOperand(1));
8511  dl = N->getDebugLoc();
8512  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8513  // Make the DAGCombiner fold the bitcasts.
8514  DCI.AddToWorklist(Vec.getNode());
8515  DCI.AddToWorklist(ExtElt.getNode());
8516  DCI.AddToWorklist(V.getNode());
8517  return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8518                      St->getPointerInfo(), St->isVolatile(),
8519                      St->isNonTemporal(), St->getAlignment(),
8520                      St->getTBAAInfo());
8521}
8522
8523/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8524/// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8525/// i64 vector to have f64 elements, since the value can then be loaded
8526/// directly into a VFP register.
8527static bool hasNormalLoadOperand(SDNode *N) {
8528  unsigned NumElts = N->getValueType(0).getVectorNumElements();
8529  for (unsigned i = 0; i < NumElts; ++i) {
8530    SDNode *Elt = N->getOperand(i).getNode();
8531    if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8532      return true;
8533  }
8534  return false;
8535}
8536
8537/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8538/// ISD::BUILD_VECTOR.
8539static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8540                                          TargetLowering::DAGCombinerInfo &DCI){
8541  // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8542  // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8543  // into a pair of GPRs, which is fine when the value is used as a scalar,
8544  // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8545  SelectionDAG &DAG = DCI.DAG;
8546  if (N->getNumOperands() == 2) {
8547    SDValue RV = PerformVMOVDRRCombine(N, DAG);
8548    if (RV.getNode())
8549      return RV;
8550  }
8551
8552  // Load i64 elements as f64 values so that type legalization does not split
8553  // them up into i32 values.
8554  EVT VT = N->getValueType(0);
8555  if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8556    return SDValue();
8557  DebugLoc dl = N->getDebugLoc();
8558  SmallVector<SDValue, 8> Ops;
8559  unsigned NumElts = VT.getVectorNumElements();
8560  for (unsigned i = 0; i < NumElts; ++i) {
8561    SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8562    Ops.push_back(V);
8563    // Make the DAGCombiner fold the bitcast.
8564    DCI.AddToWorklist(V.getNode());
8565  }
8566  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8567  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8568  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8569}
8570
8571/// PerformInsertEltCombine - Target-specific dag combine xforms for
8572/// ISD::INSERT_VECTOR_ELT.
8573static SDValue PerformInsertEltCombine(SDNode *N,
8574                                       TargetLowering::DAGCombinerInfo &DCI) {
8575  // Bitcast an i64 load inserted into a vector to f64.
8576  // Otherwise, the i64 value will be legalized to a pair of i32 values.
8577  EVT VT = N->getValueType(0);
8578  SDNode *Elt = N->getOperand(1).getNode();
8579  if (VT.getVectorElementType() != MVT::i64 ||
8580      !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8581    return SDValue();
8582
8583  SelectionDAG &DAG = DCI.DAG;
8584  DebugLoc dl = N->getDebugLoc();
8585  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8586                                 VT.getVectorNumElements());
8587  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8588  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8589  // Make the DAGCombiner fold the bitcasts.
8590  DCI.AddToWorklist(Vec.getNode());
8591  DCI.AddToWorklist(V.getNode());
8592  SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8593                               Vec, V, N->getOperand(2));
8594  return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8595}
8596
8597/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8598/// ISD::VECTOR_SHUFFLE.
8599static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8600  // The LLVM shufflevector instruction does not require the shuffle mask
8601  // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8602  // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8603  // operands do not match the mask length, they are extended by concatenating
8604  // them with undef vectors.  That is probably the right thing for other
8605  // targets, but for NEON it is better to concatenate two double-register
8606  // size vector operands into a single quad-register size vector.  Do that
8607  // transformation here:
8608  //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8609  //   shuffle(concat(v1, v2), undef)
8610  SDValue Op0 = N->getOperand(0);
8611  SDValue Op1 = N->getOperand(1);
8612  if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8613      Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8614      Op0.getNumOperands() != 2 ||
8615      Op1.getNumOperands() != 2)
8616    return SDValue();
8617  SDValue Concat0Op1 = Op0.getOperand(1);
8618  SDValue Concat1Op1 = Op1.getOperand(1);
8619  if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8620      Concat1Op1.getOpcode() != ISD::UNDEF)
8621    return SDValue();
8622  // Skip the transformation if any of the types are illegal.
8623  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8624  EVT VT = N->getValueType(0);
8625  if (!TLI.isTypeLegal(VT) ||
8626      !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8627      !TLI.isTypeLegal(Concat1Op1.getValueType()))
8628    return SDValue();
8629
8630  SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8631                                  Op0.getOperand(0), Op1.getOperand(0));
8632  // Translate the shuffle mask.
8633  SmallVector<int, 16> NewMask;
8634  unsigned NumElts = VT.getVectorNumElements();
8635  unsigned HalfElts = NumElts/2;
8636  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8637  for (unsigned n = 0; n < NumElts; ++n) {
8638    int MaskElt = SVN->getMaskElt(n);
8639    int NewElt = -1;
8640    if (MaskElt < (int)HalfElts)
8641      NewElt = MaskElt;
8642    else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8643      NewElt = HalfElts + MaskElt - NumElts;
8644    NewMask.push_back(NewElt);
8645  }
8646  return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8647                              DAG.getUNDEF(VT), NewMask.data());
8648}
8649
8650/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8651/// NEON load/store intrinsics to merge base address updates.
8652static SDValue CombineBaseUpdate(SDNode *N,
8653                                 TargetLowering::DAGCombinerInfo &DCI) {
8654  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8655    return SDValue();
8656
8657  SelectionDAG &DAG = DCI.DAG;
8658  bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8659                      N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8660  unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8661  SDValue Addr = N->getOperand(AddrOpIdx);
8662
8663  // Search for a use of the address operand that is an increment.
8664  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8665         UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8666    SDNode *User = *UI;
8667    if (User->getOpcode() != ISD::ADD ||
8668        UI.getUse().getResNo() != Addr.getResNo())
8669      continue;
8670
8671    // Check that the add is independent of the load/store.  Otherwise, folding
8672    // it would create a cycle.
8673    if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8674      continue;
8675
8676    // Find the new opcode for the updating load/store.
8677    bool isLoad = true;
8678    bool isLaneOp = false;
8679    unsigned NewOpc = 0;
8680    unsigned NumVecs = 0;
8681    if (isIntrinsic) {
8682      unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8683      switch (IntNo) {
8684      default: llvm_unreachable("unexpected intrinsic for Neon base update");
8685      case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8686        NumVecs = 1; break;
8687      case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8688        NumVecs = 2; break;
8689      case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8690        NumVecs = 3; break;
8691      case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8692        NumVecs = 4; break;
8693      case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8694        NumVecs = 2; isLaneOp = true; break;
8695      case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8696        NumVecs = 3; isLaneOp = true; break;
8697      case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8698        NumVecs = 4; isLaneOp = true; break;
8699      case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8700        NumVecs = 1; isLoad = false; break;
8701      case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8702        NumVecs = 2; isLoad = false; break;
8703      case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8704        NumVecs = 3; isLoad = false; break;
8705      case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8706        NumVecs = 4; isLoad = false; break;
8707      case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8708        NumVecs = 2; isLoad = false; isLaneOp = true; break;
8709      case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8710        NumVecs = 3; isLoad = false; isLaneOp = true; break;
8711      case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8712        NumVecs = 4; isLoad = false; isLaneOp = true; break;
8713      }
8714    } else {
8715      isLaneOp = true;
8716      switch (N->getOpcode()) {
8717      default: llvm_unreachable("unexpected opcode for Neon base update");
8718      case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8719      case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8720      case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8721      }
8722    }
8723
8724    // Find the size of memory referenced by the load/store.
8725    EVT VecTy;
8726    if (isLoad)
8727      VecTy = N->getValueType(0);
8728    else
8729      VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8730    unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8731    if (isLaneOp)
8732      NumBytes /= VecTy.getVectorNumElements();
8733
8734    // If the increment is a constant, it must match the memory ref size.
8735    SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8736    if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8737      uint64_t IncVal = CInc->getZExtValue();
8738      if (IncVal != NumBytes)
8739        continue;
8740    } else if (NumBytes >= 3 * 16) {
8741      // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8742      // separate instructions that make it harder to use a non-constant update.
8743      continue;
8744    }
8745
8746    // Create the new updating load/store node.
8747    EVT Tys[6];
8748    unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8749    unsigned n;
8750    for (n = 0; n < NumResultVecs; ++n)
8751      Tys[n] = VecTy;
8752    Tys[n++] = MVT::i32;
8753    Tys[n] = MVT::Other;
8754    SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8755    SmallVector<SDValue, 8> Ops;
8756    Ops.push_back(N->getOperand(0)); // incoming chain
8757    Ops.push_back(N->getOperand(AddrOpIdx));
8758    Ops.push_back(Inc);
8759    for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8760      Ops.push_back(N->getOperand(i));
8761    }
8762    MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8763    SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8764                                           Ops.data(), Ops.size(),
8765                                           MemInt->getMemoryVT(),
8766                                           MemInt->getMemOperand());
8767
8768    // Update the uses.
8769    std::vector<SDValue> NewResults;
8770    for (unsigned i = 0; i < NumResultVecs; ++i) {
8771      NewResults.push_back(SDValue(UpdN.getNode(), i));
8772    }
8773    NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8774    DCI.CombineTo(N, NewResults);
8775    DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8776
8777    break;
8778  }
8779  return SDValue();
8780}
8781
8782/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8783/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8784/// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8785/// return true.
8786static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8787  SelectionDAG &DAG = DCI.DAG;
8788  EVT VT = N->getValueType(0);
8789  // vldN-dup instructions only support 64-bit vectors for N > 1.
8790  if (!VT.is64BitVector())
8791    return false;
8792
8793  // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8794  SDNode *VLD = N->getOperand(0).getNode();
8795  if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8796    return false;
8797  unsigned NumVecs = 0;
8798  unsigned NewOpc = 0;
8799  unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8800  if (IntNo == Intrinsic::arm_neon_vld2lane) {
8801    NumVecs = 2;
8802    NewOpc = ARMISD::VLD2DUP;
8803  } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8804    NumVecs = 3;
8805    NewOpc = ARMISD::VLD3DUP;
8806  } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8807    NumVecs = 4;
8808    NewOpc = ARMISD::VLD4DUP;
8809  } else {
8810    return false;
8811  }
8812
8813  // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8814  // numbers match the load.
8815  unsigned VLDLaneNo =
8816    cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8817  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8818       UI != UE; ++UI) {
8819    // Ignore uses of the chain result.
8820    if (UI.getUse().getResNo() == NumVecs)
8821      continue;
8822    SDNode *User = *UI;
8823    if (User->getOpcode() != ARMISD::VDUPLANE ||
8824        VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8825      return false;
8826  }
8827
8828  // Create the vldN-dup node.
8829  EVT Tys[5];
8830  unsigned n;
8831  for (n = 0; n < NumVecs; ++n)
8832    Tys[n] = VT;
8833  Tys[n] = MVT::Other;
8834  SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8835  SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8836  MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8837  SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8838                                           Ops, 2, VLDMemInt->getMemoryVT(),
8839                                           VLDMemInt->getMemOperand());
8840
8841  // Update the uses.
8842  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8843       UI != UE; ++UI) {
8844    unsigned ResNo = UI.getUse().getResNo();
8845    // Ignore uses of the chain result.
8846    if (ResNo == NumVecs)
8847      continue;
8848    SDNode *User = *UI;
8849    DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8850  }
8851
8852  // Now the vldN-lane intrinsic is dead except for its chain result.
8853  // Update uses of the chain.
8854  std::vector<SDValue> VLDDupResults;
8855  for (unsigned n = 0; n < NumVecs; ++n)
8856    VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8857  VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8858  DCI.CombineTo(VLD, VLDDupResults);
8859
8860  return true;
8861}
8862
8863/// PerformVDUPLANECombine - Target-specific dag combine xforms for
8864/// ARMISD::VDUPLANE.
8865static SDValue PerformVDUPLANECombine(SDNode *N,
8866                                      TargetLowering::DAGCombinerInfo &DCI) {
8867  SDValue Op = N->getOperand(0);
8868
8869  // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8870  // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8871  if (CombineVLDDUP(N, DCI))
8872    return SDValue(N, 0);
8873
8874  // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8875  // redundant.  Ignore bit_converts for now; element sizes are checked below.
8876  while (Op.getOpcode() == ISD::BITCAST)
8877    Op = Op.getOperand(0);
8878  if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8879    return SDValue();
8880
8881  // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8882  unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8883  // The canonical VMOV for a zero vector uses a 32-bit element size.
8884  unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8885  unsigned EltBits;
8886  if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8887    EltSize = 8;
8888  EVT VT = N->getValueType(0);
8889  if (EltSize > VT.getVectorElementType().getSizeInBits())
8890    return SDValue();
8891
8892  return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8893}
8894
8895// isConstVecPow2 - Return true if each vector element is a power of 2, all
8896// elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8897static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8898{
8899  integerPart cN;
8900  integerPart c0 = 0;
8901  for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8902       I != E; I++) {
8903    ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8904    if (!C)
8905      return false;
8906
8907    bool isExact;
8908    APFloat APF = C->getValueAPF();
8909    if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8910        != APFloat::opOK || !isExact)
8911      return false;
8912
8913    c0 = (I == 0) ? cN : c0;
8914    if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8915      return false;
8916  }
8917  C = c0;
8918  return true;
8919}
8920
8921/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8922/// can replace combinations of VMUL and VCVT (floating-point to integer)
8923/// when the VMUL has a constant operand that is a power of 2.
8924///
8925/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8926///  vmul.f32        d16, d17, d16
8927///  vcvt.s32.f32    d16, d16
8928/// becomes:
8929///  vcvt.s32.f32    d16, d16, #3
8930static SDValue PerformVCVTCombine(SDNode *N,
8931                                  TargetLowering::DAGCombinerInfo &DCI,
8932                                  const ARMSubtarget *Subtarget) {
8933  SelectionDAG &DAG = DCI.DAG;
8934  SDValue Op = N->getOperand(0);
8935
8936  if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8937      Op.getOpcode() != ISD::FMUL)
8938    return SDValue();
8939
8940  uint64_t C;
8941  SDValue N0 = Op->getOperand(0);
8942  SDValue ConstVec = Op->getOperand(1);
8943  bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8944
8945  if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8946      !isConstVecPow2(ConstVec, isSigned, C))
8947    return SDValue();
8948
8949  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8950    Intrinsic::arm_neon_vcvtfp2fxu;
8951  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8952                     N->getValueType(0),
8953                     DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8954                     DAG.getConstant(Log2_64(C), MVT::i32));
8955}
8956
8957/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8958/// can replace combinations of VCVT (integer to floating-point) and VDIV
8959/// when the VDIV has a constant operand that is a power of 2.
8960///
8961/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8962///  vcvt.f32.s32    d16, d16
8963///  vdiv.f32        d16, d17, d16
8964/// becomes:
8965///  vcvt.f32.s32    d16, d16, #3
8966static SDValue PerformVDIVCombine(SDNode *N,
8967                                  TargetLowering::DAGCombinerInfo &DCI,
8968                                  const ARMSubtarget *Subtarget) {
8969  SelectionDAG &DAG = DCI.DAG;
8970  SDValue Op = N->getOperand(0);
8971  unsigned OpOpcode = Op.getNode()->getOpcode();
8972
8973  if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8974      (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8975    return SDValue();
8976
8977  uint64_t C;
8978  SDValue ConstVec = N->getOperand(1);
8979  bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8980
8981  if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8982      !isConstVecPow2(ConstVec, isSigned, C))
8983    return SDValue();
8984
8985  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8986    Intrinsic::arm_neon_vcvtfxu2fp;
8987  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8988                     Op.getValueType(),
8989                     DAG.getConstant(IntrinsicOpcode, MVT::i32),
8990                     Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8991}
8992
8993/// Getvshiftimm - Check if this is a valid build_vector for the immediate
8994/// operand of a vector shift operation, where all the elements of the
8995/// build_vector must have the same constant integer value.
8996static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8997  // Ignore bit_converts.
8998  while (Op.getOpcode() == ISD::BITCAST)
8999    Op = Op.getOperand(0);
9000  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9001  APInt SplatBits, SplatUndef;
9002  unsigned SplatBitSize;
9003  bool HasAnyUndefs;
9004  if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9005                                      HasAnyUndefs, ElementBits) ||
9006      SplatBitSize > ElementBits)
9007    return false;
9008  Cnt = SplatBits.getSExtValue();
9009  return true;
9010}
9011
9012/// isVShiftLImm - Check if this is a valid build_vector for the immediate
9013/// operand of a vector shift left operation.  That value must be in the range:
9014///   0 <= Value < ElementBits for a left shift; or
9015///   0 <= Value <= ElementBits for a long left shift.
9016static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9017  assert(VT.isVector() && "vector shift count is not a vector type");
9018  unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9019  if (! getVShiftImm(Op, ElementBits, Cnt))
9020    return false;
9021  return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9022}
9023
9024/// isVShiftRImm - Check if this is a valid build_vector for the immediate
9025/// operand of a vector shift right operation.  For a shift opcode, the value
9026/// is positive, but for an intrinsic the value count must be negative. The
9027/// absolute value must be in the range:
9028///   1 <= |Value| <= ElementBits for a right shift; or
9029///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9030static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9031                         int64_t &Cnt) {
9032  assert(VT.isVector() && "vector shift count is not a vector type");
9033  unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9034  if (! getVShiftImm(Op, ElementBits, Cnt))
9035    return false;
9036  if (isIntrinsic)
9037    Cnt = -Cnt;
9038  return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9039}
9040
9041/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9042static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9043  unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9044  switch (IntNo) {
9045  default:
9046    // Don't do anything for most intrinsics.
9047    break;
9048
9049  // Vector shifts: check for immediate versions and lower them.
9050  // Note: This is done during DAG combining instead of DAG legalizing because
9051  // the build_vectors for 64-bit vector element shift counts are generally
9052  // not legal, and it is hard to see their values after they get legalized to
9053  // loads from a constant pool.
9054  case Intrinsic::arm_neon_vshifts:
9055  case Intrinsic::arm_neon_vshiftu:
9056  case Intrinsic::arm_neon_vshiftls:
9057  case Intrinsic::arm_neon_vshiftlu:
9058  case Intrinsic::arm_neon_vshiftn:
9059  case Intrinsic::arm_neon_vrshifts:
9060  case Intrinsic::arm_neon_vrshiftu:
9061  case Intrinsic::arm_neon_vrshiftn:
9062  case Intrinsic::arm_neon_vqshifts:
9063  case Intrinsic::arm_neon_vqshiftu:
9064  case Intrinsic::arm_neon_vqshiftsu:
9065  case Intrinsic::arm_neon_vqshiftns:
9066  case Intrinsic::arm_neon_vqshiftnu:
9067  case Intrinsic::arm_neon_vqshiftnsu:
9068  case Intrinsic::arm_neon_vqrshiftns:
9069  case Intrinsic::arm_neon_vqrshiftnu:
9070  case Intrinsic::arm_neon_vqrshiftnsu: {
9071    EVT VT = N->getOperand(1).getValueType();
9072    int64_t Cnt;
9073    unsigned VShiftOpc = 0;
9074
9075    switch (IntNo) {
9076    case Intrinsic::arm_neon_vshifts:
9077    case Intrinsic::arm_neon_vshiftu:
9078      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9079        VShiftOpc = ARMISD::VSHL;
9080        break;
9081      }
9082      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9083        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9084                     ARMISD::VSHRs : ARMISD::VSHRu);
9085        break;
9086      }
9087      return SDValue();
9088
9089    case Intrinsic::arm_neon_vshiftls:
9090    case Intrinsic::arm_neon_vshiftlu:
9091      if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9092        break;
9093      llvm_unreachable("invalid shift count for vshll intrinsic");
9094
9095    case Intrinsic::arm_neon_vrshifts:
9096    case Intrinsic::arm_neon_vrshiftu:
9097      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9098        break;
9099      return SDValue();
9100
9101    case Intrinsic::arm_neon_vqshifts:
9102    case Intrinsic::arm_neon_vqshiftu:
9103      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9104        break;
9105      return SDValue();
9106
9107    case Intrinsic::arm_neon_vqshiftsu:
9108      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9109        break;
9110      llvm_unreachable("invalid shift count for vqshlu intrinsic");
9111
9112    case Intrinsic::arm_neon_vshiftn:
9113    case Intrinsic::arm_neon_vrshiftn:
9114    case Intrinsic::arm_neon_vqshiftns:
9115    case Intrinsic::arm_neon_vqshiftnu:
9116    case Intrinsic::arm_neon_vqshiftnsu:
9117    case Intrinsic::arm_neon_vqrshiftns:
9118    case Intrinsic::arm_neon_vqrshiftnu:
9119    case Intrinsic::arm_neon_vqrshiftnsu:
9120      // Narrowing shifts require an immediate right shift.
9121      if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9122        break;
9123      llvm_unreachable("invalid shift count for narrowing vector shift "
9124                       "intrinsic");
9125
9126    default:
9127      llvm_unreachable("unhandled vector shift");
9128    }
9129
9130    switch (IntNo) {
9131    case Intrinsic::arm_neon_vshifts:
9132    case Intrinsic::arm_neon_vshiftu:
9133      // Opcode already set above.
9134      break;
9135    case Intrinsic::arm_neon_vshiftls:
9136    case Intrinsic::arm_neon_vshiftlu:
9137      if (Cnt == VT.getVectorElementType().getSizeInBits())
9138        VShiftOpc = ARMISD::VSHLLi;
9139      else
9140        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9141                     ARMISD::VSHLLs : ARMISD::VSHLLu);
9142      break;
9143    case Intrinsic::arm_neon_vshiftn:
9144      VShiftOpc = ARMISD::VSHRN; break;
9145    case Intrinsic::arm_neon_vrshifts:
9146      VShiftOpc = ARMISD::VRSHRs; break;
9147    case Intrinsic::arm_neon_vrshiftu:
9148      VShiftOpc = ARMISD::VRSHRu; break;
9149    case Intrinsic::arm_neon_vrshiftn:
9150      VShiftOpc = ARMISD::VRSHRN; break;
9151    case Intrinsic::arm_neon_vqshifts:
9152      VShiftOpc = ARMISD::VQSHLs; break;
9153    case Intrinsic::arm_neon_vqshiftu:
9154      VShiftOpc = ARMISD::VQSHLu; break;
9155    case Intrinsic::arm_neon_vqshiftsu:
9156      VShiftOpc = ARMISD::VQSHLsu; break;
9157    case Intrinsic::arm_neon_vqshiftns:
9158      VShiftOpc = ARMISD::VQSHRNs; break;
9159    case Intrinsic::arm_neon_vqshiftnu:
9160      VShiftOpc = ARMISD::VQSHRNu; break;
9161    case Intrinsic::arm_neon_vqshiftnsu:
9162      VShiftOpc = ARMISD::VQSHRNsu; break;
9163    case Intrinsic::arm_neon_vqrshiftns:
9164      VShiftOpc = ARMISD::VQRSHRNs; break;
9165    case Intrinsic::arm_neon_vqrshiftnu:
9166      VShiftOpc = ARMISD::VQRSHRNu; break;
9167    case Intrinsic::arm_neon_vqrshiftnsu:
9168      VShiftOpc = ARMISD::VQRSHRNsu; break;
9169    }
9170
9171    return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9172                       N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9173  }
9174
9175  case Intrinsic::arm_neon_vshiftins: {
9176    EVT VT = N->getOperand(1).getValueType();
9177    int64_t Cnt;
9178    unsigned VShiftOpc = 0;
9179
9180    if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9181      VShiftOpc = ARMISD::VSLI;
9182    else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9183      VShiftOpc = ARMISD::VSRI;
9184    else {
9185      llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9186    }
9187
9188    return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9189                       N->getOperand(1), N->getOperand(2),
9190                       DAG.getConstant(Cnt, MVT::i32));
9191  }
9192
9193  case Intrinsic::arm_neon_vqrshifts:
9194  case Intrinsic::arm_neon_vqrshiftu:
9195    // No immediate versions of these to check for.
9196    break;
9197  }
9198
9199  return SDValue();
9200}
9201
9202/// PerformShiftCombine - Checks for immediate versions of vector shifts and
9203/// lowers them.  As with the vector shift intrinsics, this is done during DAG
9204/// combining instead of DAG legalizing because the build_vectors for 64-bit
9205/// vector element shift counts are generally not legal, and it is hard to see
9206/// their values after they get legalized to loads from a constant pool.
9207static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9208                                   const ARMSubtarget *ST) {
9209  EVT VT = N->getValueType(0);
9210  if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9211    // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9212    // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9213    SDValue N1 = N->getOperand(1);
9214    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9215      SDValue N0 = N->getOperand(0);
9216      if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9217          DAG.MaskedValueIsZero(N0.getOperand(0),
9218                                APInt::getHighBitsSet(32, 16)))
9219        return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9220    }
9221  }
9222
9223  // Nothing to be done for scalar shifts.
9224  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9225  if (!VT.isVector() || !TLI.isTypeLegal(VT))
9226    return SDValue();
9227
9228  assert(ST->hasNEON() && "unexpected vector shift");
9229  int64_t Cnt;
9230
9231  switch (N->getOpcode()) {
9232  default: llvm_unreachable("unexpected shift opcode");
9233
9234  case ISD::SHL:
9235    if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9236      return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9237                         DAG.getConstant(Cnt, MVT::i32));
9238    break;
9239
9240  case ISD::SRA:
9241  case ISD::SRL:
9242    if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9243      unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9244                            ARMISD::VSHRs : ARMISD::VSHRu);
9245      return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9246                         DAG.getConstant(Cnt, MVT::i32));
9247    }
9248  }
9249  return SDValue();
9250}
9251
9252/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9253/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9254static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9255                                    const ARMSubtarget *ST) {
9256  SDValue N0 = N->getOperand(0);
9257
9258  // Check for sign- and zero-extensions of vector extract operations of 8-
9259  // and 16-bit vector elements.  NEON supports these directly.  They are
9260  // handled during DAG combining because type legalization will promote them
9261  // to 32-bit types and it is messy to recognize the operations after that.
9262  if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9263    SDValue Vec = N0.getOperand(0);
9264    SDValue Lane = N0.getOperand(1);
9265    EVT VT = N->getValueType(0);
9266    EVT EltVT = N0.getValueType();
9267    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9268
9269    if (VT == MVT::i32 &&
9270        (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9271        TLI.isTypeLegal(Vec.getValueType()) &&
9272        isa<ConstantSDNode>(Lane)) {
9273
9274      unsigned Opc = 0;
9275      switch (N->getOpcode()) {
9276      default: llvm_unreachable("unexpected opcode");
9277      case ISD::SIGN_EXTEND:
9278        Opc = ARMISD::VGETLANEs;
9279        break;
9280      case ISD::ZERO_EXTEND:
9281      case ISD::ANY_EXTEND:
9282        Opc = ARMISD::VGETLANEu;
9283        break;
9284      }
9285      return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9286    }
9287  }
9288
9289  return SDValue();
9290}
9291
9292/// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9293/// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9294static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9295                                       const ARMSubtarget *ST) {
9296  // If the target supports NEON, try to use vmax/vmin instructions for f32
9297  // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9298  // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9299  // a NaN; only do the transformation when it matches that behavior.
9300
9301  // For now only do this when using NEON for FP operations; if using VFP, it
9302  // is not obvious that the benefit outweighs the cost of switching to the
9303  // NEON pipeline.
9304  if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9305      N->getValueType(0) != MVT::f32)
9306    return SDValue();
9307
9308  SDValue CondLHS = N->getOperand(0);
9309  SDValue CondRHS = N->getOperand(1);
9310  SDValue LHS = N->getOperand(2);
9311  SDValue RHS = N->getOperand(3);
9312  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9313
9314  unsigned Opcode = 0;
9315  bool IsReversed;
9316  if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9317    IsReversed = false; // x CC y ? x : y
9318  } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9319    IsReversed = true ; // x CC y ? y : x
9320  } else {
9321    return SDValue();
9322  }
9323
9324  bool IsUnordered;
9325  switch (CC) {
9326  default: break;
9327  case ISD::SETOLT:
9328  case ISD::SETOLE:
9329  case ISD::SETLT:
9330  case ISD::SETLE:
9331  case ISD::SETULT:
9332  case ISD::SETULE:
9333    // If LHS is NaN, an ordered comparison will be false and the result will
9334    // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9335    // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9336    IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9337    if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9338      break;
9339    // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9340    // will return -0, so vmin can only be used for unsafe math or if one of
9341    // the operands is known to be nonzero.
9342    if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9343        !DAG.getTarget().Options.UnsafeFPMath &&
9344        !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9345      break;
9346    Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9347    break;
9348
9349  case ISD::SETOGT:
9350  case ISD::SETOGE:
9351  case ISD::SETGT:
9352  case ISD::SETGE:
9353  case ISD::SETUGT:
9354  case ISD::SETUGE:
9355    // If LHS is NaN, an ordered comparison will be false and the result will
9356    // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9357    // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9358    IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9359    if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9360      break;
9361    // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9362    // will return +0, so vmax can only be used for unsafe math or if one of
9363    // the operands is known to be nonzero.
9364    if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9365        !DAG.getTarget().Options.UnsafeFPMath &&
9366        !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9367      break;
9368    Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9369    break;
9370  }
9371
9372  if (!Opcode)
9373    return SDValue();
9374  return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9375}
9376
9377/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9378SDValue
9379ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9380  SDValue Cmp = N->getOperand(4);
9381  if (Cmp.getOpcode() != ARMISD::CMPZ)
9382    // Only looking at EQ and NE cases.
9383    return SDValue();
9384
9385  EVT VT = N->getValueType(0);
9386  DebugLoc dl = N->getDebugLoc();
9387  SDValue LHS = Cmp.getOperand(0);
9388  SDValue RHS = Cmp.getOperand(1);
9389  SDValue FalseVal = N->getOperand(0);
9390  SDValue TrueVal = N->getOperand(1);
9391  SDValue ARMcc = N->getOperand(2);
9392  ARMCC::CondCodes CC =
9393    (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9394
9395  // Simplify
9396  //   mov     r1, r0
9397  //   cmp     r1, x
9398  //   mov     r0, y
9399  //   moveq   r0, x
9400  // to
9401  //   cmp     r0, x
9402  //   movne   r0, y
9403  //
9404  //   mov     r1, r0
9405  //   cmp     r1, x
9406  //   mov     r0, x
9407  //   movne   r0, y
9408  // to
9409  //   cmp     r0, x
9410  //   movne   r0, y
9411  /// FIXME: Turn this into a target neutral optimization?
9412  SDValue Res;
9413  if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9414    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9415                      N->getOperand(3), Cmp);
9416  } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9417    SDValue ARMcc;
9418    SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9419    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9420                      N->getOperand(3), NewCmp);
9421  }
9422
9423  if (Res.getNode()) {
9424    APInt KnownZero, KnownOne;
9425    DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9426    // Capture demanded bits information that would be otherwise lost.
9427    if (KnownZero == 0xfffffffe)
9428      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9429                        DAG.getValueType(MVT::i1));
9430    else if (KnownZero == 0xffffff00)
9431      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9432                        DAG.getValueType(MVT::i8));
9433    else if (KnownZero == 0xffff0000)
9434      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9435                        DAG.getValueType(MVT::i16));
9436  }
9437
9438  return Res;
9439}
9440
9441SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9442                                             DAGCombinerInfo &DCI) const {
9443  switch (N->getOpcode()) {
9444  default: break;
9445  case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9446  case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9447  case ISD::SUB:        return PerformSUBCombine(N, DCI);
9448  case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9449  case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9450  case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9451  case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9452  case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9453  case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9454  case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9455  case ISD::STORE:      return PerformSTORECombine(N, DCI);
9456  case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9457  case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9458  case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9459  case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9460  case ISD::FP_TO_SINT:
9461  case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9462  case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9463  case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9464  case ISD::SHL:
9465  case ISD::SRA:
9466  case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9467  case ISD::SIGN_EXTEND:
9468  case ISD::ZERO_EXTEND:
9469  case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9470  case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9471  case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9472  case ARMISD::VLD2DUP:
9473  case ARMISD::VLD3DUP:
9474  case ARMISD::VLD4DUP:
9475    return CombineBaseUpdate(N, DCI);
9476  case ISD::INTRINSIC_VOID:
9477  case ISD::INTRINSIC_W_CHAIN:
9478    switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9479    case Intrinsic::arm_neon_vld1:
9480    case Intrinsic::arm_neon_vld2:
9481    case Intrinsic::arm_neon_vld3:
9482    case Intrinsic::arm_neon_vld4:
9483    case Intrinsic::arm_neon_vld2lane:
9484    case Intrinsic::arm_neon_vld3lane:
9485    case Intrinsic::arm_neon_vld4lane:
9486    case Intrinsic::arm_neon_vst1:
9487    case Intrinsic::arm_neon_vst2:
9488    case Intrinsic::arm_neon_vst3:
9489    case Intrinsic::arm_neon_vst4:
9490    case Intrinsic::arm_neon_vst2lane:
9491    case Intrinsic::arm_neon_vst3lane:
9492    case Intrinsic::arm_neon_vst4lane:
9493      return CombineBaseUpdate(N, DCI);
9494    default: break;
9495    }
9496    break;
9497  }
9498  return SDValue();
9499}
9500
9501bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9502                                                          EVT VT) const {
9503  return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9504}
9505
9506bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9507  // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9508  bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9509
9510  switch (VT.getSimpleVT().SimpleTy) {
9511  default:
9512    return false;
9513  case MVT::i8:
9514  case MVT::i16:
9515  case MVT::i32: {
9516    // Unaligned access can use (for example) LRDB, LRDH, LDR
9517    if (AllowsUnaligned) {
9518      if (Fast)
9519        *Fast = Subtarget->hasV7Ops();
9520      return true;
9521    }
9522    return false;
9523  }
9524  case MVT::f64:
9525  case MVT::v2f64: {
9526    // For any little-endian targets with neon, we can support unaligned ld/st
9527    // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9528    // A big-endian target may also explictly support unaligned accesses
9529    if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9530      if (Fast)
9531        *Fast = true;
9532      return true;
9533    }
9534    return false;
9535  }
9536  }
9537}
9538
9539static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9540                       unsigned AlignCheck) {
9541  return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9542          (DstAlign == 0 || DstAlign % AlignCheck == 0));
9543}
9544
9545EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9546                                           unsigned DstAlign, unsigned SrcAlign,
9547                                           bool IsMemset, bool ZeroMemset,
9548                                           bool MemcpyStrSrc,
9549                                           MachineFunction &MF) const {
9550  const Function *F = MF.getFunction();
9551
9552  // See if we can use NEON instructions for this...
9553  if ((!IsMemset || ZeroMemset) &&
9554      Subtarget->hasNEON() &&
9555      !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9556                                       Attribute::NoImplicitFloat)) {
9557    bool Fast;
9558    if (Size >= 16 &&
9559        (memOpAlign(SrcAlign, DstAlign, 16) ||
9560         (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9561      return MVT::v2f64;
9562    } else if (Size >= 8 &&
9563               (memOpAlign(SrcAlign, DstAlign, 8) ||
9564                (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9565      return MVT::f64;
9566    }
9567  }
9568
9569  // Lowering to i32/i16 if the size permits.
9570  if (Size >= 4)
9571    return MVT::i32;
9572  else if (Size >= 2)
9573    return MVT::i16;
9574
9575  // Let the target-independent logic figure it out.
9576  return MVT::Other;
9577}
9578
9579bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9580  if (Val.getOpcode() != ISD::LOAD)
9581    return false;
9582
9583  EVT VT1 = Val.getValueType();
9584  if (!VT1.isSimple() || !VT1.isInteger() ||
9585      !VT2.isSimple() || !VT2.isInteger())
9586    return false;
9587
9588  switch (VT1.getSimpleVT().SimpleTy) {
9589  default: break;
9590  case MVT::i1:
9591  case MVT::i8:
9592  case MVT::i16:
9593    // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9594    return true;
9595  }
9596
9597  return false;
9598}
9599
9600static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9601  if (V < 0)
9602    return false;
9603
9604  unsigned Scale = 1;
9605  switch (VT.getSimpleVT().SimpleTy) {
9606  default: return false;
9607  case MVT::i1:
9608  case MVT::i8:
9609    // Scale == 1;
9610    break;
9611  case MVT::i16:
9612    // Scale == 2;
9613    Scale = 2;
9614    break;
9615  case MVT::i32:
9616    // Scale == 4;
9617    Scale = 4;
9618    break;
9619  }
9620
9621  if ((V & (Scale - 1)) != 0)
9622    return false;
9623  V /= Scale;
9624  return V == (V & ((1LL << 5) - 1));
9625}
9626
9627static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9628                                      const ARMSubtarget *Subtarget) {
9629  bool isNeg = false;
9630  if (V < 0) {
9631    isNeg = true;
9632    V = - V;
9633  }
9634
9635  switch (VT.getSimpleVT().SimpleTy) {
9636  default: return false;
9637  case MVT::i1:
9638  case MVT::i8:
9639  case MVT::i16:
9640  case MVT::i32:
9641    // + imm12 or - imm8
9642    if (isNeg)
9643      return V == (V & ((1LL << 8) - 1));
9644    return V == (V & ((1LL << 12) - 1));
9645  case MVT::f32:
9646  case MVT::f64:
9647    // Same as ARM mode. FIXME: NEON?
9648    if (!Subtarget->hasVFP2())
9649      return false;
9650    if ((V & 3) != 0)
9651      return false;
9652    V >>= 2;
9653    return V == (V & ((1LL << 8) - 1));
9654  }
9655}
9656
9657/// isLegalAddressImmediate - Return true if the integer value can be used
9658/// as the offset of the target addressing mode for load / store of the
9659/// given type.
9660static bool isLegalAddressImmediate(int64_t V, EVT VT,
9661                                    const ARMSubtarget *Subtarget) {
9662  if (V == 0)
9663    return true;
9664
9665  if (!VT.isSimple())
9666    return false;
9667
9668  if (Subtarget->isThumb1Only())
9669    return isLegalT1AddressImmediate(V, VT);
9670  else if (Subtarget->isThumb2())
9671    return isLegalT2AddressImmediate(V, VT, Subtarget);
9672
9673  // ARM mode.
9674  if (V < 0)
9675    V = - V;
9676  switch (VT.getSimpleVT().SimpleTy) {
9677  default: return false;
9678  case MVT::i1:
9679  case MVT::i8:
9680  case MVT::i32:
9681    // +- imm12
9682    return V == (V & ((1LL << 12) - 1));
9683  case MVT::i16:
9684    // +- imm8
9685    return V == (V & ((1LL << 8) - 1));
9686  case MVT::f32:
9687  case MVT::f64:
9688    if (!Subtarget->hasVFP2()) // FIXME: NEON?
9689      return false;
9690    if ((V & 3) != 0)
9691      return false;
9692    V >>= 2;
9693    return V == (V & ((1LL << 8) - 1));
9694  }
9695}
9696
9697bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9698                                                      EVT VT) const {
9699  int Scale = AM.Scale;
9700  if (Scale < 0)
9701    return false;
9702
9703  switch (VT.getSimpleVT().SimpleTy) {
9704  default: return false;
9705  case MVT::i1:
9706  case MVT::i8:
9707  case MVT::i16:
9708  case MVT::i32:
9709    if (Scale == 1)
9710      return true;
9711    // r + r << imm
9712    Scale = Scale & ~1;
9713    return Scale == 2 || Scale == 4 || Scale == 8;
9714  case MVT::i64:
9715    // r + r
9716    if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9717      return true;
9718    return false;
9719  case MVT::isVoid:
9720    // Note, we allow "void" uses (basically, uses that aren't loads or
9721    // stores), because arm allows folding a scale into many arithmetic
9722    // operations.  This should be made more precise and revisited later.
9723
9724    // Allow r << imm, but the imm has to be a multiple of two.
9725    if (Scale & 1) return false;
9726    return isPowerOf2_32(Scale);
9727  }
9728}
9729
9730/// isLegalAddressingMode - Return true if the addressing mode represented
9731/// by AM is legal for this target, for a load/store of the specified type.
9732bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9733                                              Type *Ty) const {
9734  EVT VT = getValueType(Ty, true);
9735  if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9736    return false;
9737
9738  // Can never fold addr of global into load/store.
9739  if (AM.BaseGV)
9740    return false;
9741
9742  switch (AM.Scale) {
9743  case 0:  // no scale reg, must be "r+i" or "r", or "i".
9744    break;
9745  case 1:
9746    if (Subtarget->isThumb1Only())
9747      return false;
9748    // FALL THROUGH.
9749  default:
9750    // ARM doesn't support any R+R*scale+imm addr modes.
9751    if (AM.BaseOffs)
9752      return false;
9753
9754    if (!VT.isSimple())
9755      return false;
9756
9757    if (Subtarget->isThumb2())
9758      return isLegalT2ScaledAddressingMode(AM, VT);
9759
9760    int Scale = AM.Scale;
9761    switch (VT.getSimpleVT().SimpleTy) {
9762    default: return false;
9763    case MVT::i1:
9764    case MVT::i8:
9765    case MVT::i32:
9766      if (Scale < 0) Scale = -Scale;
9767      if (Scale == 1)
9768        return true;
9769      // r + r << imm
9770      return isPowerOf2_32(Scale & ~1);
9771    case MVT::i16:
9772    case MVT::i64:
9773      // r + r
9774      if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9775        return true;
9776      return false;
9777
9778    case MVT::isVoid:
9779      // Note, we allow "void" uses (basically, uses that aren't loads or
9780      // stores), because arm allows folding a scale into many arithmetic
9781      // operations.  This should be made more precise and revisited later.
9782
9783      // Allow r << imm, but the imm has to be a multiple of two.
9784      if (Scale & 1) return false;
9785      return isPowerOf2_32(Scale);
9786    }
9787  }
9788  return true;
9789}
9790
9791/// isLegalICmpImmediate - Return true if the specified immediate is legal
9792/// icmp immediate, that is the target has icmp instructions which can compare
9793/// a register against the immediate without having to materialize the
9794/// immediate into a register.
9795bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9796  // Thumb2 and ARM modes can use cmn for negative immediates.
9797  if (!Subtarget->isThumb())
9798    return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9799  if (Subtarget->isThumb2())
9800    return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9801  // Thumb1 doesn't have cmn, and only 8-bit immediates.
9802  return Imm >= 0 && Imm <= 255;
9803}
9804
9805/// isLegalAddImmediate - Return true if the specified immediate is a legal add
9806/// *or sub* immediate, that is the target has add or sub instructions which can
9807/// add a register with the immediate without having to materialize the
9808/// immediate into a register.
9809bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9810  // Same encoding for add/sub, just flip the sign.
9811  int64_t AbsImm = llvm::abs64(Imm);
9812  if (!Subtarget->isThumb())
9813    return ARM_AM::getSOImmVal(AbsImm) != -1;
9814  if (Subtarget->isThumb2())
9815    return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9816  // Thumb1 only has 8-bit unsigned immediate.
9817  return AbsImm >= 0 && AbsImm <= 255;
9818}
9819
9820static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9821                                      bool isSEXTLoad, SDValue &Base,
9822                                      SDValue &Offset, bool &isInc,
9823                                      SelectionDAG &DAG) {
9824  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9825    return false;
9826
9827  if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9828    // AddressingMode 3
9829    Base = Ptr->getOperand(0);
9830    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9831      int RHSC = (int)RHS->getZExtValue();
9832      if (RHSC < 0 && RHSC > -256) {
9833        assert(Ptr->getOpcode() == ISD::ADD);
9834        isInc = false;
9835        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9836        return true;
9837      }
9838    }
9839    isInc = (Ptr->getOpcode() == ISD::ADD);
9840    Offset = Ptr->getOperand(1);
9841    return true;
9842  } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9843    // AddressingMode 2
9844    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9845      int RHSC = (int)RHS->getZExtValue();
9846      if (RHSC < 0 && RHSC > -0x1000) {
9847        assert(Ptr->getOpcode() == ISD::ADD);
9848        isInc = false;
9849        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9850        Base = Ptr->getOperand(0);
9851        return true;
9852      }
9853    }
9854
9855    if (Ptr->getOpcode() == ISD::ADD) {
9856      isInc = true;
9857      ARM_AM::ShiftOpc ShOpcVal=
9858        ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9859      if (ShOpcVal != ARM_AM::no_shift) {
9860        Base = Ptr->getOperand(1);
9861        Offset = Ptr->getOperand(0);
9862      } else {
9863        Base = Ptr->getOperand(0);
9864        Offset = Ptr->getOperand(1);
9865      }
9866      return true;
9867    }
9868
9869    isInc = (Ptr->getOpcode() == ISD::ADD);
9870    Base = Ptr->getOperand(0);
9871    Offset = Ptr->getOperand(1);
9872    return true;
9873  }
9874
9875  // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9876  return false;
9877}
9878
9879static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9880                                     bool isSEXTLoad, SDValue &Base,
9881                                     SDValue &Offset, bool &isInc,
9882                                     SelectionDAG &DAG) {
9883  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9884    return false;
9885
9886  Base = Ptr->getOperand(0);
9887  if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9888    int RHSC = (int)RHS->getZExtValue();
9889    if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9890      assert(Ptr->getOpcode() == ISD::ADD);
9891      isInc = false;
9892      Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9893      return true;
9894    } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9895      isInc = Ptr->getOpcode() == ISD::ADD;
9896      Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9897      return true;
9898    }
9899  }
9900
9901  return false;
9902}
9903
9904/// getPreIndexedAddressParts - returns true by value, base pointer and
9905/// offset pointer and addressing mode by reference if the node's address
9906/// can be legally represented as pre-indexed load / store address.
9907bool
9908ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9909                                             SDValue &Offset,
9910                                             ISD::MemIndexedMode &AM,
9911                                             SelectionDAG &DAG) const {
9912  if (Subtarget->isThumb1Only())
9913    return false;
9914
9915  EVT VT;
9916  SDValue Ptr;
9917  bool isSEXTLoad = false;
9918  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9919    Ptr = LD->getBasePtr();
9920    VT  = LD->getMemoryVT();
9921    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9922  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9923    Ptr = ST->getBasePtr();
9924    VT  = ST->getMemoryVT();
9925  } else
9926    return false;
9927
9928  bool isInc;
9929  bool isLegal = false;
9930  if (Subtarget->isThumb2())
9931    isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9932                                       Offset, isInc, DAG);
9933  else
9934    isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9935                                        Offset, isInc, DAG);
9936  if (!isLegal)
9937    return false;
9938
9939  AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9940  return true;
9941}
9942
9943/// getPostIndexedAddressParts - returns true by value, base pointer and
9944/// offset pointer and addressing mode by reference if this node can be
9945/// combined with a load / store to form a post-indexed load / store.
9946bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9947                                                   SDValue &Base,
9948                                                   SDValue &Offset,
9949                                                   ISD::MemIndexedMode &AM,
9950                                                   SelectionDAG &DAG) const {
9951  if (Subtarget->isThumb1Only())
9952    return false;
9953
9954  EVT VT;
9955  SDValue Ptr;
9956  bool isSEXTLoad = false;
9957  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9958    VT  = LD->getMemoryVT();
9959    Ptr = LD->getBasePtr();
9960    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9961  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9962    VT  = ST->getMemoryVT();
9963    Ptr = ST->getBasePtr();
9964  } else
9965    return false;
9966
9967  bool isInc;
9968  bool isLegal = false;
9969  if (Subtarget->isThumb2())
9970    isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9971                                       isInc, DAG);
9972  else
9973    isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9974                                        isInc, DAG);
9975  if (!isLegal)
9976    return false;
9977
9978  if (Ptr != Base) {
9979    // Swap base ptr and offset to catch more post-index load / store when
9980    // it's legal. In Thumb2 mode, offset must be an immediate.
9981    if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9982        !Subtarget->isThumb2())
9983      std::swap(Base, Offset);
9984
9985    // Post-indexed load / store update the base pointer.
9986    if (Ptr != Base)
9987      return false;
9988  }
9989
9990  AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9991  return true;
9992}
9993
9994void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9995                                                       APInt &KnownZero,
9996                                                       APInt &KnownOne,
9997                                                       const SelectionDAG &DAG,
9998                                                       unsigned Depth) const {
9999  KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10000  switch (Op.getOpcode()) {
10001  default: break;
10002  case ARMISD::CMOV: {
10003    // Bits are known zero/one if known on the LHS and RHS.
10004    DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10005    if (KnownZero == 0 && KnownOne == 0) return;
10006
10007    APInt KnownZeroRHS, KnownOneRHS;
10008    DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10009    KnownZero &= KnownZeroRHS;
10010    KnownOne  &= KnownOneRHS;
10011    return;
10012  }
10013  }
10014}
10015
10016//===----------------------------------------------------------------------===//
10017//                           ARM Inline Assembly Support
10018//===----------------------------------------------------------------------===//
10019
10020bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10021  // Looking for "rev" which is V6+.
10022  if (!Subtarget->hasV6Ops())
10023    return false;
10024
10025  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10026  std::string AsmStr = IA->getAsmString();
10027  SmallVector<StringRef, 4> AsmPieces;
10028  SplitString(AsmStr, AsmPieces, ";\n");
10029
10030  switch (AsmPieces.size()) {
10031  default: return false;
10032  case 1:
10033    AsmStr = AsmPieces[0];
10034    AsmPieces.clear();
10035    SplitString(AsmStr, AsmPieces, " \t,");
10036
10037    // rev $0, $1
10038    if (AsmPieces.size() == 3 &&
10039        AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10040        IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10041      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10042      if (Ty && Ty->getBitWidth() == 32)
10043        return IntrinsicLowering::LowerToByteSwap(CI);
10044    }
10045    break;
10046  }
10047
10048  return false;
10049}
10050
10051/// getConstraintType - Given a constraint letter, return the type of
10052/// constraint it is for this target.
10053ARMTargetLowering::ConstraintType
10054ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10055  if (Constraint.size() == 1) {
10056    switch (Constraint[0]) {
10057    default:  break;
10058    case 'l': return C_RegisterClass;
10059    case 'w': return C_RegisterClass;
10060    case 'h': return C_RegisterClass;
10061    case 'x': return C_RegisterClass;
10062    case 't': return C_RegisterClass;
10063    case 'j': return C_Other; // Constant for movw.
10064      // An address with a single base register. Due to the way we
10065      // currently handle addresses it is the same as an 'r' memory constraint.
10066    case 'Q': return C_Memory;
10067    }
10068  } else if (Constraint.size() == 2) {
10069    switch (Constraint[0]) {
10070    default: break;
10071    // All 'U+' constraints are addresses.
10072    case 'U': return C_Memory;
10073    }
10074  }
10075  return TargetLowering::getConstraintType(Constraint);
10076}
10077
10078/// Examine constraint type and operand type and determine a weight value.
10079/// This object must already have been set up with the operand type
10080/// and the current alternative constraint selected.
10081TargetLowering::ConstraintWeight
10082ARMTargetLowering::getSingleConstraintMatchWeight(
10083    AsmOperandInfo &info, const char *constraint) const {
10084  ConstraintWeight weight = CW_Invalid;
10085  Value *CallOperandVal = info.CallOperandVal;
10086    // If we don't have a value, we can't do a match,
10087    // but allow it at the lowest weight.
10088  if (CallOperandVal == NULL)
10089    return CW_Default;
10090  Type *type = CallOperandVal->getType();
10091  // Look at the constraint type.
10092  switch (*constraint) {
10093  default:
10094    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10095    break;
10096  case 'l':
10097    if (type->isIntegerTy()) {
10098      if (Subtarget->isThumb())
10099        weight = CW_SpecificReg;
10100      else
10101        weight = CW_Register;
10102    }
10103    break;
10104  case 'w':
10105    if (type->isFloatingPointTy())
10106      weight = CW_Register;
10107    break;
10108  }
10109  return weight;
10110}
10111
10112typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10113RCPair
10114ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10115                                                EVT VT) const {
10116  if (Constraint.size() == 1) {
10117    // GCC ARM Constraint Letters
10118    switch (Constraint[0]) {
10119    case 'l': // Low regs or general regs.
10120      if (Subtarget->isThumb())
10121        return RCPair(0U, &ARM::tGPRRegClass);
10122      return RCPair(0U, &ARM::GPRRegClass);
10123    case 'h': // High regs or no regs.
10124      if (Subtarget->isThumb())
10125        return RCPair(0U, &ARM::hGPRRegClass);
10126      break;
10127    case 'r':
10128      return RCPair(0U, &ARM::GPRRegClass);
10129    case 'w':
10130      if (VT == MVT::f32)
10131        return RCPair(0U, &ARM::SPRRegClass);
10132      if (VT.getSizeInBits() == 64)
10133        return RCPair(0U, &ARM::DPRRegClass);
10134      if (VT.getSizeInBits() == 128)
10135        return RCPair(0U, &ARM::QPRRegClass);
10136      break;
10137    case 'x':
10138      if (VT == MVT::f32)
10139        return RCPair(0U, &ARM::SPR_8RegClass);
10140      if (VT.getSizeInBits() == 64)
10141        return RCPair(0U, &ARM::DPR_8RegClass);
10142      if (VT.getSizeInBits() == 128)
10143        return RCPair(0U, &ARM::QPR_8RegClass);
10144      break;
10145    case 't':
10146      if (VT == MVT::f32)
10147        return RCPair(0U, &ARM::SPRRegClass);
10148      break;
10149    }
10150  }
10151  if (StringRef("{cc}").equals_lower(Constraint))
10152    return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10153
10154  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10155}
10156
10157/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10158/// vector.  If it is invalid, don't add anything to Ops.
10159void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10160                                                     std::string &Constraint,
10161                                                     std::vector<SDValue>&Ops,
10162                                                     SelectionDAG &DAG) const {
10163  SDValue Result(0, 0);
10164
10165  // Currently only support length 1 constraints.
10166  if (Constraint.length() != 1) return;
10167
10168  char ConstraintLetter = Constraint[0];
10169  switch (ConstraintLetter) {
10170  default: break;
10171  case 'j':
10172  case 'I': case 'J': case 'K': case 'L':
10173  case 'M': case 'N': case 'O':
10174    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10175    if (!C)
10176      return;
10177
10178    int64_t CVal64 = C->getSExtValue();
10179    int CVal = (int) CVal64;
10180    // None of these constraints allow values larger than 32 bits.  Check
10181    // that the value fits in an int.
10182    if (CVal != CVal64)
10183      return;
10184
10185    switch (ConstraintLetter) {
10186      case 'j':
10187        // Constant suitable for movw, must be between 0 and
10188        // 65535.
10189        if (Subtarget->hasV6T2Ops())
10190          if (CVal >= 0 && CVal <= 65535)
10191            break;
10192        return;
10193      case 'I':
10194        if (Subtarget->isThumb1Only()) {
10195          // This must be a constant between 0 and 255, for ADD
10196          // immediates.
10197          if (CVal >= 0 && CVal <= 255)
10198            break;
10199        } else if (Subtarget->isThumb2()) {
10200          // A constant that can be used as an immediate value in a
10201          // data-processing instruction.
10202          if (ARM_AM::getT2SOImmVal(CVal) != -1)
10203            break;
10204        } else {
10205          // A constant that can be used as an immediate value in a
10206          // data-processing instruction.
10207          if (ARM_AM::getSOImmVal(CVal) != -1)
10208            break;
10209        }
10210        return;
10211
10212      case 'J':
10213        if (Subtarget->isThumb()) {  // FIXME thumb2
10214          // This must be a constant between -255 and -1, for negated ADD
10215          // immediates. This can be used in GCC with an "n" modifier that
10216          // prints the negated value, for use with SUB instructions. It is
10217          // not useful otherwise but is implemented for compatibility.
10218          if (CVal >= -255 && CVal <= -1)
10219            break;
10220        } else {
10221          // This must be a constant between -4095 and 4095. It is not clear
10222          // what this constraint is intended for. Implemented for
10223          // compatibility with GCC.
10224          if (CVal >= -4095 && CVal <= 4095)
10225            break;
10226        }
10227        return;
10228
10229      case 'K':
10230        if (Subtarget->isThumb1Only()) {
10231          // A 32-bit value where only one byte has a nonzero value. Exclude
10232          // zero to match GCC. This constraint is used by GCC internally for
10233          // constants that can be loaded with a move/shift combination.
10234          // It is not useful otherwise but is implemented for compatibility.
10235          if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10236            break;
10237        } else if (Subtarget->isThumb2()) {
10238          // A constant whose bitwise inverse can be used as an immediate
10239          // value in a data-processing instruction. This can be used in GCC
10240          // with a "B" modifier that prints the inverted value, for use with
10241          // BIC and MVN instructions. It is not useful otherwise but is
10242          // implemented for compatibility.
10243          if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10244            break;
10245        } else {
10246          // A constant whose bitwise inverse can be used as an immediate
10247          // value in a data-processing instruction. This can be used in GCC
10248          // with a "B" modifier that prints the inverted value, for use with
10249          // BIC and MVN instructions. It is not useful otherwise but is
10250          // implemented for compatibility.
10251          if (ARM_AM::getSOImmVal(~CVal) != -1)
10252            break;
10253        }
10254        return;
10255
10256      case 'L':
10257        if (Subtarget->isThumb1Only()) {
10258          // This must be a constant between -7 and 7,
10259          // for 3-operand ADD/SUB immediate instructions.
10260          if (CVal >= -7 && CVal < 7)
10261            break;
10262        } else if (Subtarget->isThumb2()) {
10263          // A constant whose negation can be used as an immediate value in a
10264          // data-processing instruction. This can be used in GCC with an "n"
10265          // modifier that prints the negated value, for use with SUB
10266          // instructions. It is not useful otherwise but is implemented for
10267          // compatibility.
10268          if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10269            break;
10270        } else {
10271          // A constant whose negation can be used as an immediate value in a
10272          // data-processing instruction. This can be used in GCC with an "n"
10273          // modifier that prints the negated value, for use with SUB
10274          // instructions. It is not useful otherwise but is implemented for
10275          // compatibility.
10276          if (ARM_AM::getSOImmVal(-CVal) != -1)
10277            break;
10278        }
10279        return;
10280
10281      case 'M':
10282        if (Subtarget->isThumb()) { // FIXME thumb2
10283          // This must be a multiple of 4 between 0 and 1020, for
10284          // ADD sp + immediate.
10285          if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10286            break;
10287        } else {
10288          // A power of two or a constant between 0 and 32.  This is used in
10289          // GCC for the shift amount on shifted register operands, but it is
10290          // useful in general for any shift amounts.
10291          if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10292            break;
10293        }
10294        return;
10295
10296      case 'N':
10297        if (Subtarget->isThumb()) {  // FIXME thumb2
10298          // This must be a constant between 0 and 31, for shift amounts.
10299          if (CVal >= 0 && CVal <= 31)
10300            break;
10301        }
10302        return;
10303
10304      case 'O':
10305        if (Subtarget->isThumb()) {  // FIXME thumb2
10306          // This must be a multiple of 4 between -508 and 508, for
10307          // ADD/SUB sp = sp + immediate.
10308          if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10309            break;
10310        }
10311        return;
10312    }
10313    Result = DAG.getTargetConstant(CVal, Op.getValueType());
10314    break;
10315  }
10316
10317  if (Result.getNode()) {
10318    Ops.push_back(Result);
10319    return;
10320  }
10321  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10322}
10323
10324bool
10325ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10326  // The ARM target isn't yet aware of offsets.
10327  return false;
10328}
10329
10330bool ARM::isBitFieldInvertedMask(unsigned v) {
10331  if (v == 0xffffffff)
10332    return 0;
10333  // there can be 1's on either or both "outsides", all the "inside"
10334  // bits must be 0's
10335  unsigned int lsb = 0, msb = 31;
10336  while (v & (1 << msb)) --msb;
10337  while (v & (1 << lsb)) ++lsb;
10338  for (unsigned int i = lsb; i <= msb; ++i) {
10339    if (v & (1 << i))
10340      return 0;
10341  }
10342  return 1;
10343}
10344
10345/// isFPImmLegal - Returns true if the target can instruction select the
10346/// specified FP immediate natively. If false, the legalizer will
10347/// materialize the FP immediate as a load from a constant pool.
10348bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10349  if (!Subtarget->hasVFP3())
10350    return false;
10351  if (VT == MVT::f32)
10352    return ARM_AM::getFP32Imm(Imm) != -1;
10353  if (VT == MVT::f64)
10354    return ARM_AM::getFP64Imm(Imm) != -1;
10355  return false;
10356}
10357
10358/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10359/// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10360/// specified in the intrinsic calls.
10361bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10362                                           const CallInst &I,
10363                                           unsigned Intrinsic) const {
10364  switch (Intrinsic) {
10365  case Intrinsic::arm_neon_vld1:
10366  case Intrinsic::arm_neon_vld2:
10367  case Intrinsic::arm_neon_vld3:
10368  case Intrinsic::arm_neon_vld4:
10369  case Intrinsic::arm_neon_vld2lane:
10370  case Intrinsic::arm_neon_vld3lane:
10371  case Intrinsic::arm_neon_vld4lane: {
10372    Info.opc = ISD::INTRINSIC_W_CHAIN;
10373    // Conservatively set memVT to the entire set of vectors loaded.
10374    uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10375    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10376    Info.ptrVal = I.getArgOperand(0);
10377    Info.offset = 0;
10378    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10379    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10380    Info.vol = false; // volatile loads with NEON intrinsics not supported
10381    Info.readMem = true;
10382    Info.writeMem = false;
10383    return true;
10384  }
10385  case Intrinsic::arm_neon_vst1:
10386  case Intrinsic::arm_neon_vst2:
10387  case Intrinsic::arm_neon_vst3:
10388  case Intrinsic::arm_neon_vst4:
10389  case Intrinsic::arm_neon_vst2lane:
10390  case Intrinsic::arm_neon_vst3lane:
10391  case Intrinsic::arm_neon_vst4lane: {
10392    Info.opc = ISD::INTRINSIC_VOID;
10393    // Conservatively set memVT to the entire set of vectors stored.
10394    unsigned NumElts = 0;
10395    for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10396      Type *ArgTy = I.getArgOperand(ArgI)->getType();
10397      if (!ArgTy->isVectorTy())
10398        break;
10399      NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10400    }
10401    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10402    Info.ptrVal = I.getArgOperand(0);
10403    Info.offset = 0;
10404    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10405    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10406    Info.vol = false; // volatile stores with NEON intrinsics not supported
10407    Info.readMem = false;
10408    Info.writeMem = true;
10409    return true;
10410  }
10411  case Intrinsic::arm_strexd: {
10412    Info.opc = ISD::INTRINSIC_W_CHAIN;
10413    Info.memVT = MVT::i64;
10414    Info.ptrVal = I.getArgOperand(2);
10415    Info.offset = 0;
10416    Info.align = 8;
10417    Info.vol = true;
10418    Info.readMem = false;
10419    Info.writeMem = true;
10420    return true;
10421  }
10422  case Intrinsic::arm_ldrexd: {
10423    Info.opc = ISD::INTRINSIC_W_CHAIN;
10424    Info.memVT = MVT::i64;
10425    Info.ptrVal = I.getArgOperand(0);
10426    Info.offset = 0;
10427    Info.align = 8;
10428    Info.vol = true;
10429    Info.readMem = true;
10430    Info.writeMem = false;
10431    return true;
10432  }
10433  default:
10434    break;
10435  }
10436
10437  return false;
10438}
10439