Issue description:
[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 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
126   if (VT.isInteger()) {
127     setOperationAction(ISD::SHL, VT, Custom);
128     setOperationAction(ISD::SRA, VT, Custom);
129     setOperationAction(ISD::SRL, VT, Custom);
130   }
131
132   // Promote all bit-wise operations.
133   if (VT.isInteger() && VT != PromotedBitwiseVT) {
134     setOperationAction(ISD::AND, VT, Promote);
135     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136     setOperationAction(ISD::OR,  VT, Promote);
137     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
138     setOperationAction(ISD::XOR, VT, Promote);
139     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140   }
141
142   // Neon does not support vector divide/remainder operations.
143   setOperationAction(ISD::SDIV, VT, Expand);
144   setOperationAction(ISD::UDIV, VT, Expand);
145   setOperationAction(ISD::FDIV, VT, Expand);
146   setOperationAction(ISD::SREM, VT, Expand);
147   setOperationAction(ISD::UREM, VT, Expand);
148   setOperationAction(ISD::FREM, VT, Expand);
149 }
150
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152   addRegisterClass(VT, &ARM::DPRRegClass);
153   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 }
155
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157   addRegisterClass(VT, &ARM::QPRRegClass);
158   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 }
160
161 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
162   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
163     return new TargetLoweringObjectFileMachO();
164
165   return new ARMElfTargetObjectFile();
166 }
167
168 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
169     : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<ARMSubtarget>();
171   RegInfo = TM.getRegisterInfo();
172   Itins = TM.getInstrItineraryData();
173
174   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175
176   if (Subtarget->isTargetDarwin()) {
177     // Uses VFP for Thumb libfuncs if available.
178     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
179       // Single-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184
185       // Double-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190
191       // Single-precision comparisons.
192       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
199       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
200
201       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
208       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
209
210       // Double-precision comparisons.
211       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
218       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
219
220       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
227       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
228
229       // Floating-point to integer conversions.
230       // i64 conversions are done via library routines even when generating VFP
231       // instructions, so use the same ones.
232       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236
237       // Conversions between floating types.
238       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
240
241       // Integer to floating-point conversions.
242       // i64 conversions are done via library routines even when generating VFP
243       // instructions, so use the same ones.
244       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245       // e.g., __floatunsidf vs. __floatunssidfvfp.
246       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250     }
251   }
252
253   // These libcalls are not available in 32-bit.
254   setLibcallName(RTLIB::SHL_I128, 0);
255   setLibcallName(RTLIB::SRL_I128, 0);
256   setLibcallName(RTLIB::SRA_I128, 0);
257
258   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
259     // Double-precision floating-point arithmetic helper functions
260     // RTABI chapter 4.1.2, Table 2
261     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
269
270     // Double-precision floating-point comparison helper functions
271     // RTABI chapter 4.1.2, Table 3
272     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
286     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
287     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
288     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
296
297     // Single-precision floating-point arithmetic helper functions
298     // RTABI chapter 4.1.2, Table 4
299     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
307
308     // Single-precision floating-point comparison helper functions
309     // RTABI chapter 4.1.2, Table 5
310     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
324     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
325     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
326     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
334
335     // Floating-point to integer conversions.
336     // RTABI chapter 4.1.2, Table 6
337     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
353
354     // Conversions between floating types.
355     // RTABI chapter 4.1.2, Table 7
356     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
358     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
360
361     // Integer to floating-point conversions.
362     // RTABI chapter 4.1.2, Table 8
363     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379
380     // Long long helper functions
381     // RTABI chapter 4.2, Table 9
382     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
383     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
392
393     // Integer division functions
394     // RTABI chapter 4.3.1
395     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
411
412     // Memory operations
413     // RTABI chapter 4.3.4
414     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
415     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
417     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
420   }
421
422   // Use divmod compiler-rt calls for iOS 5.0 and later.
423   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
424       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
425     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
426     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
427   }
428
429   if (Subtarget->isThumb1Only())
430     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
431   else
432     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
433   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
434       !Subtarget->isThumb1Only()) {
435     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
436     if (!Subtarget->isFPOnlySP())
437       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
438
439     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440   }
441
442   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
444     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
445          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
446       setTruncStoreAction((MVT::SimpleValueType)VT,
447                           (MVT::SimpleValueType)InnerVT, Expand);
448     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
449     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
451   }
452
453   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
454
455   if (Subtarget->hasNEON()) {
456     addDRTypeForNEON(MVT::v2f32);
457     addDRTypeForNEON(MVT::v8i8);
458     addDRTypeForNEON(MVT::v4i16);
459     addDRTypeForNEON(MVT::v2i32);
460     addDRTypeForNEON(MVT::v1i64);
461
462     addQRTypeForNEON(MVT::v4f32);
463     addQRTypeForNEON(MVT::v2f64);
464     addQRTypeForNEON(MVT::v16i8);
465     addQRTypeForNEON(MVT::v8i16);
466     addQRTypeForNEON(MVT::v4i32);
467     addQRTypeForNEON(MVT::v2i64);
468
469     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
470     // neither Neon nor VFP support any arithmetic operations on it.
471     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
472     // supported for v4f32.
473     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
474     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
476     // FIXME: Code duplication: FDIV and FREM are expanded always, see
477     // ARMTargetLowering::addTypeForNEON method for details.
478     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
479     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
480     // FIXME: Create unittest.
481     // In another words, find a way when "copysign" appears in DAG with vector
482     // operands.
483     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
484     // FIXME: Code duplication: SETCC has custom operation action, see
485     // ARMTargetLowering::addTypeForNEON method for details.
486     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
487     // FIXME: Create unittest for FNEG and for FABS.
488     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
489     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
490     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
492     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
493     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
495     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
498     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
500     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
501     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
502     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
503     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
504     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
506
507     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
517     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
518
519     // Neon does not support some operations on v1i64 and v2i64 types.
520     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
521     // Custom handling for some quad-vector types to detect VMULL.
522     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
523     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
524     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
525     // Custom handling for some vector types to avoid expensive expansions
526     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
529     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
530     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
531     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
532     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
533     // a destination type that is wider than the source, and nor does
534     // it have a FP_TO_[SU]INT instruction with a narrower destination than
535     // source.
536     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
537     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
538     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
539     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540
541     setTargetDAGCombine(ISD::INTRINSIC_VOID);
542     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
543     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
544     setTargetDAGCombine(ISD::SHL);
545     setTargetDAGCombine(ISD::SRL);
546     setTargetDAGCombine(ISD::SRA);
547     setTargetDAGCombine(ISD::SIGN_EXTEND);
548     setTargetDAGCombine(ISD::ZERO_EXTEND);
549     setTargetDAGCombine(ISD::ANY_EXTEND);
550     setTargetDAGCombine(ISD::SELECT_CC);
551     setTargetDAGCombine(ISD::BUILD_VECTOR);
552     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
553     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
554     setTargetDAGCombine(ISD::STORE);
555     setTargetDAGCombine(ISD::FP_TO_SINT);
556     setTargetDAGCombine(ISD::FP_TO_UINT);
557     setTargetDAGCombine(ISD::FDIV);
558
559     // It is legal to extload from v4i8 to v4i16 or v4i32.
560     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
561                   MVT::v4i16, MVT::v2i16,
562                   MVT::v2i32};
563     for (unsigned i = 0; i < 6; ++i) {
564       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
565       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
566       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
567     }
568   }
569
570   // ARM and Thumb2 support UMLAL/SMLAL.
571   if (!Subtarget->isThumb1Only())
572     setTargetDAGCombine(ISD::ADDC);
573
574
575   computeRegisterProperties();
576
577   // ARM does not have f32 extending load.
578   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
579
580   // ARM does not have i1 sign extending load.
581   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
582
583   // ARM supports all 4 flavors of integer indexed load / store.
584   if (!Subtarget->isThumb1Only()) {
585     for (unsigned im = (unsigned)ISD::PRE_INC;
586          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
587       setIndexedLoadAction(im,  MVT::i1,  Legal);
588       setIndexedLoadAction(im,  MVT::i8,  Legal);
589       setIndexedLoadAction(im,  MVT::i16, Legal);
590       setIndexedLoadAction(im,  MVT::i32, Legal);
591       setIndexedStoreAction(im, MVT::i1,  Legal);
592       setIndexedStoreAction(im, MVT::i8,  Legal);
593       setIndexedStoreAction(im, MVT::i16, Legal);
594       setIndexedStoreAction(im, MVT::i32, Legal);
595     }
596   }
597
598   // i64 operation support.
599   setOperationAction(ISD::MUL,     MVT::i64, Expand);
600   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
601   if (Subtarget->isThumb1Only()) {
602     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
603     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
604   }
605   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
606       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
607     setOperationAction(ISD::MULHS, MVT::i32, Expand);
608
609   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
610   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
611   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
612   setOperationAction(ISD::SRL,       MVT::i64, Custom);
613   setOperationAction(ISD::SRA,       MVT::i64, Custom);
614
615   if (!Subtarget->isThumb1Only()) {
616     // FIXME: We should do this for Thumb1 as well.
617     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
618     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
619     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
620     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
621   }
622
623   // ARM does not have ROTL.
624   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
625   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
626   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
627   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
628     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
629
630   // These just redirect to CTTZ and CTLZ on ARM.
631   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
632   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
633
634   // Only ARMv6 has BSWAP.
635   if (!Subtarget->hasV6Ops())
636     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
637
638   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
639       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
640     // These are expanded into libcalls if the cpu doesn't have HW divider.
641     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
642     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
643   }
644   setOperationAction(ISD::SREM,  MVT::i32, Expand);
645   setOperationAction(ISD::UREM,  MVT::i32, Expand);
646   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
647   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
648
649   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
650   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
651   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
652   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
653   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
654
655   setOperationAction(ISD::TRAP, MVT::Other, Legal);
656
657   // Use the default implementation.
658   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
659   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
660   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
661   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
662   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
663   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
664
665   if (!Subtarget->isTargetDarwin()) {
666     // Non-Darwin platforms may return values in these registers via the
667     // personality function.
668     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
669     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
670     setExceptionPointerRegister(ARM::R0);
671     setExceptionSelectorRegister(ARM::R1);
672   }
673
674   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
675   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
676   // the default expansion.
677   // FIXME: This should be checking for v6k, not just v6.
678   if (Subtarget->hasDataBarrier() ||
679       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
680     // membarrier needs custom lowering; the rest are legal and handled
681     // normally.
682     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
683     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
684     // Custom lowering for 64-bit ops
685     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
686     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
690     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
691     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
692     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
693     setInsertFencesForAtomic(true);
694   } else {
695     // Set them all for expansion, which will force libcalls.
696     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
697     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
698     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
710     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
711     // Unordered/Monotonic case.
712     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
713     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
714     // Since the libcalls include locking, fold in the fences
715     setShouldFoldAtomicFences(true);
716   }
717
718   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
719
720   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
721   if (!Subtarget->hasV6Ops()) {
722     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
723     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
724   }
725   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
726
727   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
728       !Subtarget->isThumb1Only()) {
729     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
730     // iff target supports vfp2.
731     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
732     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
733   }
734
735   // We want to custom lower some of our intrinsics.
736   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
737   if (Subtarget->isTargetDarwin()) {
738     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
739     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
740     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
741   }
742
743   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
744   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
745   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
746   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
747   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
748   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
749   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
750   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
751   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
752
753   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
754   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
755   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
756   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
757   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
758
759   // We don't support sin/cos/fmod/copysign/pow
760   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
761   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
762   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
763   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
764   setOperationAction(ISD::FREM,      MVT::f64, Expand);
765   setOperationAction(ISD::FREM,      MVT::f32, Expand);
766   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
767       !Subtarget->isThumb1Only()) {
768     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
769     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
770   }
771   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
772   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
773
774   if (!Subtarget->hasVFP4()) {
775     setOperationAction(ISD::FMA, MVT::f64, Expand);
776     setOperationAction(ISD::FMA, MVT::f32, Expand);
777   }
778
779   // Various VFP goodness
780   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
781     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
782     if (Subtarget->hasVFP2()) {
783       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
784       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
785       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
786       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
787     }
788     // Special handling for half-precision FP.
789     if (!Subtarget->hasFP16()) {
790       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
791       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
792     }
793   }
794
795   // We have target-specific dag combine patterns for the following nodes:
796   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
797   setTargetDAGCombine(ISD::ADD);
798   setTargetDAGCombine(ISD::SUB);
799   setTargetDAGCombine(ISD::MUL);
800   setTargetDAGCombine(ISD::AND);
801   setTargetDAGCombine(ISD::OR);
802   setTargetDAGCombine(ISD::XOR);
803
804   if (Subtarget->hasV6Ops())
805     setTargetDAGCombine(ISD::SRL);
806
807   setStackPointerRegisterToSaveRestore(ARM::SP);
808
809   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
810       !Subtarget->hasVFP2())
811     setSchedulingPreference(Sched::RegPressure);
812   else
813     setSchedulingPreference(Sched::Hybrid);
814
815   //// temporary - rewrite interface to use type
816   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
817   maxStoresPerMemset = 16;
818   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
819
820   // On ARM arguments smaller than 4 bytes are extended, so all arguments
821   // are at least 4 bytes aligned.
822   setMinStackArgumentAlignment(4);
823
824   benefitFromCodePlacementOpt = true;
825
826   // Prefer likely predicted branches to selects on out-of-order cores.
827   predictableSelectIsExpensive = Subtarget->isLikeA9();
828
829   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
830 }
831
832 // FIXME: It might make sense to define the representative register class as the
833 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
834 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
835 // SPR's representative would be DPR_VFP2. This should work well if register
836 // pressure tracking were modified such that a register use would increment the
837 // pressure of the register class's representative and all of it's super
838 // classes' representatives transitively. We have not implemented this because
839 // of the difficulty prior to coalescing of modeling operand register classes
840 // due to the common occurrence of cross class copies and subregister insertions
841 // and extractions.
842 std::pair<const TargetRegisterClass*, uint8_t>
843 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
844   const TargetRegisterClass *RRC = 0;
845   uint8_t Cost = 1;
846   switch (VT.getSimpleVT().SimpleTy) {
847   default:
848     return TargetLowering::findRepresentativeClass(VT);
849   // Use DPR as representative register class for all floating point
850   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
851   // the cost is 1 for both f32 and f64.
852   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
853   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
854     RRC = &ARM::DPRRegClass;
855     // When NEON is used for SP, only half of the register file is available
856     // because operations that define both SP and DP results will be constrained
857     // to the VFP2 class (D0-D15). We currently model this constraint prior to
858     // coalescing by double-counting the SP regs. See the FIXME above.
859     if (Subtarget->useNEONForSinglePrecisionFP())
860       Cost = 2;
861     break;
862   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
863   case MVT::v4f32: case MVT::v2f64:
864     RRC = &ARM::DPRRegClass;
865     Cost = 2;
866     break;
867   case MVT::v4i64:
868     RRC = &ARM::DPRRegClass;
869     Cost = 4;
870     break;
871   case MVT::v8i64:
872     RRC = &ARM::DPRRegClass;
873     Cost = 8;
874     break;
875   }
876   return std::make_pair(RRC, Cost);
877 }
878
879 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
880   switch (Opcode) {
881   default: return 0;
882   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
883   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
884   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
885   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
886   case ARMISD::CALL:          return "ARMISD::CALL";
887   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
888   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
889   case ARMISD::tCALL:         return "ARMISD::tCALL";
890   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
891   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
892   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
893   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
894   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
895   case ARMISD::CMP:           return "ARMISD::CMP";
896   case ARMISD::CMN:           return "ARMISD::CMN";
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
905   case ARMISD::RBIT:          return "ARMISD::RBIT";
906
907   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
908   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
909   case ARMISD::SITOF:         return "ARMISD::SITOF";
910   case ARMISD::UITOF:         return "ARMISD::UITOF";
911
912   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
913   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
914   case ARMISD::RRX:           return "ARMISD::RRX";
915
916   case ARMISD::ADDC:          return "ARMISD::ADDC";
917   case ARMISD::ADDE:          return "ARMISD::ADDE";
918   case ARMISD::SUBC:          return "ARMISD::SUBC";
919   case ARMISD::SUBE:          return "ARMISD::SUBE";
920
921   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
922   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
923
924   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
925   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
926
927   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
928
929   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
930
931   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
932
933   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
934   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
935
936   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
937
938   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
939   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
940   case ARMISD::VCGE:          return "ARMISD::VCGE";
941   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
942   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
943   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
944   case ARMISD::VCGT:          return "ARMISD::VCGT";
945   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
946   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
947   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
948   case ARMISD::VTST:          return "ARMISD::VTST";
949
950   case ARMISD::VSHL:          return "ARMISD::VSHL";
951   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
952   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
953   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
954   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
955   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
956   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
957   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
958   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
959   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
960   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
961   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
962   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
963   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
964   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
965   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
966   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
967   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
968   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
969   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
970   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
971   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
972   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
973   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
974   case ARMISD::VDUP:          return "ARMISD::VDUP";
975   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
976   case ARMISD::VEXT:          return "ARMISD::VEXT";
977   case ARMISD::VREV64:        return "ARMISD::VREV64";
978   case ARMISD::VREV32:        return "ARMISD::VREV32";
979   case ARMISD::VREV16:        return "ARMISD::VREV16";
980   case ARMISD::VZIP:          return "ARMISD::VZIP";
981   case ARMISD::VUZP:          return "ARMISD::VUZP";
982   case ARMISD::VTRN:          return "ARMISD::VTRN";
983   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
984   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
985   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
986   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
987   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
988   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
989   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
990   case ARMISD::FMAX:          return "ARMISD::FMAX";
991   case ARMISD::FMIN:          return "ARMISD::FMIN";
992   case ARMISD::BFI:           return "ARMISD::BFI";
993   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
994   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
995   case ARMISD::VBSL:          return "ARMISD::VBSL";
996   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
997   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
998   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
999   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1000   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1001   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1002   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1003   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1004   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1005   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1006   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1007   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1008   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1009   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1010   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1011   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1012   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1013   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1014   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1015   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1016   }
1017 }
1018
1019 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1020   if (!VT.isVector()) return getPointerTy();
1021   return VT.changeVectorElementTypeToInteger();
1022 }
1023
1024 /// getRegClassFor - Return the register class that should be used for the
1025 /// specified value type.
1026 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1027   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1028   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1029   // load / store 4 to 8 consecutive D registers.
1030   if (Subtarget->hasNEON()) {
1031     if (VT == MVT::v4i64)
1032       return &ARM::QQPRRegClass;
1033     if (VT == MVT::v8i64)
1034       return &ARM::QQQQPRRegClass;
1035   }
1036   return TargetLowering::getRegClassFor(VT);
1037 }
1038
1039 // Create a fast isel object.
1040 FastISel *
1041 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1042                                   const TargetLibraryInfo *libInfo) const {
1043   return ARM::createFastISel(funcInfo, libInfo);
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   case CallingConv::GHC:
1173     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1174   }
1175 }
1176
1177 /// LowerCallResult - Lower the result values of a call into the
1178 /// appropriate copies out of appropriate physical registers.
1179 SDValue
1180 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1181                                    CallingConv::ID CallConv, bool isVarArg,
1182                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1183                                    DebugLoc dl, SelectionDAG &DAG,
1184                                    SmallVectorImpl<SDValue> &InVals) const {
1185
1186   // Assign locations to each value returned by this call.
1187   SmallVector<CCValAssign, 16> RVLocs;
1188   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1189                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1190   CCInfo.AnalyzeCallResult(Ins,
1191                            CCAssignFnForNode(CallConv, /* Return*/ true,
1192                                              isVarArg));
1193
1194   // Copy all of the result registers out of their specified physreg.
1195   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1196     CCValAssign VA = RVLocs[i];
1197
1198     SDValue Val;
1199     if (VA.needsCustom()) {
1200       // Handle f64 or half of a v2f64.
1201       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1202                                       InFlag);
1203       Chain = Lo.getValue(1);
1204       InFlag = Lo.getValue(2);
1205       VA = RVLocs[++i]; // skip ahead to next loc
1206       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1207                                       InFlag);
1208       Chain = Hi.getValue(1);
1209       InFlag = Hi.getValue(2);
1210       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1211
1212       if (VA.getLocVT() == MVT::v2f64) {
1213         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1214         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1215                           DAG.getConstant(0, MVT::i32));
1216
1217         VA = RVLocs[++i]; // skip ahead to next loc
1218         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1219         Chain = Lo.getValue(1);
1220         InFlag = Lo.getValue(2);
1221         VA = RVLocs[++i]; // skip ahead to next loc
1222         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1223         Chain = Hi.getValue(1);
1224         InFlag = Hi.getValue(2);
1225         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1226         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1227                           DAG.getConstant(1, MVT::i32));
1228       }
1229     } else {
1230       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1231                                InFlag);
1232       Chain = Val.getValue(1);
1233       InFlag = Val.getValue(2);
1234     }
1235
1236     switch (VA.getLocInfo()) {
1237     default: llvm_unreachable("Unknown loc info!");
1238     case CCValAssign::Full: break;
1239     case CCValAssign::BCvt:
1240       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1241       break;
1242     }
1243
1244     InVals.push_back(Val);
1245   }
1246
1247   return Chain;
1248 }
1249
1250 /// LowerMemOpCallTo - Store the argument to the stack.
1251 SDValue
1252 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1253                                     SDValue StackPtr, SDValue Arg,
1254                                     DebugLoc dl, SelectionDAG &DAG,
1255                                     const CCValAssign &VA,
1256                                     ISD::ArgFlagsTy Flags) const {
1257   unsigned LocMemOffset = VA.getLocMemOffset();
1258   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1259   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1260   return DAG.getStore(Chain, dl, Arg, PtrOff,
1261                       MachinePointerInfo::getStack(LocMemOffset),
1262                       false, false, 0);
1263 }
1264
1265 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1266                                          SDValue Chain, SDValue &Arg,
1267                                          RegsToPassVector &RegsToPass,
1268                                          CCValAssign &VA, CCValAssign &NextVA,
1269                                          SDValue &StackPtr,
1270                                          SmallVector<SDValue, 8> &MemOpChains,
1271                                          ISD::ArgFlagsTy Flags) const {
1272
1273   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1274                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1275   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1276
1277   if (NextVA.isRegLoc())
1278     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1279   else {
1280     assert(NextVA.isMemLoc());
1281     if (StackPtr.getNode() == 0)
1282       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1283
1284     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1285                                            dl, DAG, NextVA,
1286                                            Flags));
1287   }
1288 }
1289
1290 /// LowerCall - Lowering a call into a callseq_start <-
1291 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1292 /// nodes.
1293 SDValue
1294 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1295                              SmallVectorImpl<SDValue> &InVals) const {
1296   SelectionDAG &DAG                     = CLI.DAG;
1297   DebugLoc &dl                          = CLI.DL;
1298   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1299   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1300   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1301   SDValue Chain                         = CLI.Chain;
1302   SDValue Callee                        = CLI.Callee;
1303   bool &isTailCall                      = CLI.IsTailCall;
1304   CallingConv::ID CallConv              = CLI.CallConv;
1305   bool doesNotRet                       = CLI.DoesNotReturn;
1306   bool isVarArg                         = CLI.IsVarArg;
1307
1308   MachineFunction &MF = DAG.getMachineFunction();
1309   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1310   bool IsSibCall = false;
1311   // Disable tail calls if they're not supported.
1312   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1313     isTailCall = false;
1314   if (isTailCall) {
1315     // Check if it's really possible to do a tail call.
1316     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1317                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1318                                                    Outs, OutVals, Ins, DAG);
1319     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1320     // detected sibcalls.
1321     if (isTailCall) {
1322       ++NumTailCalls;
1323       IsSibCall = true;
1324     }
1325   }
1326
1327   // Analyze operands of the call, assigning locations to each operand.
1328   SmallVector<CCValAssign, 16> ArgLocs;
1329   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1330                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1331   CCInfo.AnalyzeCallOperands(Outs,
1332                              CCAssignFnForNode(CallConv, /* Return*/ false,
1333                                                isVarArg));
1334
1335   // Get a count of how many bytes are to be pushed on the stack.
1336   unsigned NumBytes = CCInfo.getNextStackOffset();
1337
1338   // For tail calls, memory operands are available in our caller's stack.
1339   if (IsSibCall)
1340     NumBytes = 0;
1341
1342   // Adjust the stack pointer for the new arguments...
1343   // These operations are automatically eliminated by the prolog/epilog pass
1344   if (!IsSibCall)
1345     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1346
1347   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1348
1349   RegsToPassVector RegsToPass;
1350   SmallVector<SDValue, 8> MemOpChains;
1351
1352   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1353   // of tail call optimization, arguments are handled later.
1354   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1355        i != e;
1356        ++i, ++realArgIdx) {
1357     CCValAssign &VA = ArgLocs[i];
1358     SDValue Arg = OutVals[realArgIdx];
1359     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1360     bool isByVal = Flags.isByVal();
1361
1362     // Promote the value if needed.
1363     switch (VA.getLocInfo()) {
1364     default: llvm_unreachable("Unknown loc info!");
1365     case CCValAssign::Full: break;
1366     case CCValAssign::SExt:
1367       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1368       break;
1369     case CCValAssign::ZExt:
1370       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1371       break;
1372     case CCValAssign::AExt:
1373       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1374       break;
1375     case CCValAssign::BCvt:
1376       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1377       break;
1378     }
1379
1380     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1381     if (VA.needsCustom()) {
1382       if (VA.getLocVT() == MVT::v2f64) {
1383         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1384                                   DAG.getConstant(0, MVT::i32));
1385         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1386                                   DAG.getConstant(1, MVT::i32));
1387
1388         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1389                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1390
1391         VA = ArgLocs[++i]; // skip ahead to next loc
1392         if (VA.isRegLoc()) {
1393           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1394                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1395         } else {
1396           assert(VA.isMemLoc());
1397
1398           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1399                                                  dl, DAG, VA, Flags));
1400         }
1401       } else {
1402         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1403                          StackPtr, MemOpChains, Flags);
1404       }
1405     } else if (VA.isRegLoc()) {
1406       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1407     } else if (isByVal) {
1408       assert(VA.isMemLoc());
1409       unsigned offset = 0;
1410
1411       // True if this byval aggregate will be split between registers
1412       // and memory.
1413       if (CCInfo.isFirstByValRegValid()) {
1414         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1415         unsigned int i, j;
1416         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1417           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1418           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1419           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1420                                      MachinePointerInfo(),
1421                                      false, false, false, 0);
1422           MemOpChains.push_back(Load.getValue(1));
1423           RegsToPass.push_back(std::make_pair(j, Load));
1424         }
1425         offset = ARM::R4 - CCInfo.getFirstByValReg();
1426         CCInfo.clearFirstByValReg();
1427       }
1428
1429       if (Flags.getByValSize() - 4*offset > 0) {
1430         unsigned LocMemOffset = VA.getLocMemOffset();
1431         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1432         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1433                                   StkPtrOff);
1434         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1435         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1436         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1437                                            MVT::i32);
1438         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1439
1440         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1441         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1442         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1443                                           Ops, array_lengthof(Ops)));
1444       }
1445     } else if (!IsSibCall) {
1446       assert(VA.isMemLoc());
1447
1448       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1449                                              dl, DAG, VA, Flags));
1450     }
1451   }
1452
1453   if (!MemOpChains.empty())
1454     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1455                         &MemOpChains[0], MemOpChains.size());
1456
1457   // Build a sequence of copy-to-reg nodes chained together with token chain
1458   // and flag operands which copy the outgoing args into the appropriate regs.
1459   SDValue InFlag;
1460   // Tail call byval lowering might overwrite argument registers so in case of
1461   // tail call optimization the copies to registers are lowered later.
1462   if (!isTailCall)
1463     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1464       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1465                                RegsToPass[i].second, InFlag);
1466       InFlag = Chain.getValue(1);
1467     }
1468
1469   // For tail calls lower the arguments to the 'real' stack slot.
1470   if (isTailCall) {
1471     // Force all the incoming stack arguments to be loaded from the stack
1472     // before any new outgoing arguments are stored to the stack, because the
1473     // outgoing stack slots may alias the incoming argument stack slots, and
1474     // the alias isn't otherwise explicit. This is slightly more conservative
1475     // than necessary, because it means that each store effectively depends
1476     // on every argument instead of just those arguments it would clobber.
1477
1478     // Do not flag preceding copytoreg stuff together with the following stuff.
1479     InFlag = SDValue();
1480     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1481       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1482                                RegsToPass[i].second, InFlag);
1483       InFlag = Chain.getValue(1);
1484     }
1485     InFlag =SDValue();
1486   }
1487
1488   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1489   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1490   // node so that legalize doesn't hack it.
1491   bool isDirect = false;
1492   bool isARMFunc = false;
1493   bool isLocalARMFunc = false;
1494   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1495
1496   if (EnableARMLongCalls) {
1497     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1498             && "long-calls with non-static relocation model!");
1499     // Handle a global address or an external symbol. If it's not one of
1500     // those, the target's already in a register, so we don't need to do
1501     // anything extra.
1502     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1503       const GlobalValue *GV = G->getGlobal();
1504       // Create a constant pool entry for the callee address
1505       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1506       ARMConstantPoolValue *CPV =
1507         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1508
1509       // Get the address of the callee into a register
1510       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1511       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1512       Callee = DAG.getLoad(getPointerTy(), dl,
1513                            DAG.getEntryNode(), CPAddr,
1514                            MachinePointerInfo::getConstantPool(),
1515                            false, false, false, 0);
1516     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1517       const char *Sym = S->getSymbol();
1518
1519       // Create a constant pool entry for the callee address
1520       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1521       ARMConstantPoolValue *CPV =
1522         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1523                                       ARMPCLabelIndex, 0);
1524       // Get the address of the callee into a register
1525       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1526       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1527       Callee = DAG.getLoad(getPointerTy(), dl,
1528                            DAG.getEntryNode(), CPAddr,
1529                            MachinePointerInfo::getConstantPool(),
1530                            false, false, false, 0);
1531     }
1532   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1533     const GlobalValue *GV = G->getGlobal();
1534     isDirect = true;
1535     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1536     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1537                    getTargetMachine().getRelocationModel() != Reloc::Static;
1538     isARMFunc = !Subtarget->isThumb() || isStub;
1539     // ARM call to a local ARM function is predicable.
1540     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1541     // tBX takes a register source operand.
1542     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1543       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1544       ARMConstantPoolValue *CPV =
1545         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1546       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1547       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1548       Callee = DAG.getLoad(getPointerTy(), dl,
1549                            DAG.getEntryNode(), CPAddr,
1550                            MachinePointerInfo::getConstantPool(),
1551                            false, false, false, 0);
1552       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1553       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1554                            getPointerTy(), Callee, PICLabel);
1555     } else {
1556       // On ELF targets for PIC code, direct calls should go through the PLT
1557       unsigned OpFlags = 0;
1558       if (Subtarget->isTargetELF() &&
1559                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1560         OpFlags = ARMII::MO_PLT;
1561       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1562     }
1563   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1564     isDirect = true;
1565     bool isStub = Subtarget->isTargetDarwin() &&
1566                   getTargetMachine().getRelocationModel() != Reloc::Static;
1567     isARMFunc = !Subtarget->isThumb() || isStub;
1568     // tBX takes a register source operand.
1569     const char *Sym = S->getSymbol();
1570     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1571       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1572       ARMConstantPoolValue *CPV =
1573         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1574                                       ARMPCLabelIndex, 4);
1575       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1576       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1577       Callee = DAG.getLoad(getPointerTy(), dl,
1578                            DAG.getEntryNode(), CPAddr,
1579                            MachinePointerInfo::getConstantPool(),
1580                            false, false, false, 0);
1581       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1582       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1583                            getPointerTy(), Callee, PICLabel);
1584     } else {
1585       unsigned OpFlags = 0;
1586       // On ELF targets for PIC code, direct calls should go through the PLT
1587       if (Subtarget->isTargetELF() &&
1588                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1589         OpFlags = ARMII::MO_PLT;
1590       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1591     }
1592   }
1593
1594   // FIXME: handle tail calls differently.
1595   unsigned CallOpc;
1596   if (Subtarget->isThumb()) {
1597     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1598       CallOpc = ARMISD::CALL_NOLINK;
1599     else if (doesNotRet && isDirect && !isARMFunc &&
1600              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1601       // "mov lr, pc; b _foo" to avoid confusing the RSP
1602       CallOpc = ARMISD::CALL_NOLINK;
1603     else
1604       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1605   } else {
1606     if (!isDirect && !Subtarget->hasV5TOps()) {
1607       CallOpc = ARMISD::CALL_NOLINK;
1608     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1609       // "mov lr, pc; b _foo" to avoid confusing the RSP
1610       CallOpc = ARMISD::CALL_NOLINK;
1611     else
1612       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1613   }
1614
1615   std::vector<SDValue> Ops;
1616   Ops.push_back(Chain);
1617   Ops.push_back(Callee);
1618
1619   // Add argument registers to the end of the list so that they are known live
1620   // into the call.
1621   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1622     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1623                                   RegsToPass[i].second.getValueType()));
1624
1625   // Add a register mask operand representing the call-preserved registers.
1626   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1627   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1628   assert(Mask && "Missing call preserved mask for calling convention");
1629   Ops.push_back(DAG.getRegisterMask(Mask));
1630
1631   if (InFlag.getNode())
1632     Ops.push_back(InFlag);
1633
1634   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1635   if (isTailCall)
1636     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1637
1638   // Returns a chain and a flag for retval copy to use.
1639   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1640   InFlag = Chain.getValue(1);
1641
1642   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1643                              DAG.getIntPtrConstant(0, true), InFlag);
1644   if (!Ins.empty())
1645     InFlag = Chain.getValue(1);
1646
1647   // Handle result values, copying them out of physregs into vregs that we
1648   // return.
1649   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1650                          dl, DAG, InVals);
1651 }
1652
1653 /// HandleByVal - Every parameter *after* a byval parameter is passed
1654 /// on the stack.  Remember the next parameter register to allocate,
1655 /// and then confiscate the rest of the parameter registers to insure
1656 /// this.
1657 void
1658 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1659   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1660   assert((State->getCallOrPrologue() == Prologue ||
1661           State->getCallOrPrologue() == Call) &&
1662          "unhandled ParmContext");
1663   if ((!State->isFirstByValRegValid()) &&
1664       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1665     State->setFirstByValReg(reg);
1666     // At a call site, a byval parameter that is split between
1667     // registers and memory needs its size truncated here.  In a
1668     // function prologue, such byval parameters are reassembled in
1669     // memory, and are not truncated.
1670     if (State->getCallOrPrologue() == Call) {
1671       unsigned excess = 4 * (ARM::R4 - reg);
1672       assert(size >= excess && "expected larger existing stack allocation");
1673       size -= excess;
1674     }
1675   }
1676   // Confiscate any remaining parameter registers to preclude their
1677   // assignment to subsequent parameters.
1678   while (State->AllocateReg(GPRArgRegs, 4))
1679     ;
1680 }
1681
1682 /// MatchingStackOffset - Return true if the given stack call argument is
1683 /// already available in the same position (relatively) of the caller's
1684 /// incoming argument stack.
1685 static
1686 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1687                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1688                          const TargetInstrInfo *TII) {
1689   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1690   int FI = INT_MAX;
1691   if (Arg.getOpcode() == ISD::CopyFromReg) {
1692     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1693     if (!TargetRegisterInfo::isVirtualRegister(VR))
1694       return false;
1695     MachineInstr *Def = MRI->getVRegDef(VR);
1696     if (!Def)
1697       return false;
1698     if (!Flags.isByVal()) {
1699       if (!TII->isLoadFromStackSlot(Def, FI))
1700         return false;
1701     } else {
1702       return false;
1703     }
1704   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1705     if (Flags.isByVal())
1706       // ByVal argument is passed in as a pointer but it's now being
1707       // dereferenced. e.g.
1708       // define @foo(%struct.X* %A) {
1709       //   tail call @bar(%struct.X* byval %A)
1710       // }
1711       return false;
1712     SDValue Ptr = Ld->getBasePtr();
1713     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1714     if (!FINode)
1715       return false;
1716     FI = FINode->getIndex();
1717   } else
1718     return false;
1719
1720   assert(FI != INT_MAX);
1721   if (!MFI->isFixedObjectIndex(FI))
1722     return false;
1723   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1724 }
1725
1726 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1727 /// for tail call optimization. Targets which want to do tail call
1728 /// optimization should implement this function.
1729 bool
1730 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1731                                                      CallingConv::ID CalleeCC,
1732                                                      bool isVarArg,
1733                                                      bool isCalleeStructRet,
1734                                                      bool isCallerStructRet,
1735                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1736                                     const SmallVectorImpl<SDValue> &OutVals,
1737                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1738                                                      SelectionDAG& DAG) const {
1739   const Function *CallerF = DAG.getMachineFunction().getFunction();
1740   CallingConv::ID CallerCC = CallerF->getCallingConv();
1741   bool CCMatch = CallerCC == CalleeCC;
1742
1743   // Look for obvious safe cases to perform tail call optimization that do not
1744   // require ABI changes. This is what gcc calls sibcall.
1745
1746   // Do not sibcall optimize vararg calls unless the call site is not passing
1747   // any arguments.
1748   if (isVarArg && !Outs.empty())
1749     return false;
1750
1751   // Also avoid sibcall optimization if either caller or callee uses struct
1752   // return semantics.
1753   if (isCalleeStructRet || isCallerStructRet)
1754     return false;
1755
1756   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1757   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1758   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1759   // support in the assembler and linker to be used. This would need to be
1760   // fixed to fully support tail calls in Thumb1.
1761   //
1762   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1763   // LR.  This means if we need to reload LR, it takes an extra instructions,
1764   // which outweighs the value of the tail call; but here we don't know yet
1765   // whether LR is going to be used.  Probably the right approach is to
1766   // generate the tail call here and turn it back into CALL/RET in
1767   // emitEpilogue if LR is used.
1768
1769   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1770   // but we need to make sure there are enough registers; the only valid
1771   // registers are the 4 used for parameters.  We don't currently do this
1772   // case.
1773   if (Subtarget->isThumb1Only())
1774     return false;
1775
1776   // If the calling conventions do not match, then we'd better make sure the
1777   // results are returned in the same way as what the caller expects.
1778   if (!CCMatch) {
1779     SmallVector<CCValAssign, 16> RVLocs1;
1780     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1781                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1782     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1783
1784     SmallVector<CCValAssign, 16> RVLocs2;
1785     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1786                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1787     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1788
1789     if (RVLocs1.size() != RVLocs2.size())
1790       return false;
1791     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1792       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1793         return false;
1794       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1795         return false;
1796       if (RVLocs1[i].isRegLoc()) {
1797         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1798           return false;
1799       } else {
1800         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1801           return false;
1802       }
1803     }
1804   }
1805
1806   // If the callee takes no arguments then go on to check the results of the
1807   // call.
1808   if (!Outs.empty()) {
1809     // Check if stack adjustment is needed. For now, do not do this if any
1810     // argument is passed on the stack.
1811     SmallVector<CCValAssign, 16> ArgLocs;
1812     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1813                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1814     CCInfo.AnalyzeCallOperands(Outs,
1815                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1816     if (CCInfo.getNextStackOffset()) {
1817       MachineFunction &MF = DAG.getMachineFunction();
1818
1819       // Check if the arguments are already laid out in the right way as
1820       // the caller's fixed stack objects.
1821       MachineFrameInfo *MFI = MF.getFrameInfo();
1822       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1823       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1824       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1825            i != e;
1826            ++i, ++realArgIdx) {
1827         CCValAssign &VA = ArgLocs[i];
1828         EVT RegVT = VA.getLocVT();
1829         SDValue Arg = OutVals[realArgIdx];
1830         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831         if (VA.getLocInfo() == CCValAssign::Indirect)
1832           return false;
1833         if (VA.needsCustom()) {
1834           // f64 and vector types are split into multiple registers or
1835           // register/stack-slot combinations.  The types will not match
1836           // the registers; give up on memory f64 refs until we figure
1837           // out what to do about this.
1838           if (!VA.isRegLoc())
1839             return false;
1840           if (!ArgLocs[++i].isRegLoc())
1841             return false;
1842           if (RegVT == MVT::v2f64) {
1843             if (!ArgLocs[++i].isRegLoc())
1844               return false;
1845             if (!ArgLocs[++i].isRegLoc())
1846               return false;
1847           }
1848         } else if (!VA.isRegLoc()) {
1849           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1850                                    MFI, MRI, TII))
1851             return false;
1852         }
1853       }
1854     }
1855   }
1856
1857   return true;
1858 }
1859
1860 SDValue
1861 ARMTargetLowering::LowerReturn(SDValue Chain,
1862                                CallingConv::ID CallConv, bool isVarArg,
1863                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1864                                const SmallVectorImpl<SDValue> &OutVals,
1865                                DebugLoc dl, SelectionDAG &DAG) const {
1866
1867   // CCValAssign - represent the assignment of the return value to a location.
1868   SmallVector<CCValAssign, 16> RVLocs;
1869
1870   // CCState - Info about the registers and stack slots.
1871   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1872                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1873
1874   // Analyze outgoing return values.
1875   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1876                                                isVarArg));
1877
1878   // If this is the first return lowered for this function, add
1879   // the regs to the liveout set for the function.
1880   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1881     for (unsigned i = 0; i != RVLocs.size(); ++i)
1882       if (RVLocs[i].isRegLoc())
1883         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1884   }
1885
1886   SDValue Flag;
1887
1888   // Copy the result values into the output registers.
1889   for (unsigned i = 0, realRVLocIdx = 0;
1890        i != RVLocs.size();
1891        ++i, ++realRVLocIdx) {
1892     CCValAssign &VA = RVLocs[i];
1893     assert(VA.isRegLoc() && "Can only return in registers!");
1894
1895     SDValue Arg = OutVals[realRVLocIdx];
1896
1897     switch (VA.getLocInfo()) {
1898     default: llvm_unreachable("Unknown loc info!");
1899     case CCValAssign::Full: break;
1900     case CCValAssign::BCvt:
1901       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1902       break;
1903     }
1904
1905     if (VA.needsCustom()) {
1906       if (VA.getLocVT() == MVT::v2f64) {
1907         // Extract the first half and return it in two registers.
1908         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1909                                    DAG.getConstant(0, MVT::i32));
1910         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1911                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1912
1913         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1914         Flag = Chain.getValue(1);
1915         VA = RVLocs[++i]; // skip ahead to next loc
1916         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1917                                  HalfGPRs.getValue(1), Flag);
1918         Flag = Chain.getValue(1);
1919         VA = RVLocs[++i]; // skip ahead to next loc
1920
1921         // Extract the 2nd half and fall through to handle it as an f64 value.
1922         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1923                           DAG.getConstant(1, MVT::i32));
1924       }
1925       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1926       // available.
1927       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1928                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1929       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1930       Flag = Chain.getValue(1);
1931       VA = RVLocs[++i]; // skip ahead to next loc
1932       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1933                                Flag);
1934     } else
1935       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1936
1937     // Guarantee that all emitted copies are
1938     // stuck together, avoiding something bad.
1939     Flag = Chain.getValue(1);
1940   }
1941
1942   SDValue result;
1943   if (Flag.getNode())
1944     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1945   else // Return Void
1946     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1947
1948   return result;
1949 }
1950
1951 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1952   if (N->getNumValues() != 1)
1953     return false;
1954   if (!N->hasNUsesOfValue(1, 0))
1955     return false;
1956
1957   SDValue TCChain = Chain;
1958   SDNode *Copy = *N->use_begin();
1959   if (Copy->getOpcode() == ISD::CopyToReg) {
1960     // If the copy has a glue operand, we conservatively assume it isn't safe to
1961     // perform a tail call.
1962     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1963       return false;
1964     TCChain = Copy->getOperand(0);
1965   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1966     SDNode *VMov = Copy;
1967     // f64 returned in a pair of GPRs.
1968     SmallPtrSet<SDNode*, 2> Copies;
1969     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1970          UI != UE; ++UI) {
1971       if (UI->getOpcode() != ISD::CopyToReg)
1972         return false;
1973       Copies.insert(*UI);
1974     }
1975     if (Copies.size() > 2)
1976       return false;
1977
1978     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1979          UI != UE; ++UI) {
1980       SDValue UseChain = UI->getOperand(0);
1981       if (Copies.count(UseChain.getNode()))
1982         // Second CopyToReg
1983         Copy = *UI;
1984       else
1985         // First CopyToReg
1986         TCChain = UseChain;
1987     }
1988   } else if (Copy->getOpcode() == ISD::BITCAST) {
1989     // f32 returned in a single GPR.
1990     if (!Copy->hasOneUse())
1991       return false;
1992     Copy = *Copy->use_begin();
1993     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1994       return false;
1995     Chain = Copy->getOperand(0);
1996   } else {
1997     return false;
1998   }
1999
2000   bool HasRet = false;
2001   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2002        UI != UE; ++UI) {
2003     if (UI->getOpcode() != ARMISD::RET_FLAG)
2004       return false;
2005     HasRet = true;
2006   }
2007
2008   if (!HasRet)
2009     return false;
2010
2011   Chain = TCChain;
2012   return true;
2013 }
2014
2015 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2016   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2017     return false;
2018
2019   if (!CI->isTailCall())
2020     return false;
2021
2022   return !Subtarget->isThumb1Only();
2023 }
2024
2025 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2026 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2027 // one of the above mentioned nodes. It has to be wrapped because otherwise
2028 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2029 // be used to form addressing mode. These wrapped nodes will be selected
2030 // into MOVi.
2031 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2032   EVT PtrVT = Op.getValueType();
2033   // FIXME there is no actual debug info here
2034   DebugLoc dl = Op.getDebugLoc();
2035   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2036   SDValue Res;
2037   if (CP->isMachineConstantPoolEntry())
2038     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2039                                     CP->getAlignment());
2040   else
2041     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2042                                     CP->getAlignment());
2043   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2044 }
2045
2046 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2047   return MachineJumpTableInfo::EK_Inline;
2048 }
2049
2050 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2051                                              SelectionDAG &DAG) const {
2052   MachineFunction &MF = DAG.getMachineFunction();
2053   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2054   unsigned ARMPCLabelIndex = 0;
2055   DebugLoc DL = Op.getDebugLoc();
2056   EVT PtrVT = getPointerTy();
2057   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2058   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2059   SDValue CPAddr;
2060   if (RelocM == Reloc::Static) {
2061     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2062   } else {
2063     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2064     ARMPCLabelIndex = AFI->createPICLabelUId();
2065     ARMConstantPoolValue *CPV =
2066       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2067                                       ARMCP::CPBlockAddress, PCAdj);
2068     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2069   }
2070   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2071   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2072                                MachinePointerInfo::getConstantPool(),
2073                                false, false, false, 0);
2074   if (RelocM == Reloc::Static)
2075     return Result;
2076   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2077   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2078 }
2079
2080 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2081 SDValue
2082 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2083                                                  SelectionDAG &DAG) const {
2084   DebugLoc dl = GA->getDebugLoc();
2085   EVT PtrVT = getPointerTy();
2086   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2087   MachineFunction &MF = DAG.getMachineFunction();
2088   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2089   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2090   ARMConstantPoolValue *CPV =
2091     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2092                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2093   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2094   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2095   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2096                          MachinePointerInfo::getConstantPool(),
2097                          false, false, false, 0);
2098   SDValue Chain = Argument.getValue(1);
2099
2100   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2101   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2102
2103   // call __tls_get_addr.
2104   ArgListTy Args;
2105   ArgListEntry Entry;
2106   Entry.Node = Argument;
2107   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2108   Args.push_back(Entry);
2109   // FIXME: is there useful debug info available here?
2110   TargetLowering::CallLoweringInfo CLI(Chain,
2111                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2112                 false, false, false, false,
2113                 0, CallingConv::C, /*isTailCall=*/false,
2114                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2115                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2116   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2117   return CallResult.first;
2118 }
2119
2120 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2121 // "local exec" model.
2122 SDValue
2123 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2124                                         SelectionDAG &DAG,
2125                                         TLSModel::Model model) const {
2126   const GlobalValue *GV = GA->getGlobal();
2127   DebugLoc dl = GA->getDebugLoc();
2128   SDValue Offset;
2129   SDValue Chain = DAG.getEntryNode();
2130   EVT PtrVT = getPointerTy();
2131   // Get the Thread Pointer
2132   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2133
2134   if (model == TLSModel::InitialExec) {
2135     MachineFunction &MF = DAG.getMachineFunction();
2136     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2137     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2138     // Initial exec model.
2139     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2140     ARMConstantPoolValue *CPV =
2141       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2142                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2143                                       true);
2144     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2145     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2146     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2147                          MachinePointerInfo::getConstantPool(),
2148                          false, false, false, 0);
2149     Chain = Offset.getValue(1);
2150
2151     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2152     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2153
2154     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2155                          MachinePointerInfo::getConstantPool(),
2156                          false, false, false, 0);
2157   } else {
2158     // local exec model
2159     assert(model == TLSModel::LocalExec);
2160     ARMConstantPoolValue *CPV =
2161       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2162     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2163     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2164     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2165                          MachinePointerInfo::getConstantPool(),
2166                          false, false, false, 0);
2167   }
2168
2169   // The address of the thread local variable is the add of the thread
2170   // pointer with the offset of the variable.
2171   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2172 }
2173
2174 SDValue
2175 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2176   // TODO: implement the "local dynamic" model
2177   assert(Subtarget->isTargetELF() &&
2178          "TLS not implemented for non-ELF targets");
2179   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2180
2181   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2182
2183   switch (model) {
2184     case TLSModel::GeneralDynamic:
2185     case TLSModel::LocalDynamic:
2186       return LowerToTLSGeneralDynamicModel(GA, DAG);
2187     case TLSModel::InitialExec:
2188     case TLSModel::LocalExec:
2189       return LowerToTLSExecModels(GA, DAG, model);
2190   }
2191   llvm_unreachable("bogus TLS model");
2192 }
2193
2194 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2195                                                  SelectionDAG &DAG) const {
2196   EVT PtrVT = getPointerTy();
2197   DebugLoc dl = Op.getDebugLoc();
2198   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2199   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2200   if (RelocM == Reloc::PIC_) {
2201     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2202     ARMConstantPoolValue *CPV =
2203       ARMConstantPoolConstant::Create(GV,
2204                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2205     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2206     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2207     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2208                                  CPAddr,
2209                                  MachinePointerInfo::getConstantPool(),
2210                                  false, false, false, 0);
2211     SDValue Chain = Result.getValue(1);
2212     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2213     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2214     if (!UseGOTOFF)
2215       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2216                            MachinePointerInfo::getGOT(),
2217                            false, false, false, 0);
2218     return Result;
2219   }
2220
2221   // If we have T2 ops, we can materialize the address directly via movt/movw
2222   // pair. This is always cheaper.
2223   if (Subtarget->useMovt()) {
2224     ++NumMovwMovt;
2225     // FIXME: Once remat is capable of dealing with instructions with register
2226     // operands, expand this into two nodes.
2227     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2228                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2229   } else {
2230     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2231     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2232     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2233                        MachinePointerInfo::getConstantPool(),
2234                        false, false, false, 0);
2235   }
2236 }
2237
2238 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2239                                                     SelectionDAG &DAG) const {
2240   EVT PtrVT = getPointerTy();
2241   DebugLoc dl = Op.getDebugLoc();
2242   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2243   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2244   MachineFunction &MF = DAG.getMachineFunction();
2245   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2246
2247   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2248   // update ARMFastISel::ARMMaterializeGV.
2249   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2250     ++NumMovwMovt;
2251     // FIXME: Once remat is capable of dealing with instructions with register
2252     // operands, expand this into two nodes.
2253     if (RelocM == Reloc::Static)
2254       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2255                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2256
2257     unsigned Wrapper = (RelocM == Reloc::PIC_)
2258       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2259     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2260                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2261     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2262       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2263                            MachinePointerInfo::getGOT(),
2264                            false, false, false, 0);
2265     return Result;
2266   }
2267
2268   unsigned ARMPCLabelIndex = 0;
2269   SDValue CPAddr;
2270   if (RelocM == Reloc::Static) {
2271     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2272   } else {
2273     ARMPCLabelIndex = AFI->createPICLabelUId();
2274     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2275     ARMConstantPoolValue *CPV =
2276       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2277                                       PCAdj);
2278     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2279   }
2280   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2281
2282   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2283                                MachinePointerInfo::getConstantPool(),
2284                                false, false, false, 0);
2285   SDValue Chain = Result.getValue(1);
2286
2287   if (RelocM == Reloc::PIC_) {
2288     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2289     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2290   }
2291
2292   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2293     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2294                          false, false, false, 0);
2295
2296   return Result;
2297 }
2298
2299 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2300                                                     SelectionDAG &DAG) const {
2301   assert(Subtarget->isTargetELF() &&
2302          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2303   MachineFunction &MF = DAG.getMachineFunction();
2304   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2306   EVT PtrVT = getPointerTy();
2307   DebugLoc dl = Op.getDebugLoc();
2308   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2309   ARMConstantPoolValue *CPV =
2310     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2311                                   ARMPCLabelIndex, PCAdj);
2312   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2313   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2314   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2315                                MachinePointerInfo::getConstantPool(),
2316                                false, false, false, 0);
2317   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2318   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2319 }
2320
2321 SDValue
2322 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2323   DebugLoc dl = Op.getDebugLoc();
2324   SDValue Val = DAG.getConstant(0, MVT::i32);
2325   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2326                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2327                      Op.getOperand(1), Val);
2328 }
2329
2330 SDValue
2331 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2332   DebugLoc dl = Op.getDebugLoc();
2333   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2334                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2335 }
2336
2337 SDValue
2338 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2339                                           const ARMSubtarget *Subtarget) const {
2340   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2341   DebugLoc dl = Op.getDebugLoc();
2342   switch (IntNo) {
2343   default: return SDValue();    // Don't custom lower most intrinsics.
2344   case Intrinsic::arm_thread_pointer: {
2345     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2346     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2347   }
2348   case Intrinsic::eh_sjlj_lsda: {
2349     MachineFunction &MF = DAG.getMachineFunction();
2350     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2351     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2352     EVT PtrVT = getPointerTy();
2353     DebugLoc dl = Op.getDebugLoc();
2354     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2355     SDValue CPAddr;
2356     unsigned PCAdj = (RelocM != Reloc::PIC_)
2357       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2358     ARMConstantPoolValue *CPV =
2359       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2360                                       ARMCP::CPLSDA, PCAdj);
2361     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2362     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2363     SDValue Result =
2364       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2365                   MachinePointerInfo::getConstantPool(),
2366                   false, false, false, 0);
2367
2368     if (RelocM == Reloc::PIC_) {
2369       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2370       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2371     }
2372     return Result;
2373   }
2374   case Intrinsic::arm_neon_vmulls:
2375   case Intrinsic::arm_neon_vmullu: {
2376     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2377       ? ARMISD::VMULLs : ARMISD::VMULLu;
2378     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2379                        Op.getOperand(1), Op.getOperand(2));
2380   }
2381   }
2382 }
2383
2384 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2385                                const ARMSubtarget *Subtarget) {
2386   DebugLoc dl = Op.getDebugLoc();
2387   if (!Subtarget->hasDataBarrier()) {
2388     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2389     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2390     // here.
2391     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2392            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2393     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2394                        DAG.getConstant(0, MVT::i32));
2395   }
2396
2397   SDValue Op5 = Op.getOperand(5);
2398   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2399   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2400   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2401   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2402
2403   ARM_MB::MemBOpt DMBOpt;
2404   if (isDeviceBarrier)
2405     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2406   else
2407     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2408   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2409                      DAG.getConstant(DMBOpt, MVT::i32));
2410 }
2411
2412
2413 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2414                                  const ARMSubtarget *Subtarget) {
2415   // FIXME: handle "fence singlethread" more efficiently.
2416   DebugLoc dl = Op.getDebugLoc();
2417   if (!Subtarget->hasDataBarrier()) {
2418     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2419     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2420     // here.
2421     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2422            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2423     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2424                        DAG.getConstant(0, MVT::i32));
2425   }
2426
2427   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2428                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2429 }
2430
2431 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2432                              const ARMSubtarget *Subtarget) {
2433   // ARM pre v5TE and Thumb1 does not have preload instructions.
2434   if (!(Subtarget->isThumb2() ||
2435         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2436     // Just preserve the chain.
2437     return Op.getOperand(0);
2438
2439   DebugLoc dl = Op.getDebugLoc();
2440   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2441   if (!isRead &&
2442       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2443     // ARMv7 with MP extension has PLDW.
2444     return Op.getOperand(0);
2445
2446   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2447   if (Subtarget->isThumb()) {
2448     // Invert the bits.
2449     isRead = ~isRead & 1;
2450     isData = ~isData & 1;
2451   }
2452
2453   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2454                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2455                      DAG.getConstant(isData, MVT::i32));
2456 }
2457
2458 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2459   MachineFunction &MF = DAG.getMachineFunction();
2460   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2461
2462   // vastart just stores the address of the VarArgsFrameIndex slot into the
2463   // memory location argument.
2464   DebugLoc dl = Op.getDebugLoc();
2465   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2466   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2467   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2468   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2469                       MachinePointerInfo(SV), false, false, 0);
2470 }
2471
2472 SDValue
2473 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2474                                         SDValue &Root, SelectionDAG &DAG,
2475                                         DebugLoc dl) const {
2476   MachineFunction &MF = DAG.getMachineFunction();
2477   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2478
2479   const TargetRegisterClass *RC;
2480   if (AFI->isThumb1OnlyFunction())
2481     RC = &ARM::tGPRRegClass;
2482   else
2483     RC = &ARM::GPRRegClass;
2484
2485   // Transform the arguments stored in physical registers into virtual ones.
2486   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2487   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2488
2489   SDValue ArgValue2;
2490   if (NextVA.isMemLoc()) {
2491     MachineFrameInfo *MFI = MF.getFrameInfo();
2492     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2493
2494     // Create load node to retrieve arguments from the stack.
2495     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2496     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2497                             MachinePointerInfo::getFixedStack(FI),
2498                             false, false, false, 0);
2499   } else {
2500     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2501     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2502   }
2503
2504   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2505 }
2506
2507 void
2508 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2509                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2510   const {
2511   unsigned NumGPRs;
2512   if (CCInfo.isFirstByValRegValid())
2513     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2514   else {
2515     unsigned int firstUnalloced;
2516     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2517                                                 sizeof(GPRArgRegs) /
2518                                                 sizeof(GPRArgRegs[0]));
2519     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2520   }
2521
2522   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2523   VARegSize = NumGPRs * 4;
2524   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2525 }
2526
2527 // The remaining GPRs hold either the beginning of variable-argument
2528 // data, or the beginning of an aggregate passed by value (usuall
2529 // byval).  Either way, we allocate stack slots adjacent to the data
2530 // provided by our caller, and store the unallocated registers there.
2531 // If this is a variadic function, the va_list pointer will begin with
2532 // these values; otherwise, this reassembles a (byval) structure that
2533 // was split between registers and memory.
2534 void
2535 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2536                                         DebugLoc dl, SDValue &Chain,
2537                                         const Value *OrigArg,
2538                                         unsigned OffsetFromOrigArg,
2539                                         unsigned ArgOffset) const {
2540   MachineFunction &MF = DAG.getMachineFunction();
2541   MachineFrameInfo *MFI = MF.getFrameInfo();
2542   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2543   unsigned firstRegToSaveIndex;
2544   if (CCInfo.isFirstByValRegValid())
2545     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2546   else {
2547     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2548       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2549   }
2550
2551   unsigned VARegSize, VARegSaveSize;
2552   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2553   if (VARegSaveSize) {
2554     // If this function is vararg, store any remaining integer argument regs
2555     // to their spots on the stack so that they may be loaded by deferencing
2556     // the result of va_next.
2557     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2558     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2559                                                      ArgOffset + VARegSaveSize
2560                                                      - VARegSize,
2561                                                      false));
2562     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2563                                     getPointerTy());
2564
2565     SmallVector<SDValue, 4> MemOps;
2566     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2567       const TargetRegisterClass *RC;
2568       if (AFI->isThumb1OnlyFunction())
2569         RC = &ARM::tGPRRegClass;
2570       else
2571         RC = &ARM::GPRRegClass;
2572
2573       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2574       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2575       SDValue Store =
2576         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2577                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2578                      false, false, 0);
2579       MemOps.push_back(Store);
2580       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2581                         DAG.getConstant(4, getPointerTy()));
2582     }
2583     if (!MemOps.empty())
2584       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2585                           &MemOps[0], MemOps.size());
2586   } else
2587     // This will point to the next argument passed via stack.
2588     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2589 }
2590
2591 SDValue
2592 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2593                                         CallingConv::ID CallConv, bool isVarArg,
2594                                         const SmallVectorImpl<ISD::InputArg>
2595                                           &Ins,
2596                                         DebugLoc dl, SelectionDAG &DAG,
2597                                         SmallVectorImpl<SDValue> &InVals)
2598                                           const {
2599   MachineFunction &MF = DAG.getMachineFunction();
2600   MachineFrameInfo *MFI = MF.getFrameInfo();
2601
2602   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2603
2604   // Assign locations to all of the incoming arguments.
2605   SmallVector<CCValAssign, 16> ArgLocs;
2606   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2607                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2608   CCInfo.AnalyzeFormalArguments(Ins,
2609                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2610                                                   isVarArg));
2611   
2612   SmallVector<SDValue, 16> ArgValues;
2613   int lastInsIndex = -1;
2614   SDValue ArgValue;
2615   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2616   unsigned CurArgIdx = 0;
2617   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2618     CCValAssign &VA = ArgLocs[i];
2619     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2620     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2621     // Arguments stored in registers.
2622     if (VA.isRegLoc()) {
2623       EVT RegVT = VA.getLocVT();
2624
2625       if (VA.needsCustom()) {
2626         // f64 and vector types are split up into multiple registers or
2627         // combinations of registers and stack slots.
2628         if (VA.getLocVT() == MVT::v2f64) {
2629           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2630                                                    Chain, DAG, dl);
2631           VA = ArgLocs[++i]; // skip ahead to next loc
2632           SDValue ArgValue2;
2633           if (VA.isMemLoc()) {
2634             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2635             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2636             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2637                                     MachinePointerInfo::getFixedStack(FI),
2638                                     false, false, false, 0);
2639           } else {
2640             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2641                                              Chain, DAG, dl);
2642           }
2643           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2644           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2645                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2646           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2647                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2648         } else
2649           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2650
2651       } else {
2652         const TargetRegisterClass *RC;
2653
2654         if (RegVT == MVT::f32)
2655           RC = &ARM::SPRRegClass;
2656         else if (RegVT == MVT::f64)
2657           RC = &ARM::DPRRegClass;
2658         else if (RegVT == MVT::v2f64)
2659           RC = &ARM::QPRRegClass;
2660         else if (RegVT == MVT::i32)
2661           RC = AFI->isThumb1OnlyFunction() ?
2662             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2663             (const TargetRegisterClass*)&ARM::GPRRegClass;
2664         else
2665           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2666
2667         // Transform the arguments in physical registers into virtual ones.
2668         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2669         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2670       }
2671
2672       // If this is an 8 or 16-bit value, it is really passed promoted
2673       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2674       // truncate to the right size.
2675       switch (VA.getLocInfo()) {
2676       default: llvm_unreachable("Unknown loc info!");
2677       case CCValAssign::Full: break;
2678       case CCValAssign::BCvt:
2679         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2680         break;
2681       case CCValAssign::SExt:
2682         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2683                                DAG.getValueType(VA.getValVT()));
2684         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2685         break;
2686       case CCValAssign::ZExt:
2687         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2688                                DAG.getValueType(VA.getValVT()));
2689         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2690         break;
2691       }
2692
2693       InVals.push_back(ArgValue);
2694
2695     } else { // VA.isRegLoc()
2696
2697       // sanity check
2698       assert(VA.isMemLoc());
2699       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2700
2701       int index = ArgLocs[i].getValNo();
2702
2703       // Some Ins[] entries become multiple ArgLoc[] entries.
2704       // Process them only once.
2705       if (index != lastInsIndex)
2706         {
2707           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2708           // FIXME: For now, all byval parameter objects are marked mutable.
2709           // This can be changed with more analysis.
2710           // In case of tail call optimization mark all arguments mutable.
2711           // Since they could be overwritten by lowering of arguments in case of
2712           // a tail call.
2713           if (Flags.isByVal()) {
2714             unsigned VARegSize, VARegSaveSize;
2715             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2716             VarArgStyleRegisters(CCInfo, DAG,
2717                                  dl, Chain, CurOrigArg, Ins[VA.getValNo()].PartOffset, 0);
2718             unsigned Bytes = Flags.getByValSize() - VARegSize;
2719             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2720             int FI = MFI->CreateFixedObject(Bytes,
2721                                             VA.getLocMemOffset(), false);
2722             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2723           } else {
2724             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2725                                             VA.getLocMemOffset(), true);
2726
2727             // Create load nodes to retrieve arguments from the stack.
2728             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2729             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2730                                          MachinePointerInfo::getFixedStack(FI),
2731                                          false, false, false, 0));
2732           }
2733           lastInsIndex = index;
2734         }
2735     }
2736   }
2737
2738   // varargs
2739   if (isVarArg)
2740     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2741                          CCInfo.getNextStackOffset());
2742
2743   return Chain;
2744 }
2745
2746 /// isFloatingPointZero - Return true if this is +0.0.
2747 static bool isFloatingPointZero(SDValue Op) {
2748   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2749     return CFP->getValueAPF().isPosZero();
2750   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2751     // Maybe this has already been legalized into the constant pool?
2752     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2753       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2754       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2755         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2756           return CFP->getValueAPF().isPosZero();
2757     }
2758   }
2759   return false;
2760 }
2761
2762 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2763 /// the given operands.
2764 SDValue
2765 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2766                              SDValue &ARMcc, SelectionDAG &DAG,
2767                              DebugLoc dl) const {
2768   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2769     unsigned C = RHSC->getZExtValue();
2770     if (!isLegalICmpImmediate(C)) {
2771       // Constant does not fit, try adjusting it by one?
2772       switch (CC) {
2773       default: break;
2774       case ISD::SETLT:
2775       case ISD::SETGE:
2776         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2777           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2778           RHS = DAG.getConstant(C-1, MVT::i32);
2779         }
2780         break;
2781       case ISD::SETULT:
2782       case ISD::SETUGE:
2783         if (C != 0 && isLegalICmpImmediate(C-1)) {
2784           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2785           RHS = DAG.getConstant(C-1, MVT::i32);
2786         }
2787         break;
2788       case ISD::SETLE:
2789       case ISD::SETGT:
2790         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2791           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2792           RHS = DAG.getConstant(C+1, MVT::i32);
2793         }
2794         break;
2795       case ISD::SETULE:
2796       case ISD::SETUGT:
2797         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2798           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2799           RHS = DAG.getConstant(C+1, MVT::i32);
2800         }
2801         break;
2802       }
2803     }
2804   }
2805
2806   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2807   ARMISD::NodeType CompareType;
2808   switch (CondCode) {
2809   default:
2810     CompareType = ARMISD::CMP;
2811     break;
2812   case ARMCC::EQ:
2813   case ARMCC::NE:
2814     // Uses only Z Flag
2815     CompareType = ARMISD::CMPZ;
2816     break;
2817   }
2818   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2819   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2820 }
2821
2822 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2823 SDValue
2824 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2825                              DebugLoc dl) const {
2826   SDValue Cmp;
2827   if (!isFloatingPointZero(RHS))
2828     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2829   else
2830     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2831   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2832 }
2833
2834 /// duplicateCmp - Glue values can have only one use, so this function
2835 /// duplicates a comparison node.
2836 SDValue
2837 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2838   unsigned Opc = Cmp.getOpcode();
2839   DebugLoc DL = Cmp.getDebugLoc();
2840   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2841     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2842
2843   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2844   Cmp = Cmp.getOperand(0);
2845   Opc = Cmp.getOpcode();
2846   if (Opc == ARMISD::CMPFP)
2847     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2848   else {
2849     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2850     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2851   }
2852   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2853 }
2854
2855 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2856   SDValue Cond = Op.getOperand(0);
2857   SDValue SelectTrue = Op.getOperand(1);
2858   SDValue SelectFalse = Op.getOperand(2);
2859   DebugLoc dl = Op.getDebugLoc();
2860
2861   // Convert:
2862   //
2863   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2864   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2865   //
2866   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2867     const ConstantSDNode *CMOVTrue =
2868       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2869     const ConstantSDNode *CMOVFalse =
2870       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2871
2872     if (CMOVTrue && CMOVFalse) {
2873       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2874       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2875
2876       SDValue True;
2877       SDValue False;
2878       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2879         True = SelectTrue;
2880         False = SelectFalse;
2881       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2882         True = SelectFalse;
2883         False = SelectTrue;
2884       }
2885
2886       if (True.getNode() && False.getNode()) {
2887         EVT VT = Op.getValueType();
2888         SDValue ARMcc = Cond.getOperand(2);
2889         SDValue CCR = Cond.getOperand(3);
2890         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2891         assert(True.getValueType() == VT);
2892         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2893       }
2894     }
2895   }
2896
2897   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2898   // undefined bits before doing a full-word comparison with zero.
2899   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2900                      DAG.getConstant(1, Cond.getValueType()));
2901
2902   return DAG.getSelectCC(dl, Cond,
2903                          DAG.getConstant(0, Cond.getValueType()),
2904                          SelectTrue, SelectFalse, ISD::SETNE);
2905 }
2906
2907 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2908   EVT VT = Op.getValueType();
2909   SDValue LHS = Op.getOperand(0);
2910   SDValue RHS = Op.getOperand(1);
2911   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2912   SDValue TrueVal = Op.getOperand(2);
2913   SDValue FalseVal = Op.getOperand(3);
2914   DebugLoc dl = Op.getDebugLoc();
2915
2916   if (LHS.getValueType() == MVT::i32) {
2917     SDValue ARMcc;
2918     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2919     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2920     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2921   }
2922
2923   ARMCC::CondCodes CondCode, CondCode2;
2924   FPCCToARMCC(CC, CondCode, CondCode2);
2925
2926   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2927   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2928   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2929   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2930                                ARMcc, CCR, Cmp);
2931   if (CondCode2 != ARMCC::AL) {
2932     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2933     // FIXME: Needs another CMP because flag can have but one use.
2934     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2935     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2936                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2937   }
2938   return Result;
2939 }
2940
2941 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2942 /// to morph to an integer compare sequence.
2943 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2944                            const ARMSubtarget *Subtarget) {
2945   SDNode *N = Op.getNode();
2946   if (!N->hasOneUse())
2947     // Otherwise it requires moving the value from fp to integer registers.
2948     return false;
2949   if (!N->getNumValues())
2950     return false;
2951   EVT VT = Op.getValueType();
2952   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2953     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2954     // vmrs are very slow, e.g. cortex-a8.
2955     return false;
2956
2957   if (isFloatingPointZero(Op)) {
2958     SeenZero = true;
2959     return true;
2960   }
2961   return ISD::isNormalLoad(N);
2962 }
2963
2964 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2965   if (isFloatingPointZero(Op))
2966     return DAG.getConstant(0, MVT::i32);
2967
2968   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2969     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2970                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2971                        Ld->isVolatile(), Ld->isNonTemporal(),
2972                        Ld->isInvariant(), Ld->getAlignment());
2973
2974   llvm_unreachable("Unknown VFP cmp argument!");
2975 }
2976
2977 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2978                            SDValue &RetVal1, SDValue &RetVal2) {
2979   if (isFloatingPointZero(Op)) {
2980     RetVal1 = DAG.getConstant(0, MVT::i32);
2981     RetVal2 = DAG.getConstant(0, MVT::i32);
2982     return;
2983   }
2984
2985   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2986     SDValue Ptr = Ld->getBasePtr();
2987     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2988                           Ld->getChain(), Ptr,
2989                           Ld->getPointerInfo(),
2990                           Ld->isVolatile(), Ld->isNonTemporal(),
2991                           Ld->isInvariant(), Ld->getAlignment());
2992
2993     EVT PtrType = Ptr.getValueType();
2994     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2995     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2996                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2997     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2998                           Ld->getChain(), NewPtr,
2999                           Ld->getPointerInfo().getWithOffset(4),
3000                           Ld->isVolatile(), Ld->isNonTemporal(),
3001                           Ld->isInvariant(), NewAlign);
3002     return;
3003   }
3004
3005   llvm_unreachable("Unknown VFP cmp argument!");
3006 }
3007
3008 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3009 /// f32 and even f64 comparisons to integer ones.
3010 SDValue
3011 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3012   SDValue Chain = Op.getOperand(0);
3013   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3014   SDValue LHS = Op.getOperand(2);
3015   SDValue RHS = Op.getOperand(3);
3016   SDValue Dest = Op.getOperand(4);
3017   DebugLoc dl = Op.getDebugLoc();
3018
3019   bool LHSSeenZero = false;
3020   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3021   bool RHSSeenZero = false;
3022   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3023   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3024     // If unsafe fp math optimization is enabled and there are no other uses of
3025     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3026     // to an integer comparison.
3027     if (CC == ISD::SETOEQ)
3028       CC = ISD::SETEQ;
3029     else if (CC == ISD::SETUNE)
3030       CC = ISD::SETNE;
3031
3032     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3033     SDValue ARMcc;
3034     if (LHS.getValueType() == MVT::f32) {
3035       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3036                         bitcastf32Toi32(LHS, DAG), Mask);
3037       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3038                         bitcastf32Toi32(RHS, DAG), Mask);
3039       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3040       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3041       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3042                          Chain, Dest, ARMcc, CCR, Cmp);
3043     }
3044
3045     SDValue LHS1, LHS2;
3046     SDValue RHS1, RHS2;
3047     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3048     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3049     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3050     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3051     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3052     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3053     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3054     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3055     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3056   }
3057
3058   return SDValue();
3059 }
3060
3061 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3062   SDValue Chain = Op.getOperand(0);
3063   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3064   SDValue LHS = Op.getOperand(2);
3065   SDValue RHS = Op.getOperand(3);
3066   SDValue Dest = Op.getOperand(4);
3067   DebugLoc dl = Op.getDebugLoc();
3068
3069   if (LHS.getValueType() == MVT::i32) {
3070     SDValue ARMcc;
3071     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3072     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3073     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3074                        Chain, Dest, ARMcc, CCR, Cmp);
3075   }
3076
3077   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3078
3079   if (getTargetMachine().Options.UnsafeFPMath &&
3080       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3081        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3082     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3083     if (Result.getNode())
3084       return Result;
3085   }
3086
3087   ARMCC::CondCodes CondCode, CondCode2;
3088   FPCCToARMCC(CC, CondCode, CondCode2);
3089
3090   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3091   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3092   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3093   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3094   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3095   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3096   if (CondCode2 != ARMCC::AL) {
3097     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3098     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3099     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3100   }
3101   return Res;
3102 }
3103
3104 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3105   SDValue Chain = Op.getOperand(0);
3106   SDValue Table = Op.getOperand(1);
3107   SDValue Index = Op.getOperand(2);
3108   DebugLoc dl = Op.getDebugLoc();
3109
3110   EVT PTy = getPointerTy();
3111   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3112   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3113   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3114   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3115   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3116   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3117   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3118   if (Subtarget->isThumb2()) {
3119     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3120     // which does another jump to the destination. This also makes it easier
3121     // to translate it to TBB / TBH later.
3122     // FIXME: This might not work if the function is extremely large.
3123     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3124                        Addr, Op.getOperand(2), JTI, UId);
3125   }
3126   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3127     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3128                        MachinePointerInfo::getJumpTable(),
3129                        false, false, false, 0);
3130     Chain = Addr.getValue(1);
3131     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3132     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3133   } else {
3134     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3135                        MachinePointerInfo::getJumpTable(),
3136                        false, false, false, 0);
3137     Chain = Addr.getValue(1);
3138     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3139   }
3140 }
3141
3142 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3143   EVT VT = Op.getValueType();
3144   DebugLoc dl = Op.getDebugLoc();
3145
3146   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3147     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3148       return Op;
3149     return DAG.UnrollVectorOp(Op.getNode());
3150   }
3151
3152   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3153          "Invalid type for custom lowering!");
3154   if (VT != MVT::v4i16)
3155     return DAG.UnrollVectorOp(Op.getNode());
3156
3157   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3158   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3159 }
3160
3161 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3162   EVT VT = Op.getValueType();
3163   if (VT.isVector())
3164     return LowerVectorFP_TO_INT(Op, DAG);
3165
3166   DebugLoc dl = Op.getDebugLoc();
3167   unsigned Opc;
3168
3169   switch (Op.getOpcode()) {
3170   default: llvm_unreachable("Invalid opcode!");
3171   case ISD::FP_TO_SINT:
3172     Opc = ARMISD::FTOSI;
3173     break;
3174   case ISD::FP_TO_UINT:
3175     Opc = ARMISD::FTOUI;
3176     break;
3177   }
3178   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3179   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3180 }
3181
3182 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3183   EVT VT = Op.getValueType();
3184   DebugLoc dl = Op.getDebugLoc();
3185
3186   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3187     if (VT.getVectorElementType() == MVT::f32)
3188       return Op;
3189     return DAG.UnrollVectorOp(Op.getNode());
3190   }
3191
3192   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3193          "Invalid type for custom lowering!");
3194   if (VT != MVT::v4f32)
3195     return DAG.UnrollVectorOp(Op.getNode());
3196
3197   unsigned CastOpc;
3198   unsigned Opc;
3199   switch (Op.getOpcode()) {
3200   default: llvm_unreachable("Invalid opcode!");
3201   case ISD::SINT_TO_FP:
3202     CastOpc = ISD::SIGN_EXTEND;
3203     Opc = ISD::SINT_TO_FP;
3204     break;
3205   case ISD::UINT_TO_FP:
3206     CastOpc = ISD::ZERO_EXTEND;
3207     Opc = ISD::UINT_TO_FP;
3208     break;
3209   }
3210
3211   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3212   return DAG.getNode(Opc, dl, VT, Op);
3213 }
3214
3215 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3216   EVT VT = Op.getValueType();
3217   if (VT.isVector())
3218     return LowerVectorINT_TO_FP(Op, DAG);
3219
3220   DebugLoc dl = Op.getDebugLoc();
3221   unsigned Opc;
3222
3223   switch (Op.getOpcode()) {
3224   default: llvm_unreachable("Invalid opcode!");
3225   case ISD::SINT_TO_FP:
3226     Opc = ARMISD::SITOF;
3227     break;
3228   case ISD::UINT_TO_FP:
3229     Opc = ARMISD::UITOF;
3230     break;
3231   }
3232
3233   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3234   return DAG.getNode(Opc, dl, VT, Op);
3235 }
3236
3237 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3238   // Implement fcopysign with a fabs and a conditional fneg.
3239   SDValue Tmp0 = Op.getOperand(0);
3240   SDValue Tmp1 = Op.getOperand(1);
3241   DebugLoc dl = Op.getDebugLoc();
3242   EVT VT = Op.getValueType();
3243   EVT SrcVT = Tmp1.getValueType();
3244   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3245     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3246   bool UseNEON = !InGPR && Subtarget->hasNEON();
3247
3248   if (UseNEON) {
3249     // Use VBSL to copy the sign bit.
3250     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3251     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3252                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3253     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3254     if (VT == MVT::f64)
3255       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3256                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3257                          DAG.getConstant(32, MVT::i32));
3258     else /*if (VT == MVT::f32)*/
3259       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3260     if (SrcVT == MVT::f32) {
3261       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3262       if (VT == MVT::f64)
3263         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3264                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3265                            DAG.getConstant(32, MVT::i32));
3266     } else if (VT == MVT::f32)
3267       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3268                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3269                          DAG.getConstant(32, MVT::i32));
3270     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3271     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3272
3273     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3274                                             MVT::i32);
3275     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3276     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3277                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3278
3279     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3280                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3281                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3282     if (VT == MVT::f32) {
3283       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3284       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3285                         DAG.getConstant(0, MVT::i32));
3286     } else {
3287       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3288     }
3289
3290     return Res;
3291   }
3292
3293   // Bitcast operand 1 to i32.
3294   if (SrcVT == MVT::f64)
3295     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3296                        &Tmp1, 1).getValue(1);
3297   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3298
3299   // Or in the signbit with integer operations.
3300   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3301   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3302   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3303   if (VT == MVT::f32) {
3304     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3305                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3306     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3307                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3308   }
3309
3310   // f64: Or the high part with signbit and then combine two parts.
3311   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3312                      &Tmp0, 1);
3313   SDValue Lo = Tmp0.getValue(0);
3314   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3315   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3316   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3317 }
3318
3319 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3320   MachineFunction &MF = DAG.getMachineFunction();
3321   MachineFrameInfo *MFI = MF.getFrameInfo();
3322   MFI->setReturnAddressIsTaken(true);
3323
3324   EVT VT = Op.getValueType();
3325   DebugLoc dl = Op.getDebugLoc();
3326   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3327   if (Depth) {
3328     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3329     SDValue Offset = DAG.getConstant(4, MVT::i32);
3330     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3331                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3332                        MachinePointerInfo(), false, false, false, 0);
3333   }
3334
3335   // Return LR, which contains the return address. Mark it an implicit live-in.
3336   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3337   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3338 }
3339
3340 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3341   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3342   MFI->setFrameAddressIsTaken(true);
3343
3344   EVT VT = Op.getValueType();
3345   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3346   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3347   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3348     ? ARM::R7 : ARM::R11;
3349   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3350   while (Depth--)
3351     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3352                             MachinePointerInfo(),
3353                             false, false, false, 0);
3354   return FrameAddr;
3355 }
3356
3357 /// ExpandBITCAST - If the target supports VFP, this function is called to
3358 /// expand a bit convert where either the source or destination type is i64 to
3359 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3360 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3361 /// vectors), since the legalizer won't know what to do with that.
3362 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3364   DebugLoc dl = N->getDebugLoc();
3365   SDValue Op = N->getOperand(0);
3366
3367   // This function is only supposed to be called for i64 types, either as the
3368   // source or destination of the bit convert.
3369   EVT SrcVT = Op.getValueType();
3370   EVT DstVT = N->getValueType(0);
3371   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3372          "ExpandBITCAST called for non-i64 type");
3373
3374   // Turn i64->f64 into VMOVDRR.
3375   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3376     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3377                              DAG.getConstant(0, MVT::i32));
3378     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3379                              DAG.getConstant(1, MVT::i32));
3380     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3381                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3382   }
3383
3384   // Turn f64->i64 into VMOVRRD.
3385   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3386     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3387                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3388     // Merge the pieces into a single i64 value.
3389     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3390   }
3391
3392   return SDValue();
3393 }
3394
3395 /// getZeroVector - Returns a vector of specified type with all zero elements.
3396 /// Zero vectors are used to represent vector negation and in those cases
3397 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3398 /// not support i64 elements, so sometimes the zero vectors will need to be
3399 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3400 /// zero vector.
3401 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3402   assert(VT.isVector() && "Expected a vector type");
3403   // The canonical modified immediate encoding of a zero vector is....0!
3404   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3405   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3406   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3407   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3408 }
3409
3410 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3411 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3412 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3413                                                 SelectionDAG &DAG) const {
3414   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3415   EVT VT = Op.getValueType();
3416   unsigned VTBits = VT.getSizeInBits();
3417   DebugLoc dl = Op.getDebugLoc();
3418   SDValue ShOpLo = Op.getOperand(0);
3419   SDValue ShOpHi = Op.getOperand(1);
3420   SDValue ShAmt  = Op.getOperand(2);
3421   SDValue ARMcc;
3422   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3423
3424   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3425
3426   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3427                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3428   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3429   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3430                                    DAG.getConstant(VTBits, MVT::i32));
3431   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3432   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3433   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3434
3435   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3436   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3437                           ARMcc, DAG, dl);
3438   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3439   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3440                            CCR, Cmp);
3441
3442   SDValue Ops[2] = { Lo, Hi };
3443   return DAG.getMergeValues(Ops, 2, dl);
3444 }
3445
3446 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3447 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3448 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3449                                                SelectionDAG &DAG) const {
3450   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3451   EVT VT = Op.getValueType();
3452   unsigned VTBits = VT.getSizeInBits();
3453   DebugLoc dl = Op.getDebugLoc();
3454   SDValue ShOpLo = Op.getOperand(0);
3455   SDValue ShOpHi = Op.getOperand(1);
3456   SDValue ShAmt  = Op.getOperand(2);
3457   SDValue ARMcc;
3458
3459   assert(Op.getOpcode() == ISD::SHL_PARTS);
3460   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3461                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3462   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3463   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3464                                    DAG.getConstant(VTBits, MVT::i32));
3465   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3466   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3467
3468   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3469   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3470   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3471                           ARMcc, DAG, dl);
3472   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3473   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3474                            CCR, Cmp);
3475
3476   SDValue Ops[2] = { Lo, Hi };
3477   return DAG.getMergeValues(Ops, 2, dl);
3478 }
3479
3480 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3481                                             SelectionDAG &DAG) const {
3482   // The rounding mode is in bits 23:22 of the FPSCR.
3483   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3484   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3485   // so that the shift + and get folded into a bitfield extract.
3486   DebugLoc dl = Op.getDebugLoc();
3487   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3488                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3489                                               MVT::i32));
3490   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3491                                   DAG.getConstant(1U << 22, MVT::i32));
3492   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3493                               DAG.getConstant(22, MVT::i32));
3494   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3495                      DAG.getConstant(3, MVT::i32));
3496 }
3497
3498 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3499                          const ARMSubtarget *ST) {
3500   EVT VT = N->getValueType(0);
3501   DebugLoc dl = N->getDebugLoc();
3502
3503   if (!ST->hasV6T2Ops())
3504     return SDValue();
3505
3506   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3507   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3508 }
3509
3510 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3511                           const ARMSubtarget *ST) {
3512   EVT VT = N->getValueType(0);
3513   DebugLoc dl = N->getDebugLoc();
3514
3515   if (!VT.isVector())
3516     return SDValue();
3517
3518   // Lower vector shifts on NEON to use VSHL.
3519   assert(ST->hasNEON() && "unexpected vector shift");
3520
3521   // Left shifts translate directly to the vshiftu intrinsic.
3522   if (N->getOpcode() == ISD::SHL)
3523     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3524                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3525                        N->getOperand(0), N->getOperand(1));
3526
3527   assert((N->getOpcode() == ISD::SRA ||
3528           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3529
3530   // NEON uses the same intrinsics for both left and right shifts.  For
3531   // right shifts, the shift amounts are negative, so negate the vector of
3532   // shift amounts.
3533   EVT ShiftVT = N->getOperand(1).getValueType();
3534   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3535                                      getZeroVector(ShiftVT, DAG, dl),
3536                                      N->getOperand(1));
3537   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3538                              Intrinsic::arm_neon_vshifts :
3539                              Intrinsic::arm_neon_vshiftu);
3540   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3541                      DAG.getConstant(vshiftInt, MVT::i32),
3542                      N->getOperand(0), NegatedCount);
3543 }
3544
3545 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3546                                 const ARMSubtarget *ST) {
3547   EVT VT = N->getValueType(0);
3548   DebugLoc dl = N->getDebugLoc();
3549
3550   // We can get here for a node like i32 = ISD::SHL i32, i64
3551   if (VT != MVT::i64)
3552     return SDValue();
3553
3554   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3555          "Unknown shift to lower!");
3556
3557   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3558   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3559       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3560     return SDValue();
3561
3562   // If we are in thumb mode, we don't have RRX.
3563   if (ST->isThumb1Only()) return SDValue();
3564
3565   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3566   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3567                            DAG.getConstant(0, MVT::i32));
3568   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3569                            DAG.getConstant(1, MVT::i32));
3570
3571   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3572   // captures the result into a carry flag.
3573   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3574   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3575
3576   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3577   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3578
3579   // Merge the pieces into a single i64 value.
3580  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3581 }
3582
3583 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3584   SDValue TmpOp0, TmpOp1;
3585   bool Invert = false;
3586   bool Swap = false;
3587   unsigned Opc = 0;
3588
3589   SDValue Op0 = Op.getOperand(0);
3590   SDValue Op1 = Op.getOperand(1);
3591   SDValue CC = Op.getOperand(2);
3592   EVT VT = Op.getValueType();
3593   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3594   DebugLoc dl = Op.getDebugLoc();
3595
3596   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3597     switch (SetCCOpcode) {
3598     default: llvm_unreachable("Illegal FP comparison");
3599     case ISD::SETUNE:
3600     case ISD::SETNE:  Invert = true; // Fallthrough
3601     case ISD::SETOEQ:
3602     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3603     case ISD::SETOLT:
3604     case ISD::SETLT: Swap = true; // Fallthrough
3605     case ISD::SETOGT:
3606     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3607     case ISD::SETOLE:
3608     case ISD::SETLE:  Swap = true; // Fallthrough
3609     case ISD::SETOGE:
3610     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3611     case ISD::SETUGE: Swap = true; // Fallthrough
3612     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3613     case ISD::SETUGT: Swap = true; // Fallthrough
3614     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3615     case ISD::SETUEQ: Invert = true; // Fallthrough
3616     case ISD::SETONE:
3617       // Expand this to (OLT | OGT).
3618       TmpOp0 = Op0;
3619       TmpOp1 = Op1;
3620       Opc = ISD::OR;
3621       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3622       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3623       break;
3624     case ISD::SETUO: Invert = true; // Fallthrough
3625     case ISD::SETO:
3626       // Expand this to (OLT | OGE).
3627       TmpOp0 = Op0;
3628       TmpOp1 = Op1;
3629       Opc = ISD::OR;
3630       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3631       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3632       break;
3633     }
3634   } else {
3635     // Integer comparisons.
3636     switch (SetCCOpcode) {
3637     default: llvm_unreachable("Illegal integer comparison");
3638     case ISD::SETNE:  Invert = true;
3639     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3640     case ISD::SETLT:  Swap = true;
3641     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3642     case ISD::SETLE:  Swap = true;
3643     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3644     case ISD::SETULT: Swap = true;
3645     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3646     case ISD::SETULE: Swap = true;
3647     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3648     }
3649
3650     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3651     if (Opc == ARMISD::VCEQ) {
3652
3653       SDValue AndOp;
3654       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3655         AndOp = Op0;
3656       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3657         AndOp = Op1;
3658
3659       // Ignore bitconvert.
3660       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3661         AndOp = AndOp.getOperand(0);
3662
3663       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3664         Opc = ARMISD::VTST;
3665         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3666         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3667         Invert = !Invert;
3668       }
3669     }
3670   }
3671
3672   if (Swap)
3673     std::swap(Op0, Op1);
3674
3675   // If one of the operands is a constant vector zero, attempt to fold the
3676   // comparison to a specialized compare-against-zero form.
3677   SDValue SingleOp;
3678   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3679     SingleOp = Op0;
3680   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3681     if (Opc == ARMISD::VCGE)
3682       Opc = ARMISD::VCLEZ;
3683     else if (Opc == ARMISD::VCGT)
3684       Opc = ARMISD::VCLTZ;
3685     SingleOp = Op1;
3686   }
3687
3688   SDValue Result;
3689   if (SingleOp.getNode()) {
3690     switch (Opc) {
3691     case ARMISD::VCEQ:
3692       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3693     case ARMISD::VCGE:
3694       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3695     case ARMISD::VCLEZ:
3696       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3697     case ARMISD::VCGT:
3698       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3699     case ARMISD::VCLTZ:
3700       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3701     default:
3702       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3703     }
3704   } else {
3705      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3706   }
3707
3708   if (Invert)
3709     Result = DAG.getNOT(dl, Result, VT);
3710
3711   return Result;
3712 }
3713
3714 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3715 /// valid vector constant for a NEON instruction with a "modified immediate"
3716 /// operand (e.g., VMOV).  If so, return the encoded value.
3717 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3718                                  unsigned SplatBitSize, SelectionDAG &DAG,
3719                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3720   unsigned OpCmode, Imm;
3721
3722   // SplatBitSize is set to the smallest size that splats the vector, so a
3723   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3724   // immediate instructions others than VMOV do not support the 8-bit encoding
3725   // of a zero vector, and the default encoding of zero is supposed to be the
3726   // 32-bit version.
3727   if (SplatBits == 0)
3728     SplatBitSize = 32;
3729
3730   switch (SplatBitSize) {
3731   case 8:
3732     if (type != VMOVModImm)
3733       return SDValue();
3734     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3735     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3736     OpCmode = 0xe;
3737     Imm = SplatBits;
3738     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3739     break;
3740
3741   case 16:
3742     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3743     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3744     if ((SplatBits & ~0xff) == 0) {
3745       // Value = 0x00nn: Op=x, Cmode=100x.
3746       OpCmode = 0x8;
3747       Imm = SplatBits;
3748       break;
3749     }
3750     if ((SplatBits & ~0xff00) == 0) {
3751       // Value = 0xnn00: Op=x, Cmode=101x.
3752       OpCmode = 0xa;
3753       Imm = SplatBits >> 8;
3754       break;
3755     }
3756     return SDValue();
3757
3758   case 32:
3759     // NEON's 32-bit VMOV supports splat values where:
3760     // * only one byte is nonzero, or
3761     // * the least significant byte is 0xff and the second byte is nonzero, or
3762     // * the least significant 2 bytes are 0xff and the third is nonzero.
3763     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3764     if ((SplatBits & ~0xff) == 0) {
3765       // Value = 0x000000nn: Op=x, Cmode=000x.
3766       OpCmode = 0;
3767       Imm = SplatBits;
3768       break;
3769     }
3770     if ((SplatBits & ~0xff00) == 0) {
3771       // Value = 0x0000nn00: Op=x, Cmode=001x.
3772       OpCmode = 0x2;
3773       Imm = SplatBits >> 8;
3774       break;
3775     }
3776     if ((SplatBits & ~0xff0000) == 0) {
3777       // Value = 0x00nn0000: Op=x, Cmode=010x.
3778       OpCmode = 0x4;
3779       Imm = SplatBits >> 16;
3780       break;
3781     }
3782     if ((SplatBits & ~0xff000000) == 0) {
3783       // Value = 0xnn000000: Op=x, Cmode=011x.
3784       OpCmode = 0x6;
3785       Imm = SplatBits >> 24;
3786       break;
3787     }
3788
3789     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3790     if (type == OtherModImm) return SDValue();
3791
3792     if ((SplatBits & ~0xffff) == 0 &&
3793         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3794       // Value = 0x0000nnff: Op=x, Cmode=1100.
3795       OpCmode = 0xc;
3796       Imm = SplatBits >> 8;
3797       SplatBits |= 0xff;
3798       break;
3799     }
3800
3801     if ((SplatBits & ~0xffffff) == 0 &&
3802         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3803       // Value = 0x00nnffff: Op=x, Cmode=1101.
3804       OpCmode = 0xd;
3805       Imm = SplatBits >> 16;
3806       SplatBits |= 0xffff;
3807       break;
3808     }
3809
3810     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3811     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3812     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3813     // and fall through here to test for a valid 64-bit splat.  But, then the
3814     // caller would also need to check and handle the change in size.
3815     return SDValue();
3816
3817   case 64: {
3818     if (type != VMOVModImm)
3819       return SDValue();
3820     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3821     uint64_t BitMask = 0xff;
3822     uint64_t Val = 0;
3823     unsigned ImmMask = 1;
3824     Imm = 0;
3825     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3826       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3827         Val |= BitMask;
3828         Imm |= ImmMask;
3829       } else if ((SplatBits & BitMask) != 0) {
3830         return SDValue();
3831       }
3832       BitMask <<= 8;
3833       ImmMask <<= 1;
3834     }
3835     // Op=1, Cmode=1110.
3836     OpCmode = 0x1e;
3837     SplatBits = Val;
3838     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3839     break;
3840   }
3841
3842   default:
3843     llvm_unreachable("unexpected size for isNEONModifiedImm");
3844   }
3845
3846   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3847   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3848 }
3849
3850 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3851                                            const ARMSubtarget *ST) const {
3852   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3853     return SDValue();
3854
3855   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3856   assert(Op.getValueType() == MVT::f32 &&
3857          "ConstantFP custom lowering should only occur for f32.");
3858
3859   // Try splatting with a VMOV.f32...
3860   APFloat FPVal = CFP->getValueAPF();
3861   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3862   if (ImmVal != -1) {
3863     DebugLoc DL = Op.getDebugLoc();
3864     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3865     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3866                                       NewVal);
3867     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3868                        DAG.getConstant(0, MVT::i32));
3869   }
3870
3871   // If that fails, try a VMOV.i32
3872   EVT VMovVT;
3873   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3874   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3875                                      VMOVModImm);
3876   if (NewVal != SDValue()) {
3877     DebugLoc DL = Op.getDebugLoc();
3878     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3879                                       NewVal);
3880     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3881                                        VecConstant);
3882     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3883                        DAG.getConstant(0, MVT::i32));
3884   }
3885
3886   // Finally, try a VMVN.i32
3887   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3888                              VMVNModImm);
3889   if (NewVal != SDValue()) {
3890     DebugLoc DL = Op.getDebugLoc();
3891     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3892     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3893                                        VecConstant);
3894     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3895                        DAG.getConstant(0, MVT::i32));
3896   }
3897
3898   return SDValue();
3899 }
3900
3901
3902 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3903                        bool &ReverseVEXT, unsigned &Imm) {
3904   unsigned NumElts = VT.getVectorNumElements();
3905   ReverseVEXT = false;
3906
3907   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3908   if (M[0] < 0)
3909     return false;
3910
3911   Imm = M[0];
3912
3913   // If this is a VEXT shuffle, the immediate value is the index of the first
3914   // element.  The other shuffle indices must be the successive elements after
3915   // the first one.
3916   unsigned ExpectedElt = Imm;
3917   for (unsigned i = 1; i < NumElts; ++i) {
3918     // Increment the expected index.  If it wraps around, it may still be
3919     // a VEXT but the source vectors must be swapped.
3920     ExpectedElt += 1;
3921     if (ExpectedElt == NumElts * 2) {
3922       ExpectedElt = 0;
3923       ReverseVEXT = true;
3924     }
3925
3926     if (M[i] < 0) continue; // ignore UNDEF indices
3927     if (ExpectedElt != static_cast<unsigned>(M[i]))
3928       return false;
3929   }
3930
3931   // Adjust the index value if the source operands will be swapped.
3932   if (ReverseVEXT)
3933     Imm -= NumElts;
3934
3935   return true;
3936 }
3937
3938 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3939 /// instruction with the specified blocksize.  (The order of the elements
3940 /// within each block of the vector is reversed.)
3941 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3942   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3943          "Only possible block sizes for VREV are: 16, 32, 64");
3944
3945   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3946   if (EltSz == 64)
3947     return false;
3948
3949   unsigned NumElts = VT.getVectorNumElements();
3950   unsigned BlockElts = M[0] + 1;
3951   // If the first shuffle index is UNDEF, be optimistic.
3952   if (M[0] < 0)
3953     BlockElts = BlockSize / EltSz;
3954
3955   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3956     return false;
3957
3958   for (unsigned i = 0; i < NumElts; ++i) {
3959     if (M[i] < 0) continue; // ignore UNDEF indices
3960     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3961       return false;
3962   }
3963
3964   return true;
3965 }
3966
3967 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3968   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3969   // range, then 0 is placed into the resulting vector. So pretty much any mask
3970   // of 8 elements can work here.
3971   return VT == MVT::v8i8 && M.size() == 8;
3972 }
3973
3974 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3975   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3976   if (EltSz == 64)
3977     return false;
3978
3979   unsigned NumElts = VT.getVectorNumElements();
3980   WhichResult = (M[0] == 0 ? 0 : 1);
3981   for (unsigned i = 0; i < NumElts; i += 2) {
3982     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3983         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3984       return false;
3985   }
3986   return true;
3987 }
3988
3989 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3990 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3991 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3992 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3993   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3994   if (EltSz == 64)
3995     return false;
3996
3997   unsigned NumElts = VT.getVectorNumElements();
3998   WhichResult = (M[0] == 0 ? 0 : 1);
3999   for (unsigned i = 0; i < NumElts; i += 2) {
4000     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4001         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4002       return false;
4003   }
4004   return true;
4005 }
4006
4007 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4008   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4009   if (EltSz == 64)
4010     return false;
4011
4012   unsigned NumElts = VT.getVectorNumElements();
4013   WhichResult = (M[0] == 0 ? 0 : 1);
4014   for (unsigned i = 0; i != NumElts; ++i) {
4015     if (M[i] < 0) continue; // ignore UNDEF indices
4016     if ((unsigned) M[i] != 2 * i + WhichResult)
4017       return false;
4018   }
4019
4020   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4021   if (VT.is64BitVector() && EltSz == 32)
4022     return false;
4023
4024   return true;
4025 }
4026
4027 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4028 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4029 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4030 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4031   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4032   if (EltSz == 64)
4033     return false;
4034
4035   unsigned Half = VT.getVectorNumElements() / 2;
4036   WhichResult = (M[0] == 0 ? 0 : 1);
4037   for (unsigned j = 0; j != 2; ++j) {
4038     unsigned Idx = WhichResult;
4039     for (unsigned i = 0; i != Half; ++i) {
4040       int MIdx = M[i + j * Half];
4041       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4042         return false;
4043       Idx += 2;
4044     }
4045   }
4046
4047   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4048   if (VT.is64BitVector() && EltSz == 32)
4049     return false;
4050
4051   return true;
4052 }
4053
4054 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4055   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4056   if (EltSz == 64)
4057     return false;
4058
4059   unsigned NumElts = VT.getVectorNumElements();
4060   WhichResult = (M[0] == 0 ? 0 : 1);
4061   unsigned Idx = WhichResult * NumElts / 2;
4062   for (unsigned i = 0; i != NumElts; i += 2) {
4063     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4064         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4065       return false;
4066     Idx += 1;
4067   }
4068
4069   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4070   if (VT.is64BitVector() && EltSz == 32)
4071     return false;
4072
4073   return true;
4074 }
4075
4076 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4077 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4078 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4079 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4080   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4081   if (EltSz == 64)
4082     return false;
4083
4084   unsigned NumElts = VT.getVectorNumElements();
4085   WhichResult = (M[0] == 0 ? 0 : 1);
4086   unsigned Idx = WhichResult * NumElts / 2;
4087   for (unsigned i = 0; i != NumElts; i += 2) {
4088     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4089         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4090       return false;
4091     Idx += 1;
4092   }
4093
4094   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4095   if (VT.is64BitVector() && EltSz == 32)
4096     return false;
4097
4098   return true;
4099 }
4100
4101 // If N is an integer constant that can be moved into a register in one
4102 // instruction, return an SDValue of such a constant (will become a MOV
4103 // instruction).  Otherwise return null.
4104 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4105                                      const ARMSubtarget *ST, DebugLoc dl) {
4106   uint64_t Val;
4107   if (!isa<ConstantSDNode>(N))
4108     return SDValue();
4109   Val = cast<ConstantSDNode>(N)->getZExtValue();
4110
4111   if (ST->isThumb1Only()) {
4112     if (Val <= 255 || ~Val <= 255)
4113       return DAG.getConstant(Val, MVT::i32);
4114   } else {
4115     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4116       return DAG.getConstant(Val, MVT::i32);
4117   }
4118   return SDValue();
4119 }
4120
4121 // If this is a case we can't handle, return null and let the default
4122 // expansion code take care of it.
4123 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4124                                              const ARMSubtarget *ST) const {
4125   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4126   DebugLoc dl = Op.getDebugLoc();
4127   EVT VT = Op.getValueType();
4128
4129   APInt SplatBits, SplatUndef;
4130   unsigned SplatBitSize;
4131   bool HasAnyUndefs;
4132   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4133     if (SplatBitSize <= 64) {
4134       // Check if an immediate VMOV works.
4135       EVT VmovVT;
4136       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4137                                       SplatUndef.getZExtValue(), SplatBitSize,
4138                                       DAG, VmovVT, VT.is128BitVector(),
4139                                       VMOVModImm);
4140       if (Val.getNode()) {
4141         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4142         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4143       }
4144
4145       // Try an immediate VMVN.
4146       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4147       Val = isNEONModifiedImm(NegatedImm,
4148                                       SplatUndef.getZExtValue(), SplatBitSize,
4149                                       DAG, VmovVT, VT.is128BitVector(),
4150                                       VMVNModImm);
4151       if (Val.getNode()) {
4152         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4153         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4154       }
4155
4156       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4157       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4158         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4159         if (ImmVal != -1) {
4160           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4161           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4162         }
4163       }
4164     }
4165   }
4166
4167   // Scan through the operands to see if only one value is used.
4168   //
4169   // As an optimisation, even if more than one value is used it may be more
4170   // profitable to splat with one value then change some lanes.
4171   //
4172   // Heuristically we decide to do this if the vector has a "dominant" value,
4173   // defined as splatted to more than half of the lanes.
4174   unsigned NumElts = VT.getVectorNumElements();
4175   bool isOnlyLowElement = true;
4176   bool usesOnlyOneValue = true;
4177   bool hasDominantValue = false;
4178   bool isConstant = true;
4179
4180   // Map of the number of times a particular SDValue appears in the
4181   // element list.
4182   DenseMap<SDValue, unsigned> ValueCounts;
4183   SDValue Value;
4184   for (unsigned i = 0; i < NumElts; ++i) {
4185     SDValue V = Op.getOperand(i);
4186     if (V.getOpcode() == ISD::UNDEF)
4187       continue;
4188     if (i > 0)
4189       isOnlyLowElement = false;
4190     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4191       isConstant = false;
4192
4193     ValueCounts.insert(std::make_pair(V, 0));
4194     unsigned &Count = ValueCounts[V];
4195     
4196     // Is this value dominant? (takes up more than half of the lanes)
4197     if (++Count > (NumElts / 2)) {
4198       hasDominantValue = true;
4199       Value = V;
4200     }
4201   }
4202   if (ValueCounts.size() != 1)
4203     usesOnlyOneValue = false;
4204   if (!Value.getNode() && ValueCounts.size() > 0)
4205     Value = ValueCounts.begin()->first;
4206
4207   if (ValueCounts.size() == 0)
4208     return DAG.getUNDEF(VT);
4209
4210   if (isOnlyLowElement)
4211     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4212
4213   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4214
4215   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4216   // i32 and try again.
4217   if (hasDominantValue && EltSize <= 32) {
4218     if (!isConstant) {
4219       SDValue N;
4220
4221       // If we are VDUPing a value that comes directly from a vector, that will
4222       // cause an unnecessary move to and from a GPR, where instead we could
4223       // just use VDUPLANE.
4224       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT)
4225         N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4226                         Value->getOperand(0), Value->getOperand(1));
4227       else
4228         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4229
4230       if (!usesOnlyOneValue) {
4231         // The dominant value was splatted as 'N', but we now have to insert
4232         // all differing elements.
4233         for (unsigned I = 0; I < NumElts; ++I) {
4234           if (Op.getOperand(I) == Value)
4235             continue;
4236           SmallVector<SDValue, 3> Ops;
4237           Ops.push_back(N);
4238           Ops.push_back(Op.getOperand(I));
4239           Ops.push_back(DAG.getConstant(I, MVT::i32));
4240           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4241         }
4242       }
4243       return N;
4244     }
4245     if (VT.getVectorElementType().isFloatingPoint()) {
4246       SmallVector<SDValue, 8> Ops;
4247       for (unsigned i = 0; i < NumElts; ++i)
4248         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4249                                   Op.getOperand(i)));
4250       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4251       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4252       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4253       if (Val.getNode())
4254         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4255     }
4256     if (usesOnlyOneValue) {
4257       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4258       if (isConstant && Val.getNode())
4259         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4260     }
4261   }
4262
4263   // If all elements are constants and the case above didn't get hit, fall back
4264   // to the default expansion, which will generate a load from the constant
4265   // pool.
4266   if (isConstant)
4267     return SDValue();
4268
4269   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4270   if (NumElts >= 4) {
4271     SDValue shuffle = ReconstructShuffle(Op, DAG);
4272     if (shuffle != SDValue())
4273       return shuffle;
4274   }
4275
4276   // Vectors with 32- or 64-bit elements can be built by directly assigning
4277   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4278   // will be legalized.
4279   if (EltSize >= 32) {
4280     // Do the expansion with floating-point types, since that is what the VFP
4281     // registers are defined to use, and since i64 is not legal.
4282     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4283     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4284     SmallVector<SDValue, 8> Ops;
4285     for (unsigned i = 0; i < NumElts; ++i)
4286       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4287     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4288     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4289   }
4290
4291   return SDValue();
4292 }
4293
4294 // Gather data to see if the operation can be modelled as a
4295 // shuffle in combination with VEXTs.
4296 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4297                                               SelectionDAG &DAG) const {
4298   DebugLoc dl = Op.getDebugLoc();
4299   EVT VT = Op.getValueType();
4300   unsigned NumElts = VT.getVectorNumElements();
4301
4302   SmallVector<SDValue, 2> SourceVecs;
4303   SmallVector<unsigned, 2> MinElts;
4304   SmallVector<unsigned, 2> MaxElts;
4305
4306   for (unsigned i = 0; i < NumElts; ++i) {
4307     SDValue V = Op.getOperand(i);
4308     if (V.getOpcode() == ISD::UNDEF)
4309       continue;
4310     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4311       // A shuffle can only come from building a vector from various
4312       // elements of other vectors.
4313       return SDValue();
4314     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4315                VT.getVectorElementType()) {
4316       // This code doesn't know how to handle shuffles where the vector
4317       // element types do not match (this happens because type legalization
4318       // promotes the return type of EXTRACT_VECTOR_ELT).
4319       // FIXME: It might be appropriate to extend this code to handle
4320       // mismatched types.
4321       return SDValue();
4322     }
4323
4324     // Record this extraction against the appropriate vector if possible...
4325     SDValue SourceVec = V.getOperand(0);
4326     // If the element number isn't a constant, we can't effectively
4327     // analyze what's going on.
4328     if (!isa<ConstantSDNode>(V.getOperand(1)))
4329       return SDValue();
4330     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4331     bool FoundSource = false;
4332     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4333       if (SourceVecs[j] == SourceVec) {
4334         if (MinElts[j] > EltNo)
4335           MinElts[j] = EltNo;
4336         if (MaxElts[j] < EltNo)
4337           MaxElts[j] = EltNo;
4338         FoundSource = true;
4339         break;
4340       }
4341     }
4342
4343     // Or record a new source if not...
4344     if (!FoundSource) {
4345       SourceVecs.push_back(SourceVec);
4346       MinElts.push_back(EltNo);
4347       MaxElts.push_back(EltNo);
4348     }
4349   }
4350
4351   // Currently only do something sane when at most two source vectors
4352   // involved.
4353   if (SourceVecs.size() > 2)
4354     return SDValue();
4355
4356   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4357   int VEXTOffsets[2] = {0, 0};
4358
4359   // This loop extracts the usage patterns of the source vectors
4360   // and prepares appropriate SDValues for a shuffle if possible.
4361   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4362     if (SourceVecs[i].getValueType() == VT) {
4363       // No VEXT necessary
4364       ShuffleSrcs[i] = SourceVecs[i];
4365       VEXTOffsets[i] = 0;
4366       continue;
4367     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4368       // It probably isn't worth padding out a smaller vector just to
4369       // break it down again in a shuffle.
4370       return SDValue();
4371     }
4372
4373     // Since only 64-bit and 128-bit vectors are legal on ARM and
4374     // we've eliminated the other cases...
4375     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4376            "unexpected vector sizes in ReconstructShuffle");
4377
4378     if (MaxElts[i] - MinElts[i] >= NumElts) {
4379       // Span too large for a VEXT to cope
4380       return SDValue();
4381     }
4382
4383     if (MinElts[i] >= NumElts) {
4384       // The extraction can just take the second half
4385       VEXTOffsets[i] = NumElts;
4386       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4387                                    SourceVecs[i],
4388                                    DAG.getIntPtrConstant(NumElts));
4389     } else if (MaxElts[i] < NumElts) {
4390       // The extraction can just take the first half
4391       VEXTOffsets[i] = 0;
4392       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4393                                    SourceVecs[i],
4394                                    DAG.getIntPtrConstant(0));
4395     } else {
4396       // An actual VEXT is needed
4397       VEXTOffsets[i] = MinElts[i];
4398       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4399                                      SourceVecs[i],
4400                                      DAG.getIntPtrConstant(0));
4401       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4402                                      SourceVecs[i],
4403                                      DAG.getIntPtrConstant(NumElts));
4404       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4405                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4406     }
4407   }
4408
4409   SmallVector<int, 8> Mask;
4410
4411   for (unsigned i = 0; i < NumElts; ++i) {
4412     SDValue Entry = Op.getOperand(i);
4413     if (Entry.getOpcode() == ISD::UNDEF) {
4414       Mask.push_back(-1);
4415       continue;
4416     }
4417
4418     SDValue ExtractVec = Entry.getOperand(0);
4419     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4420                                           .getOperand(1))->getSExtValue();
4421     if (ExtractVec == SourceVecs[0]) {
4422       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4423     } else {
4424       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4425     }
4426   }
4427
4428   // Final check before we try to produce nonsense...
4429   if (isShuffleMaskLegal(Mask, VT))
4430     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4431                                 &Mask[0]);
4432
4433   return SDValue();
4434 }
4435
4436 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4437 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4438 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4439 /// are assumed to be legal.
4440 bool
4441 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4442                                       EVT VT) const {
4443   if (VT.getVectorNumElements() == 4 &&
4444       (VT.is128BitVector() || VT.is64BitVector())) {
4445     unsigned PFIndexes[4];
4446     for (unsigned i = 0; i != 4; ++i) {
4447       if (M[i] < 0)
4448         PFIndexes[i] = 8;
4449       else
4450         PFIndexes[i] = M[i];
4451     }
4452
4453     // Compute the index in the perfect shuffle table.
4454     unsigned PFTableIndex =
4455       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4456     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4457     unsigned Cost = (PFEntry >> 30);
4458
4459     if (Cost <= 4)
4460       return true;
4461   }
4462
4463   bool ReverseVEXT;
4464   unsigned Imm, WhichResult;
4465
4466   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4467   return (EltSize >= 32 ||
4468           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4469           isVREVMask(M, VT, 64) ||
4470           isVREVMask(M, VT, 32) ||
4471           isVREVMask(M, VT, 16) ||
4472           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4473           isVTBLMask(M, VT) ||
4474           isVTRNMask(M, VT, WhichResult) ||
4475           isVUZPMask(M, VT, WhichResult) ||
4476           isVZIPMask(M, VT, WhichResult) ||
4477           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4478           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4479           isVZIP_v_undef_Mask(M, VT, WhichResult));
4480 }
4481
4482 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4483 /// the specified operations to build the shuffle.
4484 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4485                                       SDValue RHS, SelectionDAG &DAG,
4486                                       DebugLoc dl) {
4487   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4488   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4489   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4490
4491   enum {
4492     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4493     OP_VREV,
4494     OP_VDUP0,
4495     OP_VDUP1,
4496     OP_VDUP2,
4497     OP_VDUP3,
4498     OP_VEXT1,
4499     OP_VEXT2,
4500     OP_VEXT3,
4501     OP_VUZPL, // VUZP, left result
4502     OP_VUZPR, // VUZP, right result
4503     OP_VZIPL, // VZIP, left result
4504     OP_VZIPR, // VZIP, right result
4505     OP_VTRNL, // VTRN, left result
4506     OP_VTRNR  // VTRN, right result
4507   };
4508
4509   if (OpNum == OP_COPY) {
4510     if (LHSID == (1*9+2)*9+3) return LHS;
4511     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4512     return RHS;
4513   }
4514
4515   SDValue OpLHS, OpRHS;
4516   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4517   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4518   EVT VT = OpLHS.getValueType();
4519
4520   switch (OpNum) {
4521   default: llvm_unreachable("Unknown shuffle opcode!");
4522   case OP_VREV:
4523     // VREV divides the vector in half and swaps within the half.
4524     if (VT.getVectorElementType() == MVT::i32 ||
4525         VT.getVectorElementType() == MVT::f32)
4526       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4527     // vrev <4 x i16> -> VREV32
4528     if (VT.getVectorElementType() == MVT::i16)
4529       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4530     // vrev <4 x i8> -> VREV16
4531     assert(VT.getVectorElementType() == MVT::i8);
4532     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4533   case OP_VDUP0:
4534   case OP_VDUP1:
4535   case OP_VDUP2:
4536   case OP_VDUP3:
4537     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4538                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4539   case OP_VEXT1:
4540   case OP_VEXT2:
4541   case OP_VEXT3:
4542     return DAG.getNode(ARMISD::VEXT, dl, VT,
4543                        OpLHS, OpRHS,
4544                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4545   case OP_VUZPL:
4546   case OP_VUZPR:
4547     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4548                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4549   case OP_VZIPL:
4550   case OP_VZIPR:
4551     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4552                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4553   case OP_VTRNL:
4554   case OP_VTRNR:
4555     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4556                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4557   }
4558 }
4559
4560 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4561                                        ArrayRef<int> ShuffleMask,
4562                                        SelectionDAG &DAG) {
4563   // Check to see if we can use the VTBL instruction.
4564   SDValue V1 = Op.getOperand(0);
4565   SDValue V2 = Op.getOperand(1);
4566   DebugLoc DL = Op.getDebugLoc();
4567
4568   SmallVector<SDValue, 8> VTBLMask;
4569   for (ArrayRef<int>::iterator
4570          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4571     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4572
4573   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4574     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4575                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4576                                    &VTBLMask[0], 8));
4577
4578   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4579                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4580                                  &VTBLMask[0], 8));
4581 }
4582
4583 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4584   SDValue V1 = Op.getOperand(0);
4585   SDValue V2 = Op.getOperand(1);
4586   DebugLoc dl = Op.getDebugLoc();
4587   EVT VT = Op.getValueType();
4588   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4589
4590   // Convert shuffles that are directly supported on NEON to target-specific
4591   // DAG nodes, instead of keeping them as shuffles and matching them again
4592   // during code selection.  This is more efficient and avoids the possibility
4593   // of inconsistencies between legalization and selection.
4594   // FIXME: floating-point vectors should be canonicalized to integer vectors
4595   // of the same time so that they get CSEd properly.
4596   ArrayRef<int> ShuffleMask = SVN->getMask();
4597
4598   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4599   if (EltSize <= 32) {
4600     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4601       int Lane = SVN->getSplatIndex();
4602       // If this is undef splat, generate it via "just" vdup, if possible.
4603       if (Lane == -1) Lane = 0;
4604
4605       // Test if V1 is a SCALAR_TO_VECTOR.
4606       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4607         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4608       }
4609       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4610       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4611       // reaches it).
4612       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4613           !isa<ConstantSDNode>(V1.getOperand(0))) {
4614         bool IsScalarToVector = true;
4615         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4616           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4617             IsScalarToVector = false;
4618             break;
4619           }
4620         if (IsScalarToVector)
4621           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4622       }
4623       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4624                          DAG.getConstant(Lane, MVT::i32));
4625     }
4626
4627     bool ReverseVEXT;
4628     unsigned Imm;
4629     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4630       if (ReverseVEXT)
4631         std::swap(V1, V2);
4632       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4633                          DAG.getConstant(Imm, MVT::i32));
4634     }
4635
4636     if (isVREVMask(ShuffleMask, VT, 64))
4637       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4638     if (isVREVMask(ShuffleMask, VT, 32))
4639       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4640     if (isVREVMask(ShuffleMask, VT, 16))
4641       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4642
4643     // Check for Neon shuffles that modify both input vectors in place.
4644     // If both results are used, i.e., if there are two shuffles with the same
4645     // source operands and with masks corresponding to both results of one of
4646     // these operations, DAG memoization will ensure that a single node is
4647     // used for both shuffles.
4648     unsigned WhichResult;
4649     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4650       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4651                          V1, V2).getValue(WhichResult);
4652     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4653       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4654                          V1, V2).getValue(WhichResult);
4655     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4656       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4657                          V1, V2).getValue(WhichResult);
4658
4659     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4660       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4661                          V1, V1).getValue(WhichResult);
4662     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4663       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4664                          V1, V1).getValue(WhichResult);
4665     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4666       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4667                          V1, V1).getValue(WhichResult);
4668   }
4669
4670   // If the shuffle is not directly supported and it has 4 elements, use
4671   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4672   unsigned NumElts = VT.getVectorNumElements();
4673   if (NumElts == 4) {
4674     unsigned PFIndexes[4];
4675     for (unsigned i = 0; i != 4; ++i) {
4676       if (ShuffleMask[i] < 0)
4677         PFIndexes[i] = 8;
4678       else
4679         PFIndexes[i] = ShuffleMask[i];
4680     }
4681
4682     // Compute the index in the perfect shuffle table.
4683     unsigned PFTableIndex =
4684       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4685     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4686     unsigned Cost = (PFEntry >> 30);
4687
4688     if (Cost <= 4)
4689       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4690   }
4691
4692   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4693   if (EltSize >= 32) {
4694     // Do the expansion with floating-point types, since that is what the VFP
4695     // registers are defined to use, and since i64 is not legal.
4696     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4697     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4698     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4699     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4700     SmallVector<SDValue, 8> Ops;
4701     for (unsigned i = 0; i < NumElts; ++i) {
4702       if (ShuffleMask[i] < 0)
4703         Ops.push_back(DAG.getUNDEF(EltVT));
4704       else
4705         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4706                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4707                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4708                                                   MVT::i32)));
4709     }
4710     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4711     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4712   }
4713
4714   if (VT == MVT::v8i8) {
4715     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4716     if (NewOp.getNode())
4717       return NewOp;
4718   }
4719
4720   return SDValue();
4721 }
4722
4723 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4724   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4725   SDValue Lane = Op.getOperand(2);
4726   if (!isa<ConstantSDNode>(Lane))
4727     return SDValue();
4728
4729   return Op;
4730 }
4731
4732 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4733   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4734   SDValue Lane = Op.getOperand(1);
4735   if (!isa<ConstantSDNode>(Lane))
4736     return SDValue();
4737
4738   SDValue Vec = Op.getOperand(0);
4739   if (Op.getValueType() == MVT::i32 &&
4740       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4741     DebugLoc dl = Op.getDebugLoc();
4742     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4743   }
4744
4745   return Op;
4746 }
4747
4748 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4749   // The only time a CONCAT_VECTORS operation can have legal types is when
4750   // two 64-bit vectors are concatenated to a 128-bit vector.
4751   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4752          "unexpected CONCAT_VECTORS");
4753   DebugLoc dl = Op.getDebugLoc();
4754   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4755   SDValue Op0 = Op.getOperand(0);
4756   SDValue Op1 = Op.getOperand(1);
4757   if (Op0.getOpcode() != ISD::UNDEF)
4758     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4759                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4760                       DAG.getIntPtrConstant(0));
4761   if (Op1.getOpcode() != ISD::UNDEF)
4762     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4763                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4764                       DAG.getIntPtrConstant(1));
4765   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4766 }
4767
4768 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4769 /// element has been zero/sign-extended, depending on the isSigned parameter,
4770 /// from an integer type half its size.
4771 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4772                                    bool isSigned) {
4773   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4774   EVT VT = N->getValueType(0);
4775   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4776     SDNode *BVN = N->getOperand(0).getNode();
4777     if (BVN->getValueType(0) != MVT::v4i32 ||
4778         BVN->getOpcode() != ISD::BUILD_VECTOR)
4779       return false;
4780     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4781     unsigned HiElt = 1 - LoElt;
4782     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4783     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4784     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4785     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4786     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4787       return false;
4788     if (isSigned) {
4789       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4790           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4791         return true;
4792     } else {
4793       if (Hi0->isNullValue() && Hi1->isNullValue())
4794         return true;
4795     }
4796     return false;
4797   }
4798
4799   if (N->getOpcode() != ISD::BUILD_VECTOR)
4800     return false;
4801
4802   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4803     SDNode *Elt = N->getOperand(i).getNode();
4804     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4805       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4806       unsigned HalfSize = EltSize / 2;
4807       if (isSigned) {
4808         if (!isIntN(HalfSize, C->getSExtValue()))
4809           return false;
4810       } else {
4811         if (!isUIntN(HalfSize, C->getZExtValue()))
4812           return false;
4813       }
4814       continue;
4815     }
4816     return false;
4817   }
4818
4819   return true;
4820 }
4821
4822 /// isSignExtended - Check if a node is a vector value that is sign-extended
4823 /// or a constant BUILD_VECTOR with sign-extended elements.
4824 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4825   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4826     return true;
4827   if (isExtendedBUILD_VECTOR(N, DAG, true))
4828     return true;
4829   return false;
4830 }
4831
4832 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4833 /// or a constant BUILD_VECTOR with zero-extended elements.
4834 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4835   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4836     return true;
4837   if (isExtendedBUILD_VECTOR(N, DAG, false))
4838     return true;
4839   return false;
4840 }
4841
4842 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4843 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4844 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4845   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4846     return N->getOperand(0);
4847   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4848     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4849                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4850                        LD->isNonTemporal(), LD->isInvariant(),
4851                        LD->getAlignment());
4852   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4853   // have been legalized as a BITCAST from v4i32.
4854   if (N->getOpcode() == ISD::BITCAST) {
4855     SDNode *BVN = N->getOperand(0).getNode();
4856     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4857            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4858     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4859     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4860                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4861   }
4862   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4863   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4864   EVT VT = N->getValueType(0);
4865   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4866   unsigned NumElts = VT.getVectorNumElements();
4867   MVT TruncVT = MVT::getIntegerVT(EltSize);
4868   SmallVector<SDValue, 8> Ops;
4869   for (unsigned i = 0; i != NumElts; ++i) {
4870     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4871     const APInt &CInt = C->getAPIntValue();
4872     // Element types smaller than 32 bits are not legal, so use i32 elements.
4873     // The values are implicitly truncated so sext vs. zext doesn't matter.
4874     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4875   }
4876   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4877                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4878 }
4879
4880 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4881   unsigned Opcode = N->getOpcode();
4882   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4883     SDNode *N0 = N->getOperand(0).getNode();
4884     SDNode *N1 = N->getOperand(1).getNode();
4885     return N0->hasOneUse() && N1->hasOneUse() &&
4886       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4887   }
4888   return false;
4889 }
4890
4891 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4892   unsigned Opcode = N->getOpcode();
4893   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4894     SDNode *N0 = N->getOperand(0).getNode();
4895     SDNode *N1 = N->getOperand(1).getNode();
4896     return N0->hasOneUse() && N1->hasOneUse() &&
4897       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4898   }
4899   return false;
4900 }
4901
4902 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4903   // Multiplications are only custom-lowered for 128-bit vectors so that
4904   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4905   EVT VT = Op.getValueType();
4906   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4907   SDNode *N0 = Op.getOperand(0).getNode();
4908   SDNode *N1 = Op.getOperand(1).getNode();
4909   unsigned NewOpc = 0;
4910   bool isMLA = false;
4911   bool isN0SExt = isSignExtended(N0, DAG);
4912   bool isN1SExt = isSignExtended(N1, DAG);
4913   if (isN0SExt && isN1SExt)
4914     NewOpc = ARMISD::VMULLs;
4915   else {
4916     bool isN0ZExt = isZeroExtended(N0, DAG);
4917     bool isN1ZExt = isZeroExtended(N1, DAG);
4918     if (isN0ZExt && isN1ZExt)
4919       NewOpc = ARMISD::VMULLu;
4920     else if (isN1SExt || isN1ZExt) {
4921       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4922       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4923       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4924         NewOpc = ARMISD::VMULLs;
4925         isMLA = true;
4926       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4927         NewOpc = ARMISD::VMULLu;
4928         isMLA = true;
4929       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4930         std::swap(N0, N1);
4931         NewOpc = ARMISD::VMULLu;
4932         isMLA = true;
4933       }
4934     }
4935
4936     if (!NewOpc) {
4937       if (VT == MVT::v2i64)
4938         // Fall through to expand this.  It is not legal.
4939         return SDValue();
4940       else
4941         // Other vector multiplications are legal.
4942         return Op;
4943     }
4944   }
4945
4946   // Legalize to a VMULL instruction.
4947   DebugLoc DL = Op.getDebugLoc();
4948   SDValue Op0;
4949   SDValue Op1 = SkipExtension(N1, DAG);
4950   if (!isMLA) {
4951     Op0 = SkipExtension(N0, DAG);
4952     assert(Op0.getValueType().is64BitVector() &&
4953            Op1.getValueType().is64BitVector() &&
4954            "unexpected types for extended operands to VMULL");
4955     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4956   }
4957
4958   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4959   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4960   //   vmull q0, d4, d6
4961   //   vmlal q0, d5, d6
4962   // is faster than
4963   //   vaddl q0, d4, d5
4964   //   vmovl q1, d6
4965   //   vmul  q0, q0, q1
4966   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4967   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4968   EVT Op1VT = Op1.getValueType();
4969   return DAG.getNode(N0->getOpcode(), DL, VT,
4970                      DAG.getNode(NewOpc, DL, VT,
4971                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4972                      DAG.getNode(NewOpc, DL, VT,
4973                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4974 }
4975
4976 static SDValue
4977 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4978   // Convert to float
4979   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4980   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4981   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4982   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4983   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4984   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4985   // Get reciprocal estimate.
4986   // float4 recip = vrecpeq_f32(yf);
4987   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4988                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4989   // Because char has a smaller range than uchar, we can actually get away
4990   // without any newton steps.  This requires that we use a weird bias
4991   // of 0xb000, however (again, this has been exhaustively tested).
4992   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4993   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4994   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4995   Y = DAG.getConstant(0xb000, MVT::i32);
4996   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4997   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4998   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4999   // Convert back to short.
5000   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5001   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5002   return X;
5003 }
5004
5005 static SDValue
5006 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5007   SDValue N2;
5008   // Convert to float.
5009   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5010   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5011   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5012   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5013   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5014   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5015
5016   // Use reciprocal estimate and one refinement step.
5017   // float4 recip = vrecpeq_f32(yf);
5018   // recip *= vrecpsq_f32(yf, recip);
5019   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5020                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5021   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5022                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5023                    N1, N2);
5024   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5025   // Because short has a smaller range than ushort, we can actually get away
5026   // with only a single newton step.  This requires that we use a weird bias
5027   // of 89, however (again, this has been exhaustively tested).
5028   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5029   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5030   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5031   N1 = DAG.getConstant(0x89, MVT::i32);
5032   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5033   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5034   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5035   // Convert back to integer and return.
5036   // return vmovn_s32(vcvt_s32_f32(result));
5037   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5038   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5039   return N0;
5040 }
5041
5042 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5043   EVT VT = Op.getValueType();
5044   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5045          "unexpected type for custom-lowering ISD::SDIV");
5046
5047   DebugLoc dl = Op.getDebugLoc();
5048   SDValue N0 = Op.getOperand(0);
5049   SDValue N1 = Op.getOperand(1);
5050   SDValue N2, N3;
5051
5052   if (VT == MVT::v8i8) {
5053     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5054     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5055
5056     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5057                      DAG.getIntPtrConstant(4));
5058     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5059                      DAG.getIntPtrConstant(4));
5060     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5061                      DAG.getIntPtrConstant(0));
5062     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5063                      DAG.getIntPtrConstant(0));
5064
5065     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5066     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5067
5068     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5069     N0 = LowerCONCAT_VECTORS(N0, DAG);
5070
5071     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5072     return N0;
5073   }
5074   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5075 }
5076
5077 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5078   EVT VT = Op.getValueType();
5079   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5080          "unexpected type for custom-lowering ISD::UDIV");
5081
5082   DebugLoc dl = Op.getDebugLoc();
5083   SDValue N0 = Op.getOperand(0);
5084   SDValue N1 = Op.getOperand(1);
5085   SDValue N2, N3;
5086
5087   if (VT == MVT::v8i8) {
5088     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5089     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5090
5091     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5092                      DAG.getIntPtrConstant(4));
5093     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5094                      DAG.getIntPtrConstant(4));
5095     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5096                      DAG.getIntPtrConstant(0));
5097     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5098                      DAG.getIntPtrConstant(0));
5099
5100     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5101     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5102
5103     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5104     N0 = LowerCONCAT_VECTORS(N0, DAG);
5105
5106     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5107                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5108                      N0);
5109     return N0;
5110   }
5111
5112   // v4i16 sdiv ... Convert to float.
5113   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5114   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5115   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5116   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5117   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5118   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5119
5120   // Use reciprocal estimate and two refinement steps.
5121   // float4 recip = vrecpeq_f32(yf);
5122   // recip *= vrecpsq_f32(yf, recip);
5123   // recip *= vrecpsq_f32(yf, recip);
5124   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5125                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5126   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5127                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5128                    BN1, N2);
5129   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5130   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5131                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5132                    BN1, N2);
5133   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5134   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5135   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5136   // and that it will never cause us to return an answer too large).
5137   // float4 result = as_float4(as_int4(xf*recip) + 2);
5138   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5139   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5140   N1 = DAG.getConstant(2, MVT::i32);
5141   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5142   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5143   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5144   // Convert back to integer and return.
5145   // return vmovn_u32(vcvt_s32_f32(result));
5146   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5147   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5148   return N0;
5149 }
5150
5151 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5152   EVT VT = Op.getNode()->getValueType(0);
5153   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5154
5155   unsigned Opc;
5156   bool ExtraOp = false;
5157   switch (Op.getOpcode()) {
5158   default: llvm_unreachable("Invalid code");
5159   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5160   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5161   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5162   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5163   }
5164
5165   if (!ExtraOp)
5166     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5167                        Op.getOperand(1));
5168   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5169                      Op.getOperand(1), Op.getOperand(2));
5170 }
5171
5172 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5173   // Monotonic load/store is legal for all targets
5174   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5175     return Op;
5176
5177   // Aquire/Release load/store is not legal for targets without a
5178   // dmb or equivalent available.
5179   return SDValue();
5180 }
5181
5182
5183 static void
5184 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5185                     SelectionDAG &DAG, unsigned NewOp) {
5186   DebugLoc dl = Node->getDebugLoc();
5187   assert (Node->getValueType(0) == MVT::i64 &&
5188           "Only know how to expand i64 atomics");
5189
5190   SmallVector<SDValue, 6> Ops;
5191   Ops.push_back(Node->getOperand(0)); // Chain
5192   Ops.push_back(Node->getOperand(1)); // Ptr
5193   // Low part of Val1
5194   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5195                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5196   // High part of Val1
5197   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5198                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5199   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5200     // High part of Val1
5201     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5202                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5203     // High part of Val2
5204     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5205                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5206   }
5207   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5208   SDValue Result =
5209     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5210                             cast<MemSDNode>(Node)->getMemOperand());
5211   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5212   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5213   Results.push_back(Result.getValue(2));
5214 }
5215
5216 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5217   switch (Op.getOpcode()) {
5218   default: llvm_unreachable("Don't know how to custom lower this!");
5219   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5220   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5221   case ISD::GlobalAddress:
5222     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5223       LowerGlobalAddressELF(Op, DAG);
5224   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5225   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5226   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5227   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5228   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5229   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5230   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5231   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5232   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5233   case ISD::SINT_TO_FP:
5234   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5235   case ISD::FP_TO_SINT:
5236   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5237   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5238   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5239   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5240   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5241   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5242   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5243   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5244                                                                Subtarget);
5245   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5246   case ISD::SHL:
5247   case ISD::SRL:
5248   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5249   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5250   case ISD::SRL_PARTS:
5251   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5252   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5253   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5254   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5255   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5256   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5257   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5258   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5259   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5260   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5261   case ISD::MUL:           return LowerMUL(Op, DAG);
5262   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5263   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5264   case ISD::ADDC:
5265   case ISD::ADDE:
5266   case ISD::SUBC:
5267   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5268   case ISD::ATOMIC_LOAD:
5269   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5270   }
5271 }
5272
5273 /// ReplaceNodeResults - Replace the results of node with an illegal result
5274 /// type with new values built out of custom code.
5275 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5276                                            SmallVectorImpl<SDValue>&Results,
5277                                            SelectionDAG &DAG) const {
5278   SDValue Res;
5279   switch (N->getOpcode()) {
5280   default:
5281     llvm_unreachable("Don't know how to custom expand this!");
5282   case ISD::BITCAST:
5283     Res = ExpandBITCAST(N, DAG);
5284     break;
5285   case ISD::SRL:
5286   case ISD::SRA:
5287     Res = Expand64BitShift(N, DAG, Subtarget);
5288     break;
5289   case ISD::ATOMIC_LOAD_ADD:
5290     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5291     return;
5292   case ISD::ATOMIC_LOAD_AND:
5293     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5294     return;
5295   case ISD::ATOMIC_LOAD_NAND:
5296     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5297     return;
5298   case ISD::ATOMIC_LOAD_OR:
5299     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5300     return;
5301   case ISD::ATOMIC_LOAD_SUB:
5302     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5303     return;
5304   case ISD::ATOMIC_LOAD_XOR:
5305     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5306     return;
5307   case ISD::ATOMIC_SWAP:
5308     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5309     return;
5310   case ISD::ATOMIC_CMP_SWAP:
5311     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5312     return;
5313   }
5314   if (Res.getNode())
5315     Results.push_back(Res);
5316 }
5317
5318 //===----------------------------------------------------------------------===//
5319 //                           ARM Scheduler Hooks
5320 //===----------------------------------------------------------------------===//
5321
5322 MachineBasicBlock *
5323 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5324                                      MachineBasicBlock *BB,
5325                                      unsigned Size) const {
5326   unsigned dest    = MI->getOperand(0).getReg();
5327   unsigned ptr     = MI->getOperand(1).getReg();
5328   unsigned oldval  = MI->getOperand(2).getReg();
5329   unsigned newval  = MI->getOperand(3).getReg();
5330   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5331   DebugLoc dl = MI->getDebugLoc();
5332   bool isThumb2 = Subtarget->isThumb2();
5333
5334   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5335   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5336     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5337     (const TargetRegisterClass*)&ARM::GPRRegClass);
5338
5339   if (isThumb2) {
5340     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5341     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5342     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5343   }
5344
5345   unsigned ldrOpc, strOpc;
5346   switch (Size) {
5347   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5348   case 1:
5349     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5350     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5351     break;
5352   case 2:
5353     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5354     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5355     break;
5356   case 4:
5357     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5358     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5359     break;
5360   }
5361
5362   MachineFunction *MF = BB->getParent();
5363   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5364   MachineFunction::iterator It = BB;
5365   ++It; // insert the new blocks after the current block
5366
5367   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5368   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5369   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5370   MF->insert(It, loop1MBB);
5371   MF->insert(It, loop2MBB);
5372   MF->insert(It, exitMBB);
5373
5374   // Transfer the remainder of BB and its successor edges to exitMBB.
5375   exitMBB->splice(exitMBB->begin(), BB,
5376                   llvm::next(MachineBasicBlock::iterator(MI)),
5377                   BB->end());
5378   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5379
5380   //  thisMBB:
5381   //   ...
5382   //   fallthrough --> loop1MBB
5383   BB->addSuccessor(loop1MBB);
5384
5385   // loop1MBB:
5386   //   ldrex dest, [ptr]
5387   //   cmp dest, oldval
5388   //   bne exitMBB
5389   BB = loop1MBB;
5390   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5391   if (ldrOpc == ARM::t2LDREX)
5392     MIB.addImm(0);
5393   AddDefaultPred(MIB);
5394   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5395                  .addReg(dest).addReg(oldval));
5396   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5397     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5398   BB->addSuccessor(loop2MBB);
5399   BB->addSuccessor(exitMBB);
5400
5401   // loop2MBB:
5402   //   strex scratch, newval, [ptr]
5403   //   cmp scratch, #0
5404   //   bne loop1MBB
5405   BB = loop2MBB;
5406   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5407   if (strOpc == ARM::t2STREX)
5408     MIB.addImm(0);
5409   AddDefaultPred(MIB);
5410   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5411                  .addReg(scratch).addImm(0));
5412   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5413     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5414   BB->addSuccessor(loop1MBB);
5415   BB->addSuccessor(exitMBB);
5416
5417   //  exitMBB:
5418   //   ...
5419   BB = exitMBB;
5420
5421   MI->eraseFromParent();   // The instruction is gone now.
5422
5423   return BB;
5424 }
5425
5426 MachineBasicBlock *
5427 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5428                                     unsigned Size, unsigned BinOpcode) const {
5429   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5430   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5431
5432   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5433   MachineFunction *MF = BB->getParent();
5434   MachineFunction::iterator It = BB;
5435   ++It;
5436
5437   unsigned dest = MI->getOperand(0).getReg();
5438   unsigned ptr = MI->getOperand(1).getReg();
5439   unsigned incr = MI->getOperand(2).getReg();
5440   DebugLoc dl = MI->getDebugLoc();
5441   bool isThumb2 = Subtarget->isThumb2();
5442
5443   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5444   if (isThumb2) {
5445     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5446     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5447   }
5448
5449   unsigned ldrOpc, strOpc;
5450   switch (Size) {
5451   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5452   case 1:
5453     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5454     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5455     break;
5456   case 2:
5457     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5458     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5459     break;
5460   case 4:
5461     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5462     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5463     break;
5464   }
5465
5466   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5467   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5468   MF->insert(It, loopMBB);
5469   MF->insert(It, exitMBB);
5470
5471   // Transfer the remainder of BB and its successor edges to exitMBB.
5472   exitMBB->splice(exitMBB->begin(), BB,
5473                   llvm::next(MachineBasicBlock::iterator(MI)),
5474                   BB->end());
5475   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5476
5477   const TargetRegisterClass *TRC = isThumb2 ?
5478     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5479     (const TargetRegisterClass*)&ARM::GPRRegClass;
5480   unsigned scratch = MRI.createVirtualRegister(TRC);
5481   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5482
5483   //  thisMBB:
5484   //   ...
5485   //   fallthrough --> loopMBB
5486   BB->addSuccessor(loopMBB);
5487
5488   //  loopMBB:
5489   //   ldrex dest, ptr
5490   //   <binop> scratch2, dest, incr
5491   //   strex scratch, scratch2, ptr
5492   //   cmp scratch, #0
5493   //   bne- loopMBB
5494   //   fallthrough --> exitMBB
5495   BB = loopMBB;
5496   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5497   if (ldrOpc == ARM::t2LDREX)
5498     MIB.addImm(0);
5499   AddDefaultPred(MIB);
5500   if (BinOpcode) {
5501     // operand order needs to go the other way for NAND
5502     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5503       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5504                      addReg(incr).addReg(dest)).addReg(0);
5505     else
5506       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5507                      addReg(dest).addReg(incr)).addReg(0);
5508   }
5509
5510   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5511   if (strOpc == ARM::t2STREX)
5512     MIB.addImm(0);
5513   AddDefaultPred(MIB);
5514   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5515                  .addReg(scratch).addImm(0));
5516   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5517     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5518
5519   BB->addSuccessor(loopMBB);
5520   BB->addSuccessor(exitMBB);
5521
5522   //  exitMBB:
5523   //   ...
5524   BB = exitMBB;
5525
5526   MI->eraseFromParent();   // The instruction is gone now.
5527
5528   return BB;
5529 }
5530
5531 MachineBasicBlock *
5532 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5533                                           MachineBasicBlock *BB,
5534                                           unsigned Size,
5535                                           bool signExtend,
5536                                           ARMCC::CondCodes Cond) const {
5537   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5538
5539   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5540   MachineFunction *MF = BB->getParent();
5541   MachineFunction::iterator It = BB;
5542   ++It;
5543
5544   unsigned dest = MI->getOperand(0).getReg();
5545   unsigned ptr = MI->getOperand(1).getReg();
5546   unsigned incr = MI->getOperand(2).getReg();
5547   unsigned oldval = dest;
5548   DebugLoc dl = MI->getDebugLoc();
5549   bool isThumb2 = Subtarget->isThumb2();
5550
5551   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5552   if (isThumb2) {
5553     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5554     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5555   }
5556
5557   unsigned ldrOpc, strOpc, extendOpc;
5558   switch (Size) {
5559   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5560   case 1:
5561     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5562     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5563     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5564     break;
5565   case 2:
5566     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5567     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5568     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5569     break;
5570   case 4:
5571     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5572     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5573     extendOpc = 0;
5574     break;
5575   }
5576
5577   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5578   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5579   MF->insert(It, loopMBB);
5580   MF->insert(It, exitMBB);
5581
5582   // Transfer the remainder of BB and its successor edges to exitMBB.
5583   exitMBB->splice(exitMBB->begin(), BB,
5584                   llvm::next(MachineBasicBlock::iterator(MI)),
5585                   BB->end());
5586   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5587
5588   const TargetRegisterClass *TRC = isThumb2 ?
5589     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5590     (const TargetRegisterClass*)&ARM::GPRRegClass;
5591   unsigned scratch = MRI.createVirtualRegister(TRC);
5592   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5593
5594   //  thisMBB:
5595   //   ...
5596   //   fallthrough --> loopMBB
5597   BB->addSuccessor(loopMBB);
5598
5599   //  loopMBB:
5600   //   ldrex dest, ptr
5601   //   (sign extend dest, if required)
5602   //   cmp dest, incr
5603   //   cmov.cond scratch2, incr, dest
5604   //   strex scratch, scratch2, ptr
5605   //   cmp scratch, #0
5606   //   bne- loopMBB
5607   //   fallthrough --> exitMBB
5608   BB = loopMBB;
5609   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5610   if (ldrOpc == ARM::t2LDREX)
5611     MIB.addImm(0);
5612   AddDefaultPred(MIB);
5613
5614   // Sign extend the value, if necessary.
5615   if (signExtend && extendOpc) {
5616     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5617     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5618                      .addReg(dest)
5619                      .addImm(0));
5620   }
5621
5622   // Build compare and cmov instructions.
5623   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5624                  .addReg(oldval).addReg(incr));
5625   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5626          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5627
5628   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5629   if (strOpc == ARM::t2STREX)
5630     MIB.addImm(0);
5631   AddDefaultPred(MIB);
5632   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5633                  .addReg(scratch).addImm(0));
5634   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5635     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5636
5637   BB->addSuccessor(loopMBB);
5638   BB->addSuccessor(exitMBB);
5639
5640   //  exitMBB:
5641   //   ...
5642   BB = exitMBB;
5643
5644   MI->eraseFromParent();   // The instruction is gone now.
5645
5646   return BB;
5647 }
5648
5649 MachineBasicBlock *
5650 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5651                                       unsigned Op1, unsigned Op2,
5652                                       bool NeedsCarry, bool IsCmpxchg) const {
5653   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5654   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5655
5656   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5657   MachineFunction *MF = BB->getParent();
5658   MachineFunction::iterator It = BB;
5659   ++It;
5660
5661   unsigned destlo = MI->getOperand(0).getReg();
5662   unsigned desthi = MI->getOperand(1).getReg();
5663   unsigned ptr = MI->getOperand(2).getReg();
5664   unsigned vallo = MI->getOperand(3).getReg();
5665   unsigned valhi = MI->getOperand(4).getReg();
5666   DebugLoc dl = MI->getDebugLoc();
5667   bool isThumb2 = Subtarget->isThumb2();
5668
5669   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5670   if (isThumb2) {
5671     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5672     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5673     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5674   }
5675
5676   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5677   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5678
5679   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5680   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5681   if (IsCmpxchg) {
5682     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5683     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5684   }
5685   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5686   MF->insert(It, loopMBB);
5687   if (IsCmpxchg) {
5688     MF->insert(It, contBB);
5689     MF->insert(It, cont2BB);
5690   }
5691   MF->insert(It, exitMBB);
5692
5693   // Transfer the remainder of BB and its successor edges to exitMBB.
5694   exitMBB->splice(exitMBB->begin(), BB,
5695                   llvm::next(MachineBasicBlock::iterator(MI)),
5696                   BB->end());
5697   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5698
5699   const TargetRegisterClass *TRC = isThumb2 ?
5700     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5701     (const TargetRegisterClass*)&ARM::GPRRegClass;
5702   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5703
5704   //  thisMBB:
5705   //   ...
5706   //   fallthrough --> loopMBB
5707   BB->addSuccessor(loopMBB);
5708
5709   //  loopMBB:
5710   //   ldrexd r2, r3, ptr
5711   //   <binopa> r0, r2, incr
5712   //   <binopb> r1, r3, incr
5713   //   strexd storesuccess, r0, r1, ptr
5714   //   cmp storesuccess, #0
5715   //   bne- loopMBB
5716   //   fallthrough --> exitMBB
5717   //
5718   // Note that the registers are explicitly specified because there is not any
5719   // way to force the register allocator to allocate a register pair.
5720   //
5721   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5722   // need to properly enforce the restriction that the two output registers
5723   // for ldrexd must be different.
5724   BB = loopMBB;
5725   // Load
5726   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5727                  .addReg(ARM::R2, RegState::Define)
5728                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5729   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5730   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5731   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5732
5733   if (IsCmpxchg) {
5734     // Add early exit
5735     for (unsigned i = 0; i < 2; i++) {
5736       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5737                                                          ARM::CMPrr))
5738                      .addReg(i == 0 ? destlo : desthi)
5739                      .addReg(i == 0 ? vallo : valhi));
5740       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5741         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5742       BB->addSuccessor(exitMBB);
5743       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5744       BB = (i == 0 ? contBB : cont2BB);
5745     }
5746
5747     // Copy to physregs for strexd
5748     unsigned setlo = MI->getOperand(5).getReg();
5749     unsigned sethi = MI->getOperand(6).getReg();
5750     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5751     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5752   } else if (Op1) {
5753     // Perform binary operation
5754     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5755                    .addReg(destlo).addReg(vallo))
5756         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5757     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5758                    .addReg(desthi).addReg(valhi)).addReg(0);
5759   } else {
5760     // Copy to physregs for strexd
5761     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5762     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5763   }
5764
5765   // Store
5766   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5767                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5768   // Cmp+jump
5769   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5770                  .addReg(storesuccess).addImm(0));
5771   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5772     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5773
5774   BB->addSuccessor(loopMBB);
5775   BB->addSuccessor(exitMBB);
5776
5777   //  exitMBB:
5778   //   ...
5779   BB = exitMBB;
5780
5781   MI->eraseFromParent();   // The instruction is gone now.
5782
5783   return BB;
5784 }
5785
5786 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5787 /// registers the function context.
5788 void ARMTargetLowering::
5789 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5790                        MachineBasicBlock *DispatchBB, int FI) const {
5791   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5792   DebugLoc dl = MI->getDebugLoc();
5793   MachineFunction *MF = MBB->getParent();
5794   MachineRegisterInfo *MRI = &MF->getRegInfo();
5795   MachineConstantPool *MCP = MF->getConstantPool();
5796   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5797   const Function *F = MF->getFunction();
5798
5799   bool isThumb = Subtarget->isThumb();
5800   bool isThumb2 = Subtarget->isThumb2();
5801
5802   unsigned PCLabelId = AFI->createPICLabelUId();
5803   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5804   ARMConstantPoolValue *CPV =
5805     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5806   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5807
5808   const TargetRegisterClass *TRC = isThumb ?
5809     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5810     (const TargetRegisterClass*)&ARM::GPRRegClass;
5811
5812   // Grab constant pool and fixed stack memory operands.
5813   MachineMemOperand *CPMMO =
5814     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5815                              MachineMemOperand::MOLoad, 4, 4);
5816
5817   MachineMemOperand *FIMMOSt =
5818     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5819                              MachineMemOperand::MOStore, 4, 4);
5820
5821   // Load the address of the dispatch MBB into the jump buffer.
5822   if (isThumb2) {
5823     // Incoming value: jbuf
5824     //   ldr.n  r5, LCPI1_1
5825     //   orr    r5, r5, #1
5826     //   add    r5, pc
5827     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5828     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5829     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5830                    .addConstantPoolIndex(CPI)
5831                    .addMemOperand(CPMMO));
5832     // Set the low bit because of thumb mode.
5833     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5834     AddDefaultCC(
5835       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5836                      .addReg(NewVReg1, RegState::Kill)
5837                      .addImm(0x01)));
5838     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5839     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5840       .addReg(NewVReg2, RegState::Kill)
5841       .addImm(PCLabelId);
5842     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5843                    .addReg(NewVReg3, RegState::Kill)
5844                    .addFrameIndex(FI)
5845                    .addImm(36)  // &jbuf[1] :: pc
5846                    .addMemOperand(FIMMOSt));
5847   } else if (isThumb) {
5848     // Incoming value: jbuf
5849     //   ldr.n  r1, LCPI1_4
5850     //   add    r1, pc
5851     //   mov    r2, #1
5852     //   orrs   r1, r2
5853     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5854     //   str    r1, [r2]
5855     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5856     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5857                    .addConstantPoolIndex(CPI)
5858                    .addMemOperand(CPMMO));
5859     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5860     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5861       .addReg(NewVReg1, RegState::Kill)
5862       .addImm(PCLabelId);
5863     // Set the low bit because of thumb mode.
5864     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5865     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5866                    .addReg(ARM::CPSR, RegState::Define)
5867                    .addImm(1));
5868     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5869     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5870                    .addReg(ARM::CPSR, RegState::Define)
5871                    .addReg(NewVReg2, RegState::Kill)
5872                    .addReg(NewVReg3, RegState::Kill));
5873     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5874     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5875                    .addFrameIndex(FI)
5876                    .addImm(36)); // &jbuf[1] :: pc
5877     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5878                    .addReg(NewVReg4, RegState::Kill)
5879                    .addReg(NewVReg5, RegState::Kill)
5880                    .addImm(0)
5881                    .addMemOperand(FIMMOSt));
5882   } else {
5883     // Incoming value: jbuf
5884     //   ldr  r1, LCPI1_1
5885     //   add  r1, pc, r1
5886     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5887     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5888     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5889                    .addConstantPoolIndex(CPI)
5890                    .addImm(0)
5891                    .addMemOperand(CPMMO));
5892     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5893     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5894                    .addReg(NewVReg1, RegState::Kill)
5895                    .addImm(PCLabelId));
5896     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5897                    .addReg(NewVReg2, RegState::Kill)
5898                    .addFrameIndex(FI)
5899                    .addImm(36)  // &jbuf[1] :: pc
5900                    .addMemOperand(FIMMOSt));
5901   }
5902 }
5903
5904 MachineBasicBlock *ARMTargetLowering::
5905 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5906   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5907   DebugLoc dl = MI->getDebugLoc();
5908   MachineFunction *MF = MBB->getParent();
5909   MachineRegisterInfo *MRI = &MF->getRegInfo();
5910   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5911   MachineFrameInfo *MFI = MF->getFrameInfo();
5912   int FI = MFI->getFunctionContextIndex();
5913
5914   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5915     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5916     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5917
5918   // Get a mapping of the call site numbers to all of the landing pads they're
5919   // associated with.
5920   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5921   unsigned MaxCSNum = 0;
5922   MachineModuleInfo &MMI = MF->getMMI();
5923   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5924        ++BB) {
5925     if (!BB->isLandingPad()) continue;
5926
5927     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5928     // pad.
5929     for (MachineBasicBlock::iterator
5930            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5931       if (!II->isEHLabel()) continue;
5932
5933       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5934       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5935
5936       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5937       for (SmallVectorImpl<unsigned>::iterator
5938              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5939            CSI != CSE; ++CSI) {
5940         CallSiteNumToLPad[*CSI].push_back(BB);
5941         MaxCSNum = std::max(MaxCSNum, *CSI);
5942       }
5943       break;
5944     }
5945   }
5946
5947   // Get an ordered list of the machine basic blocks for the jump table.
5948   std::vector<MachineBasicBlock*> LPadList;
5949   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5950   LPadList.reserve(CallSiteNumToLPad.size());
5951   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5952     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5953     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5954            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5955       LPadList.push_back(*II);
5956       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5957     }
5958   }
5959
5960   assert(!LPadList.empty() &&
5961          "No landing pad destinations for the dispatch jump table!");
5962
5963   // Create the jump table and associated information.
5964   MachineJumpTableInfo *JTI =
5965     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5966   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5967   unsigned UId = AFI->createJumpTableUId();
5968
5969   // Create the MBBs for the dispatch code.
5970
5971   // Shove the dispatch's address into the return slot in the function context.
5972   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5973   DispatchBB->setIsLandingPad();
5974
5975   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5976   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5977   DispatchBB->addSuccessor(TrapBB);
5978
5979   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5980   DispatchBB->addSuccessor(DispContBB);
5981
5982   // Insert and MBBs.
5983   MF->insert(MF->end(), DispatchBB);
5984   MF->insert(MF->end(), DispContBB);
5985   MF->insert(MF->end(), TrapBB);
5986
5987   // Insert code into the entry block that creates and registers the function
5988   // context.
5989   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5990
5991   MachineMemOperand *FIMMOLd =
5992     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5993                              MachineMemOperand::MOLoad |
5994                              MachineMemOperand::MOVolatile, 4, 4);
5995
5996   if (AFI->isThumb1OnlyFunction())
5997     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5998   else if (!Subtarget->hasVFP2())
5999     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
6000   else
6001     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6002
6003   unsigned NumLPads = LPadList.size();
6004   if (Subtarget->isThumb2()) {
6005     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6006     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6007                    .addFrameIndex(FI)
6008                    .addImm(4)
6009                    .addMemOperand(FIMMOLd));
6010
6011     if (NumLPads < 256) {
6012       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6013                      .addReg(NewVReg1)
6014                      .addImm(LPadList.size()));
6015     } else {
6016       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6017       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6018                      .addImm(NumLPads & 0xFFFF));
6019
6020       unsigned VReg2 = VReg1;
6021       if ((NumLPads & 0xFFFF0000) != 0) {
6022         VReg2 = MRI->createVirtualRegister(TRC);
6023         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6024                        .addReg(VReg1)
6025                        .addImm(NumLPads >> 16));
6026       }
6027
6028       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6029                      .addReg(NewVReg1)
6030                      .addReg(VReg2));
6031     }
6032
6033     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6034       .addMBB(TrapBB)
6035       .addImm(ARMCC::HI)
6036       .addReg(ARM::CPSR);
6037
6038     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6039     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6040                    .addJumpTableIndex(MJTI)
6041                    .addImm(UId));
6042
6043     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6044     AddDefaultCC(
6045       AddDefaultPred(
6046         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6047         .addReg(NewVReg3, RegState::Kill)
6048         .addReg(NewVReg1)
6049         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6050
6051     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6052       .addReg(NewVReg4, RegState::Kill)
6053       .addReg(NewVReg1)
6054       .addJumpTableIndex(MJTI)
6055       .addImm(UId);
6056   } else if (Subtarget->isThumb()) {
6057     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6058     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6059                    .addFrameIndex(FI)
6060                    .addImm(1)
6061                    .addMemOperand(FIMMOLd));
6062
6063     if (NumLPads < 256) {
6064       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6065                      .addReg(NewVReg1)
6066                      .addImm(NumLPads));
6067     } else {
6068       MachineConstantPool *ConstantPool = MF->getConstantPool();
6069       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6070       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6071
6072       // MachineConstantPool wants an explicit alignment.
6073       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6074       if (Align == 0)
6075         Align = getDataLayout()->getTypeAllocSize(C->getType());
6076       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6077
6078       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6079       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6080                      .addReg(VReg1, RegState::Define)
6081                      .addConstantPoolIndex(Idx));
6082       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6083                      .addReg(NewVReg1)
6084                      .addReg(VReg1));
6085     }
6086
6087     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6088       .addMBB(TrapBB)
6089       .addImm(ARMCC::HI)
6090       .addReg(ARM::CPSR);
6091
6092     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6093     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6094                    .addReg(ARM::CPSR, RegState::Define)
6095                    .addReg(NewVReg1)
6096                    .addImm(2));
6097
6098     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6099     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6100                    .addJumpTableIndex(MJTI)
6101                    .addImm(UId));
6102
6103     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6104     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6105                    .addReg(ARM::CPSR, RegState::Define)
6106                    .addReg(NewVReg2, RegState::Kill)
6107                    .addReg(NewVReg3));
6108
6109     MachineMemOperand *JTMMOLd =
6110       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6111                                MachineMemOperand::MOLoad, 4, 4);
6112
6113     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6114     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6115                    .addReg(NewVReg4, RegState::Kill)
6116                    .addImm(0)
6117                    .addMemOperand(JTMMOLd));
6118
6119     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6120     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6121                    .addReg(ARM::CPSR, RegState::Define)
6122                    .addReg(NewVReg5, RegState::Kill)
6123                    .addReg(NewVReg3));
6124
6125     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6126       .addReg(NewVReg6, RegState::Kill)
6127       .addJumpTableIndex(MJTI)
6128       .addImm(UId);
6129   } else {
6130     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6131     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6132                    .addFrameIndex(FI)
6133                    .addImm(4)
6134                    .addMemOperand(FIMMOLd));
6135
6136     if (NumLPads < 256) {
6137       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6138                      .addReg(NewVReg1)
6139                      .addImm(NumLPads));
6140     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6141       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6142       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6143                      .addImm(NumLPads & 0xFFFF));
6144
6145       unsigned VReg2 = VReg1;
6146       if ((NumLPads & 0xFFFF0000) != 0) {
6147         VReg2 = MRI->createVirtualRegister(TRC);
6148         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6149                        .addReg(VReg1)
6150                        .addImm(NumLPads >> 16));
6151       }
6152
6153       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6154                      .addReg(NewVReg1)
6155                      .addReg(VReg2));
6156     } else {
6157       MachineConstantPool *ConstantPool = MF->getConstantPool();
6158       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6159       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6160
6161       // MachineConstantPool wants an explicit alignment.
6162       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6163       if (Align == 0)
6164         Align = getDataLayout()->getTypeAllocSize(C->getType());
6165       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6166
6167       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6168       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6169                      .addReg(VReg1, RegState::Define)
6170                      .addConstantPoolIndex(Idx)
6171                      .addImm(0));
6172       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6173                      .addReg(NewVReg1)
6174                      .addReg(VReg1, RegState::Kill));
6175     }
6176
6177     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6178       .addMBB(TrapBB)
6179       .addImm(ARMCC::HI)
6180       .addReg(ARM::CPSR);
6181
6182     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6183     AddDefaultCC(
6184       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6185                      .addReg(NewVReg1)
6186                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6187     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6188     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6189                    .addJumpTableIndex(MJTI)
6190                    .addImm(UId));
6191
6192     MachineMemOperand *JTMMOLd =
6193       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6194                                MachineMemOperand::MOLoad, 4, 4);
6195     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6196     AddDefaultPred(
6197       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6198       .addReg(NewVReg3, RegState::Kill)
6199       .addReg(NewVReg4)
6200       .addImm(0)
6201       .addMemOperand(JTMMOLd));
6202
6203     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6204       .addReg(NewVReg5, RegState::Kill)
6205       .addReg(NewVReg4)
6206       .addJumpTableIndex(MJTI)
6207       .addImm(UId);
6208   }
6209
6210   // Add the jump table entries as successors to the MBB.
6211   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6212   for (std::vector<MachineBasicBlock*>::iterator
6213          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6214     MachineBasicBlock *CurMBB = *I;
6215     if (SeenMBBs.insert(CurMBB))
6216       DispContBB->addSuccessor(CurMBB);
6217   }
6218
6219   // N.B. the order the invoke BBs are processed in doesn't matter here.
6220   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6221   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6222   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6223   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6224   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6225          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6226     MachineBasicBlock *BB = *I;
6227
6228     // Remove the landing pad successor from the invoke block and replace it
6229     // with the new dispatch block.
6230     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6231                                                   BB->succ_end());
6232     while (!Successors.empty()) {
6233       MachineBasicBlock *SMBB = Successors.pop_back_val();
6234       if (SMBB->isLandingPad()) {
6235         BB->removeSuccessor(SMBB);
6236         MBBLPads.push_back(SMBB);
6237       }
6238     }
6239
6240     BB->addSuccessor(DispatchBB);
6241
6242     // Find the invoke call and mark all of the callee-saved registers as
6243     // 'implicit defined' so that they're spilled. This prevents code from
6244     // moving instructions to before the EH block, where they will never be
6245     // executed.
6246     for (MachineBasicBlock::reverse_iterator
6247            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6248       if (!II->isCall()) continue;
6249
6250       DenseMap<unsigned, bool> DefRegs;
6251       for (MachineInstr::mop_iterator
6252              OI = II->operands_begin(), OE = II->operands_end();
6253            OI != OE; ++OI) {
6254         if (!OI->isReg()) continue;
6255         DefRegs[OI->getReg()] = true;
6256       }
6257
6258       MachineInstrBuilder MIB(&*II);
6259
6260       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6261         unsigned Reg = SavedRegs[i];
6262         if (Subtarget->isThumb2() &&
6263             !ARM::tGPRRegClass.contains(Reg) &&
6264             !ARM::hGPRRegClass.contains(Reg))
6265           continue;
6266         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6267           continue;
6268         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6269           continue;
6270         if (!DefRegs[Reg])
6271           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6272       }
6273
6274       break;
6275     }
6276   }
6277
6278   // Mark all former landing pads as non-landing pads. The dispatch is the only
6279   // landing pad now.
6280   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6281          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6282     (*I)->setIsLandingPad(false);
6283
6284   // The instruction is gone now.
6285   MI->eraseFromParent();
6286
6287   return MBB;
6288 }
6289
6290 static
6291 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6292   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6293        E = MBB->succ_end(); I != E; ++I)
6294     if (*I != Succ)
6295       return *I;
6296   llvm_unreachable("Expecting a BB with two successors!");
6297 }
6298
6299 MachineBasicBlock *ARMTargetLowering::
6300 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6301   // This pseudo instruction has 3 operands: dst, src, size
6302   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6303   // Otherwise, we will generate unrolled scalar copies.
6304   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6305   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6306   MachineFunction::iterator It = BB;
6307   ++It;
6308
6309   unsigned dest = MI->getOperand(0).getReg();
6310   unsigned src = MI->getOperand(1).getReg();
6311   unsigned SizeVal = MI->getOperand(2).getImm();
6312   unsigned Align = MI->getOperand(3).getImm();
6313   DebugLoc dl = MI->getDebugLoc();
6314
6315   bool isThumb2 = Subtarget->isThumb2();
6316   MachineFunction *MF = BB->getParent();
6317   MachineRegisterInfo &MRI = MF->getRegInfo();
6318   unsigned ldrOpc, strOpc, UnitSize = 0;
6319
6320   const TargetRegisterClass *TRC = isThumb2 ?
6321     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6322     (const TargetRegisterClass*)&ARM::GPRRegClass;
6323   const TargetRegisterClass *TRC_Vec = 0;
6324
6325   if (Align & 1) {
6326     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6327     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6328     UnitSize = 1;
6329   } else if (Align & 2) {
6330     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6331     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6332     UnitSize = 2;
6333   } else {
6334     // Check whether we can use NEON instructions.
6335     if (!MF->getFunction()->getFnAttributes().
6336           hasAttribute(Attributes::NoImplicitFloat) &&
6337         Subtarget->hasNEON()) {
6338       if ((Align % 16 == 0) && SizeVal >= 16) {
6339         ldrOpc = ARM::VLD1q32wb_fixed;
6340         strOpc = ARM::VST1q32wb_fixed;
6341         UnitSize = 16;
6342         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6343       }
6344       else if ((Align % 8 == 0) && SizeVal >= 8) {
6345         ldrOpc = ARM::VLD1d32wb_fixed;
6346         strOpc = ARM::VST1d32wb_fixed;
6347         UnitSize = 8;
6348         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6349       }
6350     }
6351     // Can't use NEON instructions.
6352     if (UnitSize == 0) {
6353       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6354       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6355       UnitSize = 4;
6356     }
6357   }
6358
6359   unsigned BytesLeft = SizeVal % UnitSize;
6360   unsigned LoopSize = SizeVal - BytesLeft;
6361
6362   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6363     // Use LDR and STR to copy.
6364     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6365     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6366     unsigned srcIn = src;
6367     unsigned destIn = dest;
6368     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6369       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6370       unsigned srcOut = MRI.createVirtualRegister(TRC);
6371       unsigned destOut = MRI.createVirtualRegister(TRC);
6372       if (UnitSize >= 8) {
6373         AddDefaultPred(BuildMI(*BB, MI, dl,
6374           TII->get(ldrOpc), scratch)
6375           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6376
6377         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6378           .addReg(destIn).addImm(0).addReg(scratch));
6379       } else if (isThumb2) {
6380         AddDefaultPred(BuildMI(*BB, MI, dl,
6381           TII->get(ldrOpc), scratch)
6382           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6383
6384         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6385           .addReg(scratch).addReg(destIn)
6386           .addImm(UnitSize));
6387       } else {
6388         AddDefaultPred(BuildMI(*BB, MI, dl,
6389           TII->get(ldrOpc), scratch)
6390           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6391           .addImm(UnitSize));
6392
6393         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6394           .addReg(scratch).addReg(destIn)
6395           .addReg(0).addImm(UnitSize));
6396       }
6397       srcIn = srcOut;
6398       destIn = destOut;
6399     }
6400
6401     // Handle the leftover bytes with LDRB and STRB.
6402     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6403     // [destOut] = STRB_POST(scratch, destIn, 1)
6404     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6405     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6406     for (unsigned i = 0; i < BytesLeft; i++) {
6407       unsigned scratch = MRI.createVirtualRegister(TRC);
6408       unsigned srcOut = MRI.createVirtualRegister(TRC);
6409       unsigned destOut = MRI.createVirtualRegister(TRC);
6410       if (isThumb2) {
6411         AddDefaultPred(BuildMI(*BB, MI, dl,
6412           TII->get(ldrOpc),scratch)
6413           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6414
6415         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6416           .addReg(scratch).addReg(destIn)
6417           .addReg(0).addImm(1));
6418       } else {
6419         AddDefaultPred(BuildMI(*BB, MI, dl,
6420           TII->get(ldrOpc),scratch)
6421           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6422
6423         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6424           .addReg(scratch).addReg(destIn)
6425           .addReg(0).addImm(1));
6426       }
6427       srcIn = srcOut;
6428       destIn = destOut;
6429     }
6430     MI->eraseFromParent();   // The instruction is gone now.
6431     return BB;
6432   }
6433
6434   // Expand the pseudo op to a loop.
6435   // thisMBB:
6436   //   ...
6437   //   movw varEnd, # --> with thumb2
6438   //   movt varEnd, #
6439   //   ldrcp varEnd, idx --> without thumb2
6440   //   fallthrough --> loopMBB
6441   // loopMBB:
6442   //   PHI varPhi, varEnd, varLoop
6443   //   PHI srcPhi, src, srcLoop
6444   //   PHI destPhi, dst, destLoop
6445   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6446   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6447   //   subs varLoop, varPhi, #UnitSize
6448   //   bne loopMBB
6449   //   fallthrough --> exitMBB
6450   // exitMBB:
6451   //   epilogue to handle left-over bytes
6452   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6453   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6454   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6455   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6456   MF->insert(It, loopMBB);
6457   MF->insert(It, exitMBB);
6458
6459   // Transfer the remainder of BB and its successor edges to exitMBB.
6460   exitMBB->splice(exitMBB->begin(), BB,
6461                   llvm::next(MachineBasicBlock::iterator(MI)),
6462                   BB->end());
6463   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6464
6465   // Load an immediate to varEnd.
6466   unsigned varEnd = MRI.createVirtualRegister(TRC);
6467   if (isThumb2) {
6468     unsigned VReg1 = varEnd;
6469     if ((LoopSize & 0xFFFF0000) != 0)
6470       VReg1 = MRI.createVirtualRegister(TRC);
6471     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6472                    .addImm(LoopSize & 0xFFFF));
6473
6474     if ((LoopSize & 0xFFFF0000) != 0)
6475       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6476                      .addReg(VReg1)
6477                      .addImm(LoopSize >> 16));
6478   } else {
6479     MachineConstantPool *ConstantPool = MF->getConstantPool();
6480     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6481     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6482
6483     // MachineConstantPool wants an explicit alignment.
6484     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6485     if (Align == 0)
6486       Align = getDataLayout()->getTypeAllocSize(C->getType());
6487     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6488
6489     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6490                    .addReg(varEnd, RegState::Define)
6491                    .addConstantPoolIndex(Idx)
6492                    .addImm(0));
6493   }
6494   BB->addSuccessor(loopMBB);
6495
6496   // Generate the loop body:
6497   //   varPhi = PHI(varLoop, varEnd)
6498   //   srcPhi = PHI(srcLoop, src)
6499   //   destPhi = PHI(destLoop, dst)
6500   MachineBasicBlock *entryBB = BB;
6501   BB = loopMBB;
6502   unsigned varLoop = MRI.createVirtualRegister(TRC);
6503   unsigned varPhi = MRI.createVirtualRegister(TRC);
6504   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6505   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6506   unsigned destLoop = MRI.createVirtualRegister(TRC);
6507   unsigned destPhi = MRI.createVirtualRegister(TRC);
6508
6509   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6510     .addReg(varLoop).addMBB(loopMBB)
6511     .addReg(varEnd).addMBB(entryBB);
6512   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6513     .addReg(srcLoop).addMBB(loopMBB)
6514     .addReg(src).addMBB(entryBB);
6515   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6516     .addReg(destLoop).addMBB(loopMBB)
6517     .addReg(dest).addMBB(entryBB);
6518
6519   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6520   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6521   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6522   if (UnitSize >= 8) {
6523     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6524       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6525
6526     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6527       .addReg(destPhi).addImm(0).addReg(scratch));
6528   } else if (isThumb2) {
6529     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6530       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6531
6532     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6533       .addReg(scratch).addReg(destPhi)
6534       .addImm(UnitSize));
6535   } else {
6536     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6537       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6538       .addImm(UnitSize));
6539
6540     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6541       .addReg(scratch).addReg(destPhi)
6542       .addReg(0).addImm(UnitSize));
6543   }
6544
6545   // Decrement loop variable by UnitSize.
6546   MachineInstrBuilder MIB = BuildMI(BB, dl,
6547     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6548   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6549   MIB->getOperand(5).setReg(ARM::CPSR);
6550   MIB->getOperand(5).setIsDef(true);
6551
6552   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6553     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6554
6555   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6556   BB->addSuccessor(loopMBB);
6557   BB->addSuccessor(exitMBB);
6558
6559   // Add epilogue to handle BytesLeft.
6560   BB = exitMBB;
6561   MachineInstr *StartOfExit = exitMBB->begin();
6562   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6563   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6564
6565   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6566   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6567   unsigned srcIn = srcLoop;
6568   unsigned destIn = destLoop;
6569   for (unsigned i = 0; i < BytesLeft; i++) {
6570     unsigned scratch = MRI.createVirtualRegister(TRC);
6571     unsigned srcOut = MRI.createVirtualRegister(TRC);
6572     unsigned destOut = MRI.createVirtualRegister(TRC);
6573     if (isThumb2) {
6574       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6575         TII->get(ldrOpc),scratch)
6576         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6577
6578       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6579         .addReg(scratch).addReg(destIn)
6580         .addImm(1));
6581     } else {
6582       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6583         TII->get(ldrOpc),scratch)
6584         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6585
6586       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6587         .addReg(scratch).addReg(destIn)
6588         .addReg(0).addImm(1));
6589     }
6590     srcIn = srcOut;
6591     destIn = destOut;
6592   }
6593
6594   MI->eraseFromParent();   // The instruction is gone now.
6595   return BB;
6596 }
6597
6598 MachineBasicBlock *
6599 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6600                                                MachineBasicBlock *BB) const {
6601   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6602   DebugLoc dl = MI->getDebugLoc();
6603   bool isThumb2 = Subtarget->isThumb2();
6604   switch (MI->getOpcode()) {
6605   default: {
6606     MI->dump();
6607     llvm_unreachable("Unexpected instr type to insert");
6608   }
6609   // The Thumb2 pre-indexed stores have the same MI operands, they just
6610   // define them differently in the .td files from the isel patterns, so
6611   // they need pseudos.
6612   case ARM::t2STR_preidx:
6613     MI->setDesc(TII->get(ARM::t2STR_PRE));
6614     return BB;
6615   case ARM::t2STRB_preidx:
6616     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6617     return BB;
6618   case ARM::t2STRH_preidx:
6619     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6620     return BB;
6621
6622   case ARM::STRi_preidx:
6623   case ARM::STRBi_preidx: {
6624     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6625       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6626     // Decode the offset.
6627     unsigned Offset = MI->getOperand(4).getImm();
6628     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6629     Offset = ARM_AM::getAM2Offset(Offset);
6630     if (isSub)
6631       Offset = -Offset;
6632
6633     MachineMemOperand *MMO = *MI->memoperands_begin();
6634     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6635       .addOperand(MI->getOperand(0))  // Rn_wb
6636       .addOperand(MI->getOperand(1))  // Rt
6637       .addOperand(MI->getOperand(2))  // Rn
6638       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6639       .addOperand(MI->getOperand(5))  // pred
6640       .addOperand(MI->getOperand(6))
6641       .addMemOperand(MMO);
6642     MI->eraseFromParent();
6643     return BB;
6644   }
6645   case ARM::STRr_preidx:
6646   case ARM::STRBr_preidx:
6647   case ARM::STRH_preidx: {
6648     unsigned NewOpc;
6649     switch (MI->getOpcode()) {
6650     default: llvm_unreachable("unexpected opcode!");
6651     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6652     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6653     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6654     }
6655     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6656     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6657       MIB.addOperand(MI->getOperand(i));
6658     MI->eraseFromParent();
6659     return BB;
6660   }
6661   case ARM::ATOMIC_LOAD_ADD_I8:
6662      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6663   case ARM::ATOMIC_LOAD_ADD_I16:
6664      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6665   case ARM::ATOMIC_LOAD_ADD_I32:
6666      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6667
6668   case ARM::ATOMIC_LOAD_AND_I8:
6669      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6670   case ARM::ATOMIC_LOAD_AND_I16:
6671      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6672   case ARM::ATOMIC_LOAD_AND_I32:
6673      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6674
6675   case ARM::ATOMIC_LOAD_OR_I8:
6676      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6677   case ARM::ATOMIC_LOAD_OR_I16:
6678      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6679   case ARM::ATOMIC_LOAD_OR_I32:
6680      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6681
6682   case ARM::ATOMIC_LOAD_XOR_I8:
6683      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6684   case ARM::ATOMIC_LOAD_XOR_I16:
6685      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6686   case ARM::ATOMIC_LOAD_XOR_I32:
6687      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6688
6689   case ARM::ATOMIC_LOAD_NAND_I8:
6690      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6691   case ARM::ATOMIC_LOAD_NAND_I16:
6692      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6693   case ARM::ATOMIC_LOAD_NAND_I32:
6694      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6695
6696   case ARM::ATOMIC_LOAD_SUB_I8:
6697      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6698   case ARM::ATOMIC_LOAD_SUB_I16:
6699      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6700   case ARM::ATOMIC_LOAD_SUB_I32:
6701      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6702
6703   case ARM::ATOMIC_LOAD_MIN_I8:
6704      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6705   case ARM::ATOMIC_LOAD_MIN_I16:
6706      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6707   case ARM::ATOMIC_LOAD_MIN_I32:
6708      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6709
6710   case ARM::ATOMIC_LOAD_MAX_I8:
6711      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6712   case ARM::ATOMIC_LOAD_MAX_I16:
6713      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6714   case ARM::ATOMIC_LOAD_MAX_I32:
6715      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6716
6717   case ARM::ATOMIC_LOAD_UMIN_I8:
6718      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6719   case ARM::ATOMIC_LOAD_UMIN_I16:
6720      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6721   case ARM::ATOMIC_LOAD_UMIN_I32:
6722      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6723
6724   case ARM::ATOMIC_LOAD_UMAX_I8:
6725      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6726   case ARM::ATOMIC_LOAD_UMAX_I16:
6727      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6728   case ARM::ATOMIC_LOAD_UMAX_I32:
6729      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6730
6731   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6732   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6733   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6734
6735   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6736   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6737   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6738
6739
6740   case ARM::ATOMADD6432:
6741     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6742                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6743                               /*NeedsCarry*/ true);
6744   case ARM::ATOMSUB6432:
6745     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6746                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6747                               /*NeedsCarry*/ true);
6748   case ARM::ATOMOR6432:
6749     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6750                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6751   case ARM::ATOMXOR6432:
6752     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6753                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6754   case ARM::ATOMAND6432:
6755     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6756                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6757   case ARM::ATOMSWAP6432:
6758     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6759   case ARM::ATOMCMPXCHG6432:
6760     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6761                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6762                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6763
6764   case ARM::tMOVCCr_pseudo: {
6765     // To "insert" a SELECT_CC instruction, we actually have to insert the
6766     // diamond control-flow pattern.  The incoming instruction knows the
6767     // destination vreg to set, the condition code register to branch on, the
6768     // true/false values to select between, and a branch opcode to use.
6769     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6770     MachineFunction::iterator It = BB;
6771     ++It;
6772
6773     //  thisMBB:
6774     //  ...
6775     //   TrueVal = ...
6776     //   cmpTY ccX, r1, r2
6777     //   bCC copy1MBB
6778     //   fallthrough --> copy0MBB
6779     MachineBasicBlock *thisMBB  = BB;
6780     MachineFunction *F = BB->getParent();
6781     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6782     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6783     F->insert(It, copy0MBB);
6784     F->insert(It, sinkMBB);
6785
6786     // Transfer the remainder of BB and its successor edges to sinkMBB.
6787     sinkMBB->splice(sinkMBB->begin(), BB,
6788                     llvm::next(MachineBasicBlock::iterator(MI)),
6789                     BB->end());
6790     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6791
6792     BB->addSuccessor(copy0MBB);
6793     BB->addSuccessor(sinkMBB);
6794
6795     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6796       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6797
6798     //  copy0MBB:
6799     //   %FalseValue = ...
6800     //   # fallthrough to sinkMBB
6801     BB = copy0MBB;
6802
6803     // Update machine-CFG edges
6804     BB->addSuccessor(sinkMBB);
6805
6806     //  sinkMBB:
6807     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6808     //  ...
6809     BB = sinkMBB;
6810     BuildMI(*BB, BB->begin(), dl,
6811             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6812       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6813       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6814
6815     MI->eraseFromParent();   // The pseudo instruction is gone now.
6816     return BB;
6817   }
6818
6819   case ARM::BCCi64:
6820   case ARM::BCCZi64: {
6821     // If there is an unconditional branch to the other successor, remove it.
6822     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6823
6824     // Compare both parts that make up the double comparison separately for
6825     // equality.
6826     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6827
6828     unsigned LHS1 = MI->getOperand(1).getReg();
6829     unsigned LHS2 = MI->getOperand(2).getReg();
6830     if (RHSisZero) {
6831       AddDefaultPred(BuildMI(BB, dl,
6832                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6833                      .addReg(LHS1).addImm(0));
6834       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6835         .addReg(LHS2).addImm(0)
6836         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6837     } else {
6838       unsigned RHS1 = MI->getOperand(3).getReg();
6839       unsigned RHS2 = MI->getOperand(4).getReg();
6840       AddDefaultPred(BuildMI(BB, dl,
6841                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6842                      .addReg(LHS1).addReg(RHS1));
6843       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6844         .addReg(LHS2).addReg(RHS2)
6845         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6846     }
6847
6848     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6849     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6850     if (MI->getOperand(0).getImm() == ARMCC::NE)
6851       std::swap(destMBB, exitMBB);
6852
6853     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6854       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6855     if (isThumb2)
6856       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6857     else
6858       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6859
6860     MI->eraseFromParent();   // The pseudo instruction is gone now.
6861     return BB;
6862   }
6863
6864   case ARM::Int_eh_sjlj_setjmp:
6865   case ARM::Int_eh_sjlj_setjmp_nofp:
6866   case ARM::tInt_eh_sjlj_setjmp:
6867   case ARM::t2Int_eh_sjlj_setjmp:
6868   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6869     EmitSjLjDispatchBlock(MI, BB);
6870     return BB;
6871
6872   case ARM::ABS:
6873   case ARM::t2ABS: {
6874     // To insert an ABS instruction, we have to insert the
6875     // diamond control-flow pattern.  The incoming instruction knows the
6876     // source vreg to test against 0, the destination vreg to set,
6877     // the condition code register to branch on, the
6878     // true/false values to select between, and a branch opcode to use.
6879     // It transforms
6880     //     V1 = ABS V0
6881     // into
6882     //     V2 = MOVS V0
6883     //     BCC                      (branch to SinkBB if V0 >= 0)
6884     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6885     //     SinkBB: V1 = PHI(V2, V3)
6886     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6887     MachineFunction::iterator BBI = BB;
6888     ++BBI;
6889     MachineFunction *Fn = BB->getParent();
6890     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6891     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6892     Fn->insert(BBI, RSBBB);
6893     Fn->insert(BBI, SinkBB);
6894
6895     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6896     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6897     bool isThumb2 = Subtarget->isThumb2();
6898     MachineRegisterInfo &MRI = Fn->getRegInfo();
6899     // In Thumb mode S must not be specified if source register is the SP or
6900     // PC and if destination register is the SP, so restrict register class
6901     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6902       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6903       (const TargetRegisterClass*)&ARM::GPRRegClass);
6904
6905     // Transfer the remainder of BB and its successor edges to sinkMBB.
6906     SinkBB->splice(SinkBB->begin(), BB,
6907       llvm::next(MachineBasicBlock::iterator(MI)),
6908       BB->end());
6909     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6910
6911     BB->addSuccessor(RSBBB);
6912     BB->addSuccessor(SinkBB);
6913
6914     // fall through to SinkMBB
6915     RSBBB->addSuccessor(SinkBB);
6916
6917     // insert a cmp at the end of BB
6918     AddDefaultPred(BuildMI(BB, dl,
6919                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6920                    .addReg(ABSSrcReg).addImm(0));
6921
6922     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6923     BuildMI(BB, dl,
6924       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6925       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6926
6927     // insert rsbri in RSBBB
6928     // Note: BCC and rsbri will be converted into predicated rsbmi
6929     // by if-conversion pass
6930     BuildMI(*RSBBB, RSBBB->begin(), dl,
6931       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6932       .addReg(ABSSrcReg, RegState::Kill)
6933       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6934
6935     // insert PHI in SinkBB,
6936     // reuse ABSDstReg to not change uses of ABS instruction
6937     BuildMI(*SinkBB, SinkBB->begin(), dl,
6938       TII->get(ARM::PHI), ABSDstReg)
6939       .addReg(NewRsbDstReg).addMBB(RSBBB)
6940       .addReg(ABSSrcReg).addMBB(BB);
6941
6942     // remove ABS instruction
6943     MI->eraseFromParent();
6944
6945     // return last added BB
6946     return SinkBB;
6947   }
6948   case ARM::COPY_STRUCT_BYVAL_I32:
6949     ++NumLoopByVals;
6950     return EmitStructByval(MI, BB);
6951   }
6952 }
6953
6954 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6955                                                       SDNode *Node) const {
6956   if (!MI->hasPostISelHook()) {
6957     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6958            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6959     return;
6960   }
6961
6962   const MCInstrDesc *MCID = &MI->getDesc();
6963   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6964   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6965   // operand is still set to noreg. If needed, set the optional operand's
6966   // register to CPSR, and remove the redundant implicit def.
6967   //
6968   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6969
6970   // Rename pseudo opcodes.
6971   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6972   if (NewOpc) {
6973     const ARMBaseInstrInfo *TII =
6974       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6975     MCID = &TII->get(NewOpc);
6976
6977     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6978            "converted opcode should be the same except for cc_out");
6979
6980     MI->setDesc(*MCID);
6981
6982     // Add the optional cc_out operand
6983     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6984   }
6985   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6986
6987   // Any ARM instruction that sets the 's' bit should specify an optional
6988   // "cc_out" operand in the last operand position.
6989   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6990     assert(!NewOpc && "Optional cc_out operand required");
6991     return;
6992   }
6993   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6994   // since we already have an optional CPSR def.
6995   bool definesCPSR = false;
6996   bool deadCPSR = false;
6997   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6998        i != e; ++i) {
6999     const MachineOperand &MO = MI->getOperand(i);
7000     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7001       definesCPSR = true;
7002       if (MO.isDead())
7003         deadCPSR = true;
7004       MI->RemoveOperand(i);
7005       break;
7006     }
7007   }
7008   if (!definesCPSR) {
7009     assert(!NewOpc && "Optional cc_out operand required");
7010     return;
7011   }
7012   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7013   if (deadCPSR) {
7014     assert(!MI->getOperand(ccOutIdx).getReg() &&
7015            "expect uninitialized optional cc_out operand");
7016     return;
7017   }
7018
7019   // If this instruction was defined with an optional CPSR def and its dag node
7020   // had a live implicit CPSR def, then activate the optional CPSR def.
7021   MachineOperand &MO = MI->getOperand(ccOutIdx);
7022   MO.setReg(ARM::CPSR);
7023   MO.setIsDef(true);
7024 }
7025
7026 //===----------------------------------------------------------------------===//
7027 //                           ARM Optimization Hooks
7028 //===----------------------------------------------------------------------===//
7029
7030 // Helper function that checks if N is a null or all ones constant.
7031 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7032   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7033   if (!C)
7034     return false;
7035   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7036 }
7037
7038 // Return true if N is conditionally 0 or all ones.
7039 // Detects these expressions where cc is an i1 value:
7040 //
7041 //   (select cc 0, y)   [AllOnes=0]
7042 //   (select cc y, 0)   [AllOnes=0]
7043 //   (zext cc)          [AllOnes=0]
7044 //   (sext cc)          [AllOnes=0/1]
7045 //   (select cc -1, y)  [AllOnes=1]
7046 //   (select cc y, -1)  [AllOnes=1]
7047 //
7048 // Invert is set when N is the null/all ones constant when CC is false.
7049 // OtherOp is set to the alternative value of N.
7050 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7051                                        SDValue &CC, bool &Invert,
7052                                        SDValue &OtherOp,
7053                                        SelectionDAG &DAG) {
7054   switch (N->getOpcode()) {
7055   default: return false;
7056   case ISD::SELECT: {
7057     CC = N->getOperand(0);
7058     SDValue N1 = N->getOperand(1);
7059     SDValue N2 = N->getOperand(2);
7060     if (isZeroOrAllOnes(N1, AllOnes)) {
7061       Invert = false;
7062       OtherOp = N2;
7063       return true;
7064     }
7065     if (isZeroOrAllOnes(N2, AllOnes)) {
7066       Invert = true;
7067       OtherOp = N1;
7068       return true;
7069     }
7070     return false;
7071   }
7072   case ISD::ZERO_EXTEND:
7073     // (zext cc) can never be the all ones value.
7074     if (AllOnes)
7075       return false;
7076     // Fall through.
7077   case ISD::SIGN_EXTEND: {
7078     EVT VT = N->getValueType(0);
7079     CC = N->getOperand(0);
7080     if (CC.getValueType() != MVT::i1)
7081       return false;
7082     Invert = !AllOnes;
7083     if (AllOnes)
7084       // When looking for an AllOnes constant, N is an sext, and the 'other'
7085       // value is 0.
7086       OtherOp = DAG.getConstant(0, VT);
7087     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7088       // When looking for a 0 constant, N can be zext or sext.
7089       OtherOp = DAG.getConstant(1, VT);
7090     else
7091       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7092     return true;
7093   }
7094   }
7095 }
7096
7097 // Combine a constant select operand into its use:
7098 //
7099 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7100 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7101 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7102 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7103 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7104 //
7105 // The transform is rejected if the select doesn't have a constant operand that
7106 // is null, or all ones when AllOnes is set.
7107 //
7108 // Also recognize sext/zext from i1:
7109 //
7110 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7111 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7112 //
7113 // These transformations eventually create predicated instructions.
7114 //
7115 // @param N       The node to transform.
7116 // @param Slct    The N operand that is a select.
7117 // @param OtherOp The other N operand (x above).
7118 // @param DCI     Context.
7119 // @param AllOnes Require the select constant to be all ones instead of null.
7120 // @returns The new node, or SDValue() on failure.
7121 static
7122 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7123                             TargetLowering::DAGCombinerInfo &DCI,
7124                             bool AllOnes = false) {
7125   SelectionDAG &DAG = DCI.DAG;
7126   EVT VT = N->getValueType(0);
7127   SDValue NonConstantVal;
7128   SDValue CCOp;
7129   bool SwapSelectOps;
7130   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7131                                   NonConstantVal, DAG))
7132     return SDValue();
7133
7134   // Slct is now know to be the desired identity constant when CC is true.
7135   SDValue TrueVal = OtherOp;
7136   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7137                                  OtherOp, NonConstantVal);
7138   // Unless SwapSelectOps says CC should be false.
7139   if (SwapSelectOps)
7140     std::swap(TrueVal, FalseVal);
7141
7142   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7143                      CCOp, TrueVal, FalseVal);
7144 }
7145
7146 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7147 static
7148 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7149                                        TargetLowering::DAGCombinerInfo &DCI) {
7150   SDValue N0 = N->getOperand(0);
7151   SDValue N1 = N->getOperand(1);
7152   if (N0.getNode()->hasOneUse()) {
7153     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7154     if (Result.getNode())
7155       return Result;
7156   }
7157   if (N1.getNode()->hasOneUse()) {
7158     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7159     if (Result.getNode())
7160       return Result;
7161   }
7162   return SDValue();
7163 }
7164
7165 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7166 // (only after legalization).
7167 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7168                                  TargetLowering::DAGCombinerInfo &DCI,
7169                                  const ARMSubtarget *Subtarget) {
7170
7171   // Only perform optimization if after legalize, and if NEON is available. We
7172   // also expected both operands to be BUILD_VECTORs.
7173   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7174       || N0.getOpcode() != ISD::BUILD_VECTOR
7175       || N1.getOpcode() != ISD::BUILD_VECTOR)
7176     return SDValue();
7177
7178   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7179   EVT VT = N->getValueType(0);
7180   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7181     return SDValue();
7182
7183   // Check that the vector operands are of the right form.
7184   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7185   // operands, where N is the size of the formed vector.
7186   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7187   // index such that we have a pair wise add pattern.
7188
7189   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7190   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7191     return SDValue();
7192   SDValue Vec = N0->getOperand(0)->getOperand(0);
7193   SDNode *V = Vec.getNode();
7194   unsigned nextIndex = 0;
7195
7196   // For each operands to the ADD which are BUILD_VECTORs,
7197   // check to see if each of their operands are an EXTRACT_VECTOR with
7198   // the same vector and appropriate index.
7199   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7200     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7201         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7202
7203       SDValue ExtVec0 = N0->getOperand(i);
7204       SDValue ExtVec1 = N1->getOperand(i);
7205
7206       // First operand is the vector, verify its the same.
7207       if (V != ExtVec0->getOperand(0).getNode() ||
7208           V != ExtVec1->getOperand(0).getNode())
7209         return SDValue();
7210
7211       // Second is the constant, verify its correct.
7212       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7213       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7214
7215       // For the constant, we want to see all the even or all the odd.
7216       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7217           || C1->getZExtValue() != nextIndex+1)
7218         return SDValue();
7219
7220       // Increment index.
7221       nextIndex+=2;
7222     } else
7223       return SDValue();
7224   }
7225
7226   // Create VPADDL node.
7227   SelectionDAG &DAG = DCI.DAG;
7228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7229
7230   // Build operand list.
7231   SmallVector<SDValue, 8> Ops;
7232   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7233                                 TLI.getPointerTy()));
7234
7235   // Input is the vector.
7236   Ops.push_back(Vec);
7237
7238   // Get widened type and narrowed type.
7239   MVT widenType;
7240   unsigned numElem = VT.getVectorNumElements();
7241   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7242     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7243     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7244     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7245     default:
7246       llvm_unreachable("Invalid vector element type for padd optimization.");
7247   }
7248
7249   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7250                             widenType, &Ops[0], Ops.size());
7251   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7252 }
7253
7254 static SDValue findMUL_LOHI(SDValue V) {
7255   if (V->getOpcode() == ISD::UMUL_LOHI ||
7256       V->getOpcode() == ISD::SMUL_LOHI)
7257     return V;
7258   return SDValue();
7259 }
7260
7261 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7262                                      TargetLowering::DAGCombinerInfo &DCI,
7263                                      const ARMSubtarget *Subtarget) {
7264
7265   if (Subtarget->isThumb1Only()) return SDValue();
7266
7267   // Only perform the checks after legalize when the pattern is available.
7268   if (DCI.isBeforeLegalize()) return SDValue();
7269
7270   // Look for multiply add opportunities.
7271   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7272   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7273   // a glue link from the first add to the second add.
7274   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7275   // a S/UMLAL instruction.
7276   //          loAdd   UMUL_LOHI
7277   //            \    / :lo    \ :hi
7278   //             \  /          \          [no multiline comment]
7279   //              ADDC         |  hiAdd
7280   //                 \ :glue  /  /
7281   //                  \      /  /
7282   //                    ADDE
7283   //
7284   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7285   SDValue AddcOp0 = AddcNode->getOperand(0);
7286   SDValue AddcOp1 = AddcNode->getOperand(1);
7287
7288   // Check if the two operands are from the same mul_lohi node.
7289   if (AddcOp0.getNode() == AddcOp1.getNode())
7290     return SDValue();
7291
7292   assert(AddcNode->getNumValues() == 2 &&
7293          AddcNode->getValueType(0) == MVT::i32 &&
7294          AddcNode->getValueType(1) == MVT::Glue &&
7295          "Expect ADDC with two result values: i32, glue");
7296
7297   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7298   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7299       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7300       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7301       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7302     return SDValue();
7303
7304   // Look for the glued ADDE.
7305   SDNode* AddeNode = AddcNode->getGluedUser();
7306   if (AddeNode == NULL)
7307     return SDValue();
7308
7309   // Make sure it is really an ADDE.
7310   if (AddeNode->getOpcode() != ISD::ADDE)
7311     return SDValue();
7312
7313   assert(AddeNode->getNumOperands() == 3 &&
7314          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7315          "ADDE node has the wrong inputs");
7316
7317   // Check for the triangle shape.
7318   SDValue AddeOp0 = AddeNode->getOperand(0);
7319   SDValue AddeOp1 = AddeNode->getOperand(1);
7320
7321   // Make sure that the ADDE operands are not coming from the same node.
7322   if (AddeOp0.getNode() == AddeOp1.getNode())
7323     return SDValue();
7324
7325   // Find the MUL_LOHI node walking up ADDE's operands.
7326   bool IsLeftOperandMUL = false;
7327   SDValue MULOp = findMUL_LOHI(AddeOp0);
7328   if (MULOp == SDValue())
7329    MULOp = findMUL_LOHI(AddeOp1);
7330   else
7331     IsLeftOperandMUL = true;
7332   if (MULOp == SDValue())
7333      return SDValue();
7334
7335   // Figure out the right opcode.
7336   unsigned Opc = MULOp->getOpcode();
7337   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7338
7339   // Figure out the high and low input values to the MLAL node.
7340   SDValue* HiMul = &MULOp;
7341   SDValue* HiAdd = NULL;
7342   SDValue* LoMul = NULL;
7343   SDValue* LowAdd = NULL;
7344
7345   if (IsLeftOperandMUL)
7346     HiAdd = &AddeOp1;
7347   else
7348     HiAdd = &AddeOp0;
7349
7350
7351   if (AddcOp0->getOpcode() == Opc) {
7352     LoMul = &AddcOp0;
7353     LowAdd = &AddcOp1;
7354   }
7355   if (AddcOp1->getOpcode() == Opc) {
7356     LoMul = &AddcOp1;
7357     LowAdd = &AddcOp0;
7358   }
7359
7360   if (LoMul == NULL)
7361     return SDValue();
7362
7363   if (LoMul->getNode() != HiMul->getNode())
7364     return SDValue();
7365
7366   // Create the merged node.
7367   SelectionDAG &DAG = DCI.DAG;
7368
7369   // Build operand list.
7370   SmallVector<SDValue, 8> Ops;
7371   Ops.push_back(LoMul->getOperand(0));
7372   Ops.push_back(LoMul->getOperand(1));
7373   Ops.push_back(*LowAdd);
7374   Ops.push_back(*HiAdd);
7375
7376   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7377                                  DAG.getVTList(MVT::i32, MVT::i32),
7378                                  &Ops[0], Ops.size());
7379
7380   // Replace the ADDs' nodes uses by the MLA node's values.
7381   SDValue HiMLALResult(MLALNode.getNode(), 1);
7382   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7383
7384   SDValue LoMLALResult(MLALNode.getNode(), 0);
7385   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7386
7387   // Return original node to notify the driver to stop replacing.
7388   SDValue resNode(AddcNode, 0);
7389   return resNode;
7390 }
7391
7392 /// PerformADDCCombine - Target-specific dag combine transform from
7393 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7394 static SDValue PerformADDCCombine(SDNode *N,
7395                                  TargetLowering::DAGCombinerInfo &DCI,
7396                                  const ARMSubtarget *Subtarget) {
7397
7398   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7399
7400 }
7401
7402 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7403 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7404 /// called with the default operands, and if that fails, with commuted
7405 /// operands.
7406 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7407                                           TargetLowering::DAGCombinerInfo &DCI,
7408                                           const ARMSubtarget *Subtarget){
7409
7410   // Attempt to create vpaddl for this add.
7411   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7412   if (Result.getNode())
7413     return Result;
7414
7415   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7416   if (N0.getNode()->hasOneUse()) {
7417     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7418     if (Result.getNode()) return Result;
7419   }
7420   return SDValue();
7421 }
7422
7423 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7424 ///
7425 static SDValue PerformADDCombine(SDNode *N,
7426                                  TargetLowering::DAGCombinerInfo &DCI,
7427                                  const ARMSubtarget *Subtarget) {
7428   SDValue N0 = N->getOperand(0);
7429   SDValue N1 = N->getOperand(1);
7430
7431   // First try with the default operand order.
7432   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7433   if (Result.getNode())
7434     return Result;
7435
7436   // If that didn't work, try again with the operands commuted.
7437   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7438 }
7439
7440 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7441 ///
7442 static SDValue PerformSUBCombine(SDNode *N,
7443                                  TargetLowering::DAGCombinerInfo &DCI) {
7444   SDValue N0 = N->getOperand(0);
7445   SDValue N1 = N->getOperand(1);
7446
7447   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7448   if (N1.getNode()->hasOneUse()) {
7449     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7450     if (Result.getNode()) return Result;
7451   }
7452
7453   return SDValue();
7454 }
7455
7456 /// PerformVMULCombine
7457 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7458 /// special multiplier accumulator forwarding.
7459 ///   vmul d3, d0, d2
7460 ///   vmla d3, d1, d2
7461 /// is faster than
7462 ///   vadd d3, d0, d1
7463 ///   vmul d3, d3, d2
7464 static SDValue PerformVMULCombine(SDNode *N,
7465                                   TargetLowering::DAGCombinerInfo &DCI,
7466                                   const ARMSubtarget *Subtarget) {
7467   if (!Subtarget->hasVMLxForwarding())
7468     return SDValue();
7469
7470   SelectionDAG &DAG = DCI.DAG;
7471   SDValue N0 = N->getOperand(0);
7472   SDValue N1 = N->getOperand(1);
7473   unsigned Opcode = N0.getOpcode();
7474   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7475       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7476     Opcode = N1.getOpcode();
7477     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7478         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7479       return SDValue();
7480     std::swap(N0, N1);
7481   }
7482
7483   EVT VT = N->getValueType(0);
7484   DebugLoc DL = N->getDebugLoc();
7485   SDValue N00 = N0->getOperand(0);
7486   SDValue N01 = N0->getOperand(1);
7487   return DAG.getNode(Opcode, DL, VT,
7488                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7489                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7490 }
7491
7492 static SDValue PerformMULCombine(SDNode *N,
7493                                  TargetLowering::DAGCombinerInfo &DCI,
7494                                  const ARMSubtarget *Subtarget) {
7495   SelectionDAG &DAG = DCI.DAG;
7496
7497   if (Subtarget->isThumb1Only())
7498     return SDValue();
7499
7500   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7501     return SDValue();
7502
7503   EVT VT = N->getValueType(0);
7504   if (VT.is64BitVector() || VT.is128BitVector())
7505     return PerformVMULCombine(N, DCI, Subtarget);
7506   if (VT != MVT::i32)
7507     return SDValue();
7508
7509   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7510   if (!C)
7511     return SDValue();
7512
7513   int64_t MulAmt = C->getSExtValue();
7514   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7515
7516   ShiftAmt = ShiftAmt & (32 - 1);
7517   SDValue V = N->getOperand(0);
7518   DebugLoc DL = N->getDebugLoc();
7519
7520   SDValue Res;
7521   MulAmt >>= ShiftAmt;
7522
7523   if (MulAmt >= 0) {
7524     if (isPowerOf2_32(MulAmt - 1)) {
7525       // (mul x, 2^N + 1) => (add (shl x, N), x)
7526       Res = DAG.getNode(ISD::ADD, DL, VT,
7527                         V,
7528                         DAG.getNode(ISD::SHL, DL, VT,
7529                                     V,
7530                                     DAG.getConstant(Log2_32(MulAmt - 1),
7531                                                     MVT::i32)));
7532     } else if (isPowerOf2_32(MulAmt + 1)) {
7533       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7534       Res = DAG.getNode(ISD::SUB, DL, VT,
7535                         DAG.getNode(ISD::SHL, DL, VT,
7536                                     V,
7537                                     DAG.getConstant(Log2_32(MulAmt + 1),
7538                                                     MVT::i32)),
7539                         V);
7540     } else
7541       return SDValue();
7542   } else {
7543     uint64_t MulAmtAbs = -MulAmt;
7544     if (isPowerOf2_32(MulAmtAbs + 1)) {
7545       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7546       Res = DAG.getNode(ISD::SUB, DL, VT,
7547                         V,
7548                         DAG.getNode(ISD::SHL, DL, VT,
7549                                     V,
7550                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7551                                                     MVT::i32)));
7552     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7553       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7554       Res = DAG.getNode(ISD::ADD, DL, VT,
7555                         V,
7556                         DAG.getNode(ISD::SHL, DL, VT,
7557                                     V,
7558                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7559                                                     MVT::i32)));
7560       Res = DAG.getNode(ISD::SUB, DL, VT,
7561                         DAG.getConstant(0, MVT::i32),Res);
7562
7563     } else
7564       return SDValue();
7565   }
7566
7567   if (ShiftAmt != 0)
7568     Res = DAG.getNode(ISD::SHL, DL, VT,
7569                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7570
7571   // Do not add new nodes to DAG combiner worklist.
7572   DCI.CombineTo(N, Res, false);
7573   return SDValue();
7574 }
7575
7576 static SDValue PerformANDCombine(SDNode *N,
7577                                  TargetLowering::DAGCombinerInfo &DCI,
7578                                  const ARMSubtarget *Subtarget) {
7579
7580   // Attempt to use immediate-form VBIC
7581   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7582   DebugLoc dl = N->getDebugLoc();
7583   EVT VT = N->getValueType(0);
7584   SelectionDAG &DAG = DCI.DAG;
7585
7586   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7587     return SDValue();
7588
7589   APInt SplatBits, SplatUndef;
7590   unsigned SplatBitSize;
7591   bool HasAnyUndefs;
7592   if (BVN &&
7593       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7594     if (SplatBitSize <= 64) {
7595       EVT VbicVT;
7596       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7597                                       SplatUndef.getZExtValue(), SplatBitSize,
7598                                       DAG, VbicVT, VT.is128BitVector(),
7599                                       OtherModImm);
7600       if (Val.getNode()) {
7601         SDValue Input =
7602           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7603         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7604         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7605       }
7606     }
7607   }
7608
7609   if (!Subtarget->isThumb1Only()) {
7610     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7611     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7612     if (Result.getNode())
7613       return Result;
7614   }
7615
7616   return SDValue();
7617 }
7618
7619 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7620 static SDValue PerformORCombine(SDNode *N,
7621                                 TargetLowering::DAGCombinerInfo &DCI,
7622                                 const ARMSubtarget *Subtarget) {
7623   // Attempt to use immediate-form VORR
7624   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7625   DebugLoc dl = N->getDebugLoc();
7626   EVT VT = N->getValueType(0);
7627   SelectionDAG &DAG = DCI.DAG;
7628
7629   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7630     return SDValue();
7631
7632   APInt SplatBits, SplatUndef;
7633   unsigned SplatBitSize;
7634   bool HasAnyUndefs;
7635   if (BVN && Subtarget->hasNEON() &&
7636       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7637     if (SplatBitSize <= 64) {
7638       EVT VorrVT;
7639       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7640                                       SplatUndef.getZExtValue(), SplatBitSize,
7641                                       DAG, VorrVT, VT.is128BitVector(),
7642                                       OtherModImm);
7643       if (Val.getNode()) {
7644         SDValue Input =
7645           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7646         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7647         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7648       }
7649     }
7650   }
7651
7652   if (!Subtarget->isThumb1Only()) {
7653     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7654     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7655     if (Result.getNode())
7656       return Result;
7657   }
7658
7659   // The code below optimizes (or (and X, Y), Z).
7660   // The AND operand needs to have a single user to make these optimizations
7661   // profitable.
7662   SDValue N0 = N->getOperand(0);
7663   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7664     return SDValue();
7665   SDValue N1 = N->getOperand(1);
7666
7667   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7668   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7669       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7670     APInt SplatUndef;
7671     unsigned SplatBitSize;
7672     bool HasAnyUndefs;
7673
7674     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7675     APInt SplatBits0;
7676     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7677                                   HasAnyUndefs) && !HasAnyUndefs) {
7678       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7679       APInt SplatBits1;
7680       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7681                                     HasAnyUndefs) && !HasAnyUndefs &&
7682           SplatBits0 == ~SplatBits1) {
7683         // Canonicalize the vector type to make instruction selection simpler.
7684         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7685         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7686                                      N0->getOperand(1), N0->getOperand(0),
7687                                      N1->getOperand(0));
7688         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7689       }
7690     }
7691   }
7692
7693   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7694   // reasonable.
7695
7696   // BFI is only available on V6T2+
7697   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7698     return SDValue();
7699
7700   DebugLoc DL = N->getDebugLoc();
7701   // 1) or (and A, mask), val => ARMbfi A, val, mask
7702   //      iff (val & mask) == val
7703   //
7704   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7705   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7706   //          && mask == ~mask2
7707   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7708   //          && ~mask == mask2
7709   //  (i.e., copy a bitfield value into another bitfield of the same width)
7710
7711   if (VT != MVT::i32)
7712     return SDValue();
7713
7714   SDValue N00 = N0.getOperand(0);
7715
7716   // The value and the mask need to be constants so we can verify this is
7717   // actually a bitfield set. If the mask is 0xffff, we can do better
7718   // via a movt instruction, so don't use BFI in that case.
7719   SDValue MaskOp = N0.getOperand(1);
7720   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7721   if (!MaskC)
7722     return SDValue();
7723   unsigned Mask = MaskC->getZExtValue();
7724   if (Mask == 0xffff)
7725     return SDValue();
7726   SDValue Res;
7727   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7728   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7729   if (N1C) {
7730     unsigned Val = N1C->getZExtValue();
7731     if ((Val & ~Mask) != Val)
7732       return SDValue();
7733
7734     if (ARM::isBitFieldInvertedMask(Mask)) {
7735       Val >>= CountTrailingZeros_32(~Mask);
7736
7737       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7738                         DAG.getConstant(Val, MVT::i32),
7739                         DAG.getConstant(Mask, MVT::i32));
7740
7741       // Do not add new nodes to DAG combiner worklist.
7742       DCI.CombineTo(N, Res, false);
7743       return SDValue();
7744     }
7745   } else if (N1.getOpcode() == ISD::AND) {
7746     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7747     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7748     if (!N11C)
7749       return SDValue();
7750     unsigned Mask2 = N11C->getZExtValue();
7751
7752     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7753     // as is to match.
7754     if (ARM::isBitFieldInvertedMask(Mask) &&
7755         (Mask == ~Mask2)) {
7756       // The pack halfword instruction works better for masks that fit it,
7757       // so use that when it's available.
7758       if (Subtarget->hasT2ExtractPack() &&
7759           (Mask == 0xffff || Mask == 0xffff0000))
7760         return SDValue();
7761       // 2a
7762       unsigned amt = CountTrailingZeros_32(Mask2);
7763       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7764                         DAG.getConstant(amt, MVT::i32));
7765       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7766                         DAG.getConstant(Mask, MVT::i32));
7767       // Do not add new nodes to DAG combiner worklist.
7768       DCI.CombineTo(N, Res, false);
7769       return SDValue();
7770     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7771                (~Mask == Mask2)) {
7772       // The pack halfword instruction works better for masks that fit it,
7773       // so use that when it's available.
7774       if (Subtarget->hasT2ExtractPack() &&
7775           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7776         return SDValue();
7777       // 2b
7778       unsigned lsb = CountTrailingZeros_32(Mask);
7779       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7780                         DAG.getConstant(lsb, MVT::i32));
7781       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7782                         DAG.getConstant(Mask2, MVT::i32));
7783       // Do not add new nodes to DAG combiner worklist.
7784       DCI.CombineTo(N, Res, false);
7785       return SDValue();
7786     }
7787   }
7788
7789   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7790       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7791       ARM::isBitFieldInvertedMask(~Mask)) {
7792     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7793     // where lsb(mask) == #shamt and masked bits of B are known zero.
7794     SDValue ShAmt = N00.getOperand(1);
7795     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7796     unsigned LSB = CountTrailingZeros_32(Mask);
7797     if (ShAmtC != LSB)
7798       return SDValue();
7799
7800     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7801                       DAG.getConstant(~Mask, MVT::i32));
7802
7803     // Do not add new nodes to DAG combiner worklist.
7804     DCI.CombineTo(N, Res, false);
7805   }
7806
7807   return SDValue();
7808 }
7809
7810 static SDValue PerformXORCombine(SDNode *N,
7811                                  TargetLowering::DAGCombinerInfo &DCI,
7812                                  const ARMSubtarget *Subtarget) {
7813   EVT VT = N->getValueType(0);
7814   SelectionDAG &DAG = DCI.DAG;
7815
7816   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7817     return SDValue();
7818
7819   if (!Subtarget->isThumb1Only()) {
7820     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7821     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7822     if (Result.getNode())
7823       return Result;
7824   }
7825
7826   return SDValue();
7827 }
7828
7829 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7830 /// the bits being cleared by the AND are not demanded by the BFI.
7831 static SDValue PerformBFICombine(SDNode *N,
7832                                  TargetLowering::DAGCombinerInfo &DCI) {
7833   SDValue N1 = N->getOperand(1);
7834   if (N1.getOpcode() == ISD::AND) {
7835     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7836     if (!N11C)
7837       return SDValue();
7838     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7839     unsigned LSB = CountTrailingZeros_32(~InvMask);
7840     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7841     unsigned Mask = (1 << Width)-1;
7842     unsigned Mask2 = N11C->getZExtValue();
7843     if ((Mask & (~Mask2)) == 0)
7844       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7845                              N->getOperand(0), N1.getOperand(0),
7846                              N->getOperand(2));
7847   }
7848   return SDValue();
7849 }
7850
7851 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7852 /// ARMISD::VMOVRRD.
7853 static SDValue PerformVMOVRRDCombine(SDNode *N,
7854                                      TargetLowering::DAGCombinerInfo &DCI) {
7855   // vmovrrd(vmovdrr x, y) -> x,y
7856   SDValue InDouble = N->getOperand(0);
7857   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7858     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7859
7860   // vmovrrd(load f64) -> (load i32), (load i32)
7861   SDNode *InNode = InDouble.getNode();
7862   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7863       InNode->getValueType(0) == MVT::f64 &&
7864       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7865       !cast<LoadSDNode>(InNode)->isVolatile()) {
7866     // TODO: Should this be done for non-FrameIndex operands?
7867     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7868
7869     SelectionDAG &DAG = DCI.DAG;
7870     DebugLoc DL = LD->getDebugLoc();
7871     SDValue BasePtr = LD->getBasePtr();
7872     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7873                                  LD->getPointerInfo(), LD->isVolatile(),
7874                                  LD->isNonTemporal(), LD->isInvariant(),
7875                                  LD->getAlignment());
7876
7877     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7878                                     DAG.getConstant(4, MVT::i32));
7879     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7880                                  LD->getPointerInfo(), LD->isVolatile(),
7881                                  LD->isNonTemporal(), LD->isInvariant(),
7882                                  std::min(4U, LD->getAlignment() / 2));
7883
7884     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7885     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7886     DCI.RemoveFromWorklist(LD);
7887     DAG.DeleteNode(LD);
7888     return Result;
7889   }
7890
7891   return SDValue();
7892 }
7893
7894 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7895 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7896 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7897   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7898   SDValue Op0 = N->getOperand(0);
7899   SDValue Op1 = N->getOperand(1);
7900   if (Op0.getOpcode() == ISD::BITCAST)
7901     Op0 = Op0.getOperand(0);
7902   if (Op1.getOpcode() == ISD::BITCAST)
7903     Op1 = Op1.getOperand(0);
7904   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7905       Op0.getNode() == Op1.getNode() &&
7906       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7907     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7908                        N->getValueType(0), Op0.getOperand(0));
7909   return SDValue();
7910 }
7911
7912 /// PerformSTORECombine - Target-specific dag combine xforms for
7913 /// ISD::STORE.
7914 static SDValue PerformSTORECombine(SDNode *N,
7915                                    TargetLowering::DAGCombinerInfo &DCI) {
7916   StoreSDNode *St = cast<StoreSDNode>(N);
7917   if (St->isVolatile())
7918     return SDValue();
7919
7920   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
7921   // pack all of the elements in one place.  Next, store to memory in fewer
7922   // chunks.
7923   SDValue StVal = St->getValue();
7924   EVT VT = StVal.getValueType();
7925   if (St->isTruncatingStore() && VT.isVector()) {
7926     SelectionDAG &DAG = DCI.DAG;
7927     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7928     EVT StVT = St->getMemoryVT();
7929     unsigned NumElems = VT.getVectorNumElements();
7930     assert(StVT != VT && "Cannot truncate to the same type");
7931     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7932     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7933
7934     // From, To sizes and ElemCount must be pow of two
7935     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7936
7937     // We are going to use the original vector elt for storing.
7938     // Accumulated smaller vector elements must be a multiple of the store size.
7939     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7940
7941     unsigned SizeRatio  = FromEltSz / ToEltSz;
7942     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7943
7944     // Create a type on which we perform the shuffle.
7945     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7946                                      NumElems*SizeRatio);
7947     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7948
7949     DebugLoc DL = St->getDebugLoc();
7950     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7951     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7952     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7953
7954     // Can't shuffle using an illegal type.
7955     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7956
7957     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7958                                 DAG.getUNDEF(WideVec.getValueType()),
7959                                 ShuffleVec.data());
7960     // At this point all of the data is stored at the bottom of the
7961     // register. We now need to save it to mem.
7962
7963     // Find the largest store unit
7964     MVT StoreType = MVT::i8;
7965     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7966          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7967       MVT Tp = (MVT::SimpleValueType)tp;
7968       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7969         StoreType = Tp;
7970     }
7971     // Didn't find a legal store type.
7972     if (!TLI.isTypeLegal(StoreType))
7973       return SDValue();
7974
7975     // Bitcast the original vector into a vector of store-size units
7976     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7977             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7978     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7979     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7980     SmallVector<SDValue, 8> Chains;
7981     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7982                                         TLI.getPointerTy());
7983     SDValue BasePtr = St->getBasePtr();
7984
7985     // Perform one or more big stores into memory.
7986     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7987     for (unsigned I = 0; I < E; I++) {
7988       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7989                                    StoreType, ShuffWide,
7990                                    DAG.getIntPtrConstant(I));
7991       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7992                                 St->getPointerInfo(), St->isVolatile(),
7993                                 St->isNonTemporal(), St->getAlignment());
7994       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7995                             Increment);
7996       Chains.push_back(Ch);
7997     }
7998     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7999                        Chains.size());
8000   }
8001
8002   if (!ISD::isNormalStore(St))
8003     return SDValue();
8004
8005   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8006   // ARM stores of arguments in the same cache line.
8007   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8008       StVal.getNode()->hasOneUse()) {
8009     SelectionDAG  &DAG = DCI.DAG;
8010     DebugLoc DL = St->getDebugLoc();
8011     SDValue BasePtr = St->getBasePtr();
8012     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8013                                   StVal.getNode()->getOperand(0), BasePtr,
8014                                   St->getPointerInfo(), St->isVolatile(),
8015                                   St->isNonTemporal(), St->getAlignment());
8016
8017     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8018                                     DAG.getConstant(4, MVT::i32));
8019     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8020                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8021                         St->isNonTemporal(),
8022                         std::min(4U, St->getAlignment() / 2));
8023   }
8024
8025   if (StVal.getValueType() != MVT::i64 ||
8026       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8027     return SDValue();
8028
8029   // Bitcast an i64 store extracted from a vector to f64.
8030   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8031   SelectionDAG &DAG = DCI.DAG;
8032   DebugLoc dl = StVal.getDebugLoc();
8033   SDValue IntVec = StVal.getOperand(0);
8034   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8035                                  IntVec.getValueType().getVectorNumElements());
8036   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8037   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8038                                Vec, StVal.getOperand(1));
8039   dl = N->getDebugLoc();
8040   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8041   // Make the DAGCombiner fold the bitcasts.
8042   DCI.AddToWorklist(Vec.getNode());
8043   DCI.AddToWorklist(ExtElt.getNode());
8044   DCI.AddToWorklist(V.getNode());
8045   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8046                       St->getPointerInfo(), St->isVolatile(),
8047                       St->isNonTemporal(), St->getAlignment(),
8048                       St->getTBAAInfo());
8049 }
8050
8051 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8052 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8053 /// i64 vector to have f64 elements, since the value can then be loaded
8054 /// directly into a VFP register.
8055 static bool hasNormalLoadOperand(SDNode *N) {
8056   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8057   for (unsigned i = 0; i < NumElts; ++i) {
8058     SDNode *Elt = N->getOperand(i).getNode();
8059     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8060       return true;
8061   }
8062   return false;
8063 }
8064
8065 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8066 /// ISD::BUILD_VECTOR.
8067 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8068                                           TargetLowering::DAGCombinerInfo &DCI){
8069   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8070   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8071   // into a pair of GPRs, which is fine when the value is used as a scalar,
8072   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8073   SelectionDAG &DAG = DCI.DAG;
8074   if (N->getNumOperands() == 2) {
8075     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8076     if (RV.getNode())
8077       return RV;
8078   }
8079
8080   // Load i64 elements as f64 values so that type legalization does not split
8081   // them up into i32 values.
8082   EVT VT = N->getValueType(0);
8083   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8084     return SDValue();
8085   DebugLoc dl = N->getDebugLoc();
8086   SmallVector<SDValue, 8> Ops;
8087   unsigned NumElts = VT.getVectorNumElements();
8088   for (unsigned i = 0; i < NumElts; ++i) {
8089     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8090     Ops.push_back(V);
8091     // Make the DAGCombiner fold the bitcast.
8092     DCI.AddToWorklist(V.getNode());
8093   }
8094   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8095   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8096   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8097 }
8098
8099 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8100 /// ISD::INSERT_VECTOR_ELT.
8101 static SDValue PerformInsertEltCombine(SDNode *N,
8102                                        TargetLowering::DAGCombinerInfo &DCI) {
8103   // Bitcast an i64 load inserted into a vector to f64.
8104   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8105   EVT VT = N->getValueType(0);
8106   SDNode *Elt = N->getOperand(1).getNode();
8107   if (VT.getVectorElementType() != MVT::i64 ||
8108       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8109     return SDValue();
8110
8111   SelectionDAG &DAG = DCI.DAG;
8112   DebugLoc dl = N->getDebugLoc();
8113   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8114                                  VT.getVectorNumElements());
8115   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8116   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8117   // Make the DAGCombiner fold the bitcasts.
8118   DCI.AddToWorklist(Vec.getNode());
8119   DCI.AddToWorklist(V.getNode());
8120   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8121                                Vec, V, N->getOperand(2));
8122   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8123 }
8124
8125 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8126 /// ISD::VECTOR_SHUFFLE.
8127 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8128   // The LLVM shufflevector instruction does not require the shuffle mask
8129   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8130   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8131   // operands do not match the mask length, they are extended by concatenating
8132   // them with undef vectors.  That is probably the right thing for other
8133   // targets, but for NEON it is better to concatenate two double-register
8134   // size vector operands into a single quad-register size vector.  Do that
8135   // transformation here:
8136   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8137   //   shuffle(concat(v1, v2), undef)
8138   SDValue Op0 = N->getOperand(0);
8139   SDValue Op1 = N->getOperand(1);
8140   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8141       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8142       Op0.getNumOperands() != 2 ||
8143       Op1.getNumOperands() != 2)
8144     return SDValue();
8145   SDValue Concat0Op1 = Op0.getOperand(1);
8146   SDValue Concat1Op1 = Op1.getOperand(1);
8147   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8148       Concat1Op1.getOpcode() != ISD::UNDEF)
8149     return SDValue();
8150   // Skip the transformation if any of the types are illegal.
8151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8152   EVT VT = N->getValueType(0);
8153   if (!TLI.isTypeLegal(VT) ||
8154       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8155       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8156     return SDValue();
8157
8158   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8159                                   Op0.getOperand(0), Op1.getOperand(0));
8160   // Translate the shuffle mask.
8161   SmallVector<int, 16> NewMask;
8162   unsigned NumElts = VT.getVectorNumElements();
8163   unsigned HalfElts = NumElts/2;
8164   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8165   for (unsigned n = 0; n < NumElts; ++n) {
8166     int MaskElt = SVN->getMaskElt(n);
8167     int NewElt = -1;
8168     if (MaskElt < (int)HalfElts)
8169       NewElt = MaskElt;
8170     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8171       NewElt = HalfElts + MaskElt - NumElts;
8172     NewMask.push_back(NewElt);
8173   }
8174   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8175                               DAG.getUNDEF(VT), NewMask.data());
8176 }
8177
8178 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8179 /// NEON load/store intrinsics to merge base address updates.
8180 static SDValue CombineBaseUpdate(SDNode *N,
8181                                  TargetLowering::DAGCombinerInfo &DCI) {
8182   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8183     return SDValue();
8184
8185   SelectionDAG &DAG = DCI.DAG;
8186   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8187                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8188   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8189   SDValue Addr = N->getOperand(AddrOpIdx);
8190
8191   // Search for a use of the address operand that is an increment.
8192   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8193          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8194     SDNode *User = *UI;
8195     if (User->getOpcode() != ISD::ADD ||
8196         UI.getUse().getResNo() != Addr.getResNo())
8197       continue;
8198
8199     // Check that the add is independent of the load/store.  Otherwise, folding
8200     // it would create a cycle.
8201     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8202       continue;
8203
8204     // Find the new opcode for the updating load/store.
8205     bool isLoad = true;
8206     bool isLaneOp = false;
8207     unsigned NewOpc = 0;
8208     unsigned NumVecs = 0;
8209     if (isIntrinsic) {
8210       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8211       switch (IntNo) {
8212       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8213       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8214         NumVecs = 1; break;
8215       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8216         NumVecs = 2; break;
8217       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8218         NumVecs = 3; break;
8219       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8220         NumVecs = 4; break;
8221       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8222         NumVecs = 2; isLaneOp = true; break;
8223       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8224         NumVecs = 3; isLaneOp = true; break;
8225       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8226         NumVecs = 4; isLaneOp = true; break;
8227       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8228         NumVecs = 1; isLoad = false; break;
8229       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8230         NumVecs = 2; isLoad = false; break;
8231       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8232         NumVecs = 3; isLoad = false; break;
8233       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8234         NumVecs = 4; isLoad = false; break;
8235       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8236         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8237       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8238         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8239       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8240         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8241       }
8242     } else {
8243       isLaneOp = true;
8244       switch (N->getOpcode()) {
8245       default: llvm_unreachable("unexpected opcode for Neon base update");
8246       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8247       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8248       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8249       }
8250     }
8251
8252     // Find the size of memory referenced by the load/store.
8253     EVT VecTy;
8254     if (isLoad)
8255       VecTy = N->getValueType(0);
8256     else
8257       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8258     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8259     if (isLaneOp)
8260       NumBytes /= VecTy.getVectorNumElements();
8261
8262     // If the increment is a constant, it must match the memory ref size.
8263     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8264     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8265       uint64_t IncVal = CInc->getZExtValue();
8266       if (IncVal != NumBytes)
8267         continue;
8268     } else if (NumBytes >= 3 * 16) {
8269       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8270       // separate instructions that make it harder to use a non-constant update.
8271       continue;
8272     }
8273
8274     // Create the new updating load/store node.
8275     EVT Tys[6];
8276     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8277     unsigned n;
8278     for (n = 0; n < NumResultVecs; ++n)
8279       Tys[n] = VecTy;
8280     Tys[n++] = MVT::i32;
8281     Tys[n] = MVT::Other;
8282     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8283     SmallVector<SDValue, 8> Ops;
8284     Ops.push_back(N->getOperand(0)); // incoming chain
8285     Ops.push_back(N->getOperand(AddrOpIdx));
8286     Ops.push_back(Inc);
8287     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8288       Ops.push_back(N->getOperand(i));
8289     }
8290     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8291     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8292                                            Ops.data(), Ops.size(),
8293                                            MemInt->getMemoryVT(),
8294                                            MemInt->getMemOperand());
8295
8296     // Update the uses.
8297     std::vector<SDValue> NewResults;
8298     for (unsigned i = 0; i < NumResultVecs; ++i) {
8299       NewResults.push_back(SDValue(UpdN.getNode(), i));
8300     }
8301     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8302     DCI.CombineTo(N, NewResults);
8303     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8304
8305     break;
8306   }
8307   return SDValue();
8308 }
8309
8310 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8311 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8312 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8313 /// return true.
8314 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8315   SelectionDAG &DAG = DCI.DAG;
8316   EVT VT = N->getValueType(0);
8317   // vldN-dup instructions only support 64-bit vectors for N > 1.
8318   if (!VT.is64BitVector())
8319     return false;
8320
8321   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8322   SDNode *VLD = N->getOperand(0).getNode();
8323   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8324     return false;
8325   unsigned NumVecs = 0;
8326   unsigned NewOpc = 0;
8327   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8328   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8329     NumVecs = 2;
8330     NewOpc = ARMISD::VLD2DUP;
8331   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8332     NumVecs = 3;
8333     NewOpc = ARMISD::VLD3DUP;
8334   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8335     NumVecs = 4;
8336     NewOpc = ARMISD::VLD4DUP;
8337   } else {
8338     return false;
8339   }
8340
8341   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8342   // numbers match the load.
8343   unsigned VLDLaneNo =
8344     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8345   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8346        UI != UE; ++UI) {
8347     // Ignore uses of the chain result.
8348     if (UI.getUse().getResNo() == NumVecs)
8349       continue;
8350     SDNode *User = *UI;
8351     if (User->getOpcode() != ARMISD::VDUPLANE ||
8352         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8353       return false;
8354   }
8355
8356   // Create the vldN-dup node.
8357   EVT Tys[5];
8358   unsigned n;
8359   for (n = 0; n < NumVecs; ++n)
8360     Tys[n] = VT;
8361   Tys[n] = MVT::Other;
8362   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8363   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8364   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8365   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8366                                            Ops, 2, VLDMemInt->getMemoryVT(),
8367                                            VLDMemInt->getMemOperand());
8368
8369   // Update the uses.
8370   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8371        UI != UE; ++UI) {
8372     unsigned ResNo = UI.getUse().getResNo();
8373     // Ignore uses of the chain result.
8374     if (ResNo == NumVecs)
8375       continue;
8376     SDNode *User = *UI;
8377     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8378   }
8379
8380   // Now the vldN-lane intrinsic is dead except for its chain result.
8381   // Update uses of the chain.
8382   std::vector<SDValue> VLDDupResults;
8383   for (unsigned n = 0; n < NumVecs; ++n)
8384     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8385   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8386   DCI.CombineTo(VLD, VLDDupResults);
8387
8388   return true;
8389 }
8390
8391 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8392 /// ARMISD::VDUPLANE.
8393 static SDValue PerformVDUPLANECombine(SDNode *N,
8394                                       TargetLowering::DAGCombinerInfo &DCI) {
8395   SDValue Op = N->getOperand(0);
8396
8397   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8398   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8399   if (CombineVLDDUP(N, DCI))
8400     return SDValue(N, 0);
8401
8402   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8403   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8404   while (Op.getOpcode() == ISD::BITCAST)
8405     Op = Op.getOperand(0);
8406   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8407     return SDValue();
8408
8409   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8410   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8411   // The canonical VMOV for a zero vector uses a 32-bit element size.
8412   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8413   unsigned EltBits;
8414   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8415     EltSize = 8;
8416   EVT VT = N->getValueType(0);
8417   if (EltSize > VT.getVectorElementType().getSizeInBits())
8418     return SDValue();
8419
8420   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8421 }
8422
8423 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8424 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8425 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8426 {
8427   integerPart cN;
8428   integerPart c0 = 0;
8429   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8430        I != E; I++) {
8431     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8432     if (!C)
8433       return false;
8434
8435     bool isExact;
8436     APFloat APF = C->getValueAPF();
8437     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8438         != APFloat::opOK || !isExact)
8439       return false;
8440
8441     c0 = (I == 0) ? cN : c0;
8442     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8443       return false;
8444   }
8445   C = c0;
8446   return true;
8447 }
8448
8449 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8450 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8451 /// when the VMUL has a constant operand that is a power of 2.
8452 ///
8453 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8454 ///  vmul.f32        d16, d17, d16
8455 ///  vcvt.s32.f32    d16, d16
8456 /// becomes:
8457 ///  vcvt.s32.f32    d16, d16, #3
8458 static SDValue PerformVCVTCombine(SDNode *N,
8459                                   TargetLowering::DAGCombinerInfo &DCI,
8460                                   const ARMSubtarget *Subtarget) {
8461   SelectionDAG &DAG = DCI.DAG;
8462   SDValue Op = N->getOperand(0);
8463
8464   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8465       Op.getOpcode() != ISD::FMUL)
8466     return SDValue();
8467
8468   uint64_t C;
8469   SDValue N0 = Op->getOperand(0);
8470   SDValue ConstVec = Op->getOperand(1);
8471   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8472
8473   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8474       !isConstVecPow2(ConstVec, isSigned, C))
8475     return SDValue();
8476
8477   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8478     Intrinsic::arm_neon_vcvtfp2fxu;
8479   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8480                      N->getValueType(0),
8481                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8482                      DAG.getConstant(Log2_64(C), MVT::i32));
8483 }
8484
8485 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8486 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8487 /// when the VDIV has a constant operand that is a power of 2.
8488 ///
8489 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8490 ///  vcvt.f32.s32    d16, d16
8491 ///  vdiv.f32        d16, d17, d16
8492 /// becomes:
8493 ///  vcvt.f32.s32    d16, d16, #3
8494 static SDValue PerformVDIVCombine(SDNode *N,
8495                                   TargetLowering::DAGCombinerInfo &DCI,
8496                                   const ARMSubtarget *Subtarget) {
8497   SelectionDAG &DAG = DCI.DAG;
8498   SDValue Op = N->getOperand(0);
8499   unsigned OpOpcode = Op.getNode()->getOpcode();
8500
8501   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8502       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8503     return SDValue();
8504
8505   uint64_t C;
8506   SDValue ConstVec = N->getOperand(1);
8507   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8508
8509   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8510       !isConstVecPow2(ConstVec, isSigned, C))
8511     return SDValue();
8512
8513   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8514     Intrinsic::arm_neon_vcvtfxu2fp;
8515   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8516                      Op.getValueType(),
8517                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8518                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8519 }
8520
8521 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8522 /// operand of a vector shift operation, where all the elements of the
8523 /// build_vector must have the same constant integer value.
8524 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8525   // Ignore bit_converts.
8526   while (Op.getOpcode() == ISD::BITCAST)
8527     Op = Op.getOperand(0);
8528   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8529   APInt SplatBits, SplatUndef;
8530   unsigned SplatBitSize;
8531   bool HasAnyUndefs;
8532   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8533                                       HasAnyUndefs, ElementBits) ||
8534       SplatBitSize > ElementBits)
8535     return false;
8536   Cnt = SplatBits.getSExtValue();
8537   return true;
8538 }
8539
8540 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8541 /// operand of a vector shift left operation.  That value must be in the range:
8542 ///   0 <= Value < ElementBits for a left shift; or
8543 ///   0 <= Value <= ElementBits for a long left shift.
8544 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8545   assert(VT.isVector() && "vector shift count is not a vector type");
8546   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8547   if (! getVShiftImm(Op, ElementBits, Cnt))
8548     return false;
8549   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8550 }
8551
8552 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8553 /// operand of a vector shift right operation.  For a shift opcode, the value
8554 /// is positive, but for an intrinsic the value count must be negative. The
8555 /// absolute value must be in the range:
8556 ///   1 <= |Value| <= ElementBits for a right shift; or
8557 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8558 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8559                          int64_t &Cnt) {
8560   assert(VT.isVector() && "vector shift count is not a vector type");
8561   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8562   if (! getVShiftImm(Op, ElementBits, Cnt))
8563     return false;
8564   if (isIntrinsic)
8565     Cnt = -Cnt;
8566   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8567 }
8568
8569 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8570 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8571   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8572   switch (IntNo) {
8573   default:
8574     // Don't do anything for most intrinsics.
8575     break;
8576
8577   // Vector shifts: check for immediate versions and lower them.
8578   // Note: This is done during DAG combining instead of DAG legalizing because
8579   // the build_vectors for 64-bit vector element shift counts are generally
8580   // not legal, and it is hard to see their values after they get legalized to
8581   // loads from a constant pool.
8582   case Intrinsic::arm_neon_vshifts:
8583   case Intrinsic::arm_neon_vshiftu:
8584   case Intrinsic::arm_neon_vshiftls:
8585   case Intrinsic::arm_neon_vshiftlu:
8586   case Intrinsic::arm_neon_vshiftn:
8587   case Intrinsic::arm_neon_vrshifts:
8588   case Intrinsic::arm_neon_vrshiftu:
8589   case Intrinsic::arm_neon_vrshiftn:
8590   case Intrinsic::arm_neon_vqshifts:
8591   case Intrinsic::arm_neon_vqshiftu:
8592   case Intrinsic::arm_neon_vqshiftsu:
8593   case Intrinsic::arm_neon_vqshiftns:
8594   case Intrinsic::arm_neon_vqshiftnu:
8595   case Intrinsic::arm_neon_vqshiftnsu:
8596   case Intrinsic::arm_neon_vqrshiftns:
8597   case Intrinsic::arm_neon_vqrshiftnu:
8598   case Intrinsic::arm_neon_vqrshiftnsu: {
8599     EVT VT = N->getOperand(1).getValueType();
8600     int64_t Cnt;
8601     unsigned VShiftOpc = 0;
8602
8603     switch (IntNo) {
8604     case Intrinsic::arm_neon_vshifts:
8605     case Intrinsic::arm_neon_vshiftu:
8606       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8607         VShiftOpc = ARMISD::VSHL;
8608         break;
8609       }
8610       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8611         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8612                      ARMISD::VSHRs : ARMISD::VSHRu);
8613         break;
8614       }
8615       return SDValue();
8616
8617     case Intrinsic::arm_neon_vshiftls:
8618     case Intrinsic::arm_neon_vshiftlu:
8619       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8620         break;
8621       llvm_unreachable("invalid shift count for vshll intrinsic");
8622
8623     case Intrinsic::arm_neon_vrshifts:
8624     case Intrinsic::arm_neon_vrshiftu:
8625       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8626         break;
8627       return SDValue();
8628
8629     case Intrinsic::arm_neon_vqshifts:
8630     case Intrinsic::arm_neon_vqshiftu:
8631       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8632         break;
8633       return SDValue();
8634
8635     case Intrinsic::arm_neon_vqshiftsu:
8636       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8637         break;
8638       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8639
8640     case Intrinsic::arm_neon_vshiftn:
8641     case Intrinsic::arm_neon_vrshiftn:
8642     case Intrinsic::arm_neon_vqshiftns:
8643     case Intrinsic::arm_neon_vqshiftnu:
8644     case Intrinsic::arm_neon_vqshiftnsu:
8645     case Intrinsic::arm_neon_vqrshiftns:
8646     case Intrinsic::arm_neon_vqrshiftnu:
8647     case Intrinsic::arm_neon_vqrshiftnsu:
8648       // Narrowing shifts require an immediate right shift.
8649       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8650         break;
8651       llvm_unreachable("invalid shift count for narrowing vector shift "
8652                        "intrinsic");
8653
8654     default:
8655       llvm_unreachable("unhandled vector shift");
8656     }
8657
8658     switch (IntNo) {
8659     case Intrinsic::arm_neon_vshifts:
8660     case Intrinsic::arm_neon_vshiftu:
8661       // Opcode already set above.
8662       break;
8663     case Intrinsic::arm_neon_vshiftls:
8664     case Intrinsic::arm_neon_vshiftlu:
8665       if (Cnt == VT.getVectorElementType().getSizeInBits())
8666         VShiftOpc = ARMISD::VSHLLi;
8667       else
8668         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8669                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8670       break;
8671     case Intrinsic::arm_neon_vshiftn:
8672       VShiftOpc = ARMISD::VSHRN; break;
8673     case Intrinsic::arm_neon_vrshifts:
8674       VShiftOpc = ARMISD::VRSHRs; break;
8675     case Intrinsic::arm_neon_vrshiftu:
8676       VShiftOpc = ARMISD::VRSHRu; break;
8677     case Intrinsic::arm_neon_vrshiftn:
8678       VShiftOpc = ARMISD::VRSHRN; break;
8679     case Intrinsic::arm_neon_vqshifts:
8680       VShiftOpc = ARMISD::VQSHLs; break;
8681     case Intrinsic::arm_neon_vqshiftu:
8682       VShiftOpc = ARMISD::VQSHLu; break;
8683     case Intrinsic::arm_neon_vqshiftsu:
8684       VShiftOpc = ARMISD::VQSHLsu; break;
8685     case Intrinsic::arm_neon_vqshiftns:
8686       VShiftOpc = ARMISD::VQSHRNs; break;
8687     case Intrinsic::arm_neon_vqshiftnu:
8688       VShiftOpc = ARMISD::VQSHRNu; break;
8689     case Intrinsic::arm_neon_vqshiftnsu:
8690       VShiftOpc = ARMISD::VQSHRNsu; break;
8691     case Intrinsic::arm_neon_vqrshiftns:
8692       VShiftOpc = ARMISD::VQRSHRNs; break;
8693     case Intrinsic::arm_neon_vqrshiftnu:
8694       VShiftOpc = ARMISD::VQRSHRNu; break;
8695     case Intrinsic::arm_neon_vqrshiftnsu:
8696       VShiftOpc = ARMISD::VQRSHRNsu; break;
8697     }
8698
8699     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8700                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8701   }
8702
8703   case Intrinsic::arm_neon_vshiftins: {
8704     EVT VT = N->getOperand(1).getValueType();
8705     int64_t Cnt;
8706     unsigned VShiftOpc = 0;
8707
8708     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8709       VShiftOpc = ARMISD::VSLI;
8710     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8711       VShiftOpc = ARMISD::VSRI;
8712     else {
8713       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8714     }
8715
8716     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8717                        N->getOperand(1), N->getOperand(2),
8718                        DAG.getConstant(Cnt, MVT::i32));
8719   }
8720
8721   case Intrinsic::arm_neon_vqrshifts:
8722   case Intrinsic::arm_neon_vqrshiftu:
8723     // No immediate versions of these to check for.
8724     break;
8725   }
8726
8727   return SDValue();
8728 }
8729
8730 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8731 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8732 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8733 /// vector element shift counts are generally not legal, and it is hard to see
8734 /// their values after they get legalized to loads from a constant pool.
8735 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8736                                    const ARMSubtarget *ST) {
8737   EVT VT = N->getValueType(0);
8738   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8739     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8740     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8741     SDValue N1 = N->getOperand(1);
8742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8743       SDValue N0 = N->getOperand(0);
8744       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8745           DAG.MaskedValueIsZero(N0.getOperand(0),
8746                                 APInt::getHighBitsSet(32, 16)))
8747         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8748     }
8749   }
8750
8751   // Nothing to be done for scalar shifts.
8752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8753   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8754     return SDValue();
8755
8756   assert(ST->hasNEON() && "unexpected vector shift");
8757   int64_t Cnt;
8758
8759   switch (N->getOpcode()) {
8760   default: llvm_unreachable("unexpected shift opcode");
8761
8762   case ISD::SHL:
8763     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8764       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8765                          DAG.getConstant(Cnt, MVT::i32));
8766     break;
8767
8768   case ISD::SRA:
8769   case ISD::SRL:
8770     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8771       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8772                             ARMISD::VSHRs : ARMISD::VSHRu);
8773       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8774                          DAG.getConstant(Cnt, MVT::i32));
8775     }
8776   }
8777   return SDValue();
8778 }
8779
8780 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8781 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8782 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8783                                     const ARMSubtarget *ST) {
8784   SDValue N0 = N->getOperand(0);
8785
8786   // Check for sign- and zero-extensions of vector extract operations of 8-
8787   // and 16-bit vector elements.  NEON supports these directly.  They are
8788   // handled during DAG combining because type legalization will promote them
8789   // to 32-bit types and it is messy to recognize the operations after that.
8790   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8791     SDValue Vec = N0.getOperand(0);
8792     SDValue Lane = N0.getOperand(1);
8793     EVT VT = N->getValueType(0);
8794     EVT EltVT = N0.getValueType();
8795     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8796
8797     if (VT == MVT::i32 &&
8798         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8799         TLI.isTypeLegal(Vec.getValueType()) &&
8800         isa<ConstantSDNode>(Lane)) {
8801
8802       unsigned Opc = 0;
8803       switch (N->getOpcode()) {
8804       default: llvm_unreachable("unexpected opcode");
8805       case ISD::SIGN_EXTEND:
8806         Opc = ARMISD::VGETLANEs;
8807         break;
8808       case ISD::ZERO_EXTEND:
8809       case ISD::ANY_EXTEND:
8810         Opc = ARMISD::VGETLANEu;
8811         break;
8812       }
8813       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8814     }
8815   }
8816
8817   return SDValue();
8818 }
8819
8820 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8821 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8822 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8823                                        const ARMSubtarget *ST) {
8824   // If the target supports NEON, try to use vmax/vmin instructions for f32
8825   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8826   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8827   // a NaN; only do the transformation when it matches that behavior.
8828
8829   // For now only do this when using NEON for FP operations; if using VFP, it
8830   // is not obvious that the benefit outweighs the cost of switching to the
8831   // NEON pipeline.
8832   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8833       N->getValueType(0) != MVT::f32)
8834     return SDValue();
8835
8836   SDValue CondLHS = N->getOperand(0);
8837   SDValue CondRHS = N->getOperand(1);
8838   SDValue LHS = N->getOperand(2);
8839   SDValue RHS = N->getOperand(3);
8840   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8841
8842   unsigned Opcode = 0;
8843   bool IsReversed;
8844   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8845     IsReversed = false; // x CC y ? x : y
8846   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8847     IsReversed = true ; // x CC y ? y : x
8848   } else {
8849     return SDValue();
8850   }
8851
8852   bool IsUnordered;
8853   switch (CC) {
8854   default: break;
8855   case ISD::SETOLT:
8856   case ISD::SETOLE:
8857   case ISD::SETLT:
8858   case ISD::SETLE:
8859   case ISD::SETULT:
8860   case ISD::SETULE:
8861     // If LHS is NaN, an ordered comparison will be false and the result will
8862     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8863     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8864     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8865     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8866       break;
8867     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8868     // will return -0, so vmin can only be used for unsafe math or if one of
8869     // the operands is known to be nonzero.
8870     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8871         !DAG.getTarget().Options.UnsafeFPMath &&
8872         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8873       break;
8874     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8875     break;
8876
8877   case ISD::SETOGT:
8878   case ISD::SETOGE:
8879   case ISD::SETGT:
8880   case ISD::SETGE:
8881   case ISD::SETUGT:
8882   case ISD::SETUGE:
8883     // If LHS is NaN, an ordered comparison will be false and the result will
8884     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8885     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8886     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8887     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8888       break;
8889     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8890     // will return +0, so vmax can only be used for unsafe math or if one of
8891     // the operands is known to be nonzero.
8892     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8893         !DAG.getTarget().Options.UnsafeFPMath &&
8894         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8895       break;
8896     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8897     break;
8898   }
8899
8900   if (!Opcode)
8901     return SDValue();
8902   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8903 }
8904
8905 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8906 SDValue
8907 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8908   SDValue Cmp = N->getOperand(4);
8909   if (Cmp.getOpcode() != ARMISD::CMPZ)
8910     // Only looking at EQ and NE cases.
8911     return SDValue();
8912
8913   EVT VT = N->getValueType(0);
8914   DebugLoc dl = N->getDebugLoc();
8915   SDValue LHS = Cmp.getOperand(0);
8916   SDValue RHS = Cmp.getOperand(1);
8917   SDValue FalseVal = N->getOperand(0);
8918   SDValue TrueVal = N->getOperand(1);
8919   SDValue ARMcc = N->getOperand(2);
8920   ARMCC::CondCodes CC =
8921     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8922
8923   // Simplify
8924   //   mov     r1, r0
8925   //   cmp     r1, x
8926   //   mov     r0, y
8927   //   moveq   r0, x
8928   // to
8929   //   cmp     r0, x
8930   //   movne   r0, y
8931   //
8932   //   mov     r1, r0
8933   //   cmp     r1, x
8934   //   mov     r0, x
8935   //   movne   r0, y
8936   // to
8937   //   cmp     r0, x
8938   //   movne   r0, y
8939   /// FIXME: Turn this into a target neutral optimization?
8940   SDValue Res;
8941   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8942     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8943                       N->getOperand(3), Cmp);
8944   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8945     SDValue ARMcc;
8946     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8947     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8948                       N->getOperand(3), NewCmp);
8949   }
8950
8951   if (Res.getNode()) {
8952     APInt KnownZero, KnownOne;
8953     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8954     // Capture demanded bits information that would be otherwise lost.
8955     if (KnownZero == 0xfffffffe)
8956       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8957                         DAG.getValueType(MVT::i1));
8958     else if (KnownZero == 0xffffff00)
8959       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8960                         DAG.getValueType(MVT::i8));
8961     else if (KnownZero == 0xffff0000)
8962       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8963                         DAG.getValueType(MVT::i16));
8964   }
8965
8966   return Res;
8967 }
8968
8969 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8970                                              DAGCombinerInfo &DCI) const {
8971   switch (N->getOpcode()) {
8972   default: break;
8973   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
8974   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8975   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8976   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8977   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8978   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8979   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8980   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8981   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8982   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8983   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8984   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8985   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8986   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8987   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8988   case ISD::FP_TO_SINT:
8989   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8990   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8991   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8992   case ISD::SHL:
8993   case ISD::SRA:
8994   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8995   case ISD::SIGN_EXTEND:
8996   case ISD::ZERO_EXTEND:
8997   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8998   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8999   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9000   case ARMISD::VLD2DUP:
9001   case ARMISD::VLD3DUP:
9002   case ARMISD::VLD4DUP:
9003     return CombineBaseUpdate(N, DCI);
9004   case ISD::INTRINSIC_VOID:
9005   case ISD::INTRINSIC_W_CHAIN:
9006     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9007     case Intrinsic::arm_neon_vld1:
9008     case Intrinsic::arm_neon_vld2:
9009     case Intrinsic::arm_neon_vld3:
9010     case Intrinsic::arm_neon_vld4:
9011     case Intrinsic::arm_neon_vld2lane:
9012     case Intrinsic::arm_neon_vld3lane:
9013     case Intrinsic::arm_neon_vld4lane:
9014     case Intrinsic::arm_neon_vst1:
9015     case Intrinsic::arm_neon_vst2:
9016     case Intrinsic::arm_neon_vst3:
9017     case Intrinsic::arm_neon_vst4:
9018     case Intrinsic::arm_neon_vst2lane:
9019     case Intrinsic::arm_neon_vst3lane:
9020     case Intrinsic::arm_neon_vst4lane:
9021       return CombineBaseUpdate(N, DCI);
9022     default: break;
9023     }
9024     break;
9025   }
9026   return SDValue();
9027 }
9028
9029 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9030                                                           EVT VT) const {
9031   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9032 }
9033
9034 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9035   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9036   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9037
9038   switch (VT.getSimpleVT().SimpleTy) {
9039   default:
9040     return false;
9041   case MVT::i8:
9042   case MVT::i16:
9043   case MVT::i32:
9044     // Unaligned access can use (for example) LRDB, LRDH, LDR
9045     return AllowsUnaligned;
9046   case MVT::f64:
9047   case MVT::v2f64:
9048     // For any little-endian targets with neon, we can support unaligned ld/st
9049     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9050     // A big-endian target may also explictly support unaligned accesses
9051     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9052   }
9053 }
9054
9055 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9056                        unsigned AlignCheck) {
9057   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9058           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9059 }
9060
9061 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9062                                            unsigned DstAlign, unsigned SrcAlign,
9063                                            bool IsZeroVal,
9064                                            bool MemcpyStrSrc,
9065                                            MachineFunction &MF) const {
9066   const Function *F = MF.getFunction();
9067
9068   // See if we can use NEON instructions for this...
9069   if (IsZeroVal &&
9070       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat) &&
9071       Subtarget->hasNEON()) {
9072     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9073       return MVT::v4i32;
9074     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9075       return MVT::v2i32;
9076     }
9077   }
9078
9079   // Lowering to i32/i16 if the size permits.
9080   if (Size >= 4) {
9081     return MVT::i32;
9082   } else if (Size >= 2) {
9083     return MVT::i16;
9084   }
9085
9086   // Let the target-independent logic figure it out.
9087   return MVT::Other;
9088 }
9089
9090 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9091   if (V < 0)
9092     return false;
9093
9094   unsigned Scale = 1;
9095   switch (VT.getSimpleVT().SimpleTy) {
9096   default: return false;
9097   case MVT::i1:
9098   case MVT::i8:
9099     // Scale == 1;
9100     break;
9101   case MVT::i16:
9102     // Scale == 2;
9103     Scale = 2;
9104     break;
9105   case MVT::i32:
9106     // Scale == 4;
9107     Scale = 4;
9108     break;
9109   }
9110
9111   if ((V & (Scale - 1)) != 0)
9112     return false;
9113   V /= Scale;
9114   return V == (V & ((1LL << 5) - 1));
9115 }
9116
9117 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9118                                       const ARMSubtarget *Subtarget) {
9119   bool isNeg = false;
9120   if (V < 0) {
9121     isNeg = true;
9122     V = - V;
9123   }
9124
9125   switch (VT.getSimpleVT().SimpleTy) {
9126   default: return false;
9127   case MVT::i1:
9128   case MVT::i8:
9129   case MVT::i16:
9130   case MVT::i32:
9131     // + imm12 or - imm8
9132     if (isNeg)
9133       return V == (V & ((1LL << 8) - 1));
9134     return V == (V & ((1LL << 12) - 1));
9135   case MVT::f32:
9136   case MVT::f64:
9137     // Same as ARM mode. FIXME: NEON?
9138     if (!Subtarget->hasVFP2())
9139       return false;
9140     if ((V & 3) != 0)
9141       return false;
9142     V >>= 2;
9143     return V == (V & ((1LL << 8) - 1));
9144   }
9145 }
9146
9147 /// isLegalAddressImmediate - Return true if the integer value can be used
9148 /// as the offset of the target addressing mode for load / store of the
9149 /// given type.
9150 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9151                                     const ARMSubtarget *Subtarget) {
9152   if (V == 0)
9153     return true;
9154
9155   if (!VT.isSimple())
9156     return false;
9157
9158   if (Subtarget->isThumb1Only())
9159     return isLegalT1AddressImmediate(V, VT);
9160   else if (Subtarget->isThumb2())
9161     return isLegalT2AddressImmediate(V, VT, Subtarget);
9162
9163   // ARM mode.
9164   if (V < 0)
9165     V = - V;
9166   switch (VT.getSimpleVT().SimpleTy) {
9167   default: return false;
9168   case MVT::i1:
9169   case MVT::i8:
9170   case MVT::i32:
9171     // +- imm12
9172     return V == (V & ((1LL << 12) - 1));
9173   case MVT::i16:
9174     // +- imm8
9175     return V == (V & ((1LL << 8) - 1));
9176   case MVT::f32:
9177   case MVT::f64:
9178     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9179       return false;
9180     if ((V & 3) != 0)
9181       return false;
9182     V >>= 2;
9183     return V == (V & ((1LL << 8) - 1));
9184   }
9185 }
9186
9187 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9188                                                       EVT VT) const {
9189   int Scale = AM.Scale;
9190   if (Scale < 0)
9191     return false;
9192
9193   switch (VT.getSimpleVT().SimpleTy) {
9194   default: return false;
9195   case MVT::i1:
9196   case MVT::i8:
9197   case MVT::i16:
9198   case MVT::i32:
9199     if (Scale == 1)
9200       return true;
9201     // r + r << imm
9202     Scale = Scale & ~1;
9203     return Scale == 2 || Scale == 4 || Scale == 8;
9204   case MVT::i64:
9205     // r + r
9206     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9207       return true;
9208     return false;
9209   case MVT::isVoid:
9210     // Note, we allow "void" uses (basically, uses that aren't loads or
9211     // stores), because arm allows folding a scale into many arithmetic
9212     // operations.  This should be made more precise and revisited later.
9213
9214     // Allow r << imm, but the imm has to be a multiple of two.
9215     if (Scale & 1) return false;
9216     return isPowerOf2_32(Scale);
9217   }
9218 }
9219
9220 /// isLegalAddressingMode - Return true if the addressing mode represented
9221 /// by AM is legal for this target, for a load/store of the specified type.
9222 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9223                                               Type *Ty) const {
9224   EVT VT = getValueType(Ty, true);
9225   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9226     return false;
9227
9228   // Can never fold addr of global into load/store.
9229   if (AM.BaseGV)
9230     return false;
9231
9232   switch (AM.Scale) {
9233   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9234     break;
9235   case 1:
9236     if (Subtarget->isThumb1Only())
9237       return false;
9238     // FALL THROUGH.
9239   default:
9240     // ARM doesn't support any R+R*scale+imm addr modes.
9241     if (AM.BaseOffs)
9242       return false;
9243
9244     if (!VT.isSimple())
9245       return false;
9246
9247     if (Subtarget->isThumb2())
9248       return isLegalT2ScaledAddressingMode(AM, VT);
9249
9250     int Scale = AM.Scale;
9251     switch (VT.getSimpleVT().SimpleTy) {
9252     default: return false;
9253     case MVT::i1:
9254     case MVT::i8:
9255     case MVT::i32:
9256       if (Scale < 0) Scale = -Scale;
9257       if (Scale == 1)
9258         return true;
9259       // r + r << imm
9260       return isPowerOf2_32(Scale & ~1);
9261     case MVT::i16:
9262     case MVT::i64:
9263       // r + r
9264       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9265         return true;
9266       return false;
9267
9268     case MVT::isVoid:
9269       // Note, we allow "void" uses (basically, uses that aren't loads or
9270       // stores), because arm allows folding a scale into many arithmetic
9271       // operations.  This should be made more precise and revisited later.
9272
9273       // Allow r << imm, but the imm has to be a multiple of two.
9274       if (Scale & 1) return false;
9275       return isPowerOf2_32(Scale);
9276     }
9277   }
9278   return true;
9279 }
9280
9281 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9282 /// icmp immediate, that is the target has icmp instructions which can compare
9283 /// a register against the immediate without having to materialize the
9284 /// immediate into a register.
9285 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9286   // Thumb2 and ARM modes can use cmn for negative immediates.
9287   if (!Subtarget->isThumb())
9288     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9289   if (Subtarget->isThumb2())
9290     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9291   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9292   return Imm >= 0 && Imm <= 255;
9293 }
9294
9295 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9296 /// *or sub* immediate, that is the target has add or sub instructions which can
9297 /// add a register with the immediate without having to materialize the
9298 /// immediate into a register.
9299 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9300   // Same encoding for add/sub, just flip the sign.
9301   int64_t AbsImm = llvm::abs64(Imm);
9302   if (!Subtarget->isThumb())
9303     return ARM_AM::getSOImmVal(AbsImm) != -1;
9304   if (Subtarget->isThumb2())
9305     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9306   // Thumb1 only has 8-bit unsigned immediate.
9307   return AbsImm >= 0 && AbsImm <= 255;
9308 }
9309
9310 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9311                                       bool isSEXTLoad, SDValue &Base,
9312                                       SDValue &Offset, bool &isInc,
9313                                       SelectionDAG &DAG) {
9314   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9315     return false;
9316
9317   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9318     // AddressingMode 3
9319     Base = Ptr->getOperand(0);
9320     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9321       int RHSC = (int)RHS->getZExtValue();
9322       if (RHSC < 0 && RHSC > -256) {
9323         assert(Ptr->getOpcode() == ISD::ADD);
9324         isInc = false;
9325         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9326         return true;
9327       }
9328     }
9329     isInc = (Ptr->getOpcode() == ISD::ADD);
9330     Offset = Ptr->getOperand(1);
9331     return true;
9332   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9333     // AddressingMode 2
9334     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9335       int RHSC = (int)RHS->getZExtValue();
9336       if (RHSC < 0 && RHSC > -0x1000) {
9337         assert(Ptr->getOpcode() == ISD::ADD);
9338         isInc = false;
9339         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9340         Base = Ptr->getOperand(0);
9341         return true;
9342       }
9343     }
9344
9345     if (Ptr->getOpcode() == ISD::ADD) {
9346       isInc = true;
9347       ARM_AM::ShiftOpc ShOpcVal=
9348         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9349       if (ShOpcVal != ARM_AM::no_shift) {
9350         Base = Ptr->getOperand(1);
9351         Offset = Ptr->getOperand(0);
9352       } else {
9353         Base = Ptr->getOperand(0);
9354         Offset = Ptr->getOperand(1);
9355       }
9356       return true;
9357     }
9358
9359     isInc = (Ptr->getOpcode() == ISD::ADD);
9360     Base = Ptr->getOperand(0);
9361     Offset = Ptr->getOperand(1);
9362     return true;
9363   }
9364
9365   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9366   return false;
9367 }
9368
9369 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9370                                      bool isSEXTLoad, SDValue &Base,
9371                                      SDValue &Offset, bool &isInc,
9372                                      SelectionDAG &DAG) {
9373   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9374     return false;
9375
9376   Base = Ptr->getOperand(0);
9377   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9378     int RHSC = (int)RHS->getZExtValue();
9379     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9380       assert(Ptr->getOpcode() == ISD::ADD);
9381       isInc = false;
9382       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9383       return true;
9384     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9385       isInc = Ptr->getOpcode() == ISD::ADD;
9386       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9387       return true;
9388     }
9389   }
9390
9391   return false;
9392 }
9393
9394 /// getPreIndexedAddressParts - returns true by value, base pointer and
9395 /// offset pointer and addressing mode by reference if the node's address
9396 /// can be legally represented as pre-indexed load / store address.
9397 bool
9398 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9399                                              SDValue &Offset,
9400                                              ISD::MemIndexedMode &AM,
9401                                              SelectionDAG &DAG) const {
9402   if (Subtarget->isThumb1Only())
9403     return false;
9404
9405   EVT VT;
9406   SDValue Ptr;
9407   bool isSEXTLoad = false;
9408   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9409     Ptr = LD->getBasePtr();
9410     VT  = LD->getMemoryVT();
9411     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9412   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9413     Ptr = ST->getBasePtr();
9414     VT  = ST->getMemoryVT();
9415   } else
9416     return false;
9417
9418   bool isInc;
9419   bool isLegal = false;
9420   if (Subtarget->isThumb2())
9421     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9422                                        Offset, isInc, DAG);
9423   else
9424     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9425                                         Offset, isInc, DAG);
9426   if (!isLegal)
9427     return false;
9428
9429   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9430   return true;
9431 }
9432
9433 /// getPostIndexedAddressParts - returns true by value, base pointer and
9434 /// offset pointer and addressing mode by reference if this node can be
9435 /// combined with a load / store to form a post-indexed load / store.
9436 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9437                                                    SDValue &Base,
9438                                                    SDValue &Offset,
9439                                                    ISD::MemIndexedMode &AM,
9440                                                    SelectionDAG &DAG) const {
9441   if (Subtarget->isThumb1Only())
9442     return false;
9443
9444   EVT VT;
9445   SDValue Ptr;
9446   bool isSEXTLoad = false;
9447   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9448     VT  = LD->getMemoryVT();
9449     Ptr = LD->getBasePtr();
9450     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9451   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9452     VT  = ST->getMemoryVT();
9453     Ptr = ST->getBasePtr();
9454   } else
9455     return false;
9456
9457   bool isInc;
9458   bool isLegal = false;
9459   if (Subtarget->isThumb2())
9460     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9461                                        isInc, DAG);
9462   else
9463     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9464                                         isInc, DAG);
9465   if (!isLegal)
9466     return false;
9467
9468   if (Ptr != Base) {
9469     // Swap base ptr and offset to catch more post-index load / store when
9470     // it's legal. In Thumb2 mode, offset must be an immediate.
9471     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9472         !Subtarget->isThumb2())
9473       std::swap(Base, Offset);
9474
9475     // Post-indexed load / store update the base pointer.
9476     if (Ptr != Base)
9477       return false;
9478   }
9479
9480   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9481   return true;
9482 }
9483
9484 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9485                                                        APInt &KnownZero,
9486                                                        APInt &KnownOne,
9487                                                        const SelectionDAG &DAG,
9488                                                        unsigned Depth) const {
9489   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9490   switch (Op.getOpcode()) {
9491   default: break;
9492   case ARMISD::CMOV: {
9493     // Bits are known zero/one if known on the LHS and RHS.
9494     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9495     if (KnownZero == 0 && KnownOne == 0) return;
9496
9497     APInt KnownZeroRHS, KnownOneRHS;
9498     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9499     KnownZero &= KnownZeroRHS;
9500     KnownOne  &= KnownOneRHS;
9501     return;
9502   }
9503   }
9504 }
9505
9506 //===----------------------------------------------------------------------===//
9507 //                           ARM Inline Assembly Support
9508 //===----------------------------------------------------------------------===//
9509
9510 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9511   // Looking for "rev" which is V6+.
9512   if (!Subtarget->hasV6Ops())
9513     return false;
9514
9515   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9516   std::string AsmStr = IA->getAsmString();
9517   SmallVector<StringRef, 4> AsmPieces;
9518   SplitString(AsmStr, AsmPieces, ";\n");
9519
9520   switch (AsmPieces.size()) {
9521   default: return false;
9522   case 1:
9523     AsmStr = AsmPieces[0];
9524     AsmPieces.clear();
9525     SplitString(AsmStr, AsmPieces, " \t,");
9526
9527     // rev $0, $1
9528     if (AsmPieces.size() == 3 &&
9529         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9530         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9531       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9532       if (Ty && Ty->getBitWidth() == 32)
9533         return IntrinsicLowering::LowerToByteSwap(CI);
9534     }
9535     break;
9536   }
9537
9538   return false;
9539 }
9540
9541 /// getConstraintType - Given a constraint letter, return the type of
9542 /// constraint it is for this target.
9543 ARMTargetLowering::ConstraintType
9544 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9545   if (Constraint.size() == 1) {
9546     switch (Constraint[0]) {
9547     default:  break;
9548     case 'l': return C_RegisterClass;
9549     case 'w': return C_RegisterClass;
9550     case 'h': return C_RegisterClass;
9551     case 'x': return C_RegisterClass;
9552     case 't': return C_RegisterClass;
9553     case 'j': return C_Other; // Constant for movw.
9554       // An address with a single base register. Due to the way we
9555       // currently handle addresses it is the same as an 'r' memory constraint.
9556     case 'Q': return C_Memory;
9557     }
9558   } else if (Constraint.size() == 2) {
9559     switch (Constraint[0]) {
9560     default: break;
9561     // All 'U+' constraints are addresses.
9562     case 'U': return C_Memory;
9563     }
9564   }
9565   return TargetLowering::getConstraintType(Constraint);
9566 }
9567
9568 /// Examine constraint type and operand type and determine a weight value.
9569 /// This object must already have been set up with the operand type
9570 /// and the current alternative constraint selected.
9571 TargetLowering::ConstraintWeight
9572 ARMTargetLowering::getSingleConstraintMatchWeight(
9573     AsmOperandInfo &info, const char *constraint) const {
9574   ConstraintWeight weight = CW_Invalid;
9575   Value *CallOperandVal = info.CallOperandVal;
9576     // If we don't have a value, we can't do a match,
9577     // but allow it at the lowest weight.
9578   if (CallOperandVal == NULL)
9579     return CW_Default;
9580   Type *type = CallOperandVal->getType();
9581   // Look at the constraint type.
9582   switch (*constraint) {
9583   default:
9584     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9585     break;
9586   case 'l':
9587     if (type->isIntegerTy()) {
9588       if (Subtarget->isThumb())
9589         weight = CW_SpecificReg;
9590       else
9591         weight = CW_Register;
9592     }
9593     break;
9594   case 'w':
9595     if (type->isFloatingPointTy())
9596       weight = CW_Register;
9597     break;
9598   }
9599   return weight;
9600 }
9601
9602 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9603 RCPair
9604 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9605                                                 EVT VT) const {
9606   if (Constraint.size() == 1) {
9607     // GCC ARM Constraint Letters
9608     switch (Constraint[0]) {
9609     case 'l': // Low regs or general regs.
9610       if (Subtarget->isThumb())
9611         return RCPair(0U, &ARM::tGPRRegClass);
9612       return RCPair(0U, &ARM::GPRRegClass);
9613     case 'h': // High regs or no regs.
9614       if (Subtarget->isThumb())
9615         return RCPair(0U, &ARM::hGPRRegClass);
9616       break;
9617     case 'r':
9618       return RCPair(0U, &ARM::GPRRegClass);
9619     case 'w':
9620       if (VT == MVT::f32)
9621         return RCPair(0U, &ARM::SPRRegClass);
9622       if (VT.getSizeInBits() == 64)
9623         return RCPair(0U, &ARM::DPRRegClass);
9624       if (VT.getSizeInBits() == 128)
9625         return RCPair(0U, &ARM::QPRRegClass);
9626       break;
9627     case 'x':
9628       if (VT == MVT::f32)
9629         return RCPair(0U, &ARM::SPR_8RegClass);
9630       if (VT.getSizeInBits() == 64)
9631         return RCPair(0U, &ARM::DPR_8RegClass);
9632       if (VT.getSizeInBits() == 128)
9633         return RCPair(0U, &ARM::QPR_8RegClass);
9634       break;
9635     case 't':
9636       if (VT == MVT::f32)
9637         return RCPair(0U, &ARM::SPRRegClass);
9638       break;
9639     }
9640   }
9641   if (StringRef("{cc}").equals_lower(Constraint))
9642     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9643
9644   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9645 }
9646
9647 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9648 /// vector.  If it is invalid, don't add anything to Ops.
9649 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9650                                                      std::string &Constraint,
9651                                                      std::vector<SDValue>&Ops,
9652                                                      SelectionDAG &DAG) const {
9653   SDValue Result(0, 0);
9654
9655   // Currently only support length 1 constraints.
9656   if (Constraint.length() != 1) return;
9657
9658   char ConstraintLetter = Constraint[0];
9659   switch (ConstraintLetter) {
9660   default: break;
9661   case 'j':
9662   case 'I': case 'J': case 'K': case 'L':
9663   case 'M': case 'N': case 'O':
9664     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9665     if (!C)
9666       return;
9667
9668     int64_t CVal64 = C->getSExtValue();
9669     int CVal = (int) CVal64;
9670     // None of these constraints allow values larger than 32 bits.  Check
9671     // that the value fits in an int.
9672     if (CVal != CVal64)
9673       return;
9674
9675     switch (ConstraintLetter) {
9676       case 'j':
9677         // Constant suitable for movw, must be between 0 and
9678         // 65535.
9679         if (Subtarget->hasV6T2Ops())
9680           if (CVal >= 0 && CVal <= 65535)
9681             break;
9682         return;
9683       case 'I':
9684         if (Subtarget->isThumb1Only()) {
9685           // This must be a constant between 0 and 255, for ADD
9686           // immediates.
9687           if (CVal >= 0 && CVal <= 255)
9688             break;
9689         } else if (Subtarget->isThumb2()) {
9690           // A constant that can be used as an immediate value in a
9691           // data-processing instruction.
9692           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9693             break;
9694         } else {
9695           // A constant that can be used as an immediate value in a
9696           // data-processing instruction.
9697           if (ARM_AM::getSOImmVal(CVal) != -1)
9698             break;
9699         }
9700         return;
9701
9702       case 'J':
9703         if (Subtarget->isThumb()) {  // FIXME thumb2
9704           // This must be a constant between -255 and -1, for negated ADD
9705           // immediates. This can be used in GCC with an "n" modifier that
9706           // prints the negated value, for use with SUB instructions. It is
9707           // not useful otherwise but is implemented for compatibility.
9708           if (CVal >= -255 && CVal <= -1)
9709             break;
9710         } else {
9711           // This must be a constant between -4095 and 4095. It is not clear
9712           // what this constraint is intended for. Implemented for
9713           // compatibility with GCC.
9714           if (CVal >= -4095 && CVal <= 4095)
9715             break;
9716         }
9717         return;
9718
9719       case 'K':
9720         if (Subtarget->isThumb1Only()) {
9721           // A 32-bit value where only one byte has a nonzero value. Exclude
9722           // zero to match GCC. This constraint is used by GCC internally for
9723           // constants that can be loaded with a move/shift combination.
9724           // It is not useful otherwise but is implemented for compatibility.
9725           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9726             break;
9727         } else if (Subtarget->isThumb2()) {
9728           // A constant whose bitwise inverse can be used as an immediate
9729           // value in a data-processing instruction. This can be used in GCC
9730           // with a "B" modifier that prints the inverted value, for use with
9731           // BIC and MVN instructions. It is not useful otherwise but is
9732           // implemented for compatibility.
9733           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9734             break;
9735         } else {
9736           // A constant whose bitwise inverse can be used as an immediate
9737           // value in a data-processing instruction. This can be used in GCC
9738           // with a "B" modifier that prints the inverted value, for use with
9739           // BIC and MVN instructions. It is not useful otherwise but is
9740           // implemented for compatibility.
9741           if (ARM_AM::getSOImmVal(~CVal) != -1)
9742             break;
9743         }
9744         return;
9745
9746       case 'L':
9747         if (Subtarget->isThumb1Only()) {
9748           // This must be a constant between -7 and 7,
9749           // for 3-operand ADD/SUB immediate instructions.
9750           if (CVal >= -7 && CVal < 7)
9751             break;
9752         } else if (Subtarget->isThumb2()) {
9753           // A constant whose negation can be used as an immediate value in a
9754           // data-processing instruction. This can be used in GCC with an "n"
9755           // modifier that prints the negated value, for use with SUB
9756           // instructions. It is not useful otherwise but is implemented for
9757           // compatibility.
9758           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9759             break;
9760         } else {
9761           // A constant whose negation can be used as an immediate value in a
9762           // data-processing instruction. This can be used in GCC with an "n"
9763           // modifier that prints the negated value, for use with SUB
9764           // instructions. It is not useful otherwise but is implemented for
9765           // compatibility.
9766           if (ARM_AM::getSOImmVal(-CVal) != -1)
9767             break;
9768         }
9769         return;
9770
9771       case 'M':
9772         if (Subtarget->isThumb()) { // FIXME thumb2
9773           // This must be a multiple of 4 between 0 and 1020, for
9774           // ADD sp + immediate.
9775           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9776             break;
9777         } else {
9778           // A power of two or a constant between 0 and 32.  This is used in
9779           // GCC for the shift amount on shifted register operands, but it is
9780           // useful in general for any shift amounts.
9781           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9782             break;
9783         }
9784         return;
9785
9786       case 'N':
9787         if (Subtarget->isThumb()) {  // FIXME thumb2
9788           // This must be a constant between 0 and 31, for shift amounts.
9789           if (CVal >= 0 && CVal <= 31)
9790             break;
9791         }
9792         return;
9793
9794       case 'O':
9795         if (Subtarget->isThumb()) {  // FIXME thumb2
9796           // This must be a multiple of 4 between -508 and 508, for
9797           // ADD/SUB sp = sp + immediate.
9798           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9799             break;
9800         }
9801         return;
9802     }
9803     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9804     break;
9805   }
9806
9807   if (Result.getNode()) {
9808     Ops.push_back(Result);
9809     return;
9810   }
9811   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9812 }
9813
9814 bool
9815 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9816   // The ARM target isn't yet aware of offsets.
9817   return false;
9818 }
9819
9820 bool ARM::isBitFieldInvertedMask(unsigned v) {
9821   if (v == 0xffffffff)
9822     return 0;
9823   // there can be 1's on either or both "outsides", all the "inside"
9824   // bits must be 0's
9825   unsigned int lsb = 0, msb = 31;
9826   while (v & (1 << msb)) --msb;
9827   while (v & (1 << lsb)) ++lsb;
9828   for (unsigned int i = lsb; i <= msb; ++i) {
9829     if (v & (1 << i))
9830       return 0;
9831   }
9832   return 1;
9833 }
9834
9835 /// isFPImmLegal - Returns true if the target can instruction select the
9836 /// specified FP immediate natively. If false, the legalizer will
9837 /// materialize the FP immediate as a load from a constant pool.
9838 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9839   if (!Subtarget->hasVFP3())
9840     return false;
9841   if (VT == MVT::f32)
9842     return ARM_AM::getFP32Imm(Imm) != -1;
9843   if (VT == MVT::f64)
9844     return ARM_AM::getFP64Imm(Imm) != -1;
9845   return false;
9846 }
9847
9848 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9849 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9850 /// specified in the intrinsic calls.
9851 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9852                                            const CallInst &I,
9853                                            unsigned Intrinsic) const {
9854   switch (Intrinsic) {
9855   case Intrinsic::arm_neon_vld1:
9856   case Intrinsic::arm_neon_vld2:
9857   case Intrinsic::arm_neon_vld3:
9858   case Intrinsic::arm_neon_vld4:
9859   case Intrinsic::arm_neon_vld2lane:
9860   case Intrinsic::arm_neon_vld3lane:
9861   case Intrinsic::arm_neon_vld4lane: {
9862     Info.opc = ISD::INTRINSIC_W_CHAIN;
9863     // Conservatively set memVT to the entire set of vectors loaded.
9864     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
9865     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9866     Info.ptrVal = I.getArgOperand(0);
9867     Info.offset = 0;
9868     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9869     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9870     Info.vol = false; // volatile loads with NEON intrinsics not supported
9871     Info.readMem = true;
9872     Info.writeMem = false;
9873     return true;
9874   }
9875   case Intrinsic::arm_neon_vst1:
9876   case Intrinsic::arm_neon_vst2:
9877   case Intrinsic::arm_neon_vst3:
9878   case Intrinsic::arm_neon_vst4:
9879   case Intrinsic::arm_neon_vst2lane:
9880   case Intrinsic::arm_neon_vst3lane:
9881   case Intrinsic::arm_neon_vst4lane: {
9882     Info.opc = ISD::INTRINSIC_VOID;
9883     // Conservatively set memVT to the entire set of vectors stored.
9884     unsigned NumElts = 0;
9885     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9886       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9887       if (!ArgTy->isVectorTy())
9888         break;
9889       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
9890     }
9891     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9892     Info.ptrVal = I.getArgOperand(0);
9893     Info.offset = 0;
9894     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9895     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9896     Info.vol = false; // volatile stores with NEON intrinsics not supported
9897     Info.readMem = false;
9898     Info.writeMem = true;
9899     return true;
9900   }
9901   case Intrinsic::arm_strexd: {
9902     Info.opc = ISD::INTRINSIC_W_CHAIN;
9903     Info.memVT = MVT::i64;
9904     Info.ptrVal = I.getArgOperand(2);
9905     Info.offset = 0;
9906     Info.align = 8;
9907     Info.vol = true;
9908     Info.readMem = false;
9909     Info.writeMem = true;
9910     return true;
9911   }
9912   case Intrinsic::arm_ldrexd: {
9913     Info.opc = ISD::INTRINSIC_W_CHAIN;
9914     Info.memVT = MVT::i64;
9915     Info.ptrVal = I.getArgOperand(0);
9916     Info.offset = 0;
9917     Info.align = 8;
9918     Info.vol = true;
9919     Info.readMem = true;
9920     Info.writeMem = false;
9921     return true;
9922   }
9923   default:
9924     break;
9925   }
9926
9927   return false;
9928 }