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