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