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