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