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