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