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