Use the right register class for LDRrs.
[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 "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55
56 // This option should go away when tail calls fully work.
57 static cl::opt<bool>
58 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
59   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
60   cl::init(false));
61
62 cl::opt<bool>
63 EnableARMLongCalls("arm-long-calls", cl::Hidden,
64   cl::desc("Generate calls via indirect call instructions"),
65   cl::init(false));
66
67 static cl::opt<bool>
68 ARMInterworking("arm-interworking", cl::Hidden,
69   cl::desc("Enable / disable ARM interworking (for debugging only)"),
70   cl::init(true));
71
72 namespace {
73   class ARMCCState : public CCState {
74   public:
75     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
76                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
77                LLVMContext &C, ParmContext PC)
78         : CCState(CC, isVarArg, MF, TM, locs, C) {
79       assert(((PC == Call) || (PC == Prologue)) &&
80              "ARMCCState users must specify whether their context is call"
81              "or prologue generation.");
82       CallOrPrologue = PC;
83     }
84   };
85 }
86
87 // The APCS parameter registers.
88 static const uint16_t GPRArgRegs[] = {
89   ARM::R0, ARM::R1, ARM::R2, ARM::R3
90 };
91
92 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
93                                        EVT PromotedBitwiseVT) {
94   if (VT != PromotedLdStVT) {
95     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
96     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
97                        PromotedLdStVT.getSimpleVT());
98
99     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
100     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
101                        PromotedLdStVT.getSimpleVT());
102   }
103
104   EVT ElemTy = VT.getVectorElementType();
105   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
107   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
108   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
109   if (ElemTy == MVT::i32) {
110     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
111     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
112     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
113     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
114   } else {
115     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
116     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
117     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
118     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
119   }
120   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
121   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
122   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
123   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
124   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
125   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
129     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
130     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
136     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
137                        PromotedBitwiseVT.getSimpleVT());
138     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
139     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
140                        PromotedBitwiseVT.getSimpleVT());
141     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
142     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
143                        PromotedBitwiseVT.getSimpleVT());
144   }
145
146   // Neon does not support vector divide/remainder operations.
147   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
148   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
149   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
150   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
153 }
154
155 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
156   addRegisterClass(VT, &ARM::DPRRegClass);
157   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
158 }
159
160 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
161   addRegisterClass(VT, &ARM::QPRRegClass);
162   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
163 }
164
165 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
166   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
167     return new TargetLoweringObjectFileMachO();
168
169   return new ARMElfTargetObjectFile();
170 }
171
172 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
173     : TargetLowering(TM, createTLOF(TM)) {
174   Subtarget = &TM.getSubtarget<ARMSubtarget>();
175   RegInfo = TM.getRegisterInfo();
176   Itins = TM.getInstrItineraryData();
177
178   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
179
180   if (Subtarget->isTargetDarwin()) {
181     // Uses VFP for Thumb libfuncs if available.
182     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
183       // Single-precision floating-point arithmetic.
184       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
185       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
186       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
187       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
188
189       // Double-precision floating-point arithmetic.
190       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
191       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
192       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
193       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
194
195       // Single-precision comparisons.
196       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
197       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
198       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
199       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
200       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
201       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
202       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
203       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
204
205       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
212       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
213
214       // Double-precision comparisons.
215       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
216       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
217       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
218       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
219       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
220       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
221       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
222       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
223
224       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
231       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
232
233       // Floating-point to integer conversions.
234       // i64 conversions are done via library routines even when generating VFP
235       // instructions, so use the same ones.
236       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
237       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
238       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
239       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
240
241       // Conversions between floating types.
242       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
243       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
244
245       // Integer to floating-point conversions.
246       // i64 conversions are done via library routines even when generating VFP
247       // instructions, so use the same ones.
248       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
249       // e.g., __floatunsidf vs. __floatunssidfvfp.
250       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
251       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
252       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
253       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
254     }
255   }
256
257   // These libcalls are not available in 32-bit.
258   setLibcallName(RTLIB::SHL_I128, 0);
259   setLibcallName(RTLIB::SRL_I128, 0);
260   setLibcallName(RTLIB::SRA_I128, 0);
261
262   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
263     // Double-precision floating-point arithmetic helper functions
264     // RTABI chapter 4.1.2, Table 2
265     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
266     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
267     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
268     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
269     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
270     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
273
274     // Double-precision floating-point comparison helper functions
275     // RTABI chapter 4.1.2, Table 3
276     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
277     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
278     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
279     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
280     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
281     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
282     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
283     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
284     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
285     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
286     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
287     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
288     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
289     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
290     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
291     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
292     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
300
301     // Single-precision floating-point arithmetic helper functions
302     // RTABI chapter 4.1.2, Table 4
303     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
304     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
305     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
306     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
307     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
308     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
311
312     // Single-precision floating-point comparison helper functions
313     // RTABI chapter 4.1.2, Table 5
314     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
315     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
316     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
317     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
318     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
319     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
320     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
321     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
322     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
323     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
324     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
325     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
326     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
327     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
328     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
329     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
330     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
338
339     // Floating-point to integer conversions.
340     // RTABI chapter 4.1.2, Table 6
341     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
342     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
343     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
344     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
345     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
346     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
347     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
348     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
349     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
357
358     // Conversions between floating types.
359     // RTABI chapter 4.1.2, Table 7
360     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
361     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
362     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
363     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
364
365     // Integer to floating-point conversions.
366     // RTABI chapter 4.1.2, Table 8
367     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
368     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
369     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
370     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
371     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
372     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
373     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
374     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
375     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383
384     // Long long helper functions
385     // RTABI chapter 4.2, Table 9
386     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
387     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
388     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
389     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
390     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
396
397     // Integer division functions
398     // RTABI chapter 4.3.1
399     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
400     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
401     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
402     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
403     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
404     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
405     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
406     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
407     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
415
416     // Memory operations
417     // RTABI chapter 4.3.4
418     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
419     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
420     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
421     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
422     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
423     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
424   }
425
426   // Use divmod compiler-rt calls for iOS 5.0 and later.
427   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
428       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
429     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
430     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
431   }
432
433   if (Subtarget->isThumb1Only())
434     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
435   else
436     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
437   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
438       !Subtarget->isThumb1Only()) {
439     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
440     if (!Subtarget->isFPOnlySP())
441       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
442
443     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
444   }
445
446   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
447        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
448     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
450       setTruncStoreAction((MVT::SimpleValueType)VT,
451                           (MVT::SimpleValueType)InnerVT, Expand);
452     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
455   }
456
457   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510
511     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setTargetDAGCombine(ISD::INTRINSIC_VOID);
545     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
546     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
547     setTargetDAGCombine(ISD::SHL);
548     setTargetDAGCombine(ISD::SRL);
549     setTargetDAGCombine(ISD::SRA);
550     setTargetDAGCombine(ISD::SIGN_EXTEND);
551     setTargetDAGCombine(ISD::ZERO_EXTEND);
552     setTargetDAGCombine(ISD::ANY_EXTEND);
553     setTargetDAGCombine(ISD::SELECT_CC);
554     setTargetDAGCombine(ISD::BUILD_VECTOR);
555     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
556     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
557     setTargetDAGCombine(ISD::STORE);
558     setTargetDAGCombine(ISD::FP_TO_SINT);
559     setTargetDAGCombine(ISD::FP_TO_UINT);
560     setTargetDAGCombine(ISD::FDIV);
561
562     // It is legal to extload from v4i8 to v4i16 or v4i32.
563     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
564                   MVT::v4i16, MVT::v2i16,
565                   MVT::v2i32};
566     for (unsigned i = 0; i < 6; ++i) {
567       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
568       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
569       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
570     }
571   }
572
573   computeRegisterProperties();
574
575   // ARM does not have f32 extending load.
576   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
577
578   // ARM does not have i1 sign extending load.
579   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
580
581   // ARM supports all 4 flavors of integer indexed load / store.
582   if (!Subtarget->isThumb1Only()) {
583     for (unsigned im = (unsigned)ISD::PRE_INC;
584          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
585       setIndexedLoadAction(im,  MVT::i1,  Legal);
586       setIndexedLoadAction(im,  MVT::i8,  Legal);
587       setIndexedLoadAction(im,  MVT::i16, Legal);
588       setIndexedLoadAction(im,  MVT::i32, Legal);
589       setIndexedStoreAction(im, MVT::i1,  Legal);
590       setIndexedStoreAction(im, MVT::i8,  Legal);
591       setIndexedStoreAction(im, MVT::i16, Legal);
592       setIndexedStoreAction(im, MVT::i32, Legal);
593     }
594   }
595
596   // i64 operation support.
597   setOperationAction(ISD::MUL,     MVT::i64, Expand);
598   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
599   if (Subtarget->isThumb1Only()) {
600     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
601     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
602   }
603   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
604       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
605     setOperationAction(ISD::MULHS, MVT::i32, Expand);
606
607   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
608   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
609   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
610   setOperationAction(ISD::SRL,       MVT::i64, Custom);
611   setOperationAction(ISD::SRA,       MVT::i64, Custom);
612
613   if (!Subtarget->isThumb1Only()) {
614     // FIXME: We should do this for Thumb1 as well.
615     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
616     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
617     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
618     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
619   }
620
621   // ARM does not have ROTL.
622   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
623   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
624   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
625   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
626     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
627
628   // These just redirect to CTTZ and CTLZ on ARM.
629   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
630   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
631
632   // Only ARMv6 has BSWAP.
633   if (!Subtarget->hasV6Ops())
634     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
635
636   // These are expanded into libcalls.
637   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
638     // v7M has a hardware divider
639     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
640     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
641   }
642   setOperationAction(ISD::SREM,  MVT::i32, Expand);
643   setOperationAction(ISD::UREM,  MVT::i32, Expand);
644   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
645   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
646
647   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
648   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
649   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
650   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
651   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
652
653   setOperationAction(ISD::TRAP, MVT::Other, Legal);
654
655   // Use the default implementation.
656   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
657   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
658   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
659   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
660   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
661   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
662
663   if (!Subtarget->isTargetDarwin()) {
664     // Non-Darwin platforms may return values in these registers via the
665     // personality function.
666     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
667     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
668     setExceptionPointerRegister(ARM::R0);
669     setExceptionSelectorRegister(ARM::R1);
670   }
671
672   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
673   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
674   // the default expansion.
675   // FIXME: This should be checking for v6k, not just v6.
676   if (Subtarget->hasDataBarrier() ||
677       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
678     // membarrier needs custom lowering; the rest are legal and handled
679     // normally.
680     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
681     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
682     // Custom lowering for 64-bit ops
683     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
684     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
685     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
686     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
690     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
691     setInsertFencesForAtomic(true);
692   } else {
693     // Set them all for expansion, which will force libcalls.
694     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
695     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
696     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
697     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
698     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
708     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
709     // Unordered/Monotonic case.
710     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
711     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
712     // Since the libcalls include locking, fold in the fences
713     setShouldFoldAtomicFences(true);
714   }
715
716   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
717
718   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
719   if (!Subtarget->hasV6Ops()) {
720     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
721     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
722   }
723   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
724
725   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
726       !Subtarget->isThumb1Only()) {
727     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
728     // iff target supports vfp2.
729     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
730     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
731   }
732
733   // We want to custom lower some of our intrinsics.
734   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
735   if (Subtarget->isTargetDarwin()) {
736     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
737     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
738     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
739   }
740
741   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
742   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
743   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
744   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
745   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
746   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
747   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
748   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
749   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
750
751   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
752   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
753   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
754   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
755   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
756
757   // We don't support sin/cos/fmod/copysign/pow
758   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
759   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
760   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
761   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
762   setOperationAction(ISD::FREM,      MVT::f64, Expand);
763   setOperationAction(ISD::FREM,      MVT::f32, Expand);
764   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
765       !Subtarget->isThumb1Only()) {
766     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
767     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
768   }
769   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
770   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
771
772   if (!Subtarget->hasVFP4()) {
773     setOperationAction(ISD::FMA, MVT::f64, Expand);
774     setOperationAction(ISD::FMA, MVT::f32, Expand);
775   }
776
777   // Various VFP goodness
778   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
779     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
780     if (Subtarget->hasVFP2()) {
781       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
782       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
783       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
784       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
785     }
786     // Special handling for half-precision FP.
787     if (!Subtarget->hasFP16()) {
788       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
789       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
790     }
791   }
792
793   // We have target-specific dag combine patterns for the following nodes:
794   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
795   setTargetDAGCombine(ISD::ADD);
796   setTargetDAGCombine(ISD::SUB);
797   setTargetDAGCombine(ISD::MUL);
798
799   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
800     setTargetDAGCombine(ISD::AND);
801     setTargetDAGCombine(ISD::OR);
802     setTargetDAGCombine(ISD::XOR);
803   }
804
805   if (Subtarget->hasV6Ops())
806     setTargetDAGCombine(ISD::SRL);
807
808   setStackPointerRegisterToSaveRestore(ARM::SP);
809
810   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
811       !Subtarget->hasVFP2())
812     setSchedulingPreference(Sched::RegPressure);
813   else
814     setSchedulingPreference(Sched::Hybrid);
815
816   //// temporary - rewrite interface to use type
817   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
818   maxStoresPerMemset = 16;
819   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
820
821   // On ARM arguments smaller than 4 bytes are extended, so all arguments
822   // are at least 4 bytes aligned.
823   setMinStackArgumentAlignment(4);
824
825   benefitFromCodePlacementOpt = true;
826
827   // Prefer likely predicted branches to selects on out-of-order cores.
828   predictableSelectIsExpensive = Subtarget->isCortexA9();
829
830   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
831 }
832
833 // FIXME: It might make sense to define the representative register class as the
834 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
835 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
836 // SPR's representative would be DPR_VFP2. This should work well if register
837 // pressure tracking were modified such that a register use would increment the
838 // pressure of the register class's representative and all of it's super
839 // classes' representatives transitively. We have not implemented this because
840 // of the difficulty prior to coalescing of modeling operand register classes
841 // due to the common occurrence of cross class copies and subregister insertions
842 // and extractions.
843 std::pair<const TargetRegisterClass*, uint8_t>
844 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
845   const TargetRegisterClass *RRC = 0;
846   uint8_t Cost = 1;
847   switch (VT.getSimpleVT().SimpleTy) {
848   default:
849     return TargetLowering::findRepresentativeClass(VT);
850   // Use DPR as representative register class for all floating point
851   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
852   // the cost is 1 for both f32 and f64.
853   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
854   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
855     RRC = &ARM::DPRRegClass;
856     // When NEON is used for SP, only half of the register file is available
857     // because operations that define both SP and DP results will be constrained
858     // to the VFP2 class (D0-D15). We currently model this constraint prior to
859     // coalescing by double-counting the SP regs. See the FIXME above.
860     if (Subtarget->useNEONForSinglePrecisionFP())
861       Cost = 2;
862     break;
863   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
864   case MVT::v4f32: case MVT::v2f64:
865     RRC = &ARM::DPRRegClass;
866     Cost = 2;
867     break;
868   case MVT::v4i64:
869     RRC = &ARM::DPRRegClass;
870     Cost = 4;
871     break;
872   case MVT::v8i64:
873     RRC = &ARM::DPRRegClass;
874     Cost = 8;
875     break;
876   }
877   return std::make_pair(RRC, Cost);
878 }
879
880 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
881   switch (Opcode) {
882   default: return 0;
883   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
884   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
885   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
886   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
887   case ARMISD::CALL:          return "ARMISD::CALL";
888   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
889   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
890   case ARMISD::tCALL:         return "ARMISD::tCALL";
891   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
892   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
893   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
894   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
895   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
896   case ARMISD::CMP:           return "ARMISD::CMP";
897   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
898   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
899   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
900   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
901   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
902
903   case ARMISD::CMOV:          return "ARMISD::CMOV";
904   case ARMISD::CAND:          return "ARMISD::CAND";
905   case ARMISD::COR:           return "ARMISD::COR";
906   case ARMISD::CXOR:          return "ARMISD::CXOR";
907
908   case ARMISD::RBIT:          return "ARMISD::RBIT";
909
910   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
911   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
912   case ARMISD::SITOF:         return "ARMISD::SITOF";
913   case ARMISD::UITOF:         return "ARMISD::UITOF";
914
915   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
916   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
917   case ARMISD::RRX:           return "ARMISD::RRX";
918
919   case ARMISD::ADDC:          return "ARMISD::ADDC";
920   case ARMISD::ADDE:          return "ARMISD::ADDE";
921   case ARMISD::SUBC:          return "ARMISD::SUBC";
922   case ARMISD::SUBE:          return "ARMISD::SUBE";
923
924   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
925   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
926
927   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
928   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
929
930   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
931
932   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
933
934   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
935
936   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
937   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
938
939   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
940
941   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
942   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
943   case ARMISD::VCGE:          return "ARMISD::VCGE";
944   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
945   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
946   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
947   case ARMISD::VCGT:          return "ARMISD::VCGT";
948   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
949   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
950   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
951   case ARMISD::VTST:          return "ARMISD::VTST";
952
953   case ARMISD::VSHL:          return "ARMISD::VSHL";
954   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
955   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
956   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
957   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
958   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
959   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
960   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
961   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
962   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
963   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
964   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
965   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
966   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
967   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
968   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
969   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
970   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
971   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
972   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
973   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
974   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
975   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
976   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
977   case ARMISD::VDUP:          return "ARMISD::VDUP";
978   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
979   case ARMISD::VEXT:          return "ARMISD::VEXT";
980   case ARMISD::VREV64:        return "ARMISD::VREV64";
981   case ARMISD::VREV32:        return "ARMISD::VREV32";
982   case ARMISD::VREV16:        return "ARMISD::VREV16";
983   case ARMISD::VZIP:          return "ARMISD::VZIP";
984   case ARMISD::VUZP:          return "ARMISD::VUZP";
985   case ARMISD::VTRN:          return "ARMISD::VTRN";
986   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
987   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
988   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
989   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
990   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
991   case ARMISD::FMAX:          return "ARMISD::FMAX";
992   case ARMISD::FMIN:          return "ARMISD::FMIN";
993   case ARMISD::BFI:           return "ARMISD::BFI";
994   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
995   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
996   case ARMISD::VBSL:          return "ARMISD::VBSL";
997   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
998   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
999   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1000   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1001   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1002   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1003   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1004   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1005   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1006   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1007   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1008   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1009   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1010   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1011   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1012   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1013   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1014   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1015   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1016   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1017   }
1018 }
1019
1020 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1021   if (!VT.isVector()) return getPointerTy();
1022   return VT.changeVectorElementTypeToInteger();
1023 }
1024
1025 /// getRegClassFor - Return the register class that should be used for the
1026 /// specified value type.
1027 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1028   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1029   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1030   // load / store 4 to 8 consecutive D registers.
1031   if (Subtarget->hasNEON()) {
1032     if (VT == MVT::v4i64)
1033       return &ARM::QQPRRegClass;
1034     if (VT == MVT::v8i64)
1035       return &ARM::QQQQPRRegClass;
1036   }
1037   return TargetLowering::getRegClassFor(VT);
1038 }
1039
1040 // Create a fast isel object.
1041 FastISel *
1042 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1043   return ARM::createFastISel(funcInfo);
1044 }
1045
1046 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1047 /// be used for loads / stores from the global.
1048 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1049   return (Subtarget->isThumb1Only() ? 127 : 4095);
1050 }
1051
1052 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1053   unsigned NumVals = N->getNumValues();
1054   if (!NumVals)
1055     return Sched::RegPressure;
1056
1057   for (unsigned i = 0; i != NumVals; ++i) {
1058     EVT VT = N->getValueType(i);
1059     if (VT == MVT::Glue || VT == MVT::Other)
1060       continue;
1061     if (VT.isFloatingPoint() || VT.isVector())
1062       return Sched::ILP;
1063   }
1064
1065   if (!N->isMachineOpcode())
1066     return Sched::RegPressure;
1067
1068   // Load are scheduled for latency even if there instruction itinerary
1069   // is not available.
1070   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1071   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1072
1073   if (MCID.getNumDefs() == 0)
1074     return Sched::RegPressure;
1075   if (!Itins->isEmpty() &&
1076       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1077     return Sched::ILP;
1078
1079   return Sched::RegPressure;
1080 }
1081
1082 //===----------------------------------------------------------------------===//
1083 // Lowering Code
1084 //===----------------------------------------------------------------------===//
1085
1086 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1087 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1088   switch (CC) {
1089   default: llvm_unreachable("Unknown condition code!");
1090   case ISD::SETNE:  return ARMCC::NE;
1091   case ISD::SETEQ:  return ARMCC::EQ;
1092   case ISD::SETGT:  return ARMCC::GT;
1093   case ISD::SETGE:  return ARMCC::GE;
1094   case ISD::SETLT:  return ARMCC::LT;
1095   case ISD::SETLE:  return ARMCC::LE;
1096   case ISD::SETUGT: return ARMCC::HI;
1097   case ISD::SETUGE: return ARMCC::HS;
1098   case ISD::SETULT: return ARMCC::LO;
1099   case ISD::SETULE: return ARMCC::LS;
1100   }
1101 }
1102
1103 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1104 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1105                         ARMCC::CondCodes &CondCode2) {
1106   CondCode2 = ARMCC::AL;
1107   switch (CC) {
1108   default: llvm_unreachable("Unknown FP condition!");
1109   case ISD::SETEQ:
1110   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1111   case ISD::SETGT:
1112   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1113   case ISD::SETGE:
1114   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1115   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1116   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1117   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1118   case ISD::SETO:   CondCode = ARMCC::VC; break;
1119   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1120   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1121   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1122   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1123   case ISD::SETLT:
1124   case ISD::SETULT: CondCode = ARMCC::LT; break;
1125   case ISD::SETLE:
1126   case ISD::SETULE: CondCode = ARMCC::LE; break;
1127   case ISD::SETNE:
1128   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1129   }
1130 }
1131
1132 //===----------------------------------------------------------------------===//
1133 //                      Calling Convention Implementation
1134 //===----------------------------------------------------------------------===//
1135
1136 #include "ARMGenCallingConv.inc"
1137
1138 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1139 /// given CallingConvention value.
1140 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1141                                                  bool Return,
1142                                                  bool isVarArg) const {
1143   switch (CC) {
1144   default:
1145     llvm_unreachable("Unsupported calling convention");
1146   case CallingConv::Fast:
1147     if (Subtarget->hasVFP2() && !isVarArg) {
1148       if (!Subtarget->isAAPCS_ABI())
1149         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1150       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1151       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1152     }
1153     // Fallthrough
1154   case CallingConv::C: {
1155     // Use target triple & subtarget features to do actual dispatch.
1156     if (!Subtarget->isAAPCS_ABI())
1157       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1158     else if (Subtarget->hasVFP2() &&
1159              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1160              !isVarArg)
1161       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1162     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1163   }
1164   case CallingConv::ARM_AAPCS_VFP:
1165     if (!isVarArg)
1166       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1167     // Fallthrough
1168   case CallingConv::ARM_AAPCS:
1169     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1170   case CallingConv::ARM_APCS:
1171     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1172   }
1173 }
1174
1175 /// LowerCallResult - Lower the result values of a call into the
1176 /// appropriate copies out of appropriate physical registers.
1177 SDValue
1178 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1179                                    CallingConv::ID CallConv, bool isVarArg,
1180                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1181                                    DebugLoc dl, SelectionDAG &DAG,
1182                                    SmallVectorImpl<SDValue> &InVals) const {
1183
1184   // Assign locations to each value returned by this call.
1185   SmallVector<CCValAssign, 16> RVLocs;
1186   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1187                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1188   CCInfo.AnalyzeCallResult(Ins,
1189                            CCAssignFnForNode(CallConv, /* Return*/ true,
1190                                              isVarArg));
1191
1192   // Copy all of the result registers out of their specified physreg.
1193   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1194     CCValAssign VA = RVLocs[i];
1195
1196     SDValue Val;
1197     if (VA.needsCustom()) {
1198       // Handle f64 or half of a v2f64.
1199       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1200                                       InFlag);
1201       Chain = Lo.getValue(1);
1202       InFlag = Lo.getValue(2);
1203       VA = RVLocs[++i]; // skip ahead to next loc
1204       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1205                                       InFlag);
1206       Chain = Hi.getValue(1);
1207       InFlag = Hi.getValue(2);
1208       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1209
1210       if (VA.getLocVT() == MVT::v2f64) {
1211         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1212         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1213                           DAG.getConstant(0, MVT::i32));
1214
1215         VA = RVLocs[++i]; // skip ahead to next loc
1216         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1217         Chain = Lo.getValue(1);
1218         InFlag = Lo.getValue(2);
1219         VA = RVLocs[++i]; // skip ahead to next loc
1220         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1221         Chain = Hi.getValue(1);
1222         InFlag = Hi.getValue(2);
1223         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1224         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1225                           DAG.getConstant(1, MVT::i32));
1226       }
1227     } else {
1228       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1229                                InFlag);
1230       Chain = Val.getValue(1);
1231       InFlag = Val.getValue(2);
1232     }
1233
1234     switch (VA.getLocInfo()) {
1235     default: llvm_unreachable("Unknown loc info!");
1236     case CCValAssign::Full: break;
1237     case CCValAssign::BCvt:
1238       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1239       break;
1240     }
1241
1242     InVals.push_back(Val);
1243   }
1244
1245   return Chain;
1246 }
1247
1248 /// LowerMemOpCallTo - Store the argument to the stack.
1249 SDValue
1250 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1251                                     SDValue StackPtr, SDValue Arg,
1252                                     DebugLoc dl, SelectionDAG &DAG,
1253                                     const CCValAssign &VA,
1254                                     ISD::ArgFlagsTy Flags) const {
1255   unsigned LocMemOffset = VA.getLocMemOffset();
1256   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1257   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1258   return DAG.getStore(Chain, dl, Arg, PtrOff,
1259                       MachinePointerInfo::getStack(LocMemOffset),
1260                       false, false, 0);
1261 }
1262
1263 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1264                                          SDValue Chain, SDValue &Arg,
1265                                          RegsToPassVector &RegsToPass,
1266                                          CCValAssign &VA, CCValAssign &NextVA,
1267                                          SDValue &StackPtr,
1268                                          SmallVector<SDValue, 8> &MemOpChains,
1269                                          ISD::ArgFlagsTy Flags) const {
1270
1271   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1272                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1273   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1274
1275   if (NextVA.isRegLoc())
1276     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1277   else {
1278     assert(NextVA.isMemLoc());
1279     if (StackPtr.getNode() == 0)
1280       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1281
1282     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1283                                            dl, DAG, NextVA,
1284                                            Flags));
1285   }
1286 }
1287
1288 /// LowerCall - Lowering a call into a callseq_start <-
1289 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1290 /// nodes.
1291 SDValue
1292 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1293                              CallingConv::ID CallConv, bool isVarArg,
1294                              bool doesNotRet, bool &isTailCall,
1295                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1296                              const SmallVectorImpl<SDValue> &OutVals,
1297                              const SmallVectorImpl<ISD::InputArg> &Ins,
1298                              DebugLoc dl, SelectionDAG &DAG,
1299                              SmallVectorImpl<SDValue> &InVals) const {
1300   MachineFunction &MF = DAG.getMachineFunction();
1301   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1302   bool IsSibCall = false;
1303   // Disable tail calls if they're not supported.
1304   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1305     isTailCall = false;
1306   if (isTailCall) {
1307     // Check if it's really possible to do a tail call.
1308     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1309                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1310                                                    Outs, OutVals, Ins, DAG);
1311     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1312     // detected sibcalls.
1313     if (isTailCall) {
1314       ++NumTailCalls;
1315       IsSibCall = true;
1316     }
1317   }
1318
1319   // Analyze operands of the call, assigning locations to each operand.
1320   SmallVector<CCValAssign, 16> ArgLocs;
1321   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1322                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1323   CCInfo.AnalyzeCallOperands(Outs,
1324                              CCAssignFnForNode(CallConv, /* Return*/ false,
1325                                                isVarArg));
1326
1327   // Get a count of how many bytes are to be pushed on the stack.
1328   unsigned NumBytes = CCInfo.getNextStackOffset();
1329
1330   // For tail calls, memory operands are available in our caller's stack.
1331   if (IsSibCall)
1332     NumBytes = 0;
1333
1334   // Adjust the stack pointer for the new arguments...
1335   // These operations are automatically eliminated by the prolog/epilog pass
1336   if (!IsSibCall)
1337     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1338
1339   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1340
1341   RegsToPassVector RegsToPass;
1342   SmallVector<SDValue, 8> MemOpChains;
1343
1344   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1345   // of tail call optimization, arguments are handled later.
1346   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1347        i != e;
1348        ++i, ++realArgIdx) {
1349     CCValAssign &VA = ArgLocs[i];
1350     SDValue Arg = OutVals[realArgIdx];
1351     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1352     bool isByVal = Flags.isByVal();
1353
1354     // Promote the value if needed.
1355     switch (VA.getLocInfo()) {
1356     default: llvm_unreachable("Unknown loc info!");
1357     case CCValAssign::Full: break;
1358     case CCValAssign::SExt:
1359       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1360       break;
1361     case CCValAssign::ZExt:
1362       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1363       break;
1364     case CCValAssign::AExt:
1365       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1366       break;
1367     case CCValAssign::BCvt:
1368       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1369       break;
1370     }
1371
1372     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1373     if (VA.needsCustom()) {
1374       if (VA.getLocVT() == MVT::v2f64) {
1375         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1376                                   DAG.getConstant(0, MVT::i32));
1377         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1378                                   DAG.getConstant(1, MVT::i32));
1379
1380         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1381                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1382
1383         VA = ArgLocs[++i]; // skip ahead to next loc
1384         if (VA.isRegLoc()) {
1385           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1386                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1387         } else {
1388           assert(VA.isMemLoc());
1389
1390           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1391                                                  dl, DAG, VA, Flags));
1392         }
1393       } else {
1394         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1395                          StackPtr, MemOpChains, Flags);
1396       }
1397     } else if (VA.isRegLoc()) {
1398       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1399     } else if (isByVal) {
1400       assert(VA.isMemLoc());
1401       unsigned offset = 0;
1402
1403       // True if this byval aggregate will be split between registers
1404       // and memory.
1405       if (CCInfo.isFirstByValRegValid()) {
1406         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1407         unsigned int i, j;
1408         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1409           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1410           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1411           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1412                                      MachinePointerInfo(),
1413                                      false, false, false, 0);
1414           MemOpChains.push_back(Load.getValue(1));
1415           RegsToPass.push_back(std::make_pair(j, Load));
1416         }
1417         offset = ARM::R4 - CCInfo.getFirstByValReg();
1418         CCInfo.clearFirstByValReg();
1419       }
1420
1421       unsigned LocMemOffset = VA.getLocMemOffset();
1422       SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1423       SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1424                                 StkPtrOff);
1425       SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1426       SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1427       SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1428                                          MVT::i32);
1429       MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1430                                           Flags.getByValAlign(),
1431                                           /*isVolatile=*/false,
1432                                           /*AlwaysInline=*/false,
1433                                           MachinePointerInfo(0),
1434                                           MachinePointerInfo(0)));
1435
1436     } else if (!IsSibCall) {
1437       assert(VA.isMemLoc());
1438
1439       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1440                                              dl, DAG, VA, Flags));
1441     }
1442   }
1443
1444   if (!MemOpChains.empty())
1445     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1446                         &MemOpChains[0], MemOpChains.size());
1447
1448   // Build a sequence of copy-to-reg nodes chained together with token chain
1449   // and flag operands which copy the outgoing args into the appropriate regs.
1450   SDValue InFlag;
1451   // Tail call byval lowering might overwrite argument registers so in case of
1452   // tail call optimization the copies to registers are lowered later.
1453   if (!isTailCall)
1454     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1455       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1456                                RegsToPass[i].second, InFlag);
1457       InFlag = Chain.getValue(1);
1458     }
1459
1460   // For tail calls lower the arguments to the 'real' stack slot.
1461   if (isTailCall) {
1462     // Force all the incoming stack arguments to be loaded from the stack
1463     // before any new outgoing arguments are stored to the stack, because the
1464     // outgoing stack slots may alias the incoming argument stack slots, and
1465     // the alias isn't otherwise explicit. This is slightly more conservative
1466     // than necessary, because it means that each store effectively depends
1467     // on every argument instead of just those arguments it would clobber.
1468
1469     // Do not flag preceding copytoreg stuff together with the following stuff.
1470     InFlag = SDValue();
1471     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1472       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1473                                RegsToPass[i].second, InFlag);
1474       InFlag = Chain.getValue(1);
1475     }
1476     InFlag =SDValue();
1477   }
1478
1479   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1480   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1481   // node so that legalize doesn't hack it.
1482   bool isDirect = false;
1483   bool isARMFunc = false;
1484   bool isLocalARMFunc = false;
1485   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1486
1487   if (EnableARMLongCalls) {
1488     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1489             && "long-calls with non-static relocation model!");
1490     // Handle a global address or an external symbol. If it's not one of
1491     // those, the target's already in a register, so we don't need to do
1492     // anything extra.
1493     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1494       const GlobalValue *GV = G->getGlobal();
1495       // Create a constant pool entry for the callee address
1496       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1497       ARMConstantPoolValue *CPV =
1498         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1499
1500       // Get the address of the callee into a register
1501       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1502       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1503       Callee = DAG.getLoad(getPointerTy(), dl,
1504                            DAG.getEntryNode(), CPAddr,
1505                            MachinePointerInfo::getConstantPool(),
1506                            false, false, false, 0);
1507     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1508       const char *Sym = S->getSymbol();
1509
1510       // Create a constant pool entry for the callee address
1511       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1512       ARMConstantPoolValue *CPV =
1513         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1514                                       ARMPCLabelIndex, 0);
1515       // Get the address of the callee into a register
1516       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1517       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1518       Callee = DAG.getLoad(getPointerTy(), dl,
1519                            DAG.getEntryNode(), CPAddr,
1520                            MachinePointerInfo::getConstantPool(),
1521                            false, false, false, 0);
1522     }
1523   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1524     const GlobalValue *GV = G->getGlobal();
1525     isDirect = true;
1526     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1527     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1528                    getTargetMachine().getRelocationModel() != Reloc::Static;
1529     isARMFunc = !Subtarget->isThumb() || isStub;
1530     // ARM call to a local ARM function is predicable.
1531     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1532     // tBX takes a register source operand.
1533     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1534       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1535       ARMConstantPoolValue *CPV =
1536         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1537       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1538       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1539       Callee = DAG.getLoad(getPointerTy(), dl,
1540                            DAG.getEntryNode(), CPAddr,
1541                            MachinePointerInfo::getConstantPool(),
1542                            false, false, false, 0);
1543       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1544       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1545                            getPointerTy(), Callee, PICLabel);
1546     } else {
1547       // On ELF targets for PIC code, direct calls should go through the PLT
1548       unsigned OpFlags = 0;
1549       if (Subtarget->isTargetELF() &&
1550                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1551         OpFlags = ARMII::MO_PLT;
1552       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1553     }
1554   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1555     isDirect = true;
1556     bool isStub = Subtarget->isTargetDarwin() &&
1557                   getTargetMachine().getRelocationModel() != Reloc::Static;
1558     isARMFunc = !Subtarget->isThumb() || isStub;
1559     // tBX takes a register source operand.
1560     const char *Sym = S->getSymbol();
1561     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1562       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1563       ARMConstantPoolValue *CPV =
1564         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1565                                       ARMPCLabelIndex, 4);
1566       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1567       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1568       Callee = DAG.getLoad(getPointerTy(), dl,
1569                            DAG.getEntryNode(), CPAddr,
1570                            MachinePointerInfo::getConstantPool(),
1571                            false, false, false, 0);
1572       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1573       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1574                            getPointerTy(), Callee, PICLabel);
1575     } else {
1576       unsigned OpFlags = 0;
1577       // On ELF targets for PIC code, direct calls should go through the PLT
1578       if (Subtarget->isTargetELF() &&
1579                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1580         OpFlags = ARMII::MO_PLT;
1581       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1582     }
1583   }
1584
1585   // FIXME: handle tail calls differently.
1586   unsigned CallOpc;
1587   if (Subtarget->isThumb()) {
1588     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1589       CallOpc = ARMISD::CALL_NOLINK;
1590     else if (doesNotRet && isDirect && !isARMFunc &&
1591              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1592       // "mov lr, pc; b _foo" to avoid confusing the RSP
1593       CallOpc = ARMISD::CALL_NOLINK;
1594     else
1595       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1596   } else {
1597     if (!isDirect && !Subtarget->hasV5TOps()) {
1598       CallOpc = ARMISD::CALL_NOLINK;
1599     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1600       // "mov lr, pc; b _foo" to avoid confusing the RSP
1601       CallOpc = ARMISD::CALL_NOLINK;
1602     else
1603       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1604   }
1605
1606   std::vector<SDValue> Ops;
1607   Ops.push_back(Chain);
1608   Ops.push_back(Callee);
1609
1610   // Add argument registers to the end of the list so that they are known live
1611   // into the call.
1612   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1613     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1614                                   RegsToPass[i].second.getValueType()));
1615
1616   // Add a register mask operand representing the call-preserved registers.
1617   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1618   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1619   assert(Mask && "Missing call preserved mask for calling convention");
1620   Ops.push_back(DAG.getRegisterMask(Mask));
1621
1622   if (InFlag.getNode())
1623     Ops.push_back(InFlag);
1624
1625   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1626   if (isTailCall)
1627     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1628
1629   // Returns a chain and a flag for retval copy to use.
1630   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1631   InFlag = Chain.getValue(1);
1632
1633   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1634                              DAG.getIntPtrConstant(0, true), InFlag);
1635   if (!Ins.empty())
1636     InFlag = Chain.getValue(1);
1637
1638   // Handle result values, copying them out of physregs into vregs that we
1639   // return.
1640   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1641                          dl, DAG, InVals);
1642 }
1643
1644 /// HandleByVal - Every parameter *after* a byval parameter is passed
1645 /// on the stack.  Remember the next parameter register to allocate,
1646 /// and then confiscate the rest of the parameter registers to insure
1647 /// this.
1648 void
1649 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1650   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1651   assert((State->getCallOrPrologue() == Prologue ||
1652           State->getCallOrPrologue() == Call) &&
1653          "unhandled ParmContext");
1654   if ((!State->isFirstByValRegValid()) &&
1655       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1656     State->setFirstByValReg(reg);
1657     // At a call site, a byval parameter that is split between
1658     // registers and memory needs its size truncated here.  In a
1659     // function prologue, such byval parameters are reassembled in
1660     // memory, and are not truncated.
1661     if (State->getCallOrPrologue() == Call) {
1662       unsigned excess = 4 * (ARM::R4 - reg);
1663       assert(size >= excess && "expected larger existing stack allocation");
1664       size -= excess;
1665     }
1666   }
1667   // Confiscate any remaining parameter registers to preclude their
1668   // assignment to subsequent parameters.
1669   while (State->AllocateReg(GPRArgRegs, 4))
1670     ;
1671 }
1672
1673 /// MatchingStackOffset - Return true if the given stack call argument is
1674 /// already available in the same position (relatively) of the caller's
1675 /// incoming argument stack.
1676 static
1677 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1678                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1679                          const TargetInstrInfo *TII) {
1680   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1681   int FI = INT_MAX;
1682   if (Arg.getOpcode() == ISD::CopyFromReg) {
1683     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1684     if (!TargetRegisterInfo::isVirtualRegister(VR))
1685       return false;
1686     MachineInstr *Def = MRI->getVRegDef(VR);
1687     if (!Def)
1688       return false;
1689     if (!Flags.isByVal()) {
1690       if (!TII->isLoadFromStackSlot(Def, FI))
1691         return false;
1692     } else {
1693       return false;
1694     }
1695   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1696     if (Flags.isByVal())
1697       // ByVal argument is passed in as a pointer but it's now being
1698       // dereferenced. e.g.
1699       // define @foo(%struct.X* %A) {
1700       //   tail call @bar(%struct.X* byval %A)
1701       // }
1702       return false;
1703     SDValue Ptr = Ld->getBasePtr();
1704     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1705     if (!FINode)
1706       return false;
1707     FI = FINode->getIndex();
1708   } else
1709     return false;
1710
1711   assert(FI != INT_MAX);
1712   if (!MFI->isFixedObjectIndex(FI))
1713     return false;
1714   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1715 }
1716
1717 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1718 /// for tail call optimization. Targets which want to do tail call
1719 /// optimization should implement this function.
1720 bool
1721 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1722                                                      CallingConv::ID CalleeCC,
1723                                                      bool isVarArg,
1724                                                      bool isCalleeStructRet,
1725                                                      bool isCallerStructRet,
1726                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1727                                     const SmallVectorImpl<SDValue> &OutVals,
1728                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1729                                                      SelectionDAG& DAG) const {
1730   const Function *CallerF = DAG.getMachineFunction().getFunction();
1731   CallingConv::ID CallerCC = CallerF->getCallingConv();
1732   bool CCMatch = CallerCC == CalleeCC;
1733
1734   // Look for obvious safe cases to perform tail call optimization that do not
1735   // require ABI changes. This is what gcc calls sibcall.
1736
1737   // Do not sibcall optimize vararg calls unless the call site is not passing
1738   // any arguments.
1739   if (isVarArg && !Outs.empty())
1740     return false;
1741
1742   // Also avoid sibcall optimization if either caller or callee uses struct
1743   // return semantics.
1744   if (isCalleeStructRet || isCallerStructRet)
1745     return false;
1746
1747   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1748   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1749   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1750   // support in the assembler and linker to be used. This would need to be
1751   // fixed to fully support tail calls in Thumb1.
1752   //
1753   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1754   // LR.  This means if we need to reload LR, it takes an extra instructions,
1755   // which outweighs the value of the tail call; but here we don't know yet
1756   // whether LR is going to be used.  Probably the right approach is to
1757   // generate the tail call here and turn it back into CALL/RET in
1758   // emitEpilogue if LR is used.
1759
1760   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1761   // but we need to make sure there are enough registers; the only valid
1762   // registers are the 4 used for parameters.  We don't currently do this
1763   // case.
1764   if (Subtarget->isThumb1Only())
1765     return false;
1766
1767   // If the calling conventions do not match, then we'd better make sure the
1768   // results are returned in the same way as what the caller expects.
1769   if (!CCMatch) {
1770     SmallVector<CCValAssign, 16> RVLocs1;
1771     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1772                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1773     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1774
1775     SmallVector<CCValAssign, 16> RVLocs2;
1776     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1777                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1778     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1779
1780     if (RVLocs1.size() != RVLocs2.size())
1781       return false;
1782     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1783       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1784         return false;
1785       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1786         return false;
1787       if (RVLocs1[i].isRegLoc()) {
1788         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1789           return false;
1790       } else {
1791         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1792           return false;
1793       }
1794     }
1795   }
1796
1797   // If the callee takes no arguments then go on to check the results of the
1798   // call.
1799   if (!Outs.empty()) {
1800     // Check if stack adjustment is needed. For now, do not do this if any
1801     // argument is passed on the stack.
1802     SmallVector<CCValAssign, 16> ArgLocs;
1803     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1804                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1805     CCInfo.AnalyzeCallOperands(Outs,
1806                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1807     if (CCInfo.getNextStackOffset()) {
1808       MachineFunction &MF = DAG.getMachineFunction();
1809
1810       // Check if the arguments are already laid out in the right way as
1811       // the caller's fixed stack objects.
1812       MachineFrameInfo *MFI = MF.getFrameInfo();
1813       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1814       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1815       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1816            i != e;
1817            ++i, ++realArgIdx) {
1818         CCValAssign &VA = ArgLocs[i];
1819         EVT RegVT = VA.getLocVT();
1820         SDValue Arg = OutVals[realArgIdx];
1821         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1822         if (VA.getLocInfo() == CCValAssign::Indirect)
1823           return false;
1824         if (VA.needsCustom()) {
1825           // f64 and vector types are split into multiple registers or
1826           // register/stack-slot combinations.  The types will not match
1827           // the registers; give up on memory f64 refs until we figure
1828           // out what to do about this.
1829           if (!VA.isRegLoc())
1830             return false;
1831           if (!ArgLocs[++i].isRegLoc())
1832             return false;
1833           if (RegVT == MVT::v2f64) {
1834             if (!ArgLocs[++i].isRegLoc())
1835               return false;
1836             if (!ArgLocs[++i].isRegLoc())
1837               return false;
1838           }
1839         } else if (!VA.isRegLoc()) {
1840           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1841                                    MFI, MRI, TII))
1842             return false;
1843         }
1844       }
1845     }
1846   }
1847
1848   return true;
1849 }
1850
1851 SDValue
1852 ARMTargetLowering::LowerReturn(SDValue Chain,
1853                                CallingConv::ID CallConv, bool isVarArg,
1854                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1855                                const SmallVectorImpl<SDValue> &OutVals,
1856                                DebugLoc dl, SelectionDAG &DAG) const {
1857
1858   // CCValAssign - represent the assignment of the return value to a location.
1859   SmallVector<CCValAssign, 16> RVLocs;
1860
1861   // CCState - Info about the registers and stack slots.
1862   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1863                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1864
1865   // Analyze outgoing return values.
1866   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1867                                                isVarArg));
1868
1869   // If this is the first return lowered for this function, add
1870   // the regs to the liveout set for the function.
1871   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1872     for (unsigned i = 0; i != RVLocs.size(); ++i)
1873       if (RVLocs[i].isRegLoc())
1874         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1875   }
1876
1877   SDValue Flag;
1878
1879   // Copy the result values into the output registers.
1880   for (unsigned i = 0, realRVLocIdx = 0;
1881        i != RVLocs.size();
1882        ++i, ++realRVLocIdx) {
1883     CCValAssign &VA = RVLocs[i];
1884     assert(VA.isRegLoc() && "Can only return in registers!");
1885
1886     SDValue Arg = OutVals[realRVLocIdx];
1887
1888     switch (VA.getLocInfo()) {
1889     default: llvm_unreachable("Unknown loc info!");
1890     case CCValAssign::Full: break;
1891     case CCValAssign::BCvt:
1892       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1893       break;
1894     }
1895
1896     if (VA.needsCustom()) {
1897       if (VA.getLocVT() == MVT::v2f64) {
1898         // Extract the first half and return it in two registers.
1899         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1900                                    DAG.getConstant(0, MVT::i32));
1901         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1902                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1903
1904         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1905         Flag = Chain.getValue(1);
1906         VA = RVLocs[++i]; // skip ahead to next loc
1907         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1908                                  HalfGPRs.getValue(1), Flag);
1909         Flag = Chain.getValue(1);
1910         VA = RVLocs[++i]; // skip ahead to next loc
1911
1912         // Extract the 2nd half and fall through to handle it as an f64 value.
1913         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1914                           DAG.getConstant(1, MVT::i32));
1915       }
1916       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1917       // available.
1918       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1919                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1920       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1921       Flag = Chain.getValue(1);
1922       VA = RVLocs[++i]; // skip ahead to next loc
1923       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1924                                Flag);
1925     } else
1926       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1927
1928     // Guarantee that all emitted copies are
1929     // stuck together, avoiding something bad.
1930     Flag = Chain.getValue(1);
1931   }
1932
1933   SDValue result;
1934   if (Flag.getNode())
1935     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1936   else // Return Void
1937     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1938
1939   return result;
1940 }
1941
1942 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1943   if (N->getNumValues() != 1)
1944     return false;
1945   if (!N->hasNUsesOfValue(1, 0))
1946     return false;
1947
1948   SDValue TCChain = Chain;
1949   SDNode *Copy = *N->use_begin();
1950   if (Copy->getOpcode() == ISD::CopyToReg) {
1951     // If the copy has a glue operand, we conservatively assume it isn't safe to
1952     // perform a tail call.
1953     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1954       return false;
1955     TCChain = Copy->getOperand(0);
1956   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1957     SDNode *VMov = Copy;
1958     // f64 returned in a pair of GPRs.
1959     SmallPtrSet<SDNode*, 2> Copies;
1960     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1961          UI != UE; ++UI) {
1962       if (UI->getOpcode() != ISD::CopyToReg)
1963         return false;
1964       Copies.insert(*UI);
1965     }
1966     if (Copies.size() > 2)
1967       return false;
1968
1969     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1970          UI != UE; ++UI) {
1971       SDValue UseChain = UI->getOperand(0);
1972       if (Copies.count(UseChain.getNode()))
1973         // Second CopyToReg
1974         Copy = *UI;
1975       else
1976         // First CopyToReg
1977         TCChain = UseChain;
1978     }
1979   } else if (Copy->getOpcode() == ISD::BITCAST) {
1980     // f32 returned in a single GPR.
1981     if (!Copy->hasOneUse())
1982       return false;
1983     Copy = *Copy->use_begin();
1984     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1985       return false;
1986     Chain = Copy->getOperand(0);
1987   } else {
1988     return false;
1989   }
1990
1991   bool HasRet = false;
1992   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1993        UI != UE; ++UI) {
1994     if (UI->getOpcode() != ARMISD::RET_FLAG)
1995       return false;
1996     HasRet = true;
1997   }
1998
1999   if (!HasRet)
2000     return false;
2001
2002   Chain = TCChain;
2003   return true;
2004 }
2005
2006 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2007   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2008     return false;
2009
2010   if (!CI->isTailCall())
2011     return false;
2012
2013   return !Subtarget->isThumb1Only();
2014 }
2015
2016 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2017 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2018 // one of the above mentioned nodes. It has to be wrapped because otherwise
2019 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2020 // be used to form addressing mode. These wrapped nodes will be selected
2021 // into MOVi.
2022 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2023   EVT PtrVT = Op.getValueType();
2024   // FIXME there is no actual debug info here
2025   DebugLoc dl = Op.getDebugLoc();
2026   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2027   SDValue Res;
2028   if (CP->isMachineConstantPoolEntry())
2029     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2030                                     CP->getAlignment());
2031   else
2032     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2033                                     CP->getAlignment());
2034   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2035 }
2036
2037 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2038   return MachineJumpTableInfo::EK_Inline;
2039 }
2040
2041 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2042                                              SelectionDAG &DAG) const {
2043   MachineFunction &MF = DAG.getMachineFunction();
2044   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2045   unsigned ARMPCLabelIndex = 0;
2046   DebugLoc DL = Op.getDebugLoc();
2047   EVT PtrVT = getPointerTy();
2048   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2049   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2050   SDValue CPAddr;
2051   if (RelocM == Reloc::Static) {
2052     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2053   } else {
2054     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2055     ARMPCLabelIndex = AFI->createPICLabelUId();
2056     ARMConstantPoolValue *CPV =
2057       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2058                                       ARMCP::CPBlockAddress, PCAdj);
2059     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2060   }
2061   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2062   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2063                                MachinePointerInfo::getConstantPool(),
2064                                false, false, false, 0);
2065   if (RelocM == Reloc::Static)
2066     return Result;
2067   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2068   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2069 }
2070
2071 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2072 SDValue
2073 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2074                                                  SelectionDAG &DAG) const {
2075   DebugLoc dl = GA->getDebugLoc();
2076   EVT PtrVT = getPointerTy();
2077   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2078   MachineFunction &MF = DAG.getMachineFunction();
2079   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2080   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2081   ARMConstantPoolValue *CPV =
2082     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2083                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2084   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2085   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2086   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2087                          MachinePointerInfo::getConstantPool(),
2088                          false, false, false, 0);
2089   SDValue Chain = Argument.getValue(1);
2090
2091   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2092   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2093
2094   // call __tls_get_addr.
2095   ArgListTy Args;
2096   ArgListEntry Entry;
2097   Entry.Node = Argument;
2098   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2099   Args.push_back(Entry);
2100   // FIXME: is there useful debug info available here?
2101   std::pair<SDValue, SDValue> CallResult =
2102     LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
2103                 false, false, false, false,
2104                 0, CallingConv::C, /*isTailCall=*/false,
2105                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2106                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2107   return CallResult.first;
2108 }
2109
2110 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2111 // "local exec" model.
2112 SDValue
2113 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2114                                         SelectionDAG &DAG,
2115                                         TLSModel::Model model) const {
2116   const GlobalValue *GV = GA->getGlobal();
2117   DebugLoc dl = GA->getDebugLoc();
2118   SDValue Offset;
2119   SDValue Chain = DAG.getEntryNode();
2120   EVT PtrVT = getPointerTy();
2121   // Get the Thread Pointer
2122   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2123
2124   if (model == TLSModel::InitialExec) {
2125     MachineFunction &MF = DAG.getMachineFunction();
2126     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2127     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2128     // Initial exec model.
2129     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2130     ARMConstantPoolValue *CPV =
2131       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2132                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2133                                       true);
2134     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2135     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2136     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2137                          MachinePointerInfo::getConstantPool(),
2138                          false, false, false, 0);
2139     Chain = Offset.getValue(1);
2140
2141     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2142     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2143
2144     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2145                          MachinePointerInfo::getConstantPool(),
2146                          false, false, false, 0);
2147   } else {
2148     // local exec model
2149     assert(model == TLSModel::LocalExec);
2150     ARMConstantPoolValue *CPV =
2151       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2152     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2153     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2154     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2155                          MachinePointerInfo::getConstantPool(),
2156                          false, false, false, 0);
2157   }
2158
2159   // The address of the thread local variable is the add of the thread
2160   // pointer with the offset of the variable.
2161   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2162 }
2163
2164 SDValue
2165 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2166   // TODO: implement the "local dynamic" model
2167   assert(Subtarget->isTargetELF() &&
2168          "TLS not implemented for non-ELF targets");
2169   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2170
2171   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2172
2173   switch (model) {
2174     case TLSModel::GeneralDynamic:
2175     case TLSModel::LocalDynamic:
2176       return LowerToTLSGeneralDynamicModel(GA, DAG);
2177     case TLSModel::InitialExec:
2178     case TLSModel::LocalExec:
2179       return LowerToTLSExecModels(GA, DAG, model);
2180   }
2181   llvm_unreachable("bogus TLS model");
2182 }
2183
2184 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2185                                                  SelectionDAG &DAG) const {
2186   EVT PtrVT = getPointerTy();
2187   DebugLoc dl = Op.getDebugLoc();
2188   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2189   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2190   if (RelocM == Reloc::PIC_) {
2191     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2192     ARMConstantPoolValue *CPV =
2193       ARMConstantPoolConstant::Create(GV,
2194                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2195     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2196     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2197     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2198                                  CPAddr,
2199                                  MachinePointerInfo::getConstantPool(),
2200                                  false, false, false, 0);
2201     SDValue Chain = Result.getValue(1);
2202     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2203     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2204     if (!UseGOTOFF)
2205       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2206                            MachinePointerInfo::getGOT(),
2207                            false, false, false, 0);
2208     return Result;
2209   }
2210
2211   // If we have T2 ops, we can materialize the address directly via movt/movw
2212   // pair. This is always cheaper.
2213   if (Subtarget->useMovt()) {
2214     ++NumMovwMovt;
2215     // FIXME: Once remat is capable of dealing with instructions with register
2216     // operands, expand this into two nodes.
2217     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2218                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2219   } else {
2220     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2221     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2222     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2223                        MachinePointerInfo::getConstantPool(),
2224                        false, false, false, 0);
2225   }
2226 }
2227
2228 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2229                                                     SelectionDAG &DAG) const {
2230   EVT PtrVT = getPointerTy();
2231   DebugLoc dl = Op.getDebugLoc();
2232   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2233   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2234   MachineFunction &MF = DAG.getMachineFunction();
2235   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2236
2237   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2238   // update ARMFastISel::ARMMaterializeGV.
2239   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2240     ++NumMovwMovt;
2241     // FIXME: Once remat is capable of dealing with instructions with register
2242     // operands, expand this into two nodes.
2243     if (RelocM == Reloc::Static)
2244       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2245                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2246
2247     unsigned Wrapper = (RelocM == Reloc::PIC_)
2248       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2249     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2250                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2251     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2252       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2253                            MachinePointerInfo::getGOT(),
2254                            false, false, false, 0);
2255     return Result;
2256   }
2257
2258   unsigned ARMPCLabelIndex = 0;
2259   SDValue CPAddr;
2260   if (RelocM == Reloc::Static) {
2261     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2262   } else {
2263     ARMPCLabelIndex = AFI->createPICLabelUId();
2264     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2265     ARMConstantPoolValue *CPV =
2266       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2267                                       PCAdj);
2268     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2269   }
2270   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2271
2272   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2273                                MachinePointerInfo::getConstantPool(),
2274                                false, false, false, 0);
2275   SDValue Chain = Result.getValue(1);
2276
2277   if (RelocM == Reloc::PIC_) {
2278     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2279     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2280   }
2281
2282   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2283     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2284                          false, false, false, 0);
2285
2286   return Result;
2287 }
2288
2289 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2290                                                     SelectionDAG &DAG) const {
2291   assert(Subtarget->isTargetELF() &&
2292          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2293   MachineFunction &MF = DAG.getMachineFunction();
2294   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2295   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2296   EVT PtrVT = getPointerTy();
2297   DebugLoc dl = Op.getDebugLoc();
2298   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2299   ARMConstantPoolValue *CPV =
2300     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2301                                   ARMPCLabelIndex, PCAdj);
2302   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2303   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2304   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2305                                MachinePointerInfo::getConstantPool(),
2306                                false, false, false, 0);
2307   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2308   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2309 }
2310
2311 SDValue
2312 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2313   DebugLoc dl = Op.getDebugLoc();
2314   SDValue Val = DAG.getConstant(0, MVT::i32);
2315   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2316                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2317                      Op.getOperand(1), Val);
2318 }
2319
2320 SDValue
2321 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2322   DebugLoc dl = Op.getDebugLoc();
2323   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2324                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2325 }
2326
2327 SDValue
2328 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2329                                           const ARMSubtarget *Subtarget) const {
2330   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2331   DebugLoc dl = Op.getDebugLoc();
2332   switch (IntNo) {
2333   default: return SDValue();    // Don't custom lower most intrinsics.
2334   case Intrinsic::arm_thread_pointer: {
2335     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2336     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2337   }
2338   case Intrinsic::eh_sjlj_lsda: {
2339     MachineFunction &MF = DAG.getMachineFunction();
2340     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2341     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2342     EVT PtrVT = getPointerTy();
2343     DebugLoc dl = Op.getDebugLoc();
2344     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2345     SDValue CPAddr;
2346     unsigned PCAdj = (RelocM != Reloc::PIC_)
2347       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2348     ARMConstantPoolValue *CPV =
2349       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2350                                       ARMCP::CPLSDA, PCAdj);
2351     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2352     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2353     SDValue Result =
2354       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2355                   MachinePointerInfo::getConstantPool(),
2356                   false, false, false, 0);
2357
2358     if (RelocM == Reloc::PIC_) {
2359       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2360       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2361     }
2362     return Result;
2363   }
2364   case Intrinsic::arm_neon_vmulls:
2365   case Intrinsic::arm_neon_vmullu: {
2366     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2367       ? ARMISD::VMULLs : ARMISD::VMULLu;
2368     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2369                        Op.getOperand(1), Op.getOperand(2));
2370   }
2371   }
2372 }
2373
2374 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2375                                const ARMSubtarget *Subtarget) {
2376   DebugLoc dl = Op.getDebugLoc();
2377   if (!Subtarget->hasDataBarrier()) {
2378     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2379     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2380     // here.
2381     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2382            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2383     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2384                        DAG.getConstant(0, MVT::i32));
2385   }
2386
2387   SDValue Op5 = Op.getOperand(5);
2388   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2389   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2390   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2391   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2392
2393   ARM_MB::MemBOpt DMBOpt;
2394   if (isDeviceBarrier)
2395     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2396   else
2397     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2398   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2399                      DAG.getConstant(DMBOpt, MVT::i32));
2400 }
2401
2402
2403 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2404                                  const ARMSubtarget *Subtarget) {
2405   // FIXME: handle "fence singlethread" more efficiently.
2406   DebugLoc dl = Op.getDebugLoc();
2407   if (!Subtarget->hasDataBarrier()) {
2408     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2409     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2410     // here.
2411     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2412            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2413     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2414                        DAG.getConstant(0, MVT::i32));
2415   }
2416
2417   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2418                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2419 }
2420
2421 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2422                              const ARMSubtarget *Subtarget) {
2423   // ARM pre v5TE and Thumb1 does not have preload instructions.
2424   if (!(Subtarget->isThumb2() ||
2425         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2426     // Just preserve the chain.
2427     return Op.getOperand(0);
2428
2429   DebugLoc dl = Op.getDebugLoc();
2430   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2431   if (!isRead &&
2432       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2433     // ARMv7 with MP extension has PLDW.
2434     return Op.getOperand(0);
2435
2436   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2437   if (Subtarget->isThumb()) {
2438     // Invert the bits.
2439     isRead = ~isRead & 1;
2440     isData = ~isData & 1;
2441   }
2442
2443   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2444                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2445                      DAG.getConstant(isData, MVT::i32));
2446 }
2447
2448 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2449   MachineFunction &MF = DAG.getMachineFunction();
2450   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2451
2452   // vastart just stores the address of the VarArgsFrameIndex slot into the
2453   // memory location argument.
2454   DebugLoc dl = Op.getDebugLoc();
2455   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2456   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2457   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2458   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2459                       MachinePointerInfo(SV), false, false, 0);
2460 }
2461
2462 SDValue
2463 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2464                                         SDValue &Root, SelectionDAG &DAG,
2465                                         DebugLoc dl) const {
2466   MachineFunction &MF = DAG.getMachineFunction();
2467   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2468
2469   const TargetRegisterClass *RC;
2470   if (AFI->isThumb1OnlyFunction())
2471     RC = &ARM::tGPRRegClass;
2472   else
2473     RC = &ARM::GPRRegClass;
2474
2475   // Transform the arguments stored in physical registers into virtual ones.
2476   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2477   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2478
2479   SDValue ArgValue2;
2480   if (NextVA.isMemLoc()) {
2481     MachineFrameInfo *MFI = MF.getFrameInfo();
2482     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2483
2484     // Create load node to retrieve arguments from the stack.
2485     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2486     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2487                             MachinePointerInfo::getFixedStack(FI),
2488                             false, false, false, 0);
2489   } else {
2490     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2491     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2492   }
2493
2494   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2495 }
2496
2497 void
2498 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2499                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2500   const {
2501   unsigned NumGPRs;
2502   if (CCInfo.isFirstByValRegValid())
2503     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2504   else {
2505     unsigned int firstUnalloced;
2506     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2507                                                 sizeof(GPRArgRegs) /
2508                                                 sizeof(GPRArgRegs[0]));
2509     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2510   }
2511
2512   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2513   VARegSize = NumGPRs * 4;
2514   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2515 }
2516
2517 // The remaining GPRs hold either the beginning of variable-argument
2518 // data, or the beginning of an aggregate passed by value (usuall
2519 // byval).  Either way, we allocate stack slots adjacent to the data
2520 // provided by our caller, and store the unallocated registers there.
2521 // If this is a variadic function, the va_list pointer will begin with
2522 // these values; otherwise, this reassembles a (byval) structure that
2523 // was split between registers and memory.
2524 void
2525 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2526                                         DebugLoc dl, SDValue &Chain,
2527                                         unsigned ArgOffset) const {
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   MachineFrameInfo *MFI = MF.getFrameInfo();
2530   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2531   unsigned firstRegToSaveIndex;
2532   if (CCInfo.isFirstByValRegValid())
2533     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2534   else {
2535     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2536       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2537   }
2538
2539   unsigned VARegSize, VARegSaveSize;
2540   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2541   if (VARegSaveSize) {
2542     // If this function is vararg, store any remaining integer argument regs
2543     // to their spots on the stack so that they may be loaded by deferencing
2544     // the result of va_next.
2545     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2546     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2547                                                      ArgOffset + VARegSaveSize
2548                                                      - VARegSize,
2549                                                      false));
2550     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2551                                     getPointerTy());
2552
2553     SmallVector<SDValue, 4> MemOps;
2554     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2555       const TargetRegisterClass *RC;
2556       if (AFI->isThumb1OnlyFunction())
2557         RC = &ARM::tGPRRegClass;
2558       else
2559         RC = &ARM::GPRRegClass;
2560
2561       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2562       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2563       SDValue Store =
2564         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2565                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2566                      false, false, 0);
2567       MemOps.push_back(Store);
2568       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2569                         DAG.getConstant(4, getPointerTy()));
2570     }
2571     if (!MemOps.empty())
2572       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2573                           &MemOps[0], MemOps.size());
2574   } else
2575     // This will point to the next argument passed via stack.
2576     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2577 }
2578
2579 SDValue
2580 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2581                                         CallingConv::ID CallConv, bool isVarArg,
2582                                         const SmallVectorImpl<ISD::InputArg>
2583                                           &Ins,
2584                                         DebugLoc dl, SelectionDAG &DAG,
2585                                         SmallVectorImpl<SDValue> &InVals)
2586                                           const {
2587   MachineFunction &MF = DAG.getMachineFunction();
2588   MachineFrameInfo *MFI = MF.getFrameInfo();
2589
2590   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2591
2592   // Assign locations to all of the incoming arguments.
2593   SmallVector<CCValAssign, 16> ArgLocs;
2594   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2595                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2596   CCInfo.AnalyzeFormalArguments(Ins,
2597                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2598                                                   isVarArg));
2599
2600   SmallVector<SDValue, 16> ArgValues;
2601   int lastInsIndex = -1;
2602
2603   SDValue ArgValue;
2604   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2605     CCValAssign &VA = ArgLocs[i];
2606
2607     // Arguments stored in registers.
2608     if (VA.isRegLoc()) {
2609       EVT RegVT = VA.getLocVT();
2610
2611       if (VA.needsCustom()) {
2612         // f64 and vector types are split up into multiple registers or
2613         // combinations of registers and stack slots.
2614         if (VA.getLocVT() == MVT::v2f64) {
2615           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2616                                                    Chain, DAG, dl);
2617           VA = ArgLocs[++i]; // skip ahead to next loc
2618           SDValue ArgValue2;
2619           if (VA.isMemLoc()) {
2620             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2621             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2622             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2623                                     MachinePointerInfo::getFixedStack(FI),
2624                                     false, false, false, 0);
2625           } else {
2626             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2627                                              Chain, DAG, dl);
2628           }
2629           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2630           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2631                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2632           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2633                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2634         } else
2635           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2636
2637       } else {
2638         const TargetRegisterClass *RC;
2639
2640         if (RegVT == MVT::f32)
2641           RC = &ARM::SPRRegClass;
2642         else if (RegVT == MVT::f64)
2643           RC = &ARM::DPRRegClass;
2644         else if (RegVT == MVT::v2f64)
2645           RC = &ARM::QPRRegClass;
2646         else if (RegVT == MVT::i32)
2647           RC = AFI->isThumb1OnlyFunction() ?
2648             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2649             (const TargetRegisterClass*)&ARM::GPRRegClass;
2650         else
2651           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2652
2653         // Transform the arguments in physical registers into virtual ones.
2654         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2655         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2656       }
2657
2658       // If this is an 8 or 16-bit value, it is really passed promoted
2659       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2660       // truncate to the right size.
2661       switch (VA.getLocInfo()) {
2662       default: llvm_unreachable("Unknown loc info!");
2663       case CCValAssign::Full: break;
2664       case CCValAssign::BCvt:
2665         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2666         break;
2667       case CCValAssign::SExt:
2668         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2669                                DAG.getValueType(VA.getValVT()));
2670         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2671         break;
2672       case CCValAssign::ZExt:
2673         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2674                                DAG.getValueType(VA.getValVT()));
2675         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2676         break;
2677       }
2678
2679       InVals.push_back(ArgValue);
2680
2681     } else { // VA.isRegLoc()
2682
2683       // sanity check
2684       assert(VA.isMemLoc());
2685       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2686
2687       int index = ArgLocs[i].getValNo();
2688
2689       // Some Ins[] entries become multiple ArgLoc[] entries.
2690       // Process them only once.
2691       if (index != lastInsIndex)
2692         {
2693           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2694           // FIXME: For now, all byval parameter objects are marked mutable.
2695           // This can be changed with more analysis.
2696           // In case of tail call optimization mark all arguments mutable.
2697           // Since they could be overwritten by lowering of arguments in case of
2698           // a tail call.
2699           if (Flags.isByVal()) {
2700             unsigned VARegSize, VARegSaveSize;
2701             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2702             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2703             unsigned Bytes = Flags.getByValSize() - VARegSize;
2704             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2705             int FI = MFI->CreateFixedObject(Bytes,
2706                                             VA.getLocMemOffset(), false);
2707             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2708           } else {
2709             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2710                                             VA.getLocMemOffset(), true);
2711
2712             // Create load nodes to retrieve arguments from the stack.
2713             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2714             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2715                                          MachinePointerInfo::getFixedStack(FI),
2716                                          false, false, false, 0));
2717           }
2718           lastInsIndex = index;
2719         }
2720     }
2721   }
2722
2723   // varargs
2724   if (isVarArg)
2725     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2726
2727   return Chain;
2728 }
2729
2730 /// isFloatingPointZero - Return true if this is +0.0.
2731 static bool isFloatingPointZero(SDValue Op) {
2732   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2733     return CFP->getValueAPF().isPosZero();
2734   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2735     // Maybe this has already been legalized into the constant pool?
2736     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2737       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2738       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2739         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2740           return CFP->getValueAPF().isPosZero();
2741     }
2742   }
2743   return false;
2744 }
2745
2746 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2747 /// the given operands.
2748 SDValue
2749 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2750                              SDValue &ARMcc, SelectionDAG &DAG,
2751                              DebugLoc dl) const {
2752   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2753     unsigned C = RHSC->getZExtValue();
2754     if (!isLegalICmpImmediate(C)) {
2755       // Constant does not fit, try adjusting it by one?
2756       switch (CC) {
2757       default: break;
2758       case ISD::SETLT:
2759       case ISD::SETGE:
2760         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2761           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2762           RHS = DAG.getConstant(C-1, MVT::i32);
2763         }
2764         break;
2765       case ISD::SETULT:
2766       case ISD::SETUGE:
2767         if (C != 0 && isLegalICmpImmediate(C-1)) {
2768           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2769           RHS = DAG.getConstant(C-1, MVT::i32);
2770         }
2771         break;
2772       case ISD::SETLE:
2773       case ISD::SETGT:
2774         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2775           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2776           RHS = DAG.getConstant(C+1, MVT::i32);
2777         }
2778         break;
2779       case ISD::SETULE:
2780       case ISD::SETUGT:
2781         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2782           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2783           RHS = DAG.getConstant(C+1, MVT::i32);
2784         }
2785         break;
2786       }
2787     }
2788   }
2789
2790   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2791   ARMISD::NodeType CompareType;
2792   switch (CondCode) {
2793   default:
2794     CompareType = ARMISD::CMP;
2795     break;
2796   case ARMCC::EQ:
2797   case ARMCC::NE:
2798     // Uses only Z Flag
2799     CompareType = ARMISD::CMPZ;
2800     break;
2801   }
2802   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2803   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2804 }
2805
2806 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2807 SDValue
2808 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2809                              DebugLoc dl) const {
2810   SDValue Cmp;
2811   if (!isFloatingPointZero(RHS))
2812     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2813   else
2814     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2815   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2816 }
2817
2818 /// duplicateCmp - Glue values can have only one use, so this function
2819 /// duplicates a comparison node.
2820 SDValue
2821 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2822   unsigned Opc = Cmp.getOpcode();
2823   DebugLoc DL = Cmp.getDebugLoc();
2824   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2825     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2826
2827   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2828   Cmp = Cmp.getOperand(0);
2829   Opc = Cmp.getOpcode();
2830   if (Opc == ARMISD::CMPFP)
2831     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2832   else {
2833     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2834     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2835   }
2836   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2837 }
2838
2839 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2840   SDValue Cond = Op.getOperand(0);
2841   SDValue SelectTrue = Op.getOperand(1);
2842   SDValue SelectFalse = Op.getOperand(2);
2843   DebugLoc dl = Op.getDebugLoc();
2844
2845   // Convert:
2846   //
2847   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2848   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2849   //
2850   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2851     const ConstantSDNode *CMOVTrue =
2852       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2853     const ConstantSDNode *CMOVFalse =
2854       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2855
2856     if (CMOVTrue && CMOVFalse) {
2857       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2858       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2859
2860       SDValue True;
2861       SDValue False;
2862       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2863         True = SelectTrue;
2864         False = SelectFalse;
2865       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2866         True = SelectFalse;
2867         False = SelectTrue;
2868       }
2869
2870       if (True.getNode() && False.getNode()) {
2871         EVT VT = Op.getValueType();
2872         SDValue ARMcc = Cond.getOperand(2);
2873         SDValue CCR = Cond.getOperand(3);
2874         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2875         assert(True.getValueType() == VT);
2876         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2877       }
2878     }
2879   }
2880
2881   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2882   // undefined bits before doing a full-word comparison with zero.
2883   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2884                      DAG.getConstant(1, Cond.getValueType()));
2885
2886   return DAG.getSelectCC(dl, Cond,
2887                          DAG.getConstant(0, Cond.getValueType()),
2888                          SelectTrue, SelectFalse, ISD::SETNE);
2889 }
2890
2891 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2892   EVT VT = Op.getValueType();
2893   SDValue LHS = Op.getOperand(0);
2894   SDValue RHS = Op.getOperand(1);
2895   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2896   SDValue TrueVal = Op.getOperand(2);
2897   SDValue FalseVal = Op.getOperand(3);
2898   DebugLoc dl = Op.getDebugLoc();
2899
2900   if (LHS.getValueType() == MVT::i32) {
2901     SDValue ARMcc;
2902     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2903     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2904     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2905   }
2906
2907   ARMCC::CondCodes CondCode, CondCode2;
2908   FPCCToARMCC(CC, CondCode, CondCode2);
2909
2910   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2911   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2912   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2913   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2914                                ARMcc, CCR, Cmp);
2915   if (CondCode2 != ARMCC::AL) {
2916     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2917     // FIXME: Needs another CMP because flag can have but one use.
2918     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2919     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2920                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2921   }
2922   return Result;
2923 }
2924
2925 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2926 /// to morph to an integer compare sequence.
2927 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2928                            const ARMSubtarget *Subtarget) {
2929   SDNode *N = Op.getNode();
2930   if (!N->hasOneUse())
2931     // Otherwise it requires moving the value from fp to integer registers.
2932     return false;
2933   if (!N->getNumValues())
2934     return false;
2935   EVT VT = Op.getValueType();
2936   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2937     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2938     // vmrs are very slow, e.g. cortex-a8.
2939     return false;
2940
2941   if (isFloatingPointZero(Op)) {
2942     SeenZero = true;
2943     return true;
2944   }
2945   return ISD::isNormalLoad(N);
2946 }
2947
2948 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2949   if (isFloatingPointZero(Op))
2950     return DAG.getConstant(0, MVT::i32);
2951
2952   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2953     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2954                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2955                        Ld->isVolatile(), Ld->isNonTemporal(),
2956                        Ld->isInvariant(), Ld->getAlignment());
2957
2958   llvm_unreachable("Unknown VFP cmp argument!");
2959 }
2960
2961 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2962                            SDValue &RetVal1, SDValue &RetVal2) {
2963   if (isFloatingPointZero(Op)) {
2964     RetVal1 = DAG.getConstant(0, MVT::i32);
2965     RetVal2 = DAG.getConstant(0, MVT::i32);
2966     return;
2967   }
2968
2969   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2970     SDValue Ptr = Ld->getBasePtr();
2971     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2972                           Ld->getChain(), Ptr,
2973                           Ld->getPointerInfo(),
2974                           Ld->isVolatile(), Ld->isNonTemporal(),
2975                           Ld->isInvariant(), Ld->getAlignment());
2976
2977     EVT PtrType = Ptr.getValueType();
2978     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2979     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2980                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2981     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2982                           Ld->getChain(), NewPtr,
2983                           Ld->getPointerInfo().getWithOffset(4),
2984                           Ld->isVolatile(), Ld->isNonTemporal(),
2985                           Ld->isInvariant(), NewAlign);
2986     return;
2987   }
2988
2989   llvm_unreachable("Unknown VFP cmp argument!");
2990 }
2991
2992 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2993 /// f32 and even f64 comparisons to integer ones.
2994 SDValue
2995 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2996   SDValue Chain = Op.getOperand(0);
2997   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2998   SDValue LHS = Op.getOperand(2);
2999   SDValue RHS = Op.getOperand(3);
3000   SDValue Dest = Op.getOperand(4);
3001   DebugLoc dl = Op.getDebugLoc();
3002
3003   bool LHSSeenZero = false;
3004   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3005   bool RHSSeenZero = false;
3006   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3007   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3008     // If unsafe fp math optimization is enabled and there are no other uses of
3009     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3010     // to an integer comparison.
3011     if (CC == ISD::SETOEQ)
3012       CC = ISD::SETEQ;
3013     else if (CC == ISD::SETUNE)
3014       CC = ISD::SETNE;
3015
3016     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3017     SDValue ARMcc;
3018     if (LHS.getValueType() == MVT::f32) {
3019       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3020                         bitcastf32Toi32(LHS, DAG), Mask);
3021       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3022                         bitcastf32Toi32(RHS, DAG), Mask);
3023       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3024       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3025       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3026                          Chain, Dest, ARMcc, CCR, Cmp);
3027     }
3028
3029     SDValue LHS1, LHS2;
3030     SDValue RHS1, RHS2;
3031     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3032     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3033     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3034     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3035     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3036     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3037     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3038     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3039     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3040   }
3041
3042   return SDValue();
3043 }
3044
3045 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3046   SDValue Chain = Op.getOperand(0);
3047   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3048   SDValue LHS = Op.getOperand(2);
3049   SDValue RHS = Op.getOperand(3);
3050   SDValue Dest = Op.getOperand(4);
3051   DebugLoc dl = Op.getDebugLoc();
3052
3053   if (LHS.getValueType() == MVT::i32) {
3054     SDValue ARMcc;
3055     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3056     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3057     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3058                        Chain, Dest, ARMcc, CCR, Cmp);
3059   }
3060
3061   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3062
3063   if (getTargetMachine().Options.UnsafeFPMath &&
3064       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3065        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3066     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3067     if (Result.getNode())
3068       return Result;
3069   }
3070
3071   ARMCC::CondCodes CondCode, CondCode2;
3072   FPCCToARMCC(CC, CondCode, CondCode2);
3073
3074   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3075   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3076   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3077   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3078   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3079   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3080   if (CondCode2 != ARMCC::AL) {
3081     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3082     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3083     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3084   }
3085   return Res;
3086 }
3087
3088 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3089   SDValue Chain = Op.getOperand(0);
3090   SDValue Table = Op.getOperand(1);
3091   SDValue Index = Op.getOperand(2);
3092   DebugLoc dl = Op.getDebugLoc();
3093
3094   EVT PTy = getPointerTy();
3095   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3096   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3097   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3098   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3099   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3100   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3101   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3102   if (Subtarget->isThumb2()) {
3103     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3104     // which does another jump to the destination. This also makes it easier
3105     // to translate it to TBB / TBH later.
3106     // FIXME: This might not work if the function is extremely large.
3107     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3108                        Addr, Op.getOperand(2), JTI, UId);
3109   }
3110   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3111     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3112                        MachinePointerInfo::getJumpTable(),
3113                        false, false, false, 0);
3114     Chain = Addr.getValue(1);
3115     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3116     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3117   } else {
3118     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3119                        MachinePointerInfo::getJumpTable(),
3120                        false, false, false, 0);
3121     Chain = Addr.getValue(1);
3122     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3123   }
3124 }
3125
3126 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3127   EVT VT = Op.getValueType();
3128   DebugLoc dl = Op.getDebugLoc();
3129
3130   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3131     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3132       return Op;
3133     return DAG.UnrollVectorOp(Op.getNode());
3134   }
3135
3136   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3137          "Invalid type for custom lowering!");
3138   if (VT != MVT::v4i16)
3139     return DAG.UnrollVectorOp(Op.getNode());
3140
3141   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3142   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3143 }
3144
3145 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3146   EVT VT = Op.getValueType();
3147   if (VT.isVector())
3148     return LowerVectorFP_TO_INT(Op, DAG);
3149
3150   DebugLoc dl = Op.getDebugLoc();
3151   unsigned Opc;
3152
3153   switch (Op.getOpcode()) {
3154   default: llvm_unreachable("Invalid opcode!");
3155   case ISD::FP_TO_SINT:
3156     Opc = ARMISD::FTOSI;
3157     break;
3158   case ISD::FP_TO_UINT:
3159     Opc = ARMISD::FTOUI;
3160     break;
3161   }
3162   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3163   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3164 }
3165
3166 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3167   EVT VT = Op.getValueType();
3168   DebugLoc dl = Op.getDebugLoc();
3169
3170   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3171     if (VT.getVectorElementType() == MVT::f32)
3172       return Op;
3173     return DAG.UnrollVectorOp(Op.getNode());
3174   }
3175
3176   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3177          "Invalid type for custom lowering!");
3178   if (VT != MVT::v4f32)
3179     return DAG.UnrollVectorOp(Op.getNode());
3180
3181   unsigned CastOpc;
3182   unsigned Opc;
3183   switch (Op.getOpcode()) {
3184   default: llvm_unreachable("Invalid opcode!");
3185   case ISD::SINT_TO_FP:
3186     CastOpc = ISD::SIGN_EXTEND;
3187     Opc = ISD::SINT_TO_FP;
3188     break;
3189   case ISD::UINT_TO_FP:
3190     CastOpc = ISD::ZERO_EXTEND;
3191     Opc = ISD::UINT_TO_FP;
3192     break;
3193   }
3194
3195   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3196   return DAG.getNode(Opc, dl, VT, Op);
3197 }
3198
3199 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3200   EVT VT = Op.getValueType();
3201   if (VT.isVector())
3202     return LowerVectorINT_TO_FP(Op, DAG);
3203
3204   DebugLoc dl = Op.getDebugLoc();
3205   unsigned Opc;
3206
3207   switch (Op.getOpcode()) {
3208   default: llvm_unreachable("Invalid opcode!");
3209   case ISD::SINT_TO_FP:
3210     Opc = ARMISD::SITOF;
3211     break;
3212   case ISD::UINT_TO_FP:
3213     Opc = ARMISD::UITOF;
3214     break;
3215   }
3216
3217   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3218   return DAG.getNode(Opc, dl, VT, Op);
3219 }
3220
3221 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3222   // Implement fcopysign with a fabs and a conditional fneg.
3223   SDValue Tmp0 = Op.getOperand(0);
3224   SDValue Tmp1 = Op.getOperand(1);
3225   DebugLoc dl = Op.getDebugLoc();
3226   EVT VT = Op.getValueType();
3227   EVT SrcVT = Tmp1.getValueType();
3228   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3229     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3230   bool UseNEON = !InGPR && Subtarget->hasNEON();
3231
3232   if (UseNEON) {
3233     // Use VBSL to copy the sign bit.
3234     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3235     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3236                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3237     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3238     if (VT == MVT::f64)
3239       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3240                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3241                          DAG.getConstant(32, MVT::i32));
3242     else /*if (VT == MVT::f32)*/
3243       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3244     if (SrcVT == MVT::f32) {
3245       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3246       if (VT == MVT::f64)
3247         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3248                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3249                            DAG.getConstant(32, MVT::i32));
3250     } else if (VT == MVT::f32)
3251       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3252                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3253                          DAG.getConstant(32, MVT::i32));
3254     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3255     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3256
3257     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3258                                             MVT::i32);
3259     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3260     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3261                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3262
3263     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3264                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3265                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3266     if (VT == MVT::f32) {
3267       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3268       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3269                         DAG.getConstant(0, MVT::i32));
3270     } else {
3271       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3272     }
3273
3274     return Res;
3275   }
3276
3277   // Bitcast operand 1 to i32.
3278   if (SrcVT == MVT::f64)
3279     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3280                        &Tmp1, 1).getValue(1);
3281   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3282
3283   // Or in the signbit with integer operations.
3284   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3285   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3286   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3287   if (VT == MVT::f32) {
3288     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3289                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3290     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3291                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3292   }
3293
3294   // f64: Or the high part with signbit and then combine two parts.
3295   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3296                      &Tmp0, 1);
3297   SDValue Lo = Tmp0.getValue(0);
3298   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3299   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3300   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3301 }
3302
3303 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3304   MachineFunction &MF = DAG.getMachineFunction();
3305   MachineFrameInfo *MFI = MF.getFrameInfo();
3306   MFI->setReturnAddressIsTaken(true);
3307
3308   EVT VT = Op.getValueType();
3309   DebugLoc dl = Op.getDebugLoc();
3310   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3311   if (Depth) {
3312     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3313     SDValue Offset = DAG.getConstant(4, MVT::i32);
3314     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3315                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3316                        MachinePointerInfo(), false, false, false, 0);
3317   }
3318
3319   // Return LR, which contains the return address. Mark it an implicit live-in.
3320   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3321   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3322 }
3323
3324 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3325   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3326   MFI->setFrameAddressIsTaken(true);
3327
3328   EVT VT = Op.getValueType();
3329   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3330   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3331   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3332     ? ARM::R7 : ARM::R11;
3333   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3334   while (Depth--)
3335     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3336                             MachinePointerInfo(),
3337                             false, false, false, 0);
3338   return FrameAddr;
3339 }
3340
3341 /// ExpandBITCAST - If the target supports VFP, this function is called to
3342 /// expand a bit convert where either the source or destination type is i64 to
3343 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3344 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3345 /// vectors), since the legalizer won't know what to do with that.
3346 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3348   DebugLoc dl = N->getDebugLoc();
3349   SDValue Op = N->getOperand(0);
3350
3351   // This function is only supposed to be called for i64 types, either as the
3352   // source or destination of the bit convert.
3353   EVT SrcVT = Op.getValueType();
3354   EVT DstVT = N->getValueType(0);
3355   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3356          "ExpandBITCAST called for non-i64 type");
3357
3358   // Turn i64->f64 into VMOVDRR.
3359   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3360     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3361                              DAG.getConstant(0, MVT::i32));
3362     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3363                              DAG.getConstant(1, MVT::i32));
3364     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3365                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3366   }
3367
3368   // Turn f64->i64 into VMOVRRD.
3369   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3370     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3371                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3372     // Merge the pieces into a single i64 value.
3373     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3374   }
3375
3376   return SDValue();
3377 }
3378
3379 /// getZeroVector - Returns a vector of specified type with all zero elements.
3380 /// Zero vectors are used to represent vector negation and in those cases
3381 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3382 /// not support i64 elements, so sometimes the zero vectors will need to be
3383 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3384 /// zero vector.
3385 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3386   assert(VT.isVector() && "Expected a vector type");
3387   // The canonical modified immediate encoding of a zero vector is....0!
3388   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3389   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3390   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3391   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3392 }
3393
3394 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3395 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3396 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3397                                                 SelectionDAG &DAG) const {
3398   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3399   EVT VT = Op.getValueType();
3400   unsigned VTBits = VT.getSizeInBits();
3401   DebugLoc dl = Op.getDebugLoc();
3402   SDValue ShOpLo = Op.getOperand(0);
3403   SDValue ShOpHi = Op.getOperand(1);
3404   SDValue ShAmt  = Op.getOperand(2);
3405   SDValue ARMcc;
3406   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3407
3408   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3409
3410   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3411                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3412   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3413   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3414                                    DAG.getConstant(VTBits, MVT::i32));
3415   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3416   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3417   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3418
3419   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3420   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3421                           ARMcc, DAG, dl);
3422   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3423   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3424                            CCR, Cmp);
3425
3426   SDValue Ops[2] = { Lo, Hi };
3427   return DAG.getMergeValues(Ops, 2, dl);
3428 }
3429
3430 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3431 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3432 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3433                                                SelectionDAG &DAG) const {
3434   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3435   EVT VT = Op.getValueType();
3436   unsigned VTBits = VT.getSizeInBits();
3437   DebugLoc dl = Op.getDebugLoc();
3438   SDValue ShOpLo = Op.getOperand(0);
3439   SDValue ShOpHi = Op.getOperand(1);
3440   SDValue ShAmt  = Op.getOperand(2);
3441   SDValue ARMcc;
3442
3443   assert(Op.getOpcode() == ISD::SHL_PARTS);
3444   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3445                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3446   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3447   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3448                                    DAG.getConstant(VTBits, MVT::i32));
3449   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3450   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3451
3452   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3453   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3454   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3455                           ARMcc, DAG, dl);
3456   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3457   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3458                            CCR, Cmp);
3459
3460   SDValue Ops[2] = { Lo, Hi };
3461   return DAG.getMergeValues(Ops, 2, dl);
3462 }
3463
3464 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3465                                             SelectionDAG &DAG) const {
3466   // The rounding mode is in bits 23:22 of the FPSCR.
3467   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3468   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3469   // so that the shift + and get folded into a bitfield extract.
3470   DebugLoc dl = Op.getDebugLoc();
3471   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3472                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3473                                               MVT::i32));
3474   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3475                                   DAG.getConstant(1U << 22, MVT::i32));
3476   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3477                               DAG.getConstant(22, MVT::i32));
3478   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3479                      DAG.getConstant(3, MVT::i32));
3480 }
3481
3482 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3483                          const ARMSubtarget *ST) {
3484   EVT VT = N->getValueType(0);
3485   DebugLoc dl = N->getDebugLoc();
3486
3487   if (!ST->hasV6T2Ops())
3488     return SDValue();
3489
3490   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3491   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3492 }
3493
3494 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3495                           const ARMSubtarget *ST) {
3496   EVT VT = N->getValueType(0);
3497   DebugLoc dl = N->getDebugLoc();
3498
3499   if (!VT.isVector())
3500     return SDValue();
3501
3502   // Lower vector shifts on NEON to use VSHL.
3503   assert(ST->hasNEON() && "unexpected vector shift");
3504
3505   // Left shifts translate directly to the vshiftu intrinsic.
3506   if (N->getOpcode() == ISD::SHL)
3507     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3508                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3509                        N->getOperand(0), N->getOperand(1));
3510
3511   assert((N->getOpcode() == ISD::SRA ||
3512           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3513
3514   // NEON uses the same intrinsics for both left and right shifts.  For
3515   // right shifts, the shift amounts are negative, so negate the vector of
3516   // shift amounts.
3517   EVT ShiftVT = N->getOperand(1).getValueType();
3518   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3519                                      getZeroVector(ShiftVT, DAG, dl),
3520                                      N->getOperand(1));
3521   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3522                              Intrinsic::arm_neon_vshifts :
3523                              Intrinsic::arm_neon_vshiftu);
3524   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3525                      DAG.getConstant(vshiftInt, MVT::i32),
3526                      N->getOperand(0), NegatedCount);
3527 }
3528
3529 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3530                                 const ARMSubtarget *ST) {
3531   EVT VT = N->getValueType(0);
3532   DebugLoc dl = N->getDebugLoc();
3533
3534   // We can get here for a node like i32 = ISD::SHL i32, i64
3535   if (VT != MVT::i64)
3536     return SDValue();
3537
3538   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3539          "Unknown shift to lower!");
3540
3541   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3542   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3543       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3544     return SDValue();
3545
3546   // If we are in thumb mode, we don't have RRX.
3547   if (ST->isThumb1Only()) return SDValue();
3548
3549   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3550   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3551                            DAG.getConstant(0, MVT::i32));
3552   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3553                            DAG.getConstant(1, MVT::i32));
3554
3555   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3556   // captures the result into a carry flag.
3557   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3558   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3559
3560   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3561   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3562
3563   // Merge the pieces into a single i64 value.
3564  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3565 }
3566
3567 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3568   SDValue TmpOp0, TmpOp1;
3569   bool Invert = false;
3570   bool Swap = false;
3571   unsigned Opc = 0;
3572
3573   SDValue Op0 = Op.getOperand(0);
3574   SDValue Op1 = Op.getOperand(1);
3575   SDValue CC = Op.getOperand(2);
3576   EVT VT = Op.getValueType();
3577   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3578   DebugLoc dl = Op.getDebugLoc();
3579
3580   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3581     switch (SetCCOpcode) {
3582     default: llvm_unreachable("Illegal FP comparison");
3583     case ISD::SETUNE:
3584     case ISD::SETNE:  Invert = true; // Fallthrough
3585     case ISD::SETOEQ:
3586     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3587     case ISD::SETOLT:
3588     case ISD::SETLT: Swap = true; // Fallthrough
3589     case ISD::SETOGT:
3590     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3591     case ISD::SETOLE:
3592     case ISD::SETLE:  Swap = true; // Fallthrough
3593     case ISD::SETOGE:
3594     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3595     case ISD::SETUGE: Swap = true; // Fallthrough
3596     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3597     case ISD::SETUGT: Swap = true; // Fallthrough
3598     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3599     case ISD::SETUEQ: Invert = true; // Fallthrough
3600     case ISD::SETONE:
3601       // Expand this to (OLT | OGT).
3602       TmpOp0 = Op0;
3603       TmpOp1 = Op1;
3604       Opc = ISD::OR;
3605       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3606       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3607       break;
3608     case ISD::SETUO: Invert = true; // Fallthrough
3609     case ISD::SETO:
3610       // Expand this to (OLT | OGE).
3611       TmpOp0 = Op0;
3612       TmpOp1 = Op1;
3613       Opc = ISD::OR;
3614       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3615       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3616       break;
3617     }
3618   } else {
3619     // Integer comparisons.
3620     switch (SetCCOpcode) {
3621     default: llvm_unreachable("Illegal integer comparison");
3622     case ISD::SETNE:  Invert = true;
3623     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3624     case ISD::SETLT:  Swap = true;
3625     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3626     case ISD::SETLE:  Swap = true;
3627     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3628     case ISD::SETULT: Swap = true;
3629     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3630     case ISD::SETULE: Swap = true;
3631     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3632     }
3633
3634     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3635     if (Opc == ARMISD::VCEQ) {
3636
3637       SDValue AndOp;
3638       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3639         AndOp = Op0;
3640       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3641         AndOp = Op1;
3642
3643       // Ignore bitconvert.
3644       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3645         AndOp = AndOp.getOperand(0);
3646
3647       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3648         Opc = ARMISD::VTST;
3649         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3650         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3651         Invert = !Invert;
3652       }
3653     }
3654   }
3655
3656   if (Swap)
3657     std::swap(Op0, Op1);
3658
3659   // If one of the operands is a constant vector zero, attempt to fold the
3660   // comparison to a specialized compare-against-zero form.
3661   SDValue SingleOp;
3662   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3663     SingleOp = Op0;
3664   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3665     if (Opc == ARMISD::VCGE)
3666       Opc = ARMISD::VCLEZ;
3667     else if (Opc == ARMISD::VCGT)
3668       Opc = ARMISD::VCLTZ;
3669     SingleOp = Op1;
3670   }
3671
3672   SDValue Result;
3673   if (SingleOp.getNode()) {
3674     switch (Opc) {
3675     case ARMISD::VCEQ:
3676       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3677     case ARMISD::VCGE:
3678       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3679     case ARMISD::VCLEZ:
3680       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3681     case ARMISD::VCGT:
3682       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3683     case ARMISD::VCLTZ:
3684       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3685     default:
3686       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3687     }
3688   } else {
3689      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3690   }
3691
3692   if (Invert)
3693     Result = DAG.getNOT(dl, Result, VT);
3694
3695   return Result;
3696 }
3697
3698 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3699 /// valid vector constant for a NEON instruction with a "modified immediate"
3700 /// operand (e.g., VMOV).  If so, return the encoded value.
3701 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3702                                  unsigned SplatBitSize, SelectionDAG &DAG,
3703                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3704   unsigned OpCmode, Imm;
3705
3706   // SplatBitSize is set to the smallest size that splats the vector, so a
3707   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3708   // immediate instructions others than VMOV do not support the 8-bit encoding
3709   // of a zero vector, and the default encoding of zero is supposed to be the
3710   // 32-bit version.
3711   if (SplatBits == 0)
3712     SplatBitSize = 32;
3713
3714   switch (SplatBitSize) {
3715   case 8:
3716     if (type != VMOVModImm)
3717       return SDValue();
3718     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3719     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3720     OpCmode = 0xe;
3721     Imm = SplatBits;
3722     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3723     break;
3724
3725   case 16:
3726     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3727     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3728     if ((SplatBits & ~0xff) == 0) {
3729       // Value = 0x00nn: Op=x, Cmode=100x.
3730       OpCmode = 0x8;
3731       Imm = SplatBits;
3732       break;
3733     }
3734     if ((SplatBits & ~0xff00) == 0) {
3735       // Value = 0xnn00: Op=x, Cmode=101x.
3736       OpCmode = 0xa;
3737       Imm = SplatBits >> 8;
3738       break;
3739     }
3740     return SDValue();
3741
3742   case 32:
3743     // NEON's 32-bit VMOV supports splat values where:
3744     // * only one byte is nonzero, or
3745     // * the least significant byte is 0xff and the second byte is nonzero, or
3746     // * the least significant 2 bytes are 0xff and the third is nonzero.
3747     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3748     if ((SplatBits & ~0xff) == 0) {
3749       // Value = 0x000000nn: Op=x, Cmode=000x.
3750       OpCmode = 0;
3751       Imm = SplatBits;
3752       break;
3753     }
3754     if ((SplatBits & ~0xff00) == 0) {
3755       // Value = 0x0000nn00: Op=x, Cmode=001x.
3756       OpCmode = 0x2;
3757       Imm = SplatBits >> 8;
3758       break;
3759     }
3760     if ((SplatBits & ~0xff0000) == 0) {
3761       // Value = 0x00nn0000: Op=x, Cmode=010x.
3762       OpCmode = 0x4;
3763       Imm = SplatBits >> 16;
3764       break;
3765     }
3766     if ((SplatBits & ~0xff000000) == 0) {
3767       // Value = 0xnn000000: Op=x, Cmode=011x.
3768       OpCmode = 0x6;
3769       Imm = SplatBits >> 24;
3770       break;
3771     }
3772
3773     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3774     if (type == OtherModImm) return SDValue();
3775
3776     if ((SplatBits & ~0xffff) == 0 &&
3777         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3778       // Value = 0x0000nnff: Op=x, Cmode=1100.
3779       OpCmode = 0xc;
3780       Imm = SplatBits >> 8;
3781       SplatBits |= 0xff;
3782       break;
3783     }
3784
3785     if ((SplatBits & ~0xffffff) == 0 &&
3786         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3787       // Value = 0x00nnffff: Op=x, Cmode=1101.
3788       OpCmode = 0xd;
3789       Imm = SplatBits >> 16;
3790       SplatBits |= 0xffff;
3791       break;
3792     }
3793
3794     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3795     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3796     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3797     // and fall through here to test for a valid 64-bit splat.  But, then the
3798     // caller would also need to check and handle the change in size.
3799     return SDValue();
3800
3801   case 64: {
3802     if (type != VMOVModImm)
3803       return SDValue();
3804     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3805     uint64_t BitMask = 0xff;
3806     uint64_t Val = 0;
3807     unsigned ImmMask = 1;
3808     Imm = 0;
3809     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3810       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3811         Val |= BitMask;
3812         Imm |= ImmMask;
3813       } else if ((SplatBits & BitMask) != 0) {
3814         return SDValue();
3815       }
3816       BitMask <<= 8;
3817       ImmMask <<= 1;
3818     }
3819     // Op=1, Cmode=1110.
3820     OpCmode = 0x1e;
3821     SplatBits = Val;
3822     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3823     break;
3824   }
3825
3826   default:
3827     llvm_unreachable("unexpected size for isNEONModifiedImm");
3828   }
3829
3830   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3831   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3832 }
3833
3834 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3835                                            const ARMSubtarget *ST) const {
3836   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3837     return SDValue();
3838
3839   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3840   assert(Op.getValueType() == MVT::f32 &&
3841          "ConstantFP custom lowering should only occur for f32.");
3842
3843   // Try splatting with a VMOV.f32...
3844   APFloat FPVal = CFP->getValueAPF();
3845   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3846   if (ImmVal != -1) {
3847     DebugLoc DL = Op.getDebugLoc();
3848     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3849     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3850                                       NewVal);
3851     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3852                        DAG.getConstant(0, MVT::i32));
3853   }
3854
3855   // If that fails, try a VMOV.i32
3856   EVT VMovVT;
3857   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3858   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3859                                      VMOVModImm);
3860   if (NewVal != SDValue()) {
3861     DebugLoc DL = Op.getDebugLoc();
3862     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3863                                       NewVal);
3864     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3865                                        VecConstant);
3866     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3867                        DAG.getConstant(0, MVT::i32));
3868   }
3869
3870   // Finally, try a VMVN.i32
3871   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3872                              VMVNModImm);
3873   if (NewVal != SDValue()) {
3874     DebugLoc DL = Op.getDebugLoc();
3875     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3876     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3877                                        VecConstant);
3878     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3879                        DAG.getConstant(0, MVT::i32));
3880   }
3881
3882   return SDValue();
3883 }
3884
3885
3886 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3887                        bool &ReverseVEXT, unsigned &Imm) {
3888   unsigned NumElts = VT.getVectorNumElements();
3889   ReverseVEXT = false;
3890
3891   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3892   if (M[0] < 0)
3893     return false;
3894
3895   Imm = M[0];
3896
3897   // If this is a VEXT shuffle, the immediate value is the index of the first
3898   // element.  The other shuffle indices must be the successive elements after
3899   // the first one.
3900   unsigned ExpectedElt = Imm;
3901   for (unsigned i = 1; i < NumElts; ++i) {
3902     // Increment the expected index.  If it wraps around, it may still be
3903     // a VEXT but the source vectors must be swapped.
3904     ExpectedElt += 1;
3905     if (ExpectedElt == NumElts * 2) {
3906       ExpectedElt = 0;
3907       ReverseVEXT = true;
3908     }
3909
3910     if (M[i] < 0) continue; // ignore UNDEF indices
3911     if (ExpectedElt != static_cast<unsigned>(M[i]))
3912       return false;
3913   }
3914
3915   // Adjust the index value if the source operands will be swapped.
3916   if (ReverseVEXT)
3917     Imm -= NumElts;
3918
3919   return true;
3920 }
3921
3922 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3923 /// instruction with the specified blocksize.  (The order of the elements
3924 /// within each block of the vector is reversed.)
3925 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3926   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3927          "Only possible block sizes for VREV are: 16, 32, 64");
3928
3929   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3930   if (EltSz == 64)
3931     return false;
3932
3933   unsigned NumElts = VT.getVectorNumElements();
3934   unsigned BlockElts = M[0] + 1;
3935   // If the first shuffle index is UNDEF, be optimistic.
3936   if (M[0] < 0)
3937     BlockElts = BlockSize / EltSz;
3938
3939   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3940     return false;
3941
3942   for (unsigned i = 0; i < NumElts; ++i) {
3943     if (M[i] < 0) continue; // ignore UNDEF indices
3944     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3945       return false;
3946   }
3947
3948   return true;
3949 }
3950
3951 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3952   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3953   // range, then 0 is placed into the resulting vector. So pretty much any mask
3954   // of 8 elements can work here.
3955   return VT == MVT::v8i8 && M.size() == 8;
3956 }
3957
3958 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3959   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3960   if (EltSz == 64)
3961     return false;
3962
3963   unsigned NumElts = VT.getVectorNumElements();
3964   WhichResult = (M[0] == 0 ? 0 : 1);
3965   for (unsigned i = 0; i < NumElts; i += 2) {
3966     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3967         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3968       return false;
3969   }
3970   return true;
3971 }
3972
3973 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3974 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3975 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3976 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3977   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3978   if (EltSz == 64)
3979     return false;
3980
3981   unsigned NumElts = VT.getVectorNumElements();
3982   WhichResult = (M[0] == 0 ? 0 : 1);
3983   for (unsigned i = 0; i < NumElts; i += 2) {
3984     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3985         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3986       return false;
3987   }
3988   return true;
3989 }
3990
3991 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3992   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3993   if (EltSz == 64)
3994     return false;
3995
3996   unsigned NumElts = VT.getVectorNumElements();
3997   WhichResult = (M[0] == 0 ? 0 : 1);
3998   for (unsigned i = 0; i != NumElts; ++i) {
3999     if (M[i] < 0) continue; // ignore UNDEF indices
4000     if ((unsigned) M[i] != 2 * i + WhichResult)
4001       return false;
4002   }
4003
4004   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4005   if (VT.is64BitVector() && EltSz == 32)
4006     return false;
4007
4008   return true;
4009 }
4010
4011 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4012 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4013 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4014 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4015   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4016   if (EltSz == 64)
4017     return false;
4018
4019   unsigned Half = VT.getVectorNumElements() / 2;
4020   WhichResult = (M[0] == 0 ? 0 : 1);
4021   for (unsigned j = 0; j != 2; ++j) {
4022     unsigned Idx = WhichResult;
4023     for (unsigned i = 0; i != Half; ++i) {
4024       int MIdx = M[i + j * Half];
4025       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4026         return false;
4027       Idx += 2;
4028     }
4029   }
4030
4031   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4032   if (VT.is64BitVector() && EltSz == 32)
4033     return false;
4034
4035   return true;
4036 }
4037
4038 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4039   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4040   if (EltSz == 64)
4041     return false;
4042
4043   unsigned NumElts = VT.getVectorNumElements();
4044   WhichResult = (M[0] == 0 ? 0 : 1);
4045   unsigned Idx = WhichResult * NumElts / 2;
4046   for (unsigned i = 0; i != NumElts; i += 2) {
4047     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4048         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4049       return false;
4050     Idx += 1;
4051   }
4052
4053   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4054   if (VT.is64BitVector() && EltSz == 32)
4055     return false;
4056
4057   return true;
4058 }
4059
4060 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4061 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4062 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4063 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4064   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4065   if (EltSz == 64)
4066     return false;
4067
4068   unsigned NumElts = VT.getVectorNumElements();
4069   WhichResult = (M[0] == 0 ? 0 : 1);
4070   unsigned Idx = WhichResult * NumElts / 2;
4071   for (unsigned i = 0; i != NumElts; i += 2) {
4072     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4073         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4074       return false;
4075     Idx += 1;
4076   }
4077
4078   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4079   if (VT.is64BitVector() && EltSz == 32)
4080     return false;
4081
4082   return true;
4083 }
4084
4085 // If N is an integer constant that can be moved into a register in one
4086 // instruction, return an SDValue of such a constant (will become a MOV
4087 // instruction).  Otherwise return null.
4088 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4089                                      const ARMSubtarget *ST, DebugLoc dl) {
4090   uint64_t Val;
4091   if (!isa<ConstantSDNode>(N))
4092     return SDValue();
4093   Val = cast<ConstantSDNode>(N)->getZExtValue();
4094
4095   if (ST->isThumb1Only()) {
4096     if (Val <= 255 || ~Val <= 255)
4097       return DAG.getConstant(Val, MVT::i32);
4098   } else {
4099     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4100       return DAG.getConstant(Val, MVT::i32);
4101   }
4102   return SDValue();
4103 }
4104
4105 // If this is a case we can't handle, return null and let the default
4106 // expansion code take care of it.
4107 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4108                                              const ARMSubtarget *ST) const {
4109   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4110   DebugLoc dl = Op.getDebugLoc();
4111   EVT VT = Op.getValueType();
4112
4113   APInt SplatBits, SplatUndef;
4114   unsigned SplatBitSize;
4115   bool HasAnyUndefs;
4116   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4117     if (SplatBitSize <= 64) {
4118       // Check if an immediate VMOV works.
4119       EVT VmovVT;
4120       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4121                                       SplatUndef.getZExtValue(), SplatBitSize,
4122                                       DAG, VmovVT, VT.is128BitVector(),
4123                                       VMOVModImm);
4124       if (Val.getNode()) {
4125         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4126         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4127       }
4128
4129       // Try an immediate VMVN.
4130       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4131       Val = isNEONModifiedImm(NegatedImm,
4132                                       SplatUndef.getZExtValue(), SplatBitSize,
4133                                       DAG, VmovVT, VT.is128BitVector(),
4134                                       VMVNModImm);
4135       if (Val.getNode()) {
4136         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4137         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4138       }
4139
4140       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4141       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4142         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4143         if (ImmVal != -1) {
4144           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4145           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4146         }
4147       }
4148     }
4149   }
4150
4151   // Scan through the operands to see if only one value is used.
4152   unsigned NumElts = VT.getVectorNumElements();
4153   bool isOnlyLowElement = true;
4154   bool usesOnlyOneValue = true;
4155   bool isConstant = true;
4156   SDValue Value;
4157   for (unsigned i = 0; i < NumElts; ++i) {
4158     SDValue V = Op.getOperand(i);
4159     if (V.getOpcode() == ISD::UNDEF)
4160       continue;
4161     if (i > 0)
4162       isOnlyLowElement = false;
4163     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4164       isConstant = false;
4165
4166     if (!Value.getNode())
4167       Value = V;
4168     else if (V != Value)
4169       usesOnlyOneValue = false;
4170   }
4171
4172   if (!Value.getNode())
4173     return DAG.getUNDEF(VT);
4174
4175   if (isOnlyLowElement)
4176     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4177
4178   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4179
4180   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4181   // i32 and try again.
4182   if (usesOnlyOneValue && EltSize <= 32) {
4183     if (!isConstant)
4184       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4185     if (VT.getVectorElementType().isFloatingPoint()) {
4186       SmallVector<SDValue, 8> Ops;
4187       for (unsigned i = 0; i < NumElts; ++i)
4188         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4189                                   Op.getOperand(i)));
4190       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4191       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4192       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4193       if (Val.getNode())
4194         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4195     }
4196     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4197     if (Val.getNode())
4198       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4199   }
4200
4201   // If all elements are constants and the case above didn't get hit, fall back
4202   // to the default expansion, which will generate a load from the constant
4203   // pool.
4204   if (isConstant)
4205     return SDValue();
4206
4207   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4208   if (NumElts >= 4) {
4209     SDValue shuffle = ReconstructShuffle(Op, DAG);
4210     if (shuffle != SDValue())
4211       return shuffle;
4212   }
4213
4214   // Vectors with 32- or 64-bit elements can be built by directly assigning
4215   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4216   // will be legalized.
4217   if (EltSize >= 32) {
4218     // Do the expansion with floating-point types, since that is what the VFP
4219     // registers are defined to use, and since i64 is not legal.
4220     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4221     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4222     SmallVector<SDValue, 8> Ops;
4223     for (unsigned i = 0; i < NumElts; ++i)
4224       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4225     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4226     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4227   }
4228
4229   return SDValue();
4230 }
4231
4232 // Gather data to see if the operation can be modelled as a
4233 // shuffle in combination with VEXTs.
4234 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4235                                               SelectionDAG &DAG) const {
4236   DebugLoc dl = Op.getDebugLoc();
4237   EVT VT = Op.getValueType();
4238   unsigned NumElts = VT.getVectorNumElements();
4239
4240   SmallVector<SDValue, 2> SourceVecs;
4241   SmallVector<unsigned, 2> MinElts;
4242   SmallVector<unsigned, 2> MaxElts;
4243
4244   for (unsigned i = 0; i < NumElts; ++i) {
4245     SDValue V = Op.getOperand(i);
4246     if (V.getOpcode() == ISD::UNDEF)
4247       continue;
4248     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4249       // A shuffle can only come from building a vector from various
4250       // elements of other vectors.
4251       return SDValue();
4252     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4253                VT.getVectorElementType()) {
4254       // This code doesn't know how to handle shuffles where the vector
4255       // element types do not match (this happens because type legalization
4256       // promotes the return type of EXTRACT_VECTOR_ELT).
4257       // FIXME: It might be appropriate to extend this code to handle
4258       // mismatched types.
4259       return SDValue();
4260     }
4261
4262     // Record this extraction against the appropriate vector if possible...
4263     SDValue SourceVec = V.getOperand(0);
4264     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4265     bool FoundSource = false;
4266     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4267       if (SourceVecs[j] == SourceVec) {
4268         if (MinElts[j] > EltNo)
4269           MinElts[j] = EltNo;
4270         if (MaxElts[j] < EltNo)
4271           MaxElts[j] = EltNo;
4272         FoundSource = true;
4273         break;
4274       }
4275     }
4276
4277     // Or record a new source if not...
4278     if (!FoundSource) {
4279       SourceVecs.push_back(SourceVec);
4280       MinElts.push_back(EltNo);
4281       MaxElts.push_back(EltNo);
4282     }
4283   }
4284
4285   // Currently only do something sane when at most two source vectors
4286   // involved.
4287   if (SourceVecs.size() > 2)
4288     return SDValue();
4289
4290   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4291   int VEXTOffsets[2] = {0, 0};
4292
4293   // This loop extracts the usage patterns of the source vectors
4294   // and prepares appropriate SDValues for a shuffle if possible.
4295   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4296     if (SourceVecs[i].getValueType() == VT) {
4297       // No VEXT necessary
4298       ShuffleSrcs[i] = SourceVecs[i];
4299       VEXTOffsets[i] = 0;
4300       continue;
4301     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4302       // It probably isn't worth padding out a smaller vector just to
4303       // break it down again in a shuffle.
4304       return SDValue();
4305     }
4306
4307     // Since only 64-bit and 128-bit vectors are legal on ARM and
4308     // we've eliminated the other cases...
4309     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4310            "unexpected vector sizes in ReconstructShuffle");
4311
4312     if (MaxElts[i] - MinElts[i] >= NumElts) {
4313       // Span too large for a VEXT to cope
4314       return SDValue();
4315     }
4316
4317     if (MinElts[i] >= NumElts) {
4318       // The extraction can just take the second half
4319       VEXTOffsets[i] = NumElts;
4320       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4321                                    SourceVecs[i],
4322                                    DAG.getIntPtrConstant(NumElts));
4323     } else if (MaxElts[i] < NumElts) {
4324       // The extraction can just take the first half
4325       VEXTOffsets[i] = 0;
4326       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4327                                    SourceVecs[i],
4328                                    DAG.getIntPtrConstant(0));
4329     } else {
4330       // An actual VEXT is needed
4331       VEXTOffsets[i] = MinElts[i];
4332       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4333                                      SourceVecs[i],
4334                                      DAG.getIntPtrConstant(0));
4335       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4336                                      SourceVecs[i],
4337                                      DAG.getIntPtrConstant(NumElts));
4338       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4339                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4340     }
4341   }
4342
4343   SmallVector<int, 8> Mask;
4344
4345   for (unsigned i = 0; i < NumElts; ++i) {
4346     SDValue Entry = Op.getOperand(i);
4347     if (Entry.getOpcode() == ISD::UNDEF) {
4348       Mask.push_back(-1);
4349       continue;
4350     }
4351
4352     SDValue ExtractVec = Entry.getOperand(0);
4353     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4354                                           .getOperand(1))->getSExtValue();
4355     if (ExtractVec == SourceVecs[0]) {
4356       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4357     } else {
4358       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4359     }
4360   }
4361
4362   // Final check before we try to produce nonsense...
4363   if (isShuffleMaskLegal(Mask, VT))
4364     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4365                                 &Mask[0]);
4366
4367   return SDValue();
4368 }
4369
4370 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4371 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4372 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4373 /// are assumed to be legal.
4374 bool
4375 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4376                                       EVT VT) const {
4377   if (VT.getVectorNumElements() == 4 &&
4378       (VT.is128BitVector() || VT.is64BitVector())) {
4379     unsigned PFIndexes[4];
4380     for (unsigned i = 0; i != 4; ++i) {
4381       if (M[i] < 0)
4382         PFIndexes[i] = 8;
4383       else
4384         PFIndexes[i] = M[i];
4385     }
4386
4387     // Compute the index in the perfect shuffle table.
4388     unsigned PFTableIndex =
4389       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4390     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4391     unsigned Cost = (PFEntry >> 30);
4392
4393     if (Cost <= 4)
4394       return true;
4395   }
4396
4397   bool ReverseVEXT;
4398   unsigned Imm, WhichResult;
4399
4400   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4401   return (EltSize >= 32 ||
4402           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4403           isVREVMask(M, VT, 64) ||
4404           isVREVMask(M, VT, 32) ||
4405           isVREVMask(M, VT, 16) ||
4406           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4407           isVTBLMask(M, VT) ||
4408           isVTRNMask(M, VT, WhichResult) ||
4409           isVUZPMask(M, VT, WhichResult) ||
4410           isVZIPMask(M, VT, WhichResult) ||
4411           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4412           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4413           isVZIP_v_undef_Mask(M, VT, WhichResult));
4414 }
4415
4416 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4417 /// the specified operations to build the shuffle.
4418 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4419                                       SDValue RHS, SelectionDAG &DAG,
4420                                       DebugLoc dl) {
4421   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4422   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4423   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4424
4425   enum {
4426     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4427     OP_VREV,
4428     OP_VDUP0,
4429     OP_VDUP1,
4430     OP_VDUP2,
4431     OP_VDUP3,
4432     OP_VEXT1,
4433     OP_VEXT2,
4434     OP_VEXT3,
4435     OP_VUZPL, // VUZP, left result
4436     OP_VUZPR, // VUZP, right result
4437     OP_VZIPL, // VZIP, left result
4438     OP_VZIPR, // VZIP, right result
4439     OP_VTRNL, // VTRN, left result
4440     OP_VTRNR  // VTRN, right result
4441   };
4442
4443   if (OpNum == OP_COPY) {
4444     if (LHSID == (1*9+2)*9+3) return LHS;
4445     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4446     return RHS;
4447   }
4448
4449   SDValue OpLHS, OpRHS;
4450   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4451   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4452   EVT VT = OpLHS.getValueType();
4453
4454   switch (OpNum) {
4455   default: llvm_unreachable("Unknown shuffle opcode!");
4456   case OP_VREV:
4457     // VREV divides the vector in half and swaps within the half.
4458     if (VT.getVectorElementType() == MVT::i32 ||
4459         VT.getVectorElementType() == MVT::f32)
4460       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4461     // vrev <4 x i16> -> VREV32
4462     if (VT.getVectorElementType() == MVT::i16)
4463       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4464     // vrev <4 x i8> -> VREV16
4465     assert(VT.getVectorElementType() == MVT::i8);
4466     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4467   case OP_VDUP0:
4468   case OP_VDUP1:
4469   case OP_VDUP2:
4470   case OP_VDUP3:
4471     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4472                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4473   case OP_VEXT1:
4474   case OP_VEXT2:
4475   case OP_VEXT3:
4476     return DAG.getNode(ARMISD::VEXT, dl, VT,
4477                        OpLHS, OpRHS,
4478                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4479   case OP_VUZPL:
4480   case OP_VUZPR:
4481     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4482                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4483   case OP_VZIPL:
4484   case OP_VZIPR:
4485     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4486                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4487   case OP_VTRNL:
4488   case OP_VTRNR:
4489     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4490                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4491   }
4492 }
4493
4494 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4495                                        ArrayRef<int> ShuffleMask,
4496                                        SelectionDAG &DAG) {
4497   // Check to see if we can use the VTBL instruction.
4498   SDValue V1 = Op.getOperand(0);
4499   SDValue V2 = Op.getOperand(1);
4500   DebugLoc DL = Op.getDebugLoc();
4501
4502   SmallVector<SDValue, 8> VTBLMask;
4503   for (ArrayRef<int>::iterator
4504          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4505     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4506
4507   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4508     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4509                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4510                                    &VTBLMask[0], 8));
4511
4512   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4513                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4514                                  &VTBLMask[0], 8));
4515 }
4516
4517 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4518   SDValue V1 = Op.getOperand(0);
4519   SDValue V2 = Op.getOperand(1);
4520   DebugLoc dl = Op.getDebugLoc();
4521   EVT VT = Op.getValueType();
4522   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4523
4524   // Convert shuffles that are directly supported on NEON to target-specific
4525   // DAG nodes, instead of keeping them as shuffles and matching them again
4526   // during code selection.  This is more efficient and avoids the possibility
4527   // of inconsistencies between legalization and selection.
4528   // FIXME: floating-point vectors should be canonicalized to integer vectors
4529   // of the same time so that they get CSEd properly.
4530   ArrayRef<int> ShuffleMask = SVN->getMask();
4531
4532   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4533   if (EltSize <= 32) {
4534     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4535       int Lane = SVN->getSplatIndex();
4536       // If this is undef splat, generate it via "just" vdup, if possible.
4537       if (Lane == -1) Lane = 0;
4538
4539       // Test if V1 is a SCALAR_TO_VECTOR.
4540       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4541         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4542       }
4543       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4544       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4545       // reaches it).
4546       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4547           !isa<ConstantSDNode>(V1.getOperand(0))) {
4548         bool IsScalarToVector = true;
4549         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4550           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4551             IsScalarToVector = false;
4552             break;
4553           }
4554         if (IsScalarToVector)
4555           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4556       }
4557       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4558                          DAG.getConstant(Lane, MVT::i32));
4559     }
4560
4561     bool ReverseVEXT;
4562     unsigned Imm;
4563     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4564       if (ReverseVEXT)
4565         std::swap(V1, V2);
4566       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4567                          DAG.getConstant(Imm, MVT::i32));
4568     }
4569
4570     if (isVREVMask(ShuffleMask, VT, 64))
4571       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4572     if (isVREVMask(ShuffleMask, VT, 32))
4573       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4574     if (isVREVMask(ShuffleMask, VT, 16))
4575       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4576
4577     // Check for Neon shuffles that modify both input vectors in place.
4578     // If both results are used, i.e., if there are two shuffles with the same
4579     // source operands and with masks corresponding to both results of one of
4580     // these operations, DAG memoization will ensure that a single node is
4581     // used for both shuffles.
4582     unsigned WhichResult;
4583     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4584       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4585                          V1, V2).getValue(WhichResult);
4586     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4587       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4588                          V1, V2).getValue(WhichResult);
4589     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4590       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4591                          V1, V2).getValue(WhichResult);
4592
4593     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4594       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4595                          V1, V1).getValue(WhichResult);
4596     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4597       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4598                          V1, V1).getValue(WhichResult);
4599     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4600       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4601                          V1, V1).getValue(WhichResult);
4602   }
4603
4604   // If the shuffle is not directly supported and it has 4 elements, use
4605   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4606   unsigned NumElts = VT.getVectorNumElements();
4607   if (NumElts == 4) {
4608     unsigned PFIndexes[4];
4609     for (unsigned i = 0; i != 4; ++i) {
4610       if (ShuffleMask[i] < 0)
4611         PFIndexes[i] = 8;
4612       else
4613         PFIndexes[i] = ShuffleMask[i];
4614     }
4615
4616     // Compute the index in the perfect shuffle table.
4617     unsigned PFTableIndex =
4618       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4619     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4620     unsigned Cost = (PFEntry >> 30);
4621
4622     if (Cost <= 4)
4623       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4624   }
4625
4626   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4627   if (EltSize >= 32) {
4628     // Do the expansion with floating-point types, since that is what the VFP
4629     // registers are defined to use, and since i64 is not legal.
4630     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4631     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4632     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4633     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4634     SmallVector<SDValue, 8> Ops;
4635     for (unsigned i = 0; i < NumElts; ++i) {
4636       if (ShuffleMask[i] < 0)
4637         Ops.push_back(DAG.getUNDEF(EltVT));
4638       else
4639         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4640                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4641                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4642                                                   MVT::i32)));
4643     }
4644     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4645     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4646   }
4647
4648   if (VT == MVT::v8i8) {
4649     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4650     if (NewOp.getNode())
4651       return NewOp;
4652   }
4653
4654   return SDValue();
4655 }
4656
4657 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4658   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4659   SDValue Lane = Op.getOperand(2);
4660   if (!isa<ConstantSDNode>(Lane))
4661     return SDValue();
4662
4663   return Op;
4664 }
4665
4666 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4667   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4668   SDValue Lane = Op.getOperand(1);
4669   if (!isa<ConstantSDNode>(Lane))
4670     return SDValue();
4671
4672   SDValue Vec = Op.getOperand(0);
4673   if (Op.getValueType() == MVT::i32 &&
4674       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4675     DebugLoc dl = Op.getDebugLoc();
4676     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4677   }
4678
4679   return Op;
4680 }
4681
4682 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4683   // The only time a CONCAT_VECTORS operation can have legal types is when
4684   // two 64-bit vectors are concatenated to a 128-bit vector.
4685   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4686          "unexpected CONCAT_VECTORS");
4687   DebugLoc dl = Op.getDebugLoc();
4688   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4689   SDValue Op0 = Op.getOperand(0);
4690   SDValue Op1 = Op.getOperand(1);
4691   if (Op0.getOpcode() != ISD::UNDEF)
4692     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4693                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4694                       DAG.getIntPtrConstant(0));
4695   if (Op1.getOpcode() != ISD::UNDEF)
4696     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4697                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4698                       DAG.getIntPtrConstant(1));
4699   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4700 }
4701
4702 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4703 /// element has been zero/sign-extended, depending on the isSigned parameter,
4704 /// from an integer type half its size.
4705 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4706                                    bool isSigned) {
4707   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4708   EVT VT = N->getValueType(0);
4709   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4710     SDNode *BVN = N->getOperand(0).getNode();
4711     if (BVN->getValueType(0) != MVT::v4i32 ||
4712         BVN->getOpcode() != ISD::BUILD_VECTOR)
4713       return false;
4714     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4715     unsigned HiElt = 1 - LoElt;
4716     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4717     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4718     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4719     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4720     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4721       return false;
4722     if (isSigned) {
4723       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4724           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4725         return true;
4726     } else {
4727       if (Hi0->isNullValue() && Hi1->isNullValue())
4728         return true;
4729     }
4730     return false;
4731   }
4732
4733   if (N->getOpcode() != ISD::BUILD_VECTOR)
4734     return false;
4735
4736   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4737     SDNode *Elt = N->getOperand(i).getNode();
4738     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4739       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4740       unsigned HalfSize = EltSize / 2;
4741       if (isSigned) {
4742         if (!isIntN(HalfSize, C->getSExtValue()))
4743           return false;
4744       } else {
4745         if (!isUIntN(HalfSize, C->getZExtValue()))
4746           return false;
4747       }
4748       continue;
4749     }
4750     return false;
4751   }
4752
4753   return true;
4754 }
4755
4756 /// isSignExtended - Check if a node is a vector value that is sign-extended
4757 /// or a constant BUILD_VECTOR with sign-extended elements.
4758 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4759   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4760     return true;
4761   if (isExtendedBUILD_VECTOR(N, DAG, true))
4762     return true;
4763   return false;
4764 }
4765
4766 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4767 /// or a constant BUILD_VECTOR with zero-extended elements.
4768 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4769   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4770     return true;
4771   if (isExtendedBUILD_VECTOR(N, DAG, false))
4772     return true;
4773   return false;
4774 }
4775
4776 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4777 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4778 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4779   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4780     return N->getOperand(0);
4781   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4782     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4783                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4784                        LD->isNonTemporal(), LD->isInvariant(),
4785                        LD->getAlignment());
4786   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4787   // have been legalized as a BITCAST from v4i32.
4788   if (N->getOpcode() == ISD::BITCAST) {
4789     SDNode *BVN = N->getOperand(0).getNode();
4790     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4791            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4792     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4793     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4794                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4795   }
4796   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4797   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4798   EVT VT = N->getValueType(0);
4799   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4800   unsigned NumElts = VT.getVectorNumElements();
4801   MVT TruncVT = MVT::getIntegerVT(EltSize);
4802   SmallVector<SDValue, 8> Ops;
4803   for (unsigned i = 0; i != NumElts; ++i) {
4804     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4805     const APInt &CInt = C->getAPIntValue();
4806     // Element types smaller than 32 bits are not legal, so use i32 elements.
4807     // The values are implicitly truncated so sext vs. zext doesn't matter.
4808     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4809   }
4810   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4811                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4812 }
4813
4814 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4815   unsigned Opcode = N->getOpcode();
4816   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4817     SDNode *N0 = N->getOperand(0).getNode();
4818     SDNode *N1 = N->getOperand(1).getNode();
4819     return N0->hasOneUse() && N1->hasOneUse() &&
4820       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4821   }
4822   return false;
4823 }
4824
4825 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4826   unsigned Opcode = N->getOpcode();
4827   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4828     SDNode *N0 = N->getOperand(0).getNode();
4829     SDNode *N1 = N->getOperand(1).getNode();
4830     return N0->hasOneUse() && N1->hasOneUse() &&
4831       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4832   }
4833   return false;
4834 }
4835
4836 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4837   // Multiplications are only custom-lowered for 128-bit vectors so that
4838   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4839   EVT VT = Op.getValueType();
4840   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4841   SDNode *N0 = Op.getOperand(0).getNode();
4842   SDNode *N1 = Op.getOperand(1).getNode();
4843   unsigned NewOpc = 0;
4844   bool isMLA = false;
4845   bool isN0SExt = isSignExtended(N0, DAG);
4846   bool isN1SExt = isSignExtended(N1, DAG);
4847   if (isN0SExt && isN1SExt)
4848     NewOpc = ARMISD::VMULLs;
4849   else {
4850     bool isN0ZExt = isZeroExtended(N0, DAG);
4851     bool isN1ZExt = isZeroExtended(N1, DAG);
4852     if (isN0ZExt && isN1ZExt)
4853       NewOpc = ARMISD::VMULLu;
4854     else if (isN1SExt || isN1ZExt) {
4855       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4856       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4857       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4858         NewOpc = ARMISD::VMULLs;
4859         isMLA = true;
4860       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4861         NewOpc = ARMISD::VMULLu;
4862         isMLA = true;
4863       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4864         std::swap(N0, N1);
4865         NewOpc = ARMISD::VMULLu;
4866         isMLA = true;
4867       }
4868     }
4869
4870     if (!NewOpc) {
4871       if (VT == MVT::v2i64)
4872         // Fall through to expand this.  It is not legal.
4873         return SDValue();
4874       else
4875         // Other vector multiplications are legal.
4876         return Op;
4877     }
4878   }
4879
4880   // Legalize to a VMULL instruction.
4881   DebugLoc DL = Op.getDebugLoc();
4882   SDValue Op0;
4883   SDValue Op1 = SkipExtension(N1, DAG);
4884   if (!isMLA) {
4885     Op0 = SkipExtension(N0, DAG);
4886     assert(Op0.getValueType().is64BitVector() &&
4887            Op1.getValueType().is64BitVector() &&
4888            "unexpected types for extended operands to VMULL");
4889     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4890   }
4891
4892   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4893   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4894   //   vmull q0, d4, d6
4895   //   vmlal q0, d5, d6
4896   // is faster than
4897   //   vaddl q0, d4, d5
4898   //   vmovl q1, d6
4899   //   vmul  q0, q0, q1
4900   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4901   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4902   EVT Op1VT = Op1.getValueType();
4903   return DAG.getNode(N0->getOpcode(), DL, VT,
4904                      DAG.getNode(NewOpc, DL, VT,
4905                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4906                      DAG.getNode(NewOpc, DL, VT,
4907                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4908 }
4909
4910 static SDValue
4911 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4912   // Convert to float
4913   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4914   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4915   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4916   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4917   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4918   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4919   // Get reciprocal estimate.
4920   // float4 recip = vrecpeq_f32(yf);
4921   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4922                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4923   // Because char has a smaller range than uchar, we can actually get away
4924   // without any newton steps.  This requires that we use a weird bias
4925   // of 0xb000, however (again, this has been exhaustively tested).
4926   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4927   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4928   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4929   Y = DAG.getConstant(0xb000, MVT::i32);
4930   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4931   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4932   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4933   // Convert back to short.
4934   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4935   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4936   return X;
4937 }
4938
4939 static SDValue
4940 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4941   SDValue N2;
4942   // Convert to float.
4943   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4944   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4945   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4946   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4947   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4948   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4949
4950   // Use reciprocal estimate and one refinement step.
4951   // float4 recip = vrecpeq_f32(yf);
4952   // recip *= vrecpsq_f32(yf, recip);
4953   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4954                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4955   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4956                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4957                    N1, N2);
4958   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4959   // Because short has a smaller range than ushort, we can actually get away
4960   // with only a single newton step.  This requires that we use a weird bias
4961   // of 89, however (again, this has been exhaustively tested).
4962   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4963   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4964   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4965   N1 = DAG.getConstant(0x89, MVT::i32);
4966   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4967   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4968   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4969   // Convert back to integer and return.
4970   // return vmovn_s32(vcvt_s32_f32(result));
4971   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4972   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4973   return N0;
4974 }
4975
4976 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4977   EVT VT = Op.getValueType();
4978   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4979          "unexpected type for custom-lowering ISD::SDIV");
4980
4981   DebugLoc dl = Op.getDebugLoc();
4982   SDValue N0 = Op.getOperand(0);
4983   SDValue N1 = Op.getOperand(1);
4984   SDValue N2, N3;
4985
4986   if (VT == MVT::v8i8) {
4987     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4988     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4989
4990     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4991                      DAG.getIntPtrConstant(4));
4992     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4993                      DAG.getIntPtrConstant(4));
4994     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4995                      DAG.getIntPtrConstant(0));
4996     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4997                      DAG.getIntPtrConstant(0));
4998
4999     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5000     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5001
5002     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5003     N0 = LowerCONCAT_VECTORS(N0, DAG);
5004
5005     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5006     return N0;
5007   }
5008   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5009 }
5010
5011 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5012   EVT VT = Op.getValueType();
5013   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5014          "unexpected type for custom-lowering ISD::UDIV");
5015
5016   DebugLoc dl = Op.getDebugLoc();
5017   SDValue N0 = Op.getOperand(0);
5018   SDValue N1 = Op.getOperand(1);
5019   SDValue N2, N3;
5020
5021   if (VT == MVT::v8i8) {
5022     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5023     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5024
5025     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5026                      DAG.getIntPtrConstant(4));
5027     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5028                      DAG.getIntPtrConstant(4));
5029     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5030                      DAG.getIntPtrConstant(0));
5031     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5032                      DAG.getIntPtrConstant(0));
5033
5034     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5035     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5036
5037     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5038     N0 = LowerCONCAT_VECTORS(N0, DAG);
5039
5040     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5041                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5042                      N0);
5043     return N0;
5044   }
5045
5046   // v4i16 sdiv ... Convert to float.
5047   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5048   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5049   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5050   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5051   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5052   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5053
5054   // Use reciprocal estimate and two refinement steps.
5055   // float4 recip = vrecpeq_f32(yf);
5056   // recip *= vrecpsq_f32(yf, recip);
5057   // recip *= vrecpsq_f32(yf, recip);
5058   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5059                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5060   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5061                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5062                    BN1, N2);
5063   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5064   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5065                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5066                    BN1, N2);
5067   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5068   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5069   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5070   // and that it will never cause us to return an answer too large).
5071   // float4 result = as_float4(as_int4(xf*recip) + 2);
5072   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5073   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5074   N1 = DAG.getConstant(2, MVT::i32);
5075   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5076   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5077   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5078   // Convert back to integer and return.
5079   // return vmovn_u32(vcvt_s32_f32(result));
5080   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5081   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5082   return N0;
5083 }
5084
5085 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5086   EVT VT = Op.getNode()->getValueType(0);
5087   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5088
5089   unsigned Opc;
5090   bool ExtraOp = false;
5091   switch (Op.getOpcode()) {
5092   default: llvm_unreachable("Invalid code");
5093   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5094   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5095   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5096   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5097   }
5098
5099   if (!ExtraOp)
5100     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5101                        Op.getOperand(1));
5102   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5103                      Op.getOperand(1), Op.getOperand(2));
5104 }
5105
5106 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5107   // Monotonic load/store is legal for all targets
5108   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5109     return Op;
5110
5111   // Aquire/Release load/store is not legal for targets without a
5112   // dmb or equivalent available.
5113   return SDValue();
5114 }
5115
5116
5117 static void
5118 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5119                     SelectionDAG &DAG, unsigned NewOp) {
5120   DebugLoc dl = Node->getDebugLoc();
5121   assert (Node->getValueType(0) == MVT::i64 &&
5122           "Only know how to expand i64 atomics");
5123
5124   SmallVector<SDValue, 6> Ops;
5125   Ops.push_back(Node->getOperand(0)); // Chain
5126   Ops.push_back(Node->getOperand(1)); // Ptr
5127   // Low part of Val1
5128   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5129                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5130   // High part of Val1
5131   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5132                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5133   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5134     // High part of Val1
5135     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5136                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5137     // High part of Val2
5138     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5139                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5140   }
5141   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5142   SDValue Result =
5143     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5144                             cast<MemSDNode>(Node)->getMemOperand());
5145   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5146   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5147   Results.push_back(Result.getValue(2));
5148 }
5149
5150 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5151   switch (Op.getOpcode()) {
5152   default: llvm_unreachable("Don't know how to custom lower this!");
5153   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5154   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5155   case ISD::GlobalAddress:
5156     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5157       LowerGlobalAddressELF(Op, DAG);
5158   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5159   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5160   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5161   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5162   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5163   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5164   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5165   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5166   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5167   case ISD::SINT_TO_FP:
5168   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5169   case ISD::FP_TO_SINT:
5170   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5171   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5172   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5173   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5174   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5175   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5176   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5177   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5178                                                                Subtarget);
5179   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5180   case ISD::SHL:
5181   case ISD::SRL:
5182   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5183   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5184   case ISD::SRL_PARTS:
5185   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5186   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5187   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5188   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5189   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5190   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5191   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5192   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5193   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5194   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5195   case ISD::MUL:           return LowerMUL(Op, DAG);
5196   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5197   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5198   case ISD::ADDC:
5199   case ISD::ADDE:
5200   case ISD::SUBC:
5201   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5202   case ISD::ATOMIC_LOAD:
5203   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5204   }
5205 }
5206
5207 /// ReplaceNodeResults - Replace the results of node with an illegal result
5208 /// type with new values built out of custom code.
5209 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5210                                            SmallVectorImpl<SDValue>&Results,
5211                                            SelectionDAG &DAG) const {
5212   SDValue Res;
5213   switch (N->getOpcode()) {
5214   default:
5215     llvm_unreachable("Don't know how to custom expand this!");
5216   case ISD::BITCAST:
5217     Res = ExpandBITCAST(N, DAG);
5218     break;
5219   case ISD::SRL:
5220   case ISD::SRA:
5221     Res = Expand64BitShift(N, DAG, Subtarget);
5222     break;
5223   case ISD::ATOMIC_LOAD_ADD:
5224     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5225     return;
5226   case ISD::ATOMIC_LOAD_AND:
5227     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5228     return;
5229   case ISD::ATOMIC_LOAD_NAND:
5230     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5231     return;
5232   case ISD::ATOMIC_LOAD_OR:
5233     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5234     return;
5235   case ISD::ATOMIC_LOAD_SUB:
5236     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5237     return;
5238   case ISD::ATOMIC_LOAD_XOR:
5239     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5240     return;
5241   case ISD::ATOMIC_SWAP:
5242     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5243     return;
5244   case ISD::ATOMIC_CMP_SWAP:
5245     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5246     return;
5247   }
5248   if (Res.getNode())
5249     Results.push_back(Res);
5250 }
5251
5252 //===----------------------------------------------------------------------===//
5253 //                           ARM Scheduler Hooks
5254 //===----------------------------------------------------------------------===//
5255
5256 MachineBasicBlock *
5257 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5258                                      MachineBasicBlock *BB,
5259                                      unsigned Size) const {
5260   unsigned dest    = MI->getOperand(0).getReg();
5261   unsigned ptr     = MI->getOperand(1).getReg();
5262   unsigned oldval  = MI->getOperand(2).getReg();
5263   unsigned newval  = MI->getOperand(3).getReg();
5264   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5265   DebugLoc dl = MI->getDebugLoc();
5266   bool isThumb2 = Subtarget->isThumb2();
5267
5268   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5269   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5270     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5271     (const TargetRegisterClass*)&ARM::GPRRegClass);
5272
5273   if (isThumb2) {
5274     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5275     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5276     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5277   }
5278
5279   unsigned ldrOpc, strOpc;
5280   switch (Size) {
5281   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5282   case 1:
5283     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5284     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5285     break;
5286   case 2:
5287     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5288     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5289     break;
5290   case 4:
5291     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5292     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5293     break;
5294   }
5295
5296   MachineFunction *MF = BB->getParent();
5297   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5298   MachineFunction::iterator It = BB;
5299   ++It; // insert the new blocks after the current block
5300
5301   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5302   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5303   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5304   MF->insert(It, loop1MBB);
5305   MF->insert(It, loop2MBB);
5306   MF->insert(It, exitMBB);
5307
5308   // Transfer the remainder of BB and its successor edges to exitMBB.
5309   exitMBB->splice(exitMBB->begin(), BB,
5310                   llvm::next(MachineBasicBlock::iterator(MI)),
5311                   BB->end());
5312   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5313
5314   //  thisMBB:
5315   //   ...
5316   //   fallthrough --> loop1MBB
5317   BB->addSuccessor(loop1MBB);
5318
5319   // loop1MBB:
5320   //   ldrex dest, [ptr]
5321   //   cmp dest, oldval
5322   //   bne exitMBB
5323   BB = loop1MBB;
5324   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5325   if (ldrOpc == ARM::t2LDREX)
5326     MIB.addImm(0);
5327   AddDefaultPred(MIB);
5328   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5329                  .addReg(dest).addReg(oldval));
5330   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5331     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5332   BB->addSuccessor(loop2MBB);
5333   BB->addSuccessor(exitMBB);
5334
5335   // loop2MBB:
5336   //   strex scratch, newval, [ptr]
5337   //   cmp scratch, #0
5338   //   bne loop1MBB
5339   BB = loop2MBB;
5340   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5341   if (strOpc == ARM::t2STREX)
5342     MIB.addImm(0);
5343   AddDefaultPred(MIB);
5344   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5345                  .addReg(scratch).addImm(0));
5346   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5347     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5348   BB->addSuccessor(loop1MBB);
5349   BB->addSuccessor(exitMBB);
5350
5351   //  exitMBB:
5352   //   ...
5353   BB = exitMBB;
5354
5355   MI->eraseFromParent();   // The instruction is gone now.
5356
5357   return BB;
5358 }
5359
5360 MachineBasicBlock *
5361 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5362                                     unsigned Size, unsigned BinOpcode) const {
5363   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5364   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5365
5366   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5367   MachineFunction *MF = BB->getParent();
5368   MachineFunction::iterator It = BB;
5369   ++It;
5370
5371   unsigned dest = MI->getOperand(0).getReg();
5372   unsigned ptr = MI->getOperand(1).getReg();
5373   unsigned incr = MI->getOperand(2).getReg();
5374   DebugLoc dl = MI->getDebugLoc();
5375   bool isThumb2 = Subtarget->isThumb2();
5376
5377   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5378   if (isThumb2) {
5379     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5380     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5381   }
5382
5383   unsigned ldrOpc, strOpc;
5384   switch (Size) {
5385   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5386   case 1:
5387     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5388     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5389     break;
5390   case 2:
5391     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5392     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5393     break;
5394   case 4:
5395     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5396     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5397     break;
5398   }
5399
5400   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5401   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5402   MF->insert(It, loopMBB);
5403   MF->insert(It, exitMBB);
5404
5405   // Transfer the remainder of BB and its successor edges to exitMBB.
5406   exitMBB->splice(exitMBB->begin(), BB,
5407                   llvm::next(MachineBasicBlock::iterator(MI)),
5408                   BB->end());
5409   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5410
5411   const TargetRegisterClass *TRC = isThumb2 ?
5412     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5413     (const TargetRegisterClass*)&ARM::GPRRegClass;
5414   unsigned scratch = MRI.createVirtualRegister(TRC);
5415   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5416
5417   //  thisMBB:
5418   //   ...
5419   //   fallthrough --> loopMBB
5420   BB->addSuccessor(loopMBB);
5421
5422   //  loopMBB:
5423   //   ldrex dest, ptr
5424   //   <binop> scratch2, dest, incr
5425   //   strex scratch, scratch2, ptr
5426   //   cmp scratch, #0
5427   //   bne- loopMBB
5428   //   fallthrough --> exitMBB
5429   BB = loopMBB;
5430   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5431   if (ldrOpc == ARM::t2LDREX)
5432     MIB.addImm(0);
5433   AddDefaultPred(MIB);
5434   if (BinOpcode) {
5435     // operand order needs to go the other way for NAND
5436     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5437       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5438                      addReg(incr).addReg(dest)).addReg(0);
5439     else
5440       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5441                      addReg(dest).addReg(incr)).addReg(0);
5442   }
5443
5444   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5445   if (strOpc == ARM::t2STREX)
5446     MIB.addImm(0);
5447   AddDefaultPred(MIB);
5448   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5449                  .addReg(scratch).addImm(0));
5450   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5451     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5452
5453   BB->addSuccessor(loopMBB);
5454   BB->addSuccessor(exitMBB);
5455
5456   //  exitMBB:
5457   //   ...
5458   BB = exitMBB;
5459
5460   MI->eraseFromParent();   // The instruction is gone now.
5461
5462   return BB;
5463 }
5464
5465 MachineBasicBlock *
5466 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5467                                           MachineBasicBlock *BB,
5468                                           unsigned Size,
5469                                           bool signExtend,
5470                                           ARMCC::CondCodes Cond) const {
5471   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5472
5473   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5474   MachineFunction *MF = BB->getParent();
5475   MachineFunction::iterator It = BB;
5476   ++It;
5477
5478   unsigned dest = MI->getOperand(0).getReg();
5479   unsigned ptr = MI->getOperand(1).getReg();
5480   unsigned incr = MI->getOperand(2).getReg();
5481   unsigned oldval = dest;
5482   DebugLoc dl = MI->getDebugLoc();
5483   bool isThumb2 = Subtarget->isThumb2();
5484
5485   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5486   if (isThumb2) {
5487     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5488     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5489   }
5490
5491   unsigned ldrOpc, strOpc, extendOpc;
5492   switch (Size) {
5493   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5494   case 1:
5495     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5496     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5497     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5498     break;
5499   case 2:
5500     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5501     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5502     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5503     break;
5504   case 4:
5505     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5506     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5507     extendOpc = 0;
5508     break;
5509   }
5510
5511   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5512   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5513   MF->insert(It, loopMBB);
5514   MF->insert(It, exitMBB);
5515
5516   // Transfer the remainder of BB and its successor edges to exitMBB.
5517   exitMBB->splice(exitMBB->begin(), BB,
5518                   llvm::next(MachineBasicBlock::iterator(MI)),
5519                   BB->end());
5520   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5521
5522   const TargetRegisterClass *TRC = isThumb2 ?
5523     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5524     (const TargetRegisterClass*)&ARM::GPRRegClass;
5525   unsigned scratch = MRI.createVirtualRegister(TRC);
5526   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5527
5528   //  thisMBB:
5529   //   ...
5530   //   fallthrough --> loopMBB
5531   BB->addSuccessor(loopMBB);
5532
5533   //  loopMBB:
5534   //   ldrex dest, ptr
5535   //   (sign extend dest, if required)
5536   //   cmp dest, incr
5537   //   cmov.cond scratch2, dest, incr
5538   //   strex scratch, scratch2, ptr
5539   //   cmp scratch, #0
5540   //   bne- loopMBB
5541   //   fallthrough --> exitMBB
5542   BB = loopMBB;
5543   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5544   if (ldrOpc == ARM::t2LDREX)
5545     MIB.addImm(0);
5546   AddDefaultPred(MIB);
5547
5548   // Sign extend the value, if necessary.
5549   if (signExtend && extendOpc) {
5550     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5551     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5552                      .addReg(dest)
5553                      .addImm(0));
5554   }
5555
5556   // Build compare and cmov instructions.
5557   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5558                  .addReg(oldval).addReg(incr));
5559   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5560          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5561
5562   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5563   if (strOpc == ARM::t2STREX)
5564     MIB.addImm(0);
5565   AddDefaultPred(MIB);
5566   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5567                  .addReg(scratch).addImm(0));
5568   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5569     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5570
5571   BB->addSuccessor(loopMBB);
5572   BB->addSuccessor(exitMBB);
5573
5574   //  exitMBB:
5575   //   ...
5576   BB = exitMBB;
5577
5578   MI->eraseFromParent();   // The instruction is gone now.
5579
5580   return BB;
5581 }
5582
5583 MachineBasicBlock *
5584 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5585                                       unsigned Op1, unsigned Op2,
5586                                       bool NeedsCarry, bool IsCmpxchg) const {
5587   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5588   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5589
5590   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5591   MachineFunction *MF = BB->getParent();
5592   MachineFunction::iterator It = BB;
5593   ++It;
5594
5595   unsigned destlo = MI->getOperand(0).getReg();
5596   unsigned desthi = MI->getOperand(1).getReg();
5597   unsigned ptr = MI->getOperand(2).getReg();
5598   unsigned vallo = MI->getOperand(3).getReg();
5599   unsigned valhi = MI->getOperand(4).getReg();
5600   DebugLoc dl = MI->getDebugLoc();
5601   bool isThumb2 = Subtarget->isThumb2();
5602
5603   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5604   if (isThumb2) {
5605     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5606     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5607     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5608   }
5609
5610   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5611   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5612
5613   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5614   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5615   if (IsCmpxchg) {
5616     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5617     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5618   }
5619   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5620   MF->insert(It, loopMBB);
5621   if (IsCmpxchg) {
5622     MF->insert(It, contBB);
5623     MF->insert(It, cont2BB);
5624   }
5625   MF->insert(It, exitMBB);
5626
5627   // Transfer the remainder of BB and its successor edges to exitMBB.
5628   exitMBB->splice(exitMBB->begin(), BB,
5629                   llvm::next(MachineBasicBlock::iterator(MI)),
5630                   BB->end());
5631   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5632
5633   const TargetRegisterClass *TRC = isThumb2 ?
5634     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5635     (const TargetRegisterClass*)&ARM::GPRRegClass;
5636   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5637
5638   //  thisMBB:
5639   //   ...
5640   //   fallthrough --> loopMBB
5641   BB->addSuccessor(loopMBB);
5642
5643   //  loopMBB:
5644   //   ldrexd r2, r3, ptr
5645   //   <binopa> r0, r2, incr
5646   //   <binopb> r1, r3, incr
5647   //   strexd storesuccess, r0, r1, ptr
5648   //   cmp storesuccess, #0
5649   //   bne- loopMBB
5650   //   fallthrough --> exitMBB
5651   //
5652   // Note that the registers are explicitly specified because there is not any
5653   // way to force the register allocator to allocate a register pair.
5654   //
5655   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5656   // need to properly enforce the restriction that the two output registers
5657   // for ldrexd must be different.
5658   BB = loopMBB;
5659   // Load
5660   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5661                  .addReg(ARM::R2, RegState::Define)
5662                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5663   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5664   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5665   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5666
5667   if (IsCmpxchg) {
5668     // Add early exit
5669     for (unsigned i = 0; i < 2; i++) {
5670       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5671                                                          ARM::CMPrr))
5672                      .addReg(i == 0 ? destlo : desthi)
5673                      .addReg(i == 0 ? vallo : valhi));
5674       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5675         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5676       BB->addSuccessor(exitMBB);
5677       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5678       BB = (i == 0 ? contBB : cont2BB);
5679     }
5680
5681     // Copy to physregs for strexd
5682     unsigned setlo = MI->getOperand(5).getReg();
5683     unsigned sethi = MI->getOperand(6).getReg();
5684     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5685     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5686   } else if (Op1) {
5687     // Perform binary operation
5688     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5689                    .addReg(destlo).addReg(vallo))
5690         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5691     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5692                    .addReg(desthi).addReg(valhi)).addReg(0);
5693   } else {
5694     // Copy to physregs for strexd
5695     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5696     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5697   }
5698
5699   // Store
5700   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5701                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5702   // Cmp+jump
5703   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5704                  .addReg(storesuccess).addImm(0));
5705   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5706     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5707
5708   BB->addSuccessor(loopMBB);
5709   BB->addSuccessor(exitMBB);
5710
5711   //  exitMBB:
5712   //   ...
5713   BB = exitMBB;
5714
5715   MI->eraseFromParent();   // The instruction is gone now.
5716
5717   return BB;
5718 }
5719
5720 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5721 /// registers the function context.
5722 void ARMTargetLowering::
5723 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5724                        MachineBasicBlock *DispatchBB, int FI) const {
5725   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5726   DebugLoc dl = MI->getDebugLoc();
5727   MachineFunction *MF = MBB->getParent();
5728   MachineRegisterInfo *MRI = &MF->getRegInfo();
5729   MachineConstantPool *MCP = MF->getConstantPool();
5730   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5731   const Function *F = MF->getFunction();
5732
5733   bool isThumb = Subtarget->isThumb();
5734   bool isThumb2 = Subtarget->isThumb2();
5735
5736   unsigned PCLabelId = AFI->createPICLabelUId();
5737   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5738   ARMConstantPoolValue *CPV =
5739     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5740   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5741
5742   const TargetRegisterClass *TRC = isThumb ?
5743     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5744     (const TargetRegisterClass*)&ARM::GPRRegClass;
5745
5746   // Grab constant pool and fixed stack memory operands.
5747   MachineMemOperand *CPMMO =
5748     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5749                              MachineMemOperand::MOLoad, 4, 4);
5750
5751   MachineMemOperand *FIMMOSt =
5752     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5753                              MachineMemOperand::MOStore, 4, 4);
5754
5755   // Load the address of the dispatch MBB into the jump buffer.
5756   if (isThumb2) {
5757     // Incoming value: jbuf
5758     //   ldr.n  r5, LCPI1_1
5759     //   orr    r5, r5, #1
5760     //   add    r5, pc
5761     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5762     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5763     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5764                    .addConstantPoolIndex(CPI)
5765                    .addMemOperand(CPMMO));
5766     // Set the low bit because of thumb mode.
5767     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5768     AddDefaultCC(
5769       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5770                      .addReg(NewVReg1, RegState::Kill)
5771                      .addImm(0x01)));
5772     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5773     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5774       .addReg(NewVReg2, RegState::Kill)
5775       .addImm(PCLabelId);
5776     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5777                    .addReg(NewVReg3, RegState::Kill)
5778                    .addFrameIndex(FI)
5779                    .addImm(36)  // &jbuf[1] :: pc
5780                    .addMemOperand(FIMMOSt));
5781   } else if (isThumb) {
5782     // Incoming value: jbuf
5783     //   ldr.n  r1, LCPI1_4
5784     //   add    r1, pc
5785     //   mov    r2, #1
5786     //   orrs   r1, r2
5787     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5788     //   str    r1, [r2]
5789     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5790     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5791                    .addConstantPoolIndex(CPI)
5792                    .addMemOperand(CPMMO));
5793     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5794     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5795       .addReg(NewVReg1, RegState::Kill)
5796       .addImm(PCLabelId);
5797     // Set the low bit because of thumb mode.
5798     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5799     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5800                    .addReg(ARM::CPSR, RegState::Define)
5801                    .addImm(1));
5802     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5803     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5804                    .addReg(ARM::CPSR, RegState::Define)
5805                    .addReg(NewVReg2, RegState::Kill)
5806                    .addReg(NewVReg3, RegState::Kill));
5807     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5808     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5809                    .addFrameIndex(FI)
5810                    .addImm(36)); // &jbuf[1] :: pc
5811     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5812                    .addReg(NewVReg4, RegState::Kill)
5813                    .addReg(NewVReg5, RegState::Kill)
5814                    .addImm(0)
5815                    .addMemOperand(FIMMOSt));
5816   } else {
5817     // Incoming value: jbuf
5818     //   ldr  r1, LCPI1_1
5819     //   add  r1, pc, r1
5820     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5821     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5822     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5823                    .addConstantPoolIndex(CPI)
5824                    .addImm(0)
5825                    .addMemOperand(CPMMO));
5826     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5827     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5828                    .addReg(NewVReg1, RegState::Kill)
5829                    .addImm(PCLabelId));
5830     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5831                    .addReg(NewVReg2, RegState::Kill)
5832                    .addFrameIndex(FI)
5833                    .addImm(36)  // &jbuf[1] :: pc
5834                    .addMemOperand(FIMMOSt));
5835   }
5836 }
5837
5838 MachineBasicBlock *ARMTargetLowering::
5839 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5840   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5841   DebugLoc dl = MI->getDebugLoc();
5842   MachineFunction *MF = MBB->getParent();
5843   MachineRegisterInfo *MRI = &MF->getRegInfo();
5844   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5845   MachineFrameInfo *MFI = MF->getFrameInfo();
5846   int FI = MFI->getFunctionContextIndex();
5847
5848   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5849     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5850     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5851
5852   // Get a mapping of the call site numbers to all of the landing pads they're
5853   // associated with.
5854   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5855   unsigned MaxCSNum = 0;
5856   MachineModuleInfo &MMI = MF->getMMI();
5857   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5858        ++BB) {
5859     if (!BB->isLandingPad()) continue;
5860
5861     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5862     // pad.
5863     for (MachineBasicBlock::iterator
5864            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5865       if (!II->isEHLabel()) continue;
5866
5867       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5868       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5869
5870       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5871       for (SmallVectorImpl<unsigned>::iterator
5872              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5873            CSI != CSE; ++CSI) {
5874         CallSiteNumToLPad[*CSI].push_back(BB);
5875         MaxCSNum = std::max(MaxCSNum, *CSI);
5876       }
5877       break;
5878     }
5879   }
5880
5881   // Get an ordered list of the machine basic blocks for the jump table.
5882   std::vector<MachineBasicBlock*> LPadList;
5883   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5884   LPadList.reserve(CallSiteNumToLPad.size());
5885   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5886     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5887     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5888            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5889       LPadList.push_back(*II);
5890       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5891     }
5892   }
5893
5894   assert(!LPadList.empty() &&
5895          "No landing pad destinations for the dispatch jump table!");
5896
5897   // Create the jump table and associated information.
5898   MachineJumpTableInfo *JTI =
5899     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5900   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5901   unsigned UId = AFI->createJumpTableUId();
5902
5903   // Create the MBBs for the dispatch code.
5904
5905   // Shove the dispatch's address into the return slot in the function context.
5906   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5907   DispatchBB->setIsLandingPad();
5908
5909   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5910   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5911   DispatchBB->addSuccessor(TrapBB);
5912
5913   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5914   DispatchBB->addSuccessor(DispContBB);
5915
5916   // Insert and MBBs.
5917   MF->insert(MF->end(), DispatchBB);
5918   MF->insert(MF->end(), DispContBB);
5919   MF->insert(MF->end(), TrapBB);
5920
5921   // Insert code into the entry block that creates and registers the function
5922   // context.
5923   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5924
5925   MachineMemOperand *FIMMOLd =
5926     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5927                              MachineMemOperand::MOLoad |
5928                              MachineMemOperand::MOVolatile, 4, 4);
5929
5930   if (AFI->isThumb1OnlyFunction())
5931     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5932   else if (!Subtarget->hasVFP2())
5933     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5934   else
5935     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5936
5937   unsigned NumLPads = LPadList.size();
5938   if (Subtarget->isThumb2()) {
5939     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5940     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5941                    .addFrameIndex(FI)
5942                    .addImm(4)
5943                    .addMemOperand(FIMMOLd));
5944
5945     if (NumLPads < 256) {
5946       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5947                      .addReg(NewVReg1)
5948                      .addImm(LPadList.size()));
5949     } else {
5950       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5951       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5952                      .addImm(NumLPads & 0xFFFF));
5953
5954       unsigned VReg2 = VReg1;
5955       if ((NumLPads & 0xFFFF0000) != 0) {
5956         VReg2 = MRI->createVirtualRegister(TRC);
5957         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5958                        .addReg(VReg1)
5959                        .addImm(NumLPads >> 16));
5960       }
5961
5962       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5963                      .addReg(NewVReg1)
5964                      .addReg(VReg2));
5965     }
5966
5967     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5968       .addMBB(TrapBB)
5969       .addImm(ARMCC::HI)
5970       .addReg(ARM::CPSR);
5971
5972     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5973     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5974                    .addJumpTableIndex(MJTI)
5975                    .addImm(UId));
5976
5977     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5978     AddDefaultCC(
5979       AddDefaultPred(
5980         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5981         .addReg(NewVReg3, RegState::Kill)
5982         .addReg(NewVReg1)
5983         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5984
5985     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5986       .addReg(NewVReg4, RegState::Kill)
5987       .addReg(NewVReg1)
5988       .addJumpTableIndex(MJTI)
5989       .addImm(UId);
5990   } else if (Subtarget->isThumb()) {
5991     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5992     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
5993                    .addFrameIndex(FI)
5994                    .addImm(1)
5995                    .addMemOperand(FIMMOLd));
5996
5997     if (NumLPads < 256) {
5998       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
5999                      .addReg(NewVReg1)
6000                      .addImm(NumLPads));
6001     } else {
6002       MachineConstantPool *ConstantPool = MF->getConstantPool();
6003       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6004       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6005
6006       // MachineConstantPool wants an explicit alignment.
6007       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6008       if (Align == 0)
6009         Align = getTargetData()->getTypeAllocSize(C->getType());
6010       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6011
6012       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6013       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6014                      .addReg(VReg1, RegState::Define)
6015                      .addConstantPoolIndex(Idx));
6016       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6017                      .addReg(NewVReg1)
6018                      .addReg(VReg1));
6019     }
6020
6021     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6022       .addMBB(TrapBB)
6023       .addImm(ARMCC::HI)
6024       .addReg(ARM::CPSR);
6025
6026     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6027     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6028                    .addReg(ARM::CPSR, RegState::Define)
6029                    .addReg(NewVReg1)
6030                    .addImm(2));
6031
6032     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6033     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6034                    .addJumpTableIndex(MJTI)
6035                    .addImm(UId));
6036
6037     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6038     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6039                    .addReg(ARM::CPSR, RegState::Define)
6040                    .addReg(NewVReg2, RegState::Kill)
6041                    .addReg(NewVReg3));
6042
6043     MachineMemOperand *JTMMOLd =
6044       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6045                                MachineMemOperand::MOLoad, 4, 4);
6046
6047     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6048     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6049                    .addReg(NewVReg4, RegState::Kill)
6050                    .addImm(0)
6051                    .addMemOperand(JTMMOLd));
6052
6053     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6054     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6055                    .addReg(ARM::CPSR, RegState::Define)
6056                    .addReg(NewVReg5, RegState::Kill)
6057                    .addReg(NewVReg3));
6058
6059     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6060       .addReg(NewVReg6, RegState::Kill)
6061       .addJumpTableIndex(MJTI)
6062       .addImm(UId);
6063   } else {
6064     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6065     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6066                    .addFrameIndex(FI)
6067                    .addImm(4)
6068                    .addMemOperand(FIMMOLd));
6069
6070     if (NumLPads < 256) {
6071       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6072                      .addReg(NewVReg1)
6073                      .addImm(NumLPads));
6074     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6075       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6076       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6077                      .addImm(NumLPads & 0xFFFF));
6078
6079       unsigned VReg2 = VReg1;
6080       if ((NumLPads & 0xFFFF0000) != 0) {
6081         VReg2 = MRI->createVirtualRegister(TRC);
6082         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6083                        .addReg(VReg1)
6084                        .addImm(NumLPads >> 16));
6085       }
6086
6087       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6088                      .addReg(NewVReg1)
6089                      .addReg(VReg2));
6090     } else {
6091       MachineConstantPool *ConstantPool = MF->getConstantPool();
6092       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6093       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6094
6095       // MachineConstantPool wants an explicit alignment.
6096       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6097       if (Align == 0)
6098         Align = getTargetData()->getTypeAllocSize(C->getType());
6099       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6100
6101       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6102       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6103                      .addReg(VReg1, RegState::Define)
6104                      .addConstantPoolIndex(Idx)
6105                      .addImm(0));
6106       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6107                      .addReg(NewVReg1)
6108                      .addReg(VReg1, RegState::Kill));
6109     }
6110
6111     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6112       .addMBB(TrapBB)
6113       .addImm(ARMCC::HI)
6114       .addReg(ARM::CPSR);
6115
6116     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6117     AddDefaultCC(
6118       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6119                      .addReg(NewVReg1)
6120                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6121     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6122     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6123                    .addJumpTableIndex(MJTI)
6124                    .addImm(UId));
6125
6126     MachineMemOperand *JTMMOLd =
6127       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6128                                MachineMemOperand::MOLoad, 4, 4);
6129     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6130     AddDefaultPred(
6131       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6132       .addReg(NewVReg3, RegState::Kill)
6133       .addReg(NewVReg4)
6134       .addImm(0)
6135       .addMemOperand(JTMMOLd));
6136
6137     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6138       .addReg(NewVReg5, RegState::Kill)
6139       .addReg(NewVReg4)
6140       .addJumpTableIndex(MJTI)
6141       .addImm(UId);
6142   }
6143
6144   // Add the jump table entries as successors to the MBB.
6145   MachineBasicBlock *PrevMBB = 0;
6146   for (std::vector<MachineBasicBlock*>::iterator
6147          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6148     MachineBasicBlock *CurMBB = *I;
6149     if (PrevMBB != CurMBB)
6150       DispContBB->addSuccessor(CurMBB);
6151     PrevMBB = CurMBB;
6152   }
6153
6154   // N.B. the order the invoke BBs are processed in doesn't matter here.
6155   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6156   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6157   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6158   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6159   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6160          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6161     MachineBasicBlock *BB = *I;
6162
6163     // Remove the landing pad successor from the invoke block and replace it
6164     // with the new dispatch block.
6165     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6166                                                   BB->succ_end());
6167     while (!Successors.empty()) {
6168       MachineBasicBlock *SMBB = Successors.pop_back_val();
6169       if (SMBB->isLandingPad()) {
6170         BB->removeSuccessor(SMBB);
6171         MBBLPads.push_back(SMBB);
6172       }
6173     }
6174
6175     BB->addSuccessor(DispatchBB);
6176
6177     // Find the invoke call and mark all of the callee-saved registers as
6178     // 'implicit defined' so that they're spilled. This prevents code from
6179     // moving instructions to before the EH block, where they will never be
6180     // executed.
6181     for (MachineBasicBlock::reverse_iterator
6182            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6183       if (!II->isCall()) continue;
6184
6185       DenseMap<unsigned, bool> DefRegs;
6186       for (MachineInstr::mop_iterator
6187              OI = II->operands_begin(), OE = II->operands_end();
6188            OI != OE; ++OI) {
6189         if (!OI->isReg()) continue;
6190         DefRegs[OI->getReg()] = true;
6191       }
6192
6193       MachineInstrBuilder MIB(&*II);
6194
6195       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6196         unsigned Reg = SavedRegs[i];
6197         if (Subtarget->isThumb2() &&
6198             !ARM::tGPRRegClass.contains(Reg) &&
6199             !ARM::hGPRRegClass.contains(Reg))
6200           continue;
6201         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6202           continue;
6203         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6204           continue;
6205         if (!DefRegs[Reg])
6206           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6207       }
6208
6209       break;
6210     }
6211   }
6212
6213   // Mark all former landing pads as non-landing pads. The dispatch is the only
6214   // landing pad now.
6215   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6216          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6217     (*I)->setIsLandingPad(false);
6218
6219   // The instruction is gone now.
6220   MI->eraseFromParent();
6221
6222   return MBB;
6223 }
6224
6225 static
6226 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6227   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6228        E = MBB->succ_end(); I != E; ++I)
6229     if (*I != Succ)
6230       return *I;
6231   llvm_unreachable("Expecting a BB with two successors!");
6232 }
6233
6234 MachineBasicBlock *
6235 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6236                                                MachineBasicBlock *BB) const {
6237   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6238   DebugLoc dl = MI->getDebugLoc();
6239   bool isThumb2 = Subtarget->isThumb2();
6240   switch (MI->getOpcode()) {
6241   default: {
6242     MI->dump();
6243     llvm_unreachable("Unexpected instr type to insert");
6244   }
6245   // The Thumb2 pre-indexed stores have the same MI operands, they just
6246   // define them differently in the .td files from the isel patterns, so
6247   // they need pseudos.
6248   case ARM::t2STR_preidx:
6249     MI->setDesc(TII->get(ARM::t2STR_PRE));
6250     return BB;
6251   case ARM::t2STRB_preidx:
6252     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6253     return BB;
6254   case ARM::t2STRH_preidx:
6255     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6256     return BB;
6257
6258   case ARM::STRi_preidx:
6259   case ARM::STRBi_preidx: {
6260     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6261       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6262     // Decode the offset.
6263     unsigned Offset = MI->getOperand(4).getImm();
6264     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6265     Offset = ARM_AM::getAM2Offset(Offset);
6266     if (isSub)
6267       Offset = -Offset;
6268
6269     MachineMemOperand *MMO = *MI->memoperands_begin();
6270     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6271       .addOperand(MI->getOperand(0))  // Rn_wb
6272       .addOperand(MI->getOperand(1))  // Rt
6273       .addOperand(MI->getOperand(2))  // Rn
6274       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6275       .addOperand(MI->getOperand(5))  // pred
6276       .addOperand(MI->getOperand(6))
6277       .addMemOperand(MMO);
6278     MI->eraseFromParent();
6279     return BB;
6280   }
6281   case ARM::STRr_preidx:
6282   case ARM::STRBr_preidx:
6283   case ARM::STRH_preidx: {
6284     unsigned NewOpc;
6285     switch (MI->getOpcode()) {
6286     default: llvm_unreachable("unexpected opcode!");
6287     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6288     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6289     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6290     }
6291     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6292     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6293       MIB.addOperand(MI->getOperand(i));
6294     MI->eraseFromParent();
6295     return BB;
6296   }
6297   case ARM::ATOMIC_LOAD_ADD_I8:
6298      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6299   case ARM::ATOMIC_LOAD_ADD_I16:
6300      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6301   case ARM::ATOMIC_LOAD_ADD_I32:
6302      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6303
6304   case ARM::ATOMIC_LOAD_AND_I8:
6305      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6306   case ARM::ATOMIC_LOAD_AND_I16:
6307      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6308   case ARM::ATOMIC_LOAD_AND_I32:
6309      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6310
6311   case ARM::ATOMIC_LOAD_OR_I8:
6312      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6313   case ARM::ATOMIC_LOAD_OR_I16:
6314      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6315   case ARM::ATOMIC_LOAD_OR_I32:
6316      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6317
6318   case ARM::ATOMIC_LOAD_XOR_I8:
6319      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6320   case ARM::ATOMIC_LOAD_XOR_I16:
6321      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6322   case ARM::ATOMIC_LOAD_XOR_I32:
6323      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6324
6325   case ARM::ATOMIC_LOAD_NAND_I8:
6326      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6327   case ARM::ATOMIC_LOAD_NAND_I16:
6328      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6329   case ARM::ATOMIC_LOAD_NAND_I32:
6330      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6331
6332   case ARM::ATOMIC_LOAD_SUB_I8:
6333      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6334   case ARM::ATOMIC_LOAD_SUB_I16:
6335      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6336   case ARM::ATOMIC_LOAD_SUB_I32:
6337      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6338
6339   case ARM::ATOMIC_LOAD_MIN_I8:
6340      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6341   case ARM::ATOMIC_LOAD_MIN_I16:
6342      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6343   case ARM::ATOMIC_LOAD_MIN_I32:
6344      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6345
6346   case ARM::ATOMIC_LOAD_MAX_I8:
6347      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6348   case ARM::ATOMIC_LOAD_MAX_I16:
6349      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6350   case ARM::ATOMIC_LOAD_MAX_I32:
6351      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6352
6353   case ARM::ATOMIC_LOAD_UMIN_I8:
6354      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6355   case ARM::ATOMIC_LOAD_UMIN_I16:
6356      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6357   case ARM::ATOMIC_LOAD_UMIN_I32:
6358      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6359
6360   case ARM::ATOMIC_LOAD_UMAX_I8:
6361      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6362   case ARM::ATOMIC_LOAD_UMAX_I16:
6363      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6364   case ARM::ATOMIC_LOAD_UMAX_I32:
6365      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6366
6367   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6368   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6369   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6370
6371   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6372   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6373   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6374
6375
6376   case ARM::ATOMADD6432:
6377     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6378                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6379                               /*NeedsCarry*/ true);
6380   case ARM::ATOMSUB6432:
6381     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6382                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6383                               /*NeedsCarry*/ true);
6384   case ARM::ATOMOR6432:
6385     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6386                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6387   case ARM::ATOMXOR6432:
6388     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6389                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6390   case ARM::ATOMAND6432:
6391     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6392                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6393   case ARM::ATOMSWAP6432:
6394     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6395   case ARM::ATOMCMPXCHG6432:
6396     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6397                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6398                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6399
6400   case ARM::tMOVCCr_pseudo: {
6401     // To "insert" a SELECT_CC instruction, we actually have to insert the
6402     // diamond control-flow pattern.  The incoming instruction knows the
6403     // destination vreg to set, the condition code register to branch on, the
6404     // true/false values to select between, and a branch opcode to use.
6405     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6406     MachineFunction::iterator It = BB;
6407     ++It;
6408
6409     //  thisMBB:
6410     //  ...
6411     //   TrueVal = ...
6412     //   cmpTY ccX, r1, r2
6413     //   bCC copy1MBB
6414     //   fallthrough --> copy0MBB
6415     MachineBasicBlock *thisMBB  = BB;
6416     MachineFunction *F = BB->getParent();
6417     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6418     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6419     F->insert(It, copy0MBB);
6420     F->insert(It, sinkMBB);
6421
6422     // Transfer the remainder of BB and its successor edges to sinkMBB.
6423     sinkMBB->splice(sinkMBB->begin(), BB,
6424                     llvm::next(MachineBasicBlock::iterator(MI)),
6425                     BB->end());
6426     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6427
6428     BB->addSuccessor(copy0MBB);
6429     BB->addSuccessor(sinkMBB);
6430
6431     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6432       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6433
6434     //  copy0MBB:
6435     //   %FalseValue = ...
6436     //   # fallthrough to sinkMBB
6437     BB = copy0MBB;
6438
6439     // Update machine-CFG edges
6440     BB->addSuccessor(sinkMBB);
6441
6442     //  sinkMBB:
6443     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6444     //  ...
6445     BB = sinkMBB;
6446     BuildMI(*BB, BB->begin(), dl,
6447             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6448       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6449       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6450
6451     MI->eraseFromParent();   // The pseudo instruction is gone now.
6452     return BB;
6453   }
6454
6455   case ARM::BCCi64:
6456   case ARM::BCCZi64: {
6457     // If there is an unconditional branch to the other successor, remove it.
6458     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6459
6460     // Compare both parts that make up the double comparison separately for
6461     // equality.
6462     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6463
6464     unsigned LHS1 = MI->getOperand(1).getReg();
6465     unsigned LHS2 = MI->getOperand(2).getReg();
6466     if (RHSisZero) {
6467       AddDefaultPred(BuildMI(BB, dl,
6468                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6469                      .addReg(LHS1).addImm(0));
6470       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6471         .addReg(LHS2).addImm(0)
6472         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6473     } else {
6474       unsigned RHS1 = MI->getOperand(3).getReg();
6475       unsigned RHS2 = MI->getOperand(4).getReg();
6476       AddDefaultPred(BuildMI(BB, dl,
6477                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6478                      .addReg(LHS1).addReg(RHS1));
6479       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6480         .addReg(LHS2).addReg(RHS2)
6481         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6482     }
6483
6484     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6485     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6486     if (MI->getOperand(0).getImm() == ARMCC::NE)
6487       std::swap(destMBB, exitMBB);
6488
6489     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6490       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6491     if (isThumb2)
6492       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6493     else
6494       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6495
6496     MI->eraseFromParent();   // The pseudo instruction is gone now.
6497     return BB;
6498   }
6499
6500   case ARM::Int_eh_sjlj_setjmp:
6501   case ARM::Int_eh_sjlj_setjmp_nofp:
6502   case ARM::tInt_eh_sjlj_setjmp:
6503   case ARM::t2Int_eh_sjlj_setjmp:
6504   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6505     EmitSjLjDispatchBlock(MI, BB);
6506     return BB;
6507
6508   case ARM::ABS:
6509   case ARM::t2ABS: {
6510     // To insert an ABS instruction, we have to insert the
6511     // diamond control-flow pattern.  The incoming instruction knows the
6512     // source vreg to test against 0, the destination vreg to set,
6513     // the condition code register to branch on, the
6514     // true/false values to select between, and a branch opcode to use.
6515     // It transforms
6516     //     V1 = ABS V0
6517     // into
6518     //     V2 = MOVS V0
6519     //     BCC                      (branch to SinkBB if V0 >= 0)
6520     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6521     //     SinkBB: V1 = PHI(V2, V3)
6522     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6523     MachineFunction::iterator BBI = BB;
6524     ++BBI;
6525     MachineFunction *Fn = BB->getParent();
6526     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6527     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6528     Fn->insert(BBI, RSBBB);
6529     Fn->insert(BBI, SinkBB);
6530
6531     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6532     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6533     bool isThumb2 = Subtarget->isThumb2();
6534     MachineRegisterInfo &MRI = Fn->getRegInfo();
6535     // In Thumb mode S must not be specified if source register is the SP or
6536     // PC and if destination register is the SP, so restrict register class
6537     unsigned NewMovDstReg = MRI.createVirtualRegister(isThumb2 ?
6538       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6539       (const TargetRegisterClass*)&ARM::GPRRegClass);
6540     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6541       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6542       (const TargetRegisterClass*)&ARM::GPRRegClass);
6543
6544     // Transfer the remainder of BB and its successor edges to sinkMBB.
6545     SinkBB->splice(SinkBB->begin(), BB,
6546       llvm::next(MachineBasicBlock::iterator(MI)),
6547       BB->end());
6548     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6549
6550     BB->addSuccessor(RSBBB);
6551     BB->addSuccessor(SinkBB);
6552
6553     // fall through to SinkMBB
6554     RSBBB->addSuccessor(SinkBB);
6555
6556     // insert a movs at the end of BB
6557     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6558       NewMovDstReg)
6559       .addReg(ABSSrcReg, RegState::Kill)
6560       .addImm((unsigned)ARMCC::AL).addReg(0)
6561       .addReg(ARM::CPSR, RegState::Define);
6562
6563     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6564     BuildMI(BB, dl,
6565       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6566       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6567
6568     // insert rsbri in RSBBB
6569     // Note: BCC and rsbri will be converted into predicated rsbmi
6570     // by if-conversion pass
6571     BuildMI(*RSBBB, RSBBB->begin(), dl,
6572       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6573       .addReg(NewMovDstReg, RegState::Kill)
6574       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6575
6576     // insert PHI in SinkBB,
6577     // reuse ABSDstReg to not change uses of ABS instruction
6578     BuildMI(*SinkBB, SinkBB->begin(), dl,
6579       TII->get(ARM::PHI), ABSDstReg)
6580       .addReg(NewRsbDstReg).addMBB(RSBBB)
6581       .addReg(NewMovDstReg).addMBB(BB);
6582
6583     // remove ABS instruction
6584     MI->eraseFromParent();
6585
6586     // return last added BB
6587     return SinkBB;
6588   }
6589   }
6590 }
6591
6592 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6593                                                       SDNode *Node) const {
6594   if (!MI->hasPostISelHook()) {
6595     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6596            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6597     return;
6598   }
6599
6600   const MCInstrDesc *MCID = &MI->getDesc();
6601   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6602   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6603   // operand is still set to noreg. If needed, set the optional operand's
6604   // register to CPSR, and remove the redundant implicit def.
6605   //
6606   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6607
6608   // Rename pseudo opcodes.
6609   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6610   if (NewOpc) {
6611     const ARMBaseInstrInfo *TII =
6612       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6613     MCID = &TII->get(NewOpc);
6614
6615     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6616            "converted opcode should be the same except for cc_out");
6617
6618     MI->setDesc(*MCID);
6619
6620     // Add the optional cc_out operand
6621     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6622   }
6623   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6624
6625   // Any ARM instruction that sets the 's' bit should specify an optional
6626   // "cc_out" operand in the last operand position.
6627   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6628     assert(!NewOpc && "Optional cc_out operand required");
6629     return;
6630   }
6631   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6632   // since we already have an optional CPSR def.
6633   bool definesCPSR = false;
6634   bool deadCPSR = false;
6635   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6636        i != e; ++i) {
6637     const MachineOperand &MO = MI->getOperand(i);
6638     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6639       definesCPSR = true;
6640       if (MO.isDead())
6641         deadCPSR = true;
6642       MI->RemoveOperand(i);
6643       break;
6644     }
6645   }
6646   if (!definesCPSR) {
6647     assert(!NewOpc && "Optional cc_out operand required");
6648     return;
6649   }
6650   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6651   if (deadCPSR) {
6652     assert(!MI->getOperand(ccOutIdx).getReg() &&
6653            "expect uninitialized optional cc_out operand");
6654     return;
6655   }
6656
6657   // If this instruction was defined with an optional CPSR def and its dag node
6658   // had a live implicit CPSR def, then activate the optional CPSR def.
6659   MachineOperand &MO = MI->getOperand(ccOutIdx);
6660   MO.setReg(ARM::CPSR);
6661   MO.setIsDef(true);
6662 }
6663
6664 //===----------------------------------------------------------------------===//
6665 //                           ARM Optimization Hooks
6666 //===----------------------------------------------------------------------===//
6667
6668 static
6669 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6670                             TargetLowering::DAGCombinerInfo &DCI) {
6671   SelectionDAG &DAG = DCI.DAG;
6672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6673   EVT VT = N->getValueType(0);
6674   unsigned Opc = N->getOpcode();
6675   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6676   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6677   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6678   ISD::CondCode CC = ISD::SETCC_INVALID;
6679
6680   if (isSlctCC) {
6681     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6682   } else {
6683     SDValue CCOp = Slct.getOperand(0);
6684     if (CCOp.getOpcode() == ISD::SETCC)
6685       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6686   }
6687
6688   bool DoXform = false;
6689   bool InvCC = false;
6690   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6691           "Bad input!");
6692
6693   if (LHS.getOpcode() == ISD::Constant &&
6694       cast<ConstantSDNode>(LHS)->isNullValue()) {
6695     DoXform = true;
6696   } else if (CC != ISD::SETCC_INVALID &&
6697              RHS.getOpcode() == ISD::Constant &&
6698              cast<ConstantSDNode>(RHS)->isNullValue()) {
6699     std::swap(LHS, RHS);
6700     SDValue Op0 = Slct.getOperand(0);
6701     EVT OpVT = isSlctCC ? Op0.getValueType() :
6702                           Op0.getOperand(0).getValueType();
6703     bool isInt = OpVT.isInteger();
6704     CC = ISD::getSetCCInverse(CC, isInt);
6705
6706     if (!TLI.isCondCodeLegal(CC, OpVT))
6707       return SDValue();         // Inverse operator isn't legal.
6708
6709     DoXform = true;
6710     InvCC = true;
6711   }
6712
6713   if (DoXform) {
6714     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6715     if (isSlctCC)
6716       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6717                              Slct.getOperand(0), Slct.getOperand(1), CC);
6718     SDValue CCOp = Slct.getOperand(0);
6719     if (InvCC)
6720       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6721                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
6722     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6723                        CCOp, OtherOp, Result);
6724   }
6725   return SDValue();
6726 }
6727
6728 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6729 // (only after legalization).
6730 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6731                                  TargetLowering::DAGCombinerInfo &DCI,
6732                                  const ARMSubtarget *Subtarget) {
6733
6734   // Only perform optimization if after legalize, and if NEON is available. We
6735   // also expected both operands to be BUILD_VECTORs.
6736   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6737       || N0.getOpcode() != ISD::BUILD_VECTOR
6738       || N1.getOpcode() != ISD::BUILD_VECTOR)
6739     return SDValue();
6740
6741   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6742   EVT VT = N->getValueType(0);
6743   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6744     return SDValue();
6745
6746   // Check that the vector operands are of the right form.
6747   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6748   // operands, where N is the size of the formed vector.
6749   // Each EXTRACT_VECTOR should have the same input vector and odd or even
6750   // index such that we have a pair wise add pattern.
6751
6752   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6753   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6754     return SDValue();
6755   SDValue Vec = N0->getOperand(0)->getOperand(0);
6756   SDNode *V = Vec.getNode();
6757   unsigned nextIndex = 0;
6758
6759   // For each operands to the ADD which are BUILD_VECTORs,
6760   // check to see if each of their operands are an EXTRACT_VECTOR with
6761   // the same vector and appropriate index.
6762   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6763     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6764         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6765
6766       SDValue ExtVec0 = N0->getOperand(i);
6767       SDValue ExtVec1 = N1->getOperand(i);
6768
6769       // First operand is the vector, verify its the same.
6770       if (V != ExtVec0->getOperand(0).getNode() ||
6771           V != ExtVec1->getOperand(0).getNode())
6772         return SDValue();
6773
6774       // Second is the constant, verify its correct.
6775       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6776       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6777
6778       // For the constant, we want to see all the even or all the odd.
6779       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6780           || C1->getZExtValue() != nextIndex+1)
6781         return SDValue();
6782
6783       // Increment index.
6784       nextIndex+=2;
6785     } else
6786       return SDValue();
6787   }
6788
6789   // Create VPADDL node.
6790   SelectionDAG &DAG = DCI.DAG;
6791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6792
6793   // Build operand list.
6794   SmallVector<SDValue, 8> Ops;
6795   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6796                                 TLI.getPointerTy()));
6797
6798   // Input is the vector.
6799   Ops.push_back(Vec);
6800
6801   // Get widened type and narrowed type.
6802   MVT widenType;
6803   unsigned numElem = VT.getVectorNumElements();
6804   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6805     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6806     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6807     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6808     default:
6809       llvm_unreachable("Invalid vector element type for padd optimization.");
6810   }
6811
6812   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6813                             widenType, &Ops[0], Ops.size());
6814   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6815 }
6816
6817 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6818 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
6819 /// called with the default operands, and if that fails, with commuted
6820 /// operands.
6821 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6822                                           TargetLowering::DAGCombinerInfo &DCI,
6823                                           const ARMSubtarget *Subtarget){
6824
6825   // Attempt to create vpaddl for this add.
6826   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6827   if (Result.getNode())
6828     return Result;
6829
6830   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6831   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6832     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6833     if (Result.getNode()) return Result;
6834   }
6835   return SDValue();
6836 }
6837
6838 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6839 ///
6840 static SDValue PerformADDCombine(SDNode *N,
6841                                  TargetLowering::DAGCombinerInfo &DCI,
6842                                  const ARMSubtarget *Subtarget) {
6843   SDValue N0 = N->getOperand(0);
6844   SDValue N1 = N->getOperand(1);
6845
6846   // First try with the default operand order.
6847   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6848   if (Result.getNode())
6849     return Result;
6850
6851   // If that didn't work, try again with the operands commuted.
6852   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6853 }
6854
6855 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6856 ///
6857 static SDValue PerformSUBCombine(SDNode *N,
6858                                  TargetLowering::DAGCombinerInfo &DCI) {
6859   SDValue N0 = N->getOperand(0);
6860   SDValue N1 = N->getOperand(1);
6861
6862   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6863   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6864     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6865     if (Result.getNode()) return Result;
6866   }
6867
6868   return SDValue();
6869 }
6870
6871 /// PerformVMULCombine
6872 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6873 /// special multiplier accumulator forwarding.
6874 ///   vmul d3, d0, d2
6875 ///   vmla d3, d1, d2
6876 /// is faster than
6877 ///   vadd d3, d0, d1
6878 ///   vmul d3, d3, d2
6879 static SDValue PerformVMULCombine(SDNode *N,
6880                                   TargetLowering::DAGCombinerInfo &DCI,
6881                                   const ARMSubtarget *Subtarget) {
6882   if (!Subtarget->hasVMLxForwarding())
6883     return SDValue();
6884
6885   SelectionDAG &DAG = DCI.DAG;
6886   SDValue N0 = N->getOperand(0);
6887   SDValue N1 = N->getOperand(1);
6888   unsigned Opcode = N0.getOpcode();
6889   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6890       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6891     Opcode = N1.getOpcode();
6892     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6893         Opcode != ISD::FADD && Opcode != ISD::FSUB)
6894       return SDValue();
6895     std::swap(N0, N1);
6896   }
6897
6898   EVT VT = N->getValueType(0);
6899   DebugLoc DL = N->getDebugLoc();
6900   SDValue N00 = N0->getOperand(0);
6901   SDValue N01 = N0->getOperand(1);
6902   return DAG.getNode(Opcode, DL, VT,
6903                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6904                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6905 }
6906
6907 static SDValue PerformMULCombine(SDNode *N,
6908                                  TargetLowering::DAGCombinerInfo &DCI,
6909                                  const ARMSubtarget *Subtarget) {
6910   SelectionDAG &DAG = DCI.DAG;
6911
6912   if (Subtarget->isThumb1Only())
6913     return SDValue();
6914
6915   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6916     return SDValue();
6917
6918   EVT VT = N->getValueType(0);
6919   if (VT.is64BitVector() || VT.is128BitVector())
6920     return PerformVMULCombine(N, DCI, Subtarget);
6921   if (VT != MVT::i32)
6922     return SDValue();
6923
6924   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6925   if (!C)
6926     return SDValue();
6927
6928   int64_t MulAmt = C->getSExtValue();
6929   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6930
6931   ShiftAmt = ShiftAmt & (32 - 1);
6932   SDValue V = N->getOperand(0);
6933   DebugLoc DL = N->getDebugLoc();
6934
6935   SDValue Res;
6936   MulAmt >>= ShiftAmt;
6937
6938   if (MulAmt >= 0) {
6939     if (isPowerOf2_32(MulAmt - 1)) {
6940       // (mul x, 2^N + 1) => (add (shl x, N), x)
6941       Res = DAG.getNode(ISD::ADD, DL, VT,
6942                         V,
6943                         DAG.getNode(ISD::SHL, DL, VT,
6944                                     V,
6945                                     DAG.getConstant(Log2_32(MulAmt - 1),
6946                                                     MVT::i32)));
6947     } else if (isPowerOf2_32(MulAmt + 1)) {
6948       // (mul x, 2^N - 1) => (sub (shl x, N), x)
6949       Res = DAG.getNode(ISD::SUB, DL, VT,
6950                         DAG.getNode(ISD::SHL, DL, VT,
6951                                     V,
6952                                     DAG.getConstant(Log2_32(MulAmt + 1),
6953                                                     MVT::i32)),
6954                         V);
6955     } else
6956       return SDValue();
6957   } else {
6958     uint64_t MulAmtAbs = -MulAmt;
6959     if (isPowerOf2_32(MulAmtAbs + 1)) {
6960       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6961       Res = DAG.getNode(ISD::SUB, DL, VT,
6962                         V,
6963                         DAG.getNode(ISD::SHL, DL, VT,
6964                                     V,
6965                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
6966                                                     MVT::i32)));
6967     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
6968       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6969       Res = DAG.getNode(ISD::ADD, DL, VT,
6970                         V,
6971                         DAG.getNode(ISD::SHL, DL, VT,
6972                                     V,
6973                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
6974                                                     MVT::i32)));
6975       Res = DAG.getNode(ISD::SUB, DL, VT,
6976                         DAG.getConstant(0, MVT::i32),Res);
6977
6978     } else
6979       return SDValue();
6980   }
6981
6982   if (ShiftAmt != 0)
6983     Res = DAG.getNode(ISD::SHL, DL, VT,
6984                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
6985
6986   // Do not add new nodes to DAG combiner worklist.
6987   DCI.CombineTo(N, Res, false);
6988   return SDValue();
6989 }
6990
6991 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
6992   if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
6993     return false;
6994
6995   SDValue FalseVal = N.getOperand(0);
6996   ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
6997   if (!C)
6998     return false;
6999   if (AllOnes)
7000     return C->isAllOnesValue();
7001   return C->isNullValue();
7002 }
7003
7004 /// formConditionalOp - Combine an operation with a conditional move operand
7005 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7006 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7007 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7008                                  bool Commutable) {
7009   SDValue N0 = N->getOperand(0);
7010   SDValue N1 = N->getOperand(1);
7011
7012   bool isAND = N->getOpcode() == ISD::AND;
7013   bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7014   if (!isCand && Commutable) {
7015     isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7016     if (isCand)
7017       std::swap(N0, N1);
7018   }
7019   if (!isCand)
7020     return SDValue();
7021
7022   unsigned Opc = 0;
7023   switch (N->getOpcode()) {
7024   default: llvm_unreachable("Unexpected node");
7025   case ISD::AND: Opc = ARMISD::CAND; break;
7026   case ISD::OR:  Opc = ARMISD::COR; break;
7027   case ISD::XOR: Opc = ARMISD::CXOR; break;
7028   }
7029   return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7030                      N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7031                      N1.getOperand(4));
7032 }
7033
7034 static SDValue PerformANDCombine(SDNode *N,
7035                                  TargetLowering::DAGCombinerInfo &DCI,
7036                                  const ARMSubtarget *Subtarget) {
7037
7038   // Attempt to use immediate-form VBIC
7039   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7040   DebugLoc dl = N->getDebugLoc();
7041   EVT VT = N->getValueType(0);
7042   SelectionDAG &DAG = DCI.DAG;
7043
7044   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7045     return SDValue();
7046
7047   APInt SplatBits, SplatUndef;
7048   unsigned SplatBitSize;
7049   bool HasAnyUndefs;
7050   if (BVN &&
7051       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7052     if (SplatBitSize <= 64) {
7053       EVT VbicVT;
7054       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7055                                       SplatUndef.getZExtValue(), SplatBitSize,
7056                                       DAG, VbicVT, VT.is128BitVector(),
7057                                       OtherModImm);
7058       if (Val.getNode()) {
7059         SDValue Input =
7060           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7061         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7062         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7063       }
7064     }
7065   }
7066
7067   if (!Subtarget->isThumb1Only()) {
7068     // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7069     SDValue CAND = formConditionalOp(N, DAG, true);
7070     if (CAND.getNode())
7071       return CAND;
7072   }
7073
7074   return SDValue();
7075 }
7076
7077 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7078 static SDValue PerformORCombine(SDNode *N,
7079                                 TargetLowering::DAGCombinerInfo &DCI,
7080                                 const ARMSubtarget *Subtarget) {
7081   // Attempt to use immediate-form VORR
7082   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7083   DebugLoc dl = N->getDebugLoc();
7084   EVT VT = N->getValueType(0);
7085   SelectionDAG &DAG = DCI.DAG;
7086
7087   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7088     return SDValue();
7089
7090   APInt SplatBits, SplatUndef;
7091   unsigned SplatBitSize;
7092   bool HasAnyUndefs;
7093   if (BVN && Subtarget->hasNEON() &&
7094       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7095     if (SplatBitSize <= 64) {
7096       EVT VorrVT;
7097       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7098                                       SplatUndef.getZExtValue(), SplatBitSize,
7099                                       DAG, VorrVT, VT.is128BitVector(),
7100                                       OtherModImm);
7101       if (Val.getNode()) {
7102         SDValue Input =
7103           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7104         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7105         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7106       }
7107     }
7108   }
7109
7110   if (!Subtarget->isThumb1Only()) {
7111     // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7112     SDValue COR = formConditionalOp(N, DAG, true);
7113     if (COR.getNode())
7114       return COR;
7115   }
7116
7117   SDValue N0 = N->getOperand(0);
7118   if (N0.getOpcode() != ISD::AND)
7119     return SDValue();
7120   SDValue N1 = N->getOperand(1);
7121
7122   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7123   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7124       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7125     APInt SplatUndef;
7126     unsigned SplatBitSize;
7127     bool HasAnyUndefs;
7128
7129     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7130     APInt SplatBits0;
7131     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7132                                   HasAnyUndefs) && !HasAnyUndefs) {
7133       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7134       APInt SplatBits1;
7135       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7136                                     HasAnyUndefs) && !HasAnyUndefs &&
7137           SplatBits0 == ~SplatBits1) {
7138         // Canonicalize the vector type to make instruction selection simpler.
7139         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7140         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7141                                      N0->getOperand(1), N0->getOperand(0),
7142                                      N1->getOperand(0));
7143         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7144       }
7145     }
7146   }
7147
7148   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7149   // reasonable.
7150
7151   // BFI is only available on V6T2+
7152   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7153     return SDValue();
7154
7155   DebugLoc DL = N->getDebugLoc();
7156   // 1) or (and A, mask), val => ARMbfi A, val, mask
7157   //      iff (val & mask) == val
7158   //
7159   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7160   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7161   //          && mask == ~mask2
7162   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7163   //          && ~mask == mask2
7164   //  (i.e., copy a bitfield value into another bitfield of the same width)
7165
7166   if (VT != MVT::i32)
7167     return SDValue();
7168
7169   SDValue N00 = N0.getOperand(0);
7170
7171   // The value and the mask need to be constants so we can verify this is
7172   // actually a bitfield set. If the mask is 0xffff, we can do better
7173   // via a movt instruction, so don't use BFI in that case.
7174   SDValue MaskOp = N0.getOperand(1);
7175   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7176   if (!MaskC)
7177     return SDValue();
7178   unsigned Mask = MaskC->getZExtValue();
7179   if (Mask == 0xffff)
7180     return SDValue();
7181   SDValue Res;
7182   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7183   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7184   if (N1C) {
7185     unsigned Val = N1C->getZExtValue();
7186     if ((Val & ~Mask) != Val)
7187       return SDValue();
7188
7189     if (ARM::isBitFieldInvertedMask(Mask)) {
7190       Val >>= CountTrailingZeros_32(~Mask);
7191
7192       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7193                         DAG.getConstant(Val, MVT::i32),
7194                         DAG.getConstant(Mask, MVT::i32));
7195
7196       // Do not add new nodes to DAG combiner worklist.
7197       DCI.CombineTo(N, Res, false);
7198       return SDValue();
7199     }
7200   } else if (N1.getOpcode() == ISD::AND) {
7201     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7202     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7203     if (!N11C)
7204       return SDValue();
7205     unsigned Mask2 = N11C->getZExtValue();
7206
7207     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7208     // as is to match.
7209     if (ARM::isBitFieldInvertedMask(Mask) &&
7210         (Mask == ~Mask2)) {
7211       // The pack halfword instruction works better for masks that fit it,
7212       // so use that when it's available.
7213       if (Subtarget->hasT2ExtractPack() &&
7214           (Mask == 0xffff || Mask == 0xffff0000))
7215         return SDValue();
7216       // 2a
7217       unsigned amt = CountTrailingZeros_32(Mask2);
7218       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7219                         DAG.getConstant(amt, MVT::i32));
7220       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7221                         DAG.getConstant(Mask, MVT::i32));
7222       // Do not add new nodes to DAG combiner worklist.
7223       DCI.CombineTo(N, Res, false);
7224       return SDValue();
7225     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7226                (~Mask == Mask2)) {
7227       // The pack halfword instruction works better for masks that fit it,
7228       // so use that when it's available.
7229       if (Subtarget->hasT2ExtractPack() &&
7230           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7231         return SDValue();
7232       // 2b
7233       unsigned lsb = CountTrailingZeros_32(Mask);
7234       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7235                         DAG.getConstant(lsb, MVT::i32));
7236       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7237                         DAG.getConstant(Mask2, MVT::i32));
7238       // Do not add new nodes to DAG combiner worklist.
7239       DCI.CombineTo(N, Res, false);
7240       return SDValue();
7241     }
7242   }
7243
7244   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7245       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7246       ARM::isBitFieldInvertedMask(~Mask)) {
7247     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7248     // where lsb(mask) == #shamt and masked bits of B are known zero.
7249     SDValue ShAmt = N00.getOperand(1);
7250     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7251     unsigned LSB = CountTrailingZeros_32(Mask);
7252     if (ShAmtC != LSB)
7253       return SDValue();
7254
7255     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7256                       DAG.getConstant(~Mask, MVT::i32));
7257
7258     // Do not add new nodes to DAG combiner worklist.
7259     DCI.CombineTo(N, Res, false);
7260   }
7261
7262   return SDValue();
7263 }
7264
7265 static SDValue PerformXORCombine(SDNode *N,
7266                                  TargetLowering::DAGCombinerInfo &DCI,
7267                                  const ARMSubtarget *Subtarget) {
7268   EVT VT = N->getValueType(0);
7269   SelectionDAG &DAG = DCI.DAG;
7270
7271   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7272     return SDValue();
7273
7274   if (!Subtarget->isThumb1Only()) {
7275     // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7276     SDValue CXOR = formConditionalOp(N, DAG, true);
7277     if (CXOR.getNode())
7278       return CXOR;
7279   }
7280
7281   return SDValue();
7282 }
7283
7284 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7285 /// the bits being cleared by the AND are not demanded by the BFI.
7286 static SDValue PerformBFICombine(SDNode *N,
7287                                  TargetLowering::DAGCombinerInfo &DCI) {
7288   SDValue N1 = N->getOperand(1);
7289   if (N1.getOpcode() == ISD::AND) {
7290     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7291     if (!N11C)
7292       return SDValue();
7293     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7294     unsigned LSB = CountTrailingZeros_32(~InvMask);
7295     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7296     unsigned Mask = (1 << Width)-1;
7297     unsigned Mask2 = N11C->getZExtValue();
7298     if ((Mask & (~Mask2)) == 0)
7299       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7300                              N->getOperand(0), N1.getOperand(0),
7301                              N->getOperand(2));
7302   }
7303   return SDValue();
7304 }
7305
7306 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7307 /// ARMISD::VMOVRRD.
7308 static SDValue PerformVMOVRRDCombine(SDNode *N,
7309                                      TargetLowering::DAGCombinerInfo &DCI) {
7310   // vmovrrd(vmovdrr x, y) -> x,y
7311   SDValue InDouble = N->getOperand(0);
7312   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7313     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7314
7315   // vmovrrd(load f64) -> (load i32), (load i32)
7316   SDNode *InNode = InDouble.getNode();
7317   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7318       InNode->getValueType(0) == MVT::f64 &&
7319       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7320       !cast<LoadSDNode>(InNode)->isVolatile()) {
7321     // TODO: Should this be done for non-FrameIndex operands?
7322     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7323
7324     SelectionDAG &DAG = DCI.DAG;
7325     DebugLoc DL = LD->getDebugLoc();
7326     SDValue BasePtr = LD->getBasePtr();
7327     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7328                                  LD->getPointerInfo(), LD->isVolatile(),
7329                                  LD->isNonTemporal(), LD->isInvariant(),
7330                                  LD->getAlignment());
7331
7332     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7333                                     DAG.getConstant(4, MVT::i32));
7334     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7335                                  LD->getPointerInfo(), LD->isVolatile(),
7336                                  LD->isNonTemporal(), LD->isInvariant(),
7337                                  std::min(4U, LD->getAlignment() / 2));
7338
7339     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7340     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7341     DCI.RemoveFromWorklist(LD);
7342     DAG.DeleteNode(LD);
7343     return Result;
7344   }
7345
7346   return SDValue();
7347 }
7348
7349 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7350 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7351 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7352   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7353   SDValue Op0 = N->getOperand(0);
7354   SDValue Op1 = N->getOperand(1);
7355   if (Op0.getOpcode() == ISD::BITCAST)
7356     Op0 = Op0.getOperand(0);
7357   if (Op1.getOpcode() == ISD::BITCAST)
7358     Op1 = Op1.getOperand(0);
7359   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7360       Op0.getNode() == Op1.getNode() &&
7361       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7362     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7363                        N->getValueType(0), Op0.getOperand(0));
7364   return SDValue();
7365 }
7366
7367 /// PerformSTORECombine - Target-specific dag combine xforms for
7368 /// ISD::STORE.
7369 static SDValue PerformSTORECombine(SDNode *N,
7370                                    TargetLowering::DAGCombinerInfo &DCI) {
7371   StoreSDNode *St = cast<StoreSDNode>(N);
7372   if (St->isVolatile())
7373     return SDValue();
7374
7375   // Optimize trunc store (of multiple scalars) to shuffle and store.  First, 
7376   // pack all of the elements in one place.  Next, store to memory in fewer
7377   // chunks.
7378   SDValue StVal = St->getValue();
7379   EVT VT = StVal.getValueType();
7380   if (St->isTruncatingStore() && VT.isVector()) {
7381     SelectionDAG &DAG = DCI.DAG;
7382     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7383     EVT StVT = St->getMemoryVT();
7384     unsigned NumElems = VT.getVectorNumElements();
7385     assert(StVT != VT && "Cannot truncate to the same type");
7386     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7387     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7388
7389     // From, To sizes and ElemCount must be pow of two
7390     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7391
7392     // We are going to use the original vector elt for storing.
7393     // Accumulated smaller vector elements must be a multiple of the store size.
7394     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7395
7396     unsigned SizeRatio  = FromEltSz / ToEltSz;
7397     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7398
7399     // Create a type on which we perform the shuffle.
7400     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7401                                      NumElems*SizeRatio);
7402     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7403
7404     DebugLoc DL = St->getDebugLoc();
7405     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7406     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7407     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7408
7409     // Can't shuffle using an illegal type.
7410     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7411
7412     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7413                                 DAG.getUNDEF(WideVec.getValueType()),
7414                                 ShuffleVec.data());
7415     // At this point all of the data is stored at the bottom of the
7416     // register. We now need to save it to mem.
7417
7418     // Find the largest store unit
7419     MVT StoreType = MVT::i8;
7420     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7421          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7422       MVT Tp = (MVT::SimpleValueType)tp;
7423       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7424         StoreType = Tp;
7425     }
7426     // Didn't find a legal store type.
7427     if (!TLI.isTypeLegal(StoreType))
7428       return SDValue();
7429
7430     // Bitcast the original vector into a vector of store-size units
7431     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7432             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7433     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7434     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7435     SmallVector<SDValue, 8> Chains;
7436     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7437                                         TLI.getPointerTy());
7438     SDValue BasePtr = St->getBasePtr();
7439
7440     // Perform one or more big stores into memory.
7441     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7442     for (unsigned I = 0; I < E; I++) {
7443       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7444                                    StoreType, ShuffWide,
7445                                    DAG.getIntPtrConstant(I));
7446       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7447                                 St->getPointerInfo(), St->isVolatile(),
7448                                 St->isNonTemporal(), St->getAlignment());
7449       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7450                             Increment);
7451       Chains.push_back(Ch);
7452     }
7453     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7454                        Chains.size());
7455   }
7456
7457   if (!ISD::isNormalStore(St))
7458     return SDValue();
7459
7460   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7461   // ARM stores of arguments in the same cache line.
7462   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7463       StVal.getNode()->hasOneUse()) {
7464     SelectionDAG  &DAG = DCI.DAG;
7465     DebugLoc DL = St->getDebugLoc();
7466     SDValue BasePtr = St->getBasePtr();
7467     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7468                                   StVal.getNode()->getOperand(0), BasePtr,
7469                                   St->getPointerInfo(), St->isVolatile(),
7470                                   St->isNonTemporal(), St->getAlignment());
7471
7472     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7473                                     DAG.getConstant(4, MVT::i32));
7474     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7475                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7476                         St->isNonTemporal(),
7477                         std::min(4U, St->getAlignment() / 2));
7478   }
7479
7480   if (StVal.getValueType() != MVT::i64 ||
7481       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7482     return SDValue();
7483
7484   // Bitcast an i64 store extracted from a vector to f64.
7485   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7486   SelectionDAG &DAG = DCI.DAG;
7487   DebugLoc dl = StVal.getDebugLoc();
7488   SDValue IntVec = StVal.getOperand(0);
7489   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7490                                  IntVec.getValueType().getVectorNumElements());
7491   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7492   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7493                                Vec, StVal.getOperand(1));
7494   dl = N->getDebugLoc();
7495   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7496   // Make the DAGCombiner fold the bitcasts.
7497   DCI.AddToWorklist(Vec.getNode());
7498   DCI.AddToWorklist(ExtElt.getNode());
7499   DCI.AddToWorklist(V.getNode());
7500   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7501                       St->getPointerInfo(), St->isVolatile(),
7502                       St->isNonTemporal(), St->getAlignment(),
7503                       St->getTBAAInfo());
7504 }
7505
7506 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7507 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7508 /// i64 vector to have f64 elements, since the value can then be loaded
7509 /// directly into a VFP register.
7510 static bool hasNormalLoadOperand(SDNode *N) {
7511   unsigned NumElts = N->getValueType(0).getVectorNumElements();
7512   for (unsigned i = 0; i < NumElts; ++i) {
7513     SDNode *Elt = N->getOperand(i).getNode();
7514     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7515       return true;
7516   }
7517   return false;
7518 }
7519
7520 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7521 /// ISD::BUILD_VECTOR.
7522 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7523                                           TargetLowering::DAGCombinerInfo &DCI){
7524   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7525   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7526   // into a pair of GPRs, which is fine when the value is used as a scalar,
7527   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7528   SelectionDAG &DAG = DCI.DAG;
7529   if (N->getNumOperands() == 2) {
7530     SDValue RV = PerformVMOVDRRCombine(N, DAG);
7531     if (RV.getNode())
7532       return RV;
7533   }
7534
7535   // Load i64 elements as f64 values so that type legalization does not split
7536   // them up into i32 values.
7537   EVT VT = N->getValueType(0);
7538   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7539     return SDValue();
7540   DebugLoc dl = N->getDebugLoc();
7541   SmallVector<SDValue, 8> Ops;
7542   unsigned NumElts = VT.getVectorNumElements();
7543   for (unsigned i = 0; i < NumElts; ++i) {
7544     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7545     Ops.push_back(V);
7546     // Make the DAGCombiner fold the bitcast.
7547     DCI.AddToWorklist(V.getNode());
7548   }
7549   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7550   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7551   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7552 }
7553
7554 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7555 /// ISD::INSERT_VECTOR_ELT.
7556 static SDValue PerformInsertEltCombine(SDNode *N,
7557                                        TargetLowering::DAGCombinerInfo &DCI) {
7558   // Bitcast an i64 load inserted into a vector to f64.
7559   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7560   EVT VT = N->getValueType(0);
7561   SDNode *Elt = N->getOperand(1).getNode();
7562   if (VT.getVectorElementType() != MVT::i64 ||
7563       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7564     return SDValue();
7565
7566   SelectionDAG &DAG = DCI.DAG;
7567   DebugLoc dl = N->getDebugLoc();
7568   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7569                                  VT.getVectorNumElements());
7570   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7571   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7572   // Make the DAGCombiner fold the bitcasts.
7573   DCI.AddToWorklist(Vec.getNode());
7574   DCI.AddToWorklist(V.getNode());
7575   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7576                                Vec, V, N->getOperand(2));
7577   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7578 }
7579
7580 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7581 /// ISD::VECTOR_SHUFFLE.
7582 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7583   // The LLVM shufflevector instruction does not require the shuffle mask
7584   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7585   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7586   // operands do not match the mask length, they are extended by concatenating
7587   // them with undef vectors.  That is probably the right thing for other
7588   // targets, but for NEON it is better to concatenate two double-register
7589   // size vector operands into a single quad-register size vector.  Do that
7590   // transformation here:
7591   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7592   //   shuffle(concat(v1, v2), undef)
7593   SDValue Op0 = N->getOperand(0);
7594   SDValue Op1 = N->getOperand(1);
7595   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7596       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7597       Op0.getNumOperands() != 2 ||
7598       Op1.getNumOperands() != 2)
7599     return SDValue();
7600   SDValue Concat0Op1 = Op0.getOperand(1);
7601   SDValue Concat1Op1 = Op1.getOperand(1);
7602   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7603       Concat1Op1.getOpcode() != ISD::UNDEF)
7604     return SDValue();
7605   // Skip the transformation if any of the types are illegal.
7606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7607   EVT VT = N->getValueType(0);
7608   if (!TLI.isTypeLegal(VT) ||
7609       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7610       !TLI.isTypeLegal(Concat1Op1.getValueType()))
7611     return SDValue();
7612
7613   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7614                                   Op0.getOperand(0), Op1.getOperand(0));
7615   // Translate the shuffle mask.
7616   SmallVector<int, 16> NewMask;
7617   unsigned NumElts = VT.getVectorNumElements();
7618   unsigned HalfElts = NumElts/2;
7619   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7620   for (unsigned n = 0; n < NumElts; ++n) {
7621     int MaskElt = SVN->getMaskElt(n);
7622     int NewElt = -1;
7623     if (MaskElt < (int)HalfElts)
7624       NewElt = MaskElt;
7625     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7626       NewElt = HalfElts + MaskElt - NumElts;
7627     NewMask.push_back(NewElt);
7628   }
7629   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7630                               DAG.getUNDEF(VT), NewMask.data());
7631 }
7632
7633 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7634 /// NEON load/store intrinsics to merge base address updates.
7635 static SDValue CombineBaseUpdate(SDNode *N,
7636                                  TargetLowering::DAGCombinerInfo &DCI) {
7637   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7638     return SDValue();
7639
7640   SelectionDAG &DAG = DCI.DAG;
7641   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7642                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7643   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7644   SDValue Addr = N->getOperand(AddrOpIdx);
7645
7646   // Search for a use of the address operand that is an increment.
7647   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7648          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7649     SDNode *User = *UI;
7650     if (User->getOpcode() != ISD::ADD ||
7651         UI.getUse().getResNo() != Addr.getResNo())
7652       continue;
7653
7654     // Check that the add is independent of the load/store.  Otherwise, folding
7655     // it would create a cycle.
7656     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7657       continue;
7658
7659     // Find the new opcode for the updating load/store.
7660     bool isLoad = true;
7661     bool isLaneOp = false;
7662     unsigned NewOpc = 0;
7663     unsigned NumVecs = 0;
7664     if (isIntrinsic) {
7665       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7666       switch (IntNo) {
7667       default: llvm_unreachable("unexpected intrinsic for Neon base update");
7668       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
7669         NumVecs = 1; break;
7670       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
7671         NumVecs = 2; break;
7672       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
7673         NumVecs = 3; break;
7674       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
7675         NumVecs = 4; break;
7676       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7677         NumVecs = 2; isLaneOp = true; break;
7678       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7679         NumVecs = 3; isLaneOp = true; break;
7680       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7681         NumVecs = 4; isLaneOp = true; break;
7682       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
7683         NumVecs = 1; isLoad = false; break;
7684       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
7685         NumVecs = 2; isLoad = false; break;
7686       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
7687         NumVecs = 3; isLoad = false; break;
7688       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
7689         NumVecs = 4; isLoad = false; break;
7690       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7691         NumVecs = 2; isLoad = false; isLaneOp = true; break;
7692       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7693         NumVecs = 3; isLoad = false; isLaneOp = true; break;
7694       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7695         NumVecs = 4; isLoad = false; isLaneOp = true; break;
7696       }
7697     } else {
7698       isLaneOp = true;
7699       switch (N->getOpcode()) {
7700       default: llvm_unreachable("unexpected opcode for Neon base update");
7701       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7702       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7703       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7704       }
7705     }
7706
7707     // Find the size of memory referenced by the load/store.
7708     EVT VecTy;
7709     if (isLoad)
7710       VecTy = N->getValueType(0);
7711     else
7712       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7713     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7714     if (isLaneOp)
7715       NumBytes /= VecTy.getVectorNumElements();
7716
7717     // If the increment is a constant, it must match the memory ref size.
7718     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7719     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7720       uint64_t IncVal = CInc->getZExtValue();
7721       if (IncVal != NumBytes)
7722         continue;
7723     } else if (NumBytes >= 3 * 16) {
7724       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7725       // separate instructions that make it harder to use a non-constant update.
7726       continue;
7727     }
7728
7729     // Create the new updating load/store node.
7730     EVT Tys[6];
7731     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7732     unsigned n;
7733     for (n = 0; n < NumResultVecs; ++n)
7734       Tys[n] = VecTy;
7735     Tys[n++] = MVT::i32;
7736     Tys[n] = MVT::Other;
7737     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7738     SmallVector<SDValue, 8> Ops;
7739     Ops.push_back(N->getOperand(0)); // incoming chain
7740     Ops.push_back(N->getOperand(AddrOpIdx));
7741     Ops.push_back(Inc);
7742     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7743       Ops.push_back(N->getOperand(i));
7744     }
7745     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7746     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7747                                            Ops.data(), Ops.size(),
7748                                            MemInt->getMemoryVT(),
7749                                            MemInt->getMemOperand());
7750
7751     // Update the uses.
7752     std::vector<SDValue> NewResults;
7753     for (unsigned i = 0; i < NumResultVecs; ++i) {
7754       NewResults.push_back(SDValue(UpdN.getNode(), i));
7755     }
7756     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7757     DCI.CombineTo(N, NewResults);
7758     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7759
7760     break;
7761   }
7762   return SDValue();
7763 }
7764
7765 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7766 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7767 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
7768 /// return true.
7769 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7770   SelectionDAG &DAG = DCI.DAG;
7771   EVT VT = N->getValueType(0);
7772   // vldN-dup instructions only support 64-bit vectors for N > 1.
7773   if (!VT.is64BitVector())
7774     return false;
7775
7776   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7777   SDNode *VLD = N->getOperand(0).getNode();
7778   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7779     return false;
7780   unsigned NumVecs = 0;
7781   unsigned NewOpc = 0;
7782   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7783   if (IntNo == Intrinsic::arm_neon_vld2lane) {
7784     NumVecs = 2;
7785     NewOpc = ARMISD::VLD2DUP;
7786   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7787     NumVecs = 3;
7788     NewOpc = ARMISD::VLD3DUP;
7789   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7790     NumVecs = 4;
7791     NewOpc = ARMISD::VLD4DUP;
7792   } else {
7793     return false;
7794   }
7795
7796   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7797   // numbers match the load.
7798   unsigned VLDLaneNo =
7799     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7800   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7801        UI != UE; ++UI) {
7802     // Ignore uses of the chain result.
7803     if (UI.getUse().getResNo() == NumVecs)
7804       continue;
7805     SDNode *User = *UI;
7806     if (User->getOpcode() != ARMISD::VDUPLANE ||
7807         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7808       return false;
7809   }
7810
7811   // Create the vldN-dup node.
7812   EVT Tys[5];
7813   unsigned n;
7814   for (n = 0; n < NumVecs; ++n)
7815     Tys[n] = VT;
7816   Tys[n] = MVT::Other;
7817   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7818   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7819   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7820   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7821                                            Ops, 2, VLDMemInt->getMemoryVT(),
7822                                            VLDMemInt->getMemOperand());
7823
7824   // Update the uses.
7825   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7826        UI != UE; ++UI) {
7827     unsigned ResNo = UI.getUse().getResNo();
7828     // Ignore uses of the chain result.
7829     if (ResNo == NumVecs)
7830       continue;
7831     SDNode *User = *UI;
7832     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7833   }
7834
7835   // Now the vldN-lane intrinsic is dead except for its chain result.
7836   // Update uses of the chain.
7837   std::vector<SDValue> VLDDupResults;
7838   for (unsigned n = 0; n < NumVecs; ++n)
7839     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7840   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7841   DCI.CombineTo(VLD, VLDDupResults);
7842
7843   return true;
7844 }
7845
7846 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
7847 /// ARMISD::VDUPLANE.
7848 static SDValue PerformVDUPLANECombine(SDNode *N,
7849                                       TargetLowering::DAGCombinerInfo &DCI) {
7850   SDValue Op = N->getOperand(0);
7851
7852   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7853   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7854   if (CombineVLDDUP(N, DCI))
7855     return SDValue(N, 0);
7856
7857   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7858   // redundant.  Ignore bit_converts for now; element sizes are checked below.
7859   while (Op.getOpcode() == ISD::BITCAST)
7860     Op = Op.getOperand(0);
7861   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7862     return SDValue();
7863
7864   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7865   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7866   // The canonical VMOV for a zero vector uses a 32-bit element size.
7867   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7868   unsigned EltBits;
7869   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7870     EltSize = 8;
7871   EVT VT = N->getValueType(0);
7872   if (EltSize > VT.getVectorElementType().getSizeInBits())
7873     return SDValue();
7874
7875   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7876 }
7877
7878 // isConstVecPow2 - Return true if each vector element is a power of 2, all
7879 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7880 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7881 {
7882   integerPart cN;
7883   integerPart c0 = 0;
7884   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7885        I != E; I++) {
7886     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7887     if (!C)
7888       return false;
7889
7890     bool isExact;
7891     APFloat APF = C->getValueAPF();
7892     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7893         != APFloat::opOK || !isExact)
7894       return false;
7895
7896     c0 = (I == 0) ? cN : c0;
7897     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7898       return false;
7899   }
7900   C = c0;
7901   return true;
7902 }
7903
7904 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7905 /// can replace combinations of VMUL and VCVT (floating-point to integer)
7906 /// when the VMUL has a constant operand that is a power of 2.
7907 ///
7908 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7909 ///  vmul.f32        d16, d17, d16
7910 ///  vcvt.s32.f32    d16, d16
7911 /// becomes:
7912 ///  vcvt.s32.f32    d16, d16, #3
7913 static SDValue PerformVCVTCombine(SDNode *N,
7914                                   TargetLowering::DAGCombinerInfo &DCI,
7915                                   const ARMSubtarget *Subtarget) {
7916   SelectionDAG &DAG = DCI.DAG;
7917   SDValue Op = N->getOperand(0);
7918
7919   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7920       Op.getOpcode() != ISD::FMUL)
7921     return SDValue();
7922
7923   uint64_t C;
7924   SDValue N0 = Op->getOperand(0);
7925   SDValue ConstVec = Op->getOperand(1);
7926   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7927
7928   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7929       !isConstVecPow2(ConstVec, isSigned, C))
7930     return SDValue();
7931
7932   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7933     Intrinsic::arm_neon_vcvtfp2fxu;
7934   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7935                      N->getValueType(0),
7936                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7937                      DAG.getConstant(Log2_64(C), MVT::i32));
7938 }
7939
7940 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7941 /// can replace combinations of VCVT (integer to floating-point) and VDIV
7942 /// when the VDIV has a constant operand that is a power of 2.
7943 ///
7944 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7945 ///  vcvt.f32.s32    d16, d16
7946 ///  vdiv.f32        d16, d17, d16
7947 /// becomes:
7948 ///  vcvt.f32.s32    d16, d16, #3
7949 static SDValue PerformVDIVCombine(SDNode *N,
7950                                   TargetLowering::DAGCombinerInfo &DCI,
7951                                   const ARMSubtarget *Subtarget) {
7952   SelectionDAG &DAG = DCI.DAG;
7953   SDValue Op = N->getOperand(0);
7954   unsigned OpOpcode = Op.getNode()->getOpcode();
7955
7956   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7957       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7958     return SDValue();
7959
7960   uint64_t C;
7961   SDValue ConstVec = N->getOperand(1);
7962   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7963
7964   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7965       !isConstVecPow2(ConstVec, isSigned, C))
7966     return SDValue();
7967
7968   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7969     Intrinsic::arm_neon_vcvtfxu2fp;
7970   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7971                      Op.getValueType(),
7972                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
7973                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7974 }
7975
7976 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
7977 /// operand of a vector shift operation, where all the elements of the
7978 /// build_vector must have the same constant integer value.
7979 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7980   // Ignore bit_converts.
7981   while (Op.getOpcode() == ISD::BITCAST)
7982     Op = Op.getOperand(0);
7983   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7984   APInt SplatBits, SplatUndef;
7985   unsigned SplatBitSize;
7986   bool HasAnyUndefs;
7987   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7988                                       HasAnyUndefs, ElementBits) ||
7989       SplatBitSize > ElementBits)
7990     return false;
7991   Cnt = SplatBits.getSExtValue();
7992   return true;
7993 }
7994
7995 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7996 /// operand of a vector shift left operation.  That value must be in the range:
7997 ///   0 <= Value < ElementBits for a left shift; or
7998 ///   0 <= Value <= ElementBits for a long left shift.
7999 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8000   assert(VT.isVector() && "vector shift count is not a vector type");
8001   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8002   if (! getVShiftImm(Op, ElementBits, Cnt))
8003     return false;
8004   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8005 }
8006
8007 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8008 /// operand of a vector shift right operation.  For a shift opcode, the value
8009 /// is positive, but for an intrinsic the value count must be negative. The
8010 /// absolute value must be in the range:
8011 ///   1 <= |Value| <= ElementBits for a right shift; or
8012 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8013 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8014                          int64_t &Cnt) {
8015   assert(VT.isVector() && "vector shift count is not a vector type");
8016   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8017   if (! getVShiftImm(Op, ElementBits, Cnt))
8018     return false;
8019   if (isIntrinsic)
8020     Cnt = -Cnt;
8021   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8022 }
8023
8024 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8025 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8026   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8027   switch (IntNo) {
8028   default:
8029     // Don't do anything for most intrinsics.
8030     break;
8031
8032   // Vector shifts: check for immediate versions and lower them.
8033   // Note: This is done during DAG combining instead of DAG legalizing because
8034   // the build_vectors for 64-bit vector element shift counts are generally
8035   // not legal, and it is hard to see their values after they get legalized to
8036   // loads from a constant pool.
8037   case Intrinsic::arm_neon_vshifts:
8038   case Intrinsic::arm_neon_vshiftu:
8039   case Intrinsic::arm_neon_vshiftls:
8040   case Intrinsic::arm_neon_vshiftlu:
8041   case Intrinsic::arm_neon_vshiftn:
8042   case Intrinsic::arm_neon_vrshifts:
8043   case Intrinsic::arm_neon_vrshiftu:
8044   case Intrinsic::arm_neon_vrshiftn:
8045   case Intrinsic::arm_neon_vqshifts:
8046   case Intrinsic::arm_neon_vqshiftu:
8047   case Intrinsic::arm_neon_vqshiftsu:
8048   case Intrinsic::arm_neon_vqshiftns:
8049   case Intrinsic::arm_neon_vqshiftnu:
8050   case Intrinsic::arm_neon_vqshiftnsu:
8051   case Intrinsic::arm_neon_vqrshiftns:
8052   case Intrinsic::arm_neon_vqrshiftnu:
8053   case Intrinsic::arm_neon_vqrshiftnsu: {
8054     EVT VT = N->getOperand(1).getValueType();
8055     int64_t Cnt;
8056     unsigned VShiftOpc = 0;
8057
8058     switch (IntNo) {
8059     case Intrinsic::arm_neon_vshifts:
8060     case Intrinsic::arm_neon_vshiftu:
8061       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8062         VShiftOpc = ARMISD::VSHL;
8063         break;
8064       }
8065       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8066         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8067                      ARMISD::VSHRs : ARMISD::VSHRu);
8068         break;
8069       }
8070       return SDValue();
8071
8072     case Intrinsic::arm_neon_vshiftls:
8073     case Intrinsic::arm_neon_vshiftlu:
8074       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8075         break;
8076       llvm_unreachable("invalid shift count for vshll intrinsic");
8077
8078     case Intrinsic::arm_neon_vrshifts:
8079     case Intrinsic::arm_neon_vrshiftu:
8080       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8081         break;
8082       return SDValue();
8083
8084     case Intrinsic::arm_neon_vqshifts:
8085     case Intrinsic::arm_neon_vqshiftu:
8086       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8087         break;
8088       return SDValue();
8089
8090     case Intrinsic::arm_neon_vqshiftsu:
8091       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8092         break;
8093       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8094
8095     case Intrinsic::arm_neon_vshiftn:
8096     case Intrinsic::arm_neon_vrshiftn:
8097     case Intrinsic::arm_neon_vqshiftns:
8098     case Intrinsic::arm_neon_vqshiftnu:
8099     case Intrinsic::arm_neon_vqshiftnsu:
8100     case Intrinsic::arm_neon_vqrshiftns:
8101     case Intrinsic::arm_neon_vqrshiftnu:
8102     case Intrinsic::arm_neon_vqrshiftnsu:
8103       // Narrowing shifts require an immediate right shift.
8104       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8105         break;
8106       llvm_unreachable("invalid shift count for narrowing vector shift "
8107                        "intrinsic");
8108
8109     default:
8110       llvm_unreachable("unhandled vector shift");
8111     }
8112
8113     switch (IntNo) {
8114     case Intrinsic::arm_neon_vshifts:
8115     case Intrinsic::arm_neon_vshiftu:
8116       // Opcode already set above.
8117       break;
8118     case Intrinsic::arm_neon_vshiftls:
8119     case Intrinsic::arm_neon_vshiftlu:
8120       if (Cnt == VT.getVectorElementType().getSizeInBits())
8121         VShiftOpc = ARMISD::VSHLLi;
8122       else
8123         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8124                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8125       break;
8126     case Intrinsic::arm_neon_vshiftn:
8127       VShiftOpc = ARMISD::VSHRN; break;
8128     case Intrinsic::arm_neon_vrshifts:
8129       VShiftOpc = ARMISD::VRSHRs; break;
8130     case Intrinsic::arm_neon_vrshiftu:
8131       VShiftOpc = ARMISD::VRSHRu; break;
8132     case Intrinsic::arm_neon_vrshiftn:
8133       VShiftOpc = ARMISD::VRSHRN; break;
8134     case Intrinsic::arm_neon_vqshifts:
8135       VShiftOpc = ARMISD::VQSHLs; break;
8136     case Intrinsic::arm_neon_vqshiftu:
8137       VShiftOpc = ARMISD::VQSHLu; break;
8138     case Intrinsic::arm_neon_vqshiftsu:
8139       VShiftOpc = ARMISD::VQSHLsu; break;
8140     case Intrinsic::arm_neon_vqshiftns:
8141       VShiftOpc = ARMISD::VQSHRNs; break;
8142     case Intrinsic::arm_neon_vqshiftnu:
8143       VShiftOpc = ARMISD::VQSHRNu; break;
8144     case Intrinsic::arm_neon_vqshiftnsu:
8145       VShiftOpc = ARMISD::VQSHRNsu; break;
8146     case Intrinsic::arm_neon_vqrshiftns:
8147       VShiftOpc = ARMISD::VQRSHRNs; break;
8148     case Intrinsic::arm_neon_vqrshiftnu:
8149       VShiftOpc = ARMISD::VQRSHRNu; break;
8150     case Intrinsic::arm_neon_vqrshiftnsu:
8151       VShiftOpc = ARMISD::VQRSHRNsu; break;
8152     }
8153
8154     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8155                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8156   }
8157
8158   case Intrinsic::arm_neon_vshiftins: {
8159     EVT VT = N->getOperand(1).getValueType();
8160     int64_t Cnt;
8161     unsigned VShiftOpc = 0;
8162
8163     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8164       VShiftOpc = ARMISD::VSLI;
8165     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8166       VShiftOpc = ARMISD::VSRI;
8167     else {
8168       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8169     }
8170
8171     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8172                        N->getOperand(1), N->getOperand(2),
8173                        DAG.getConstant(Cnt, MVT::i32));
8174   }
8175
8176   case Intrinsic::arm_neon_vqrshifts:
8177   case Intrinsic::arm_neon_vqrshiftu:
8178     // No immediate versions of these to check for.
8179     break;
8180   }
8181
8182   return SDValue();
8183 }
8184
8185 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8186 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8187 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8188 /// vector element shift counts are generally not legal, and it is hard to see
8189 /// their values after they get legalized to loads from a constant pool.
8190 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8191                                    const ARMSubtarget *ST) {
8192   EVT VT = N->getValueType(0);
8193   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8194     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8195     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8196     SDValue N1 = N->getOperand(1);
8197     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8198       SDValue N0 = N->getOperand(0);
8199       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8200           DAG.MaskedValueIsZero(N0.getOperand(0),
8201                                 APInt::getHighBitsSet(32, 16)))
8202         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8203     }
8204   }
8205
8206   // Nothing to be done for scalar shifts.
8207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8208   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8209     return SDValue();
8210
8211   assert(ST->hasNEON() && "unexpected vector shift");
8212   int64_t Cnt;
8213
8214   switch (N->getOpcode()) {
8215   default: llvm_unreachable("unexpected shift opcode");
8216
8217   case ISD::SHL:
8218     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8219       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8220                          DAG.getConstant(Cnt, MVT::i32));
8221     break;
8222
8223   case ISD::SRA:
8224   case ISD::SRL:
8225     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8226       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8227                             ARMISD::VSHRs : ARMISD::VSHRu);
8228       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8229                          DAG.getConstant(Cnt, MVT::i32));
8230     }
8231   }
8232   return SDValue();
8233 }
8234
8235 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8236 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8237 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8238                                     const ARMSubtarget *ST) {
8239   SDValue N0 = N->getOperand(0);
8240
8241   // Check for sign- and zero-extensions of vector extract operations of 8-
8242   // and 16-bit vector elements.  NEON supports these directly.  They are
8243   // handled during DAG combining because type legalization will promote them
8244   // to 32-bit types and it is messy to recognize the operations after that.
8245   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8246     SDValue Vec = N0.getOperand(0);
8247     SDValue Lane = N0.getOperand(1);
8248     EVT VT = N->getValueType(0);
8249     EVT EltVT = N0.getValueType();
8250     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8251
8252     if (VT == MVT::i32 &&
8253         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8254         TLI.isTypeLegal(Vec.getValueType()) &&
8255         isa<ConstantSDNode>(Lane)) {
8256
8257       unsigned Opc = 0;
8258       switch (N->getOpcode()) {
8259       default: llvm_unreachable("unexpected opcode");
8260       case ISD::SIGN_EXTEND:
8261         Opc = ARMISD::VGETLANEs;
8262         break;
8263       case ISD::ZERO_EXTEND:
8264       case ISD::ANY_EXTEND:
8265         Opc = ARMISD::VGETLANEu;
8266         break;
8267       }
8268       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8269     }
8270   }
8271
8272   return SDValue();
8273 }
8274
8275 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8276 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8277 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8278                                        const ARMSubtarget *ST) {
8279   // If the target supports NEON, try to use vmax/vmin instructions for f32
8280   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8281   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8282   // a NaN; only do the transformation when it matches that behavior.
8283
8284   // For now only do this when using NEON for FP operations; if using VFP, it
8285   // is not obvious that the benefit outweighs the cost of switching to the
8286   // NEON pipeline.
8287   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8288       N->getValueType(0) != MVT::f32)
8289     return SDValue();
8290
8291   SDValue CondLHS = N->getOperand(0);
8292   SDValue CondRHS = N->getOperand(1);
8293   SDValue LHS = N->getOperand(2);
8294   SDValue RHS = N->getOperand(3);
8295   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8296
8297   unsigned Opcode = 0;
8298   bool IsReversed;
8299   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8300     IsReversed = false; // x CC y ? x : y
8301   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8302     IsReversed = true ; // x CC y ? y : x
8303   } else {
8304     return SDValue();
8305   }
8306
8307   bool IsUnordered;
8308   switch (CC) {
8309   default: break;
8310   case ISD::SETOLT:
8311   case ISD::SETOLE:
8312   case ISD::SETLT:
8313   case ISD::SETLE:
8314   case ISD::SETULT:
8315   case ISD::SETULE:
8316     // If LHS is NaN, an ordered comparison will be false and the result will
8317     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8318     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8319     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8320     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8321       break;
8322     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8323     // will return -0, so vmin can only be used for unsafe math or if one of
8324     // the operands is known to be nonzero.
8325     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8326         !DAG.getTarget().Options.UnsafeFPMath &&
8327         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8328       break;
8329     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8330     break;
8331
8332   case ISD::SETOGT:
8333   case ISD::SETOGE:
8334   case ISD::SETGT:
8335   case ISD::SETGE:
8336   case ISD::SETUGT:
8337   case ISD::SETUGE:
8338     // If LHS is NaN, an ordered comparison will be false and the result will
8339     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8340     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8341     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8342     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8343       break;
8344     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8345     // will return +0, so vmax can only be used for unsafe math or if one of
8346     // the operands is known to be nonzero.
8347     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8348         !DAG.getTarget().Options.UnsafeFPMath &&
8349         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8350       break;
8351     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8352     break;
8353   }
8354
8355   if (!Opcode)
8356     return SDValue();
8357   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8358 }
8359
8360 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8361 SDValue
8362 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8363   SDValue Cmp = N->getOperand(4);
8364   if (Cmp.getOpcode() != ARMISD::CMPZ)
8365     // Only looking at EQ and NE cases.
8366     return SDValue();
8367
8368   EVT VT = N->getValueType(0);
8369   DebugLoc dl = N->getDebugLoc();
8370   SDValue LHS = Cmp.getOperand(0);
8371   SDValue RHS = Cmp.getOperand(1);
8372   SDValue FalseVal = N->getOperand(0);
8373   SDValue TrueVal = N->getOperand(1);
8374   SDValue ARMcc = N->getOperand(2);
8375   ARMCC::CondCodes CC =
8376     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8377
8378   // Simplify
8379   //   mov     r1, r0
8380   //   cmp     r1, x
8381   //   mov     r0, y
8382   //   moveq   r0, x
8383   // to
8384   //   cmp     r0, x
8385   //   movne   r0, y
8386   //
8387   //   mov     r1, r0
8388   //   cmp     r1, x
8389   //   mov     r0, x
8390   //   movne   r0, y
8391   // to
8392   //   cmp     r0, x
8393   //   movne   r0, y
8394   /// FIXME: Turn this into a target neutral optimization?
8395   SDValue Res;
8396   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8397     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8398                       N->getOperand(3), Cmp);
8399   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8400     SDValue ARMcc;
8401     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8402     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8403                       N->getOperand(3), NewCmp);
8404   }
8405
8406   if (Res.getNode()) {
8407     APInt KnownZero, KnownOne;
8408     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8409     // Capture demanded bits information that would be otherwise lost.
8410     if (KnownZero == 0xfffffffe)
8411       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8412                         DAG.getValueType(MVT::i1));
8413     else if (KnownZero == 0xffffff00)
8414       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8415                         DAG.getValueType(MVT::i8));
8416     else if (KnownZero == 0xffff0000)
8417       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8418                         DAG.getValueType(MVT::i16));
8419   }
8420
8421   return Res;
8422 }
8423
8424 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8425                                              DAGCombinerInfo &DCI) const {
8426   switch (N->getOpcode()) {
8427   default: break;
8428   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8429   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8430   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8431   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8432   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8433   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8434   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8435   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8436   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8437   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8438   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8439   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8440   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8441   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8442   case ISD::FP_TO_SINT:
8443   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8444   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8445   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8446   case ISD::SHL:
8447   case ISD::SRA:
8448   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8449   case ISD::SIGN_EXTEND:
8450   case ISD::ZERO_EXTEND:
8451   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8452   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8453   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8454   case ARMISD::VLD2DUP:
8455   case ARMISD::VLD3DUP:
8456   case ARMISD::VLD4DUP:
8457     return CombineBaseUpdate(N, DCI);
8458   case ISD::INTRINSIC_VOID:
8459   case ISD::INTRINSIC_W_CHAIN:
8460     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8461     case Intrinsic::arm_neon_vld1:
8462     case Intrinsic::arm_neon_vld2:
8463     case Intrinsic::arm_neon_vld3:
8464     case Intrinsic::arm_neon_vld4:
8465     case Intrinsic::arm_neon_vld2lane:
8466     case Intrinsic::arm_neon_vld3lane:
8467     case Intrinsic::arm_neon_vld4lane:
8468     case Intrinsic::arm_neon_vst1:
8469     case Intrinsic::arm_neon_vst2:
8470     case Intrinsic::arm_neon_vst3:
8471     case Intrinsic::arm_neon_vst4:
8472     case Intrinsic::arm_neon_vst2lane:
8473     case Intrinsic::arm_neon_vst3lane:
8474     case Intrinsic::arm_neon_vst4lane:
8475       return CombineBaseUpdate(N, DCI);
8476     default: break;
8477     }
8478     break;
8479   }
8480   return SDValue();
8481 }
8482
8483 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8484                                                           EVT VT) const {
8485   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8486 }
8487
8488 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8489   if (!Subtarget->allowsUnalignedMem())
8490     return false;
8491
8492   switch (VT.getSimpleVT().SimpleTy) {
8493   default:
8494     return false;
8495   case MVT::i8:
8496   case MVT::i16:
8497   case MVT::i32:
8498     return true;
8499   // FIXME: VLD1 etc with standard alignment is legal.
8500   }
8501 }
8502
8503 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8504                        unsigned AlignCheck) {
8505   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8506           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8507 }
8508
8509 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8510                                            unsigned DstAlign, unsigned SrcAlign,
8511                                            bool IsZeroVal,
8512                                            bool MemcpyStrSrc,
8513                                            MachineFunction &MF) const {
8514   const Function *F = MF.getFunction();
8515
8516   // See if we can use NEON instructions for this...
8517   if (IsZeroVal &&
8518       !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8519       Subtarget->hasNEON()) {
8520     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8521       return MVT::v4i32;
8522     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8523       return MVT::v2i32;
8524     }
8525   }
8526
8527   // Lowering to i32/i16 if the size permits.
8528   if (Size >= 4) {
8529     return MVT::i32;
8530   } else if (Size >= 2) {
8531     return MVT::i16;
8532   }
8533
8534   // Let the target-independent logic figure it out.
8535   return MVT::Other;
8536 }
8537
8538 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8539   if (V < 0)
8540     return false;
8541
8542   unsigned Scale = 1;
8543   switch (VT.getSimpleVT().SimpleTy) {
8544   default: return false;
8545   case MVT::i1:
8546   case MVT::i8:
8547     // Scale == 1;
8548     break;
8549   case MVT::i16:
8550     // Scale == 2;
8551     Scale = 2;
8552     break;
8553   case MVT::i32:
8554     // Scale == 4;
8555     Scale = 4;
8556     break;
8557   }
8558
8559   if ((V & (Scale - 1)) != 0)
8560     return false;
8561   V /= Scale;
8562   return V == (V & ((1LL << 5) - 1));
8563 }
8564
8565 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8566                                       const ARMSubtarget *Subtarget) {
8567   bool isNeg = false;
8568   if (V < 0) {
8569     isNeg = true;
8570     V = - V;
8571   }
8572
8573   switch (VT.getSimpleVT().SimpleTy) {
8574   default: return false;
8575   case MVT::i1:
8576   case MVT::i8:
8577   case MVT::i16:
8578   case MVT::i32:
8579     // + imm12 or - imm8
8580     if (isNeg)
8581       return V == (V & ((1LL << 8) - 1));
8582     return V == (V & ((1LL << 12) - 1));
8583   case MVT::f32:
8584   case MVT::f64:
8585     // Same as ARM mode. FIXME: NEON?
8586     if (!Subtarget->hasVFP2())
8587       return false;
8588     if ((V & 3) != 0)
8589       return false;
8590     V >>= 2;
8591     return V == (V & ((1LL << 8) - 1));
8592   }
8593 }
8594
8595 /// isLegalAddressImmediate - Return true if the integer value can be used
8596 /// as the offset of the target addressing mode for load / store of the
8597 /// given type.
8598 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8599                                     const ARMSubtarget *Subtarget) {
8600   if (V == 0)
8601     return true;
8602
8603   if (!VT.isSimple())
8604     return false;
8605
8606   if (Subtarget->isThumb1Only())
8607     return isLegalT1AddressImmediate(V, VT);
8608   else if (Subtarget->isThumb2())
8609     return isLegalT2AddressImmediate(V, VT, Subtarget);
8610
8611   // ARM mode.
8612   if (V < 0)
8613     V = - V;
8614   switch (VT.getSimpleVT().SimpleTy) {
8615   default: return false;
8616   case MVT::i1:
8617   case MVT::i8:
8618   case MVT::i32:
8619     // +- imm12
8620     return V == (V & ((1LL << 12) - 1));
8621   case MVT::i16:
8622     // +- imm8
8623     return V == (V & ((1LL << 8) - 1));
8624   case MVT::f32:
8625   case MVT::f64:
8626     if (!Subtarget->hasVFP2()) // FIXME: NEON?
8627       return false;
8628     if ((V & 3) != 0)
8629       return false;
8630     V >>= 2;
8631     return V == (V & ((1LL << 8) - 1));
8632   }
8633 }
8634
8635 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8636                                                       EVT VT) const {
8637   int Scale = AM.Scale;
8638   if (Scale < 0)
8639     return false;
8640
8641   switch (VT.getSimpleVT().SimpleTy) {
8642   default: return false;
8643   case MVT::i1:
8644   case MVT::i8:
8645   case MVT::i16:
8646   case MVT::i32:
8647     if (Scale == 1)
8648       return true;
8649     // r + r << imm
8650     Scale = Scale & ~1;
8651     return Scale == 2 || Scale == 4 || Scale == 8;
8652   case MVT::i64:
8653     // r + r
8654     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8655       return true;
8656     return false;
8657   case MVT::isVoid:
8658     // Note, we allow "void" uses (basically, uses that aren't loads or
8659     // stores), because arm allows folding a scale into many arithmetic
8660     // operations.  This should be made more precise and revisited later.
8661
8662     // Allow r << imm, but the imm has to be a multiple of two.
8663     if (Scale & 1) return false;
8664     return isPowerOf2_32(Scale);
8665   }
8666 }
8667
8668 /// isLegalAddressingMode - Return true if the addressing mode represented
8669 /// by AM is legal for this target, for a load/store of the specified type.
8670 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8671                                               Type *Ty) const {
8672   EVT VT = getValueType(Ty, true);
8673   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8674     return false;
8675
8676   // Can never fold addr of global into load/store.
8677   if (AM.BaseGV)
8678     return false;
8679
8680   switch (AM.Scale) {
8681   case 0:  // no scale reg, must be "r+i" or "r", or "i".
8682     break;
8683   case 1:
8684     if (Subtarget->isThumb1Only())
8685       return false;
8686     // FALL THROUGH.
8687   default:
8688     // ARM doesn't support any R+R*scale+imm addr modes.
8689     if (AM.BaseOffs)
8690       return false;
8691
8692     if (!VT.isSimple())
8693       return false;
8694
8695     if (Subtarget->isThumb2())
8696       return isLegalT2ScaledAddressingMode(AM, VT);
8697
8698     int Scale = AM.Scale;
8699     switch (VT.getSimpleVT().SimpleTy) {
8700     default: return false;
8701     case MVT::i1:
8702     case MVT::i8:
8703     case MVT::i32:
8704       if (Scale < 0) Scale = -Scale;
8705       if (Scale == 1)
8706         return true;
8707       // r + r << imm
8708       return isPowerOf2_32(Scale & ~1);
8709     case MVT::i16:
8710     case MVT::i64:
8711       // r + r
8712       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8713         return true;
8714       return false;
8715
8716     case MVT::isVoid:
8717       // Note, we allow "void" uses (basically, uses that aren't loads or
8718       // stores), because arm allows folding a scale into many arithmetic
8719       // operations.  This should be made more precise and revisited later.
8720
8721       // Allow r << imm, but the imm has to be a multiple of two.
8722       if (Scale & 1) return false;
8723       return isPowerOf2_32(Scale);
8724     }
8725   }
8726   return true;
8727 }
8728
8729 /// isLegalICmpImmediate - Return true if the specified immediate is legal
8730 /// icmp immediate, that is the target has icmp instructions which can compare
8731 /// a register against the immediate without having to materialize the
8732 /// immediate into a register.
8733 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8734   // Thumb2 and ARM modes can use cmn for negative immediates.
8735   if (!Subtarget->isThumb())
8736     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
8737   if (Subtarget->isThumb2())
8738     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
8739   // Thumb1 doesn't have cmn, and only 8-bit immediates.
8740   return Imm >= 0 && Imm <= 255;
8741 }
8742
8743 /// isLegalAddImmediate - Return true if the specified immediate is legal
8744 /// add immediate, that is the target has add instructions which can add
8745 /// a register with the immediate without having to materialize the
8746 /// immediate into a register.
8747 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8748   return ARM_AM::getSOImmVal(Imm) != -1;
8749 }
8750
8751 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8752                                       bool isSEXTLoad, SDValue &Base,
8753                                       SDValue &Offset, bool &isInc,
8754                                       SelectionDAG &DAG) {
8755   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8756     return false;
8757
8758   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8759     // AddressingMode 3
8760     Base = Ptr->getOperand(0);
8761     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8762       int RHSC = (int)RHS->getZExtValue();
8763       if (RHSC < 0 && RHSC > -256) {
8764         assert(Ptr->getOpcode() == ISD::ADD);
8765         isInc = false;
8766         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8767         return true;
8768       }
8769     }
8770     isInc = (Ptr->getOpcode() == ISD::ADD);
8771     Offset = Ptr->getOperand(1);
8772     return true;
8773   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8774     // AddressingMode 2
8775     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8776       int RHSC = (int)RHS->getZExtValue();
8777       if (RHSC < 0 && RHSC > -0x1000) {
8778         assert(Ptr->getOpcode() == ISD::ADD);
8779         isInc = false;
8780         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8781         Base = Ptr->getOperand(0);
8782         return true;
8783       }
8784     }
8785
8786     if (Ptr->getOpcode() == ISD::ADD) {
8787       isInc = true;
8788       ARM_AM::ShiftOpc ShOpcVal=
8789         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8790       if (ShOpcVal != ARM_AM::no_shift) {
8791         Base = Ptr->getOperand(1);
8792         Offset = Ptr->getOperand(0);
8793       } else {
8794         Base = Ptr->getOperand(0);
8795         Offset = Ptr->getOperand(1);
8796       }
8797       return true;
8798     }
8799
8800     isInc = (Ptr->getOpcode() == ISD::ADD);
8801     Base = Ptr->getOperand(0);
8802     Offset = Ptr->getOperand(1);
8803     return true;
8804   }
8805
8806   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8807   return false;
8808 }
8809
8810 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8811                                      bool isSEXTLoad, SDValue &Base,
8812                                      SDValue &Offset, bool &isInc,
8813                                      SelectionDAG &DAG) {
8814   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8815     return false;
8816
8817   Base = Ptr->getOperand(0);
8818   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8819     int RHSC = (int)RHS->getZExtValue();
8820     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8821       assert(Ptr->getOpcode() == ISD::ADD);
8822       isInc = false;
8823       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8824       return true;
8825     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8826       isInc = Ptr->getOpcode() == ISD::ADD;
8827       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8828       return true;
8829     }
8830   }
8831
8832   return false;
8833 }
8834
8835 /// getPreIndexedAddressParts - returns true by value, base pointer and
8836 /// offset pointer and addressing mode by reference if the node's address
8837 /// can be legally represented as pre-indexed load / store address.
8838 bool
8839 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8840                                              SDValue &Offset,
8841                                              ISD::MemIndexedMode &AM,
8842                                              SelectionDAG &DAG) const {
8843   if (Subtarget->isThumb1Only())
8844     return false;
8845
8846   EVT VT;
8847   SDValue Ptr;
8848   bool isSEXTLoad = false;
8849   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8850     Ptr = LD->getBasePtr();
8851     VT  = LD->getMemoryVT();
8852     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8853   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8854     Ptr = ST->getBasePtr();
8855     VT  = ST->getMemoryVT();
8856   } else
8857     return false;
8858
8859   bool isInc;
8860   bool isLegal = false;
8861   if (Subtarget->isThumb2())
8862     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8863                                        Offset, isInc, DAG);
8864   else
8865     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8866                                         Offset, isInc, DAG);
8867   if (!isLegal)
8868     return false;
8869
8870   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8871   return true;
8872 }
8873
8874 /// getPostIndexedAddressParts - returns true by value, base pointer and
8875 /// offset pointer and addressing mode by reference if this node can be
8876 /// combined with a load / store to form a post-indexed load / store.
8877 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8878                                                    SDValue &Base,
8879                                                    SDValue &Offset,
8880                                                    ISD::MemIndexedMode &AM,
8881                                                    SelectionDAG &DAG) const {
8882   if (Subtarget->isThumb1Only())
8883     return false;
8884
8885   EVT VT;
8886   SDValue Ptr;
8887   bool isSEXTLoad = false;
8888   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8889     VT  = LD->getMemoryVT();
8890     Ptr = LD->getBasePtr();
8891     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8892   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8893     VT  = ST->getMemoryVT();
8894     Ptr = ST->getBasePtr();
8895   } else
8896     return false;
8897
8898   bool isInc;
8899   bool isLegal = false;
8900   if (Subtarget->isThumb2())
8901     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8902                                        isInc, DAG);
8903   else
8904     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8905                                         isInc, DAG);
8906   if (!isLegal)
8907     return false;
8908
8909   if (Ptr != Base) {
8910     // Swap base ptr and offset to catch more post-index load / store when
8911     // it's legal. In Thumb2 mode, offset must be an immediate.
8912     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8913         !Subtarget->isThumb2())
8914       std::swap(Base, Offset);
8915
8916     // Post-indexed load / store update the base pointer.
8917     if (Ptr != Base)
8918       return false;
8919   }
8920
8921   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8922   return true;
8923 }
8924
8925 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8926                                                        APInt &KnownZero,
8927                                                        APInt &KnownOne,
8928                                                        const SelectionDAG &DAG,
8929                                                        unsigned Depth) const {
8930   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
8931   switch (Op.getOpcode()) {
8932   default: break;
8933   case ARMISD::CMOV: {
8934     // Bits are known zero/one if known on the LHS and RHS.
8935     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
8936     if (KnownZero == 0 && KnownOne == 0) return;
8937
8938     APInt KnownZeroRHS, KnownOneRHS;
8939     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
8940     KnownZero &= KnownZeroRHS;
8941     KnownOne  &= KnownOneRHS;
8942     return;
8943   }
8944   }
8945 }
8946
8947 //===----------------------------------------------------------------------===//
8948 //                           ARM Inline Assembly Support
8949 //===----------------------------------------------------------------------===//
8950
8951 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8952   // Looking for "rev" which is V6+.
8953   if (!Subtarget->hasV6Ops())
8954     return false;
8955
8956   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8957   std::string AsmStr = IA->getAsmString();
8958   SmallVector<StringRef, 4> AsmPieces;
8959   SplitString(AsmStr, AsmPieces, ";\n");
8960
8961   switch (AsmPieces.size()) {
8962   default: return false;
8963   case 1:
8964     AsmStr = AsmPieces[0];
8965     AsmPieces.clear();
8966     SplitString(AsmStr, AsmPieces, " \t,");
8967
8968     // rev $0, $1
8969     if (AsmPieces.size() == 3 &&
8970         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8971         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8972       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8973       if (Ty && Ty->getBitWidth() == 32)
8974         return IntrinsicLowering::LowerToByteSwap(CI);
8975     }
8976     break;
8977   }
8978
8979   return false;
8980 }
8981
8982 /// getConstraintType - Given a constraint letter, return the type of
8983 /// constraint it is for this target.
8984 ARMTargetLowering::ConstraintType
8985 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8986   if (Constraint.size() == 1) {
8987     switch (Constraint[0]) {
8988     default:  break;
8989     case 'l': return C_RegisterClass;
8990     case 'w': return C_RegisterClass;
8991     case 'h': return C_RegisterClass;
8992     case 'x': return C_RegisterClass;
8993     case 't': return C_RegisterClass;
8994     case 'j': return C_Other; // Constant for movw.
8995       // An address with a single base register. Due to the way we
8996       // currently handle addresses it is the same as an 'r' memory constraint.
8997     case 'Q': return C_Memory;
8998     }
8999   } else if (Constraint.size() == 2) {
9000     switch (Constraint[0]) {
9001     default: break;
9002     // All 'U+' constraints are addresses.
9003     case 'U': return C_Memory;
9004     }
9005   }
9006   return TargetLowering::getConstraintType(Constraint);
9007 }
9008
9009 /// Examine constraint type and operand type and determine a weight value.
9010 /// This object must already have been set up with the operand type
9011 /// and the current alternative constraint selected.
9012 TargetLowering::ConstraintWeight
9013 ARMTargetLowering::getSingleConstraintMatchWeight(
9014     AsmOperandInfo &info, const char *constraint) const {
9015   ConstraintWeight weight = CW_Invalid;
9016   Value *CallOperandVal = info.CallOperandVal;
9017     // If we don't have a value, we can't do a match,
9018     // but allow it at the lowest weight.
9019   if (CallOperandVal == NULL)
9020     return CW_Default;
9021   Type *type = CallOperandVal->getType();
9022   // Look at the constraint type.
9023   switch (*constraint) {
9024   default:
9025     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9026     break;
9027   case 'l':
9028     if (type->isIntegerTy()) {
9029       if (Subtarget->isThumb())
9030         weight = CW_SpecificReg;
9031       else
9032         weight = CW_Register;
9033     }
9034     break;
9035   case 'w':
9036     if (type->isFloatingPointTy())
9037       weight = CW_Register;
9038     break;
9039   }
9040   return weight;
9041 }
9042
9043 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9044 RCPair
9045 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9046                                                 EVT VT) const {
9047   if (Constraint.size() == 1) {
9048     // GCC ARM Constraint Letters
9049     switch (Constraint[0]) {
9050     case 'l': // Low regs or general regs.
9051       if (Subtarget->isThumb())
9052         return RCPair(0U, &ARM::tGPRRegClass);
9053       return RCPair(0U, &ARM::GPRRegClass);
9054     case 'h': // High regs or no regs.
9055       if (Subtarget->isThumb())
9056         return RCPair(0U, &ARM::hGPRRegClass);
9057       break;
9058     case 'r':
9059       return RCPair(0U, &ARM::GPRRegClass);
9060     case 'w':
9061       if (VT == MVT::f32)
9062         return RCPair(0U, &ARM::SPRRegClass);
9063       if (VT.getSizeInBits() == 64)
9064         return RCPair(0U, &ARM::DPRRegClass);
9065       if (VT.getSizeInBits() == 128)
9066         return RCPair(0U, &ARM::QPRRegClass);
9067       break;
9068     case 'x':
9069       if (VT == MVT::f32)
9070         return RCPair(0U, &ARM::SPR_8RegClass);
9071       if (VT.getSizeInBits() == 64)
9072         return RCPair(0U, &ARM::DPR_8RegClass);
9073       if (VT.getSizeInBits() == 128)
9074         return RCPair(0U, &ARM::QPR_8RegClass);
9075       break;
9076     case 't':
9077       if (VT == MVT::f32)
9078         return RCPair(0U, &ARM::SPRRegClass);
9079       break;
9080     }
9081   }
9082   if (StringRef("{cc}").equals_lower(Constraint))
9083     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9084
9085   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9086 }
9087
9088 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9089 /// vector.  If it is invalid, don't add anything to Ops.
9090 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9091                                                      std::string &Constraint,
9092                                                      std::vector<SDValue>&Ops,
9093                                                      SelectionDAG &DAG) const {
9094   SDValue Result(0, 0);
9095
9096   // Currently only support length 1 constraints.
9097   if (Constraint.length() != 1) return;
9098
9099   char ConstraintLetter = Constraint[0];
9100   switch (ConstraintLetter) {
9101   default: break;
9102   case 'j':
9103   case 'I': case 'J': case 'K': case 'L':
9104   case 'M': case 'N': case 'O':
9105     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9106     if (!C)
9107       return;
9108
9109     int64_t CVal64 = C->getSExtValue();
9110     int CVal = (int) CVal64;
9111     // None of these constraints allow values larger than 32 bits.  Check
9112     // that the value fits in an int.
9113     if (CVal != CVal64)
9114       return;
9115
9116     switch (ConstraintLetter) {
9117       case 'j':
9118         // Constant suitable for movw, must be between 0 and
9119         // 65535.
9120         if (Subtarget->hasV6T2Ops())
9121           if (CVal >= 0 && CVal <= 65535)
9122             break;
9123         return;
9124       case 'I':
9125         if (Subtarget->isThumb1Only()) {
9126           // This must be a constant between 0 and 255, for ADD
9127           // immediates.
9128           if (CVal >= 0 && CVal <= 255)
9129             break;
9130         } else if (Subtarget->isThumb2()) {
9131           // A constant that can be used as an immediate value in a
9132           // data-processing instruction.
9133           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9134             break;
9135         } else {
9136           // A constant that can be used as an immediate value in a
9137           // data-processing instruction.
9138           if (ARM_AM::getSOImmVal(CVal) != -1)
9139             break;
9140         }
9141         return;
9142
9143       case 'J':
9144         if (Subtarget->isThumb()) {  // FIXME thumb2
9145           // This must be a constant between -255 and -1, for negated ADD
9146           // immediates. This can be used in GCC with an "n" modifier that
9147           // prints the negated value, for use with SUB instructions. It is
9148           // not useful otherwise but is implemented for compatibility.
9149           if (CVal >= -255 && CVal <= -1)
9150             break;
9151         } else {
9152           // This must be a constant between -4095 and 4095. It is not clear
9153           // what this constraint is intended for. Implemented for
9154           // compatibility with GCC.
9155           if (CVal >= -4095 && CVal <= 4095)
9156             break;
9157         }
9158         return;
9159
9160       case 'K':
9161         if (Subtarget->isThumb1Only()) {
9162           // A 32-bit value where only one byte has a nonzero value. Exclude
9163           // zero to match GCC. This constraint is used by GCC internally for
9164           // constants that can be loaded with a move/shift combination.
9165           // It is not useful otherwise but is implemented for compatibility.
9166           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9167             break;
9168         } else if (Subtarget->isThumb2()) {
9169           // A constant whose bitwise inverse can be used as an immediate
9170           // value in a data-processing instruction. This can be used in GCC
9171           // with a "B" modifier that prints the inverted value, for use with
9172           // BIC and MVN instructions. It is not useful otherwise but is
9173           // implemented for compatibility.
9174           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9175             break;
9176         } else {
9177           // A constant whose bitwise inverse can be used as an immediate
9178           // value in a data-processing instruction. This can be used in GCC
9179           // with a "B" modifier that prints the inverted value, for use with
9180           // BIC and MVN instructions. It is not useful otherwise but is
9181           // implemented for compatibility.
9182           if (ARM_AM::getSOImmVal(~CVal) != -1)
9183             break;
9184         }
9185         return;
9186
9187       case 'L':
9188         if (Subtarget->isThumb1Only()) {
9189           // This must be a constant between -7 and 7,
9190           // for 3-operand ADD/SUB immediate instructions.
9191           if (CVal >= -7 && CVal < 7)
9192             break;
9193         } else if (Subtarget->isThumb2()) {
9194           // A constant whose negation can be used as an immediate value in a
9195           // data-processing instruction. This can be used in GCC with an "n"
9196           // modifier that prints the negated value, for use with SUB
9197           // instructions. It is not useful otherwise but is implemented for
9198           // compatibility.
9199           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9200             break;
9201         } else {
9202           // A constant whose negation can be used as an immediate value in a
9203           // data-processing instruction. This can be used in GCC with an "n"
9204           // modifier that prints the negated value, for use with SUB
9205           // instructions. It is not useful otherwise but is implemented for
9206           // compatibility.
9207           if (ARM_AM::getSOImmVal(-CVal) != -1)
9208             break;
9209         }
9210         return;
9211
9212       case 'M':
9213         if (Subtarget->isThumb()) { // FIXME thumb2
9214           // This must be a multiple of 4 between 0 and 1020, for
9215           // ADD sp + immediate.
9216           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9217             break;
9218         } else {
9219           // A power of two or a constant between 0 and 32.  This is used in
9220           // GCC for the shift amount on shifted register operands, but it is
9221           // useful in general for any shift amounts.
9222           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9223             break;
9224         }
9225         return;
9226
9227       case 'N':
9228         if (Subtarget->isThumb()) {  // FIXME thumb2
9229           // This must be a constant between 0 and 31, for shift amounts.
9230           if (CVal >= 0 && CVal <= 31)
9231             break;
9232         }
9233         return;
9234
9235       case 'O':
9236         if (Subtarget->isThumb()) {  // FIXME thumb2
9237           // This must be a multiple of 4 between -508 and 508, for
9238           // ADD/SUB sp = sp + immediate.
9239           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9240             break;
9241         }
9242         return;
9243     }
9244     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9245     break;
9246   }
9247
9248   if (Result.getNode()) {
9249     Ops.push_back(Result);
9250     return;
9251   }
9252   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9253 }
9254
9255 bool
9256 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9257   // The ARM target isn't yet aware of offsets.
9258   return false;
9259 }
9260
9261 bool ARM::isBitFieldInvertedMask(unsigned v) {
9262   if (v == 0xffffffff)
9263     return 0;
9264   // there can be 1's on either or both "outsides", all the "inside"
9265   // bits must be 0's
9266   unsigned int lsb = 0, msb = 31;
9267   while (v & (1 << msb)) --msb;
9268   while (v & (1 << lsb)) ++lsb;
9269   for (unsigned int i = lsb; i <= msb; ++i) {
9270     if (v & (1 << i))
9271       return 0;
9272   }
9273   return 1;
9274 }
9275
9276 /// isFPImmLegal - Returns true if the target can instruction select the
9277 /// specified FP immediate natively. If false, the legalizer will
9278 /// materialize the FP immediate as a load from a constant pool.
9279 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9280   if (!Subtarget->hasVFP3())
9281     return false;
9282   if (VT == MVT::f32)
9283     return ARM_AM::getFP32Imm(Imm) != -1;
9284   if (VT == MVT::f64)
9285     return ARM_AM::getFP64Imm(Imm) != -1;
9286   return false;
9287 }
9288
9289 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9290 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9291 /// specified in the intrinsic calls.
9292 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9293                                            const CallInst &I,
9294                                            unsigned Intrinsic) const {
9295   switch (Intrinsic) {
9296   case Intrinsic::arm_neon_vld1:
9297   case Intrinsic::arm_neon_vld2:
9298   case Intrinsic::arm_neon_vld3:
9299   case Intrinsic::arm_neon_vld4:
9300   case Intrinsic::arm_neon_vld2lane:
9301   case Intrinsic::arm_neon_vld3lane:
9302   case Intrinsic::arm_neon_vld4lane: {
9303     Info.opc = ISD::INTRINSIC_W_CHAIN;
9304     // Conservatively set memVT to the entire set of vectors loaded.
9305     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9306     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9307     Info.ptrVal = I.getArgOperand(0);
9308     Info.offset = 0;
9309     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9310     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9311     Info.vol = false; // volatile loads with NEON intrinsics not supported
9312     Info.readMem = true;
9313     Info.writeMem = false;
9314     return true;
9315   }
9316   case Intrinsic::arm_neon_vst1:
9317   case Intrinsic::arm_neon_vst2:
9318   case Intrinsic::arm_neon_vst3:
9319   case Intrinsic::arm_neon_vst4:
9320   case Intrinsic::arm_neon_vst2lane:
9321   case Intrinsic::arm_neon_vst3lane:
9322   case Intrinsic::arm_neon_vst4lane: {
9323     Info.opc = ISD::INTRINSIC_VOID;
9324     // Conservatively set memVT to the entire set of vectors stored.
9325     unsigned NumElts = 0;
9326     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9327       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9328       if (!ArgTy->isVectorTy())
9329         break;
9330       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9331     }
9332     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9333     Info.ptrVal = I.getArgOperand(0);
9334     Info.offset = 0;
9335     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9336     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9337     Info.vol = false; // volatile stores with NEON intrinsics not supported
9338     Info.readMem = false;
9339     Info.writeMem = true;
9340     return true;
9341   }
9342   case Intrinsic::arm_strexd: {
9343     Info.opc = ISD::INTRINSIC_W_CHAIN;
9344     Info.memVT = MVT::i64;
9345     Info.ptrVal = I.getArgOperand(2);
9346     Info.offset = 0;
9347     Info.align = 8;
9348     Info.vol = true;
9349     Info.readMem = false;
9350     Info.writeMem = true;
9351     return true;
9352   }
9353   case Intrinsic::arm_ldrexd: {
9354     Info.opc = ISD::INTRINSIC_W_CHAIN;
9355     Info.memVT = MVT::i64;
9356     Info.ptrVal = I.getArgOperand(0);
9357     Info.offset = 0;
9358     Info.align = 8;
9359     Info.vol = true;
9360     Info.readMem = true;
9361     Info.writeMem = false;
9362     return true;
9363   }
9364   default:
9365     break;
9366   }
9367
9368   return false;
9369 }