OSDN Git Service

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