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