Mark FP_ROUND for converting NEON v2f64 to v2f32 as expand. Add a missing
[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::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507
508     setOperationAction(ISD::FABS, MVT::v4f32, Expand);
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Neon does not support some operations on v1i64 and v2i64 types.
526     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
527     // Custom handling for some quad-vector types to detect VMULL.
528     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
529     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
530     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
531     // Custom handling for some vector types to avoid expensive expansions
532     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
533     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
534     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
535     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
536     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
537     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
538     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
539     // a destination type that is wider than the source, and nor does
540     // it have a FP_TO_[SU]INT instruction with a narrower destination than
541     // source.
542     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
543     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
544     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
545     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
546
547     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
548
549     setTargetDAGCombine(ISD::INTRINSIC_VOID);
550     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552     setTargetDAGCombine(ISD::SHL);
553     setTargetDAGCombine(ISD::SRL);
554     setTargetDAGCombine(ISD::SRA);
555     setTargetDAGCombine(ISD::SIGN_EXTEND);
556     setTargetDAGCombine(ISD::ZERO_EXTEND);
557     setTargetDAGCombine(ISD::ANY_EXTEND);
558     setTargetDAGCombine(ISD::SELECT_CC);
559     setTargetDAGCombine(ISD::BUILD_VECTOR);
560     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562     setTargetDAGCombine(ISD::STORE);
563     setTargetDAGCombine(ISD::FP_TO_SINT);
564     setTargetDAGCombine(ISD::FP_TO_UINT);
565     setTargetDAGCombine(ISD::FDIV);
566
567     // It is legal to extload from v4i8 to v4i16 or v4i32.
568     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569                   MVT::v4i16, MVT::v2i16,
570                   MVT::v2i32};
571     for (unsigned i = 0; i < 6; ++i) {
572       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
575     }
576   }
577
578   // ARM and Thumb2 support UMLAL/SMLAL.
579   if (!Subtarget->isThumb1Only())
580     setTargetDAGCombine(ISD::ADDC);
581
582
583   computeRegisterProperties();
584
585   // ARM does not have f32 extending load.
586   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
587
588   // ARM does not have i1 sign extending load.
589   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
590
591   // ARM supports all 4 flavors of integer indexed load / store.
592   if (!Subtarget->isThumb1Only()) {
593     for (unsigned im = (unsigned)ISD::PRE_INC;
594          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
595       setIndexedLoadAction(im,  MVT::i1,  Legal);
596       setIndexedLoadAction(im,  MVT::i8,  Legal);
597       setIndexedLoadAction(im,  MVT::i16, Legal);
598       setIndexedLoadAction(im,  MVT::i32, Legal);
599       setIndexedStoreAction(im, MVT::i1,  Legal);
600       setIndexedStoreAction(im, MVT::i8,  Legal);
601       setIndexedStoreAction(im, MVT::i16, Legal);
602       setIndexedStoreAction(im, MVT::i32, Legal);
603     }
604   }
605
606   // i64 operation support.
607   setOperationAction(ISD::MUL,     MVT::i64, Expand);
608   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
609   if (Subtarget->isThumb1Only()) {
610     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
611     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
612   }
613   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
614       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
615     setOperationAction(ISD::MULHS, MVT::i32, Expand);
616
617   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
618   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
619   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
620   setOperationAction(ISD::SRL,       MVT::i64, Custom);
621   setOperationAction(ISD::SRA,       MVT::i64, Custom);
622
623   if (!Subtarget->isThumb1Only()) {
624     // FIXME: We should do this for Thumb1 as well.
625     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
626     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
627     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
628     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
629   }
630
631   // ARM does not have ROTL.
632   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
633   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
634   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
635   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
636     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
637
638   // These just redirect to CTTZ and CTLZ on ARM.
639   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
640   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
641
642   // Only ARMv6 has BSWAP.
643   if (!Subtarget->hasV6Ops())
644     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
645
646   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
647       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
648     // These are expanded into libcalls if the cpu doesn't have HW divider.
649     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
650     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
651   }
652   setOperationAction(ISD::SREM,  MVT::i32, Expand);
653   setOperationAction(ISD::UREM,  MVT::i32, Expand);
654   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
655   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
656
657   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
658   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
659   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
660   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
661   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
662
663   setOperationAction(ISD::TRAP, MVT::Other, Legal);
664
665   // Use the default implementation.
666   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
667   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
668   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
669   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
670   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
671   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
672
673   if (!Subtarget->isTargetDarwin()) {
674     // Non-Darwin platforms may return values in these registers via the
675     // personality function.
676     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
677     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
678     setExceptionPointerRegister(ARM::R0);
679     setExceptionSelectorRegister(ARM::R1);
680   }
681
682   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
683   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
684   // the default expansion.
685   // FIXME: This should be checking for v6k, not just v6.
686   if (Subtarget->hasDataBarrier() ||
687       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
688     // membarrier needs custom lowering; the rest are legal and handled
689     // normally.
690     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
691     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
692     // Custom lowering for 64-bit ops
693     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
694     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
695     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
696     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
697     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
698     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
699     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
700     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
701     setInsertFencesForAtomic(true);
702   } else {
703     // Set them all for expansion, which will force libcalls.
704     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
705     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
706     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
710     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
711     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
712     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
713     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
714     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
715     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
716     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
717     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
718     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
719     // Unordered/Monotonic case.
720     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
721     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
722     // Since the libcalls include locking, fold in the fences
723     setShouldFoldAtomicFences(true);
724   }
725
726   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
727
728   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
729   if (!Subtarget->hasV6Ops()) {
730     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
731     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
732   }
733   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
734
735   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
736       !Subtarget->isThumb1Only()) {
737     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
738     // iff target supports vfp2.
739     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
740     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
741   }
742
743   // We want to custom lower some of our intrinsics.
744   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
745   if (Subtarget->isTargetDarwin()) {
746     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
747     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
748     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
749   }
750
751   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
752   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
753   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
754   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
755   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
756   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
757   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
758   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
759   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
760
761   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
762   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
763   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
764   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
765   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
766
767   // We don't support sin/cos/fmod/copysign/pow
768   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
769   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
770   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
771   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
772   setOperationAction(ISD::FREM,      MVT::f64, Expand);
773   setOperationAction(ISD::FREM,      MVT::f32, Expand);
774   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
775       !Subtarget->isThumb1Only()) {
776     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
777     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
778   }
779   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
780   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
781
782   if (!Subtarget->hasVFP4()) {
783     setOperationAction(ISD::FMA, MVT::f64, Expand);
784     setOperationAction(ISD::FMA, MVT::f32, Expand);
785   }
786
787   // Various VFP goodness
788   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
789     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
790     if (Subtarget->hasVFP2()) {
791       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
792       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
793       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
794       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
795     }
796     // Special handling for half-precision FP.
797     if (!Subtarget->hasFP16()) {
798       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
799       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
800     }
801   }
802
803   // We have target-specific dag combine patterns for the following nodes:
804   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
805   setTargetDAGCombine(ISD::ADD);
806   setTargetDAGCombine(ISD::SUB);
807   setTargetDAGCombine(ISD::MUL);
808   setTargetDAGCombine(ISD::AND);
809   setTargetDAGCombine(ISD::OR);
810   setTargetDAGCombine(ISD::XOR);
811
812   if (Subtarget->hasV6Ops())
813     setTargetDAGCombine(ISD::SRL);
814
815   setStackPointerRegisterToSaveRestore(ARM::SP);
816
817   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
818       !Subtarget->hasVFP2())
819     setSchedulingPreference(Sched::RegPressure);
820   else
821     setSchedulingPreference(Sched::Hybrid);
822
823   //// temporary - rewrite interface to use type
824   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
825   maxStoresPerMemset = 16;
826   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
827
828   // On ARM arguments smaller than 4 bytes are extended, so all arguments
829   // are at least 4 bytes aligned.
830   setMinStackArgumentAlignment(4);
831
832   benefitFromCodePlacementOpt = true;
833
834   // Prefer likely predicted branches to selects on out-of-order cores.
835   predictableSelectIsExpensive = Subtarget->isLikeA9();
836
837   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
838 }
839
840 // FIXME: It might make sense to define the representative register class as the
841 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
842 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
843 // SPR's representative would be DPR_VFP2. This should work well if register
844 // pressure tracking were modified such that a register use would increment the
845 // pressure of the register class's representative and all of it's super
846 // classes' representatives transitively. We have not implemented this because
847 // of the difficulty prior to coalescing of modeling operand register classes
848 // due to the common occurrence of cross class copies and subregister insertions
849 // and extractions.
850 std::pair<const TargetRegisterClass*, uint8_t>
851 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
852   const TargetRegisterClass *RRC = 0;
853   uint8_t Cost = 1;
854   switch (VT.getSimpleVT().SimpleTy) {
855   default:
856     return TargetLowering::findRepresentativeClass(VT);
857   // Use DPR as representative register class for all floating point
858   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
859   // the cost is 1 for both f32 and f64.
860   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
861   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
862     RRC = &ARM::DPRRegClass;
863     // When NEON is used for SP, only half of the register file is available
864     // because operations that define both SP and DP results will be constrained
865     // to the VFP2 class (D0-D15). We currently model this constraint prior to
866     // coalescing by double-counting the SP regs. See the FIXME above.
867     if (Subtarget->useNEONForSinglePrecisionFP())
868       Cost = 2;
869     break;
870   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
871   case MVT::v4f32: case MVT::v2f64:
872     RRC = &ARM::DPRRegClass;
873     Cost = 2;
874     break;
875   case MVT::v4i64:
876     RRC = &ARM::DPRRegClass;
877     Cost = 4;
878     break;
879   case MVT::v8i64:
880     RRC = &ARM::DPRRegClass;
881     Cost = 8;
882     break;
883   }
884   return std::make_pair(RRC, Cost);
885 }
886
887 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
888   switch (Opcode) {
889   default: return 0;
890   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
891   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
892   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
893   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
894   case ARMISD::CALL:          return "ARMISD::CALL";
895   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
896   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
897   case ARMISD::tCALL:         return "ARMISD::tCALL";
898   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
899   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
900   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
901   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
902   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
903   case ARMISD::CMP:           return "ARMISD::CMP";
904   case ARMISD::CMN:           return "ARMISD::CMN";
905   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
906   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
907   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
908   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
909   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
910
911   case ARMISD::CMOV:          return "ARMISD::CMOV";
912
913   case ARMISD::RBIT:          return "ARMISD::RBIT";
914
915   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
916   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
917   case ARMISD::SITOF:         return "ARMISD::SITOF";
918   case ARMISD::UITOF:         return "ARMISD::UITOF";
919
920   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
921   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
922   case ARMISD::RRX:           return "ARMISD::RRX";
923
924   case ARMISD::ADDC:          return "ARMISD::ADDC";
925   case ARMISD::ADDE:          return "ARMISD::ADDE";
926   case ARMISD::SUBC:          return "ARMISD::SUBC";
927   case ARMISD::SUBE:          return "ARMISD::SUBE";
928
929   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
930   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
931
932   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
933   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
934
935   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
936
937   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
938
939   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
940
941   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
942   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
943
944   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
945
946   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
947   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
948   case ARMISD::VCGE:          return "ARMISD::VCGE";
949   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
950   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
951   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
952   case ARMISD::VCGT:          return "ARMISD::VCGT";
953   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
954   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
955   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
956   case ARMISD::VTST:          return "ARMISD::VTST";
957
958   case ARMISD::VSHL:          return "ARMISD::VSHL";
959   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
960   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
961   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
962   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
963   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
964   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
965   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
966   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
967   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
968   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
969   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
970   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
971   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
972   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
973   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
974   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
975   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
976   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
977   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
978   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
979   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
980   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
981   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
982   case ARMISD::VDUP:          return "ARMISD::VDUP";
983   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
984   case ARMISD::VEXT:          return "ARMISD::VEXT";
985   case ARMISD::VREV64:        return "ARMISD::VREV64";
986   case ARMISD::VREV32:        return "ARMISD::VREV32";
987   case ARMISD::VREV16:        return "ARMISD::VREV16";
988   case ARMISD::VZIP:          return "ARMISD::VZIP";
989   case ARMISD::VUZP:          return "ARMISD::VUZP";
990   case ARMISD::VTRN:          return "ARMISD::VTRN";
991   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
992   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
993   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
994   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
995   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
996   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
997   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
998   case ARMISD::FMAX:          return "ARMISD::FMAX";
999   case ARMISD::FMIN:          return "ARMISD::FMIN";
1000   case ARMISD::BFI:           return "ARMISD::BFI";
1001   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1002   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1003   case ARMISD::VBSL:          return "ARMISD::VBSL";
1004   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1005   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1006   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1007   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1008   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1009   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1010   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1011   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1012   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1013   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1014   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1015   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1016   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1017   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1018   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1019   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1020   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1021   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1022   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1023   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1024   }
1025 }
1026
1027 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1028   if (!VT.isVector()) return getPointerTy();
1029   return VT.changeVectorElementTypeToInteger();
1030 }
1031
1032 /// getRegClassFor - Return the register class that should be used for the
1033 /// specified value type.
1034 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1035   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1036   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1037   // load / store 4 to 8 consecutive D registers.
1038   if (Subtarget->hasNEON()) {
1039     if (VT == MVT::v4i64)
1040       return &ARM::QQPRRegClass;
1041     if (VT == MVT::v8i64)
1042       return &ARM::QQQQPRRegClass;
1043   }
1044   return TargetLowering::getRegClassFor(VT);
1045 }
1046
1047 // Create a fast isel object.
1048 FastISel *
1049 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1050                                   const TargetLibraryInfo *libInfo) const {
1051   return ARM::createFastISel(funcInfo, libInfo);
1052 }
1053
1054 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1055 /// be used for loads / stores from the global.
1056 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1057   return (Subtarget->isThumb1Only() ? 127 : 4095);
1058 }
1059
1060 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1061   unsigned NumVals = N->getNumValues();
1062   if (!NumVals)
1063     return Sched::RegPressure;
1064
1065   for (unsigned i = 0; i != NumVals; ++i) {
1066     EVT VT = N->getValueType(i);
1067     if (VT == MVT::Glue || VT == MVT::Other)
1068       continue;
1069     if (VT.isFloatingPoint() || VT.isVector())
1070       return Sched::ILP;
1071   }
1072
1073   if (!N->isMachineOpcode())
1074     return Sched::RegPressure;
1075
1076   // Load are scheduled for latency even if there instruction itinerary
1077   // is not available.
1078   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1079   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1080
1081   if (MCID.getNumDefs() == 0)
1082     return Sched::RegPressure;
1083   if (!Itins->isEmpty() &&
1084       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1085     return Sched::ILP;
1086
1087   return Sched::RegPressure;
1088 }
1089
1090 //===----------------------------------------------------------------------===//
1091 // Lowering Code
1092 //===----------------------------------------------------------------------===//
1093
1094 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1095 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1096   switch (CC) {
1097   default: llvm_unreachable("Unknown condition code!");
1098   case ISD::SETNE:  return ARMCC::NE;
1099   case ISD::SETEQ:  return ARMCC::EQ;
1100   case ISD::SETGT:  return ARMCC::GT;
1101   case ISD::SETGE:  return ARMCC::GE;
1102   case ISD::SETLT:  return ARMCC::LT;
1103   case ISD::SETLE:  return ARMCC::LE;
1104   case ISD::SETUGT: return ARMCC::HI;
1105   case ISD::SETUGE: return ARMCC::HS;
1106   case ISD::SETULT: return ARMCC::LO;
1107   case ISD::SETULE: return ARMCC::LS;
1108   }
1109 }
1110
1111 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1112 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1113                         ARMCC::CondCodes &CondCode2) {
1114   CondCode2 = ARMCC::AL;
1115   switch (CC) {
1116   default: llvm_unreachable("Unknown FP condition!");
1117   case ISD::SETEQ:
1118   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1119   case ISD::SETGT:
1120   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1121   case ISD::SETGE:
1122   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1123   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1124   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1125   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1126   case ISD::SETO:   CondCode = ARMCC::VC; break;
1127   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1128   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1129   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1130   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1131   case ISD::SETLT:
1132   case ISD::SETULT: CondCode = ARMCC::LT; break;
1133   case ISD::SETLE:
1134   case ISD::SETULE: CondCode = ARMCC::LE; break;
1135   case ISD::SETNE:
1136   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1137   }
1138 }
1139
1140 //===----------------------------------------------------------------------===//
1141 //                      Calling Convention Implementation
1142 //===----------------------------------------------------------------------===//
1143
1144 #include "ARMGenCallingConv.inc"
1145
1146 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1147 /// given CallingConvention value.
1148 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1149                                                  bool Return,
1150                                                  bool isVarArg) const {
1151   switch (CC) {
1152   default:
1153     llvm_unreachable("Unsupported calling convention");
1154   case CallingConv::Fast:
1155     if (Subtarget->hasVFP2() && !isVarArg) {
1156       if (!Subtarget->isAAPCS_ABI())
1157         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1158       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1159       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1160     }
1161     // Fallthrough
1162   case CallingConv::C: {
1163     // Use target triple & subtarget features to do actual dispatch.
1164     if (!Subtarget->isAAPCS_ABI())
1165       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1166     else if (Subtarget->hasVFP2() &&
1167              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1168              !isVarArg)
1169       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1170     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1171   }
1172   case CallingConv::ARM_AAPCS_VFP:
1173     if (!isVarArg)
1174       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1175     // Fallthrough
1176   case CallingConv::ARM_AAPCS:
1177     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1178   case CallingConv::ARM_APCS:
1179     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1180   case CallingConv::GHC:
1181     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1182   }
1183 }
1184
1185 /// LowerCallResult - Lower the result values of a call into the
1186 /// appropriate copies out of appropriate physical registers.
1187 SDValue
1188 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1189                                    CallingConv::ID CallConv, bool isVarArg,
1190                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1191                                    DebugLoc dl, SelectionDAG &DAG,
1192                                    SmallVectorImpl<SDValue> &InVals) const {
1193
1194   // Assign locations to each value returned by this call.
1195   SmallVector<CCValAssign, 16> RVLocs;
1196   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1197                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1198   CCInfo.AnalyzeCallResult(Ins,
1199                            CCAssignFnForNode(CallConv, /* Return*/ true,
1200                                              isVarArg));
1201
1202   // Copy all of the result registers out of their specified physreg.
1203   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1204     CCValAssign VA = RVLocs[i];
1205
1206     SDValue Val;
1207     if (VA.needsCustom()) {
1208       // Handle f64 or half of a v2f64.
1209       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1210                                       InFlag);
1211       Chain = Lo.getValue(1);
1212       InFlag = Lo.getValue(2);
1213       VA = RVLocs[++i]; // skip ahead to next loc
1214       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1215                                       InFlag);
1216       Chain = Hi.getValue(1);
1217       InFlag = Hi.getValue(2);
1218       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1219
1220       if (VA.getLocVT() == MVT::v2f64) {
1221         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1222         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1223                           DAG.getConstant(0, MVT::i32));
1224
1225         VA = RVLocs[++i]; // skip ahead to next loc
1226         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1227         Chain = Lo.getValue(1);
1228         InFlag = Lo.getValue(2);
1229         VA = RVLocs[++i]; // skip ahead to next loc
1230         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1231         Chain = Hi.getValue(1);
1232         InFlag = Hi.getValue(2);
1233         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1234         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1235                           DAG.getConstant(1, MVT::i32));
1236       }
1237     } else {
1238       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1239                                InFlag);
1240       Chain = Val.getValue(1);
1241       InFlag = Val.getValue(2);
1242     }
1243
1244     switch (VA.getLocInfo()) {
1245     default: llvm_unreachable("Unknown loc info!");
1246     case CCValAssign::Full: break;
1247     case CCValAssign::BCvt:
1248       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1249       break;
1250     }
1251
1252     InVals.push_back(Val);
1253   }
1254
1255   return Chain;
1256 }
1257
1258 /// LowerMemOpCallTo - Store the argument to the stack.
1259 SDValue
1260 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1261                                     SDValue StackPtr, SDValue Arg,
1262                                     DebugLoc dl, SelectionDAG &DAG,
1263                                     const CCValAssign &VA,
1264                                     ISD::ArgFlagsTy Flags) const {
1265   unsigned LocMemOffset = VA.getLocMemOffset();
1266   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1267   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1268   return DAG.getStore(Chain, dl, Arg, PtrOff,
1269                       MachinePointerInfo::getStack(LocMemOffset),
1270                       false, false, 0);
1271 }
1272
1273 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1274                                          SDValue Chain, SDValue &Arg,
1275                                          RegsToPassVector &RegsToPass,
1276                                          CCValAssign &VA, CCValAssign &NextVA,
1277                                          SDValue &StackPtr,
1278                                          SmallVector<SDValue, 8> &MemOpChains,
1279                                          ISD::ArgFlagsTy Flags) const {
1280
1281   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1282                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1283   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1284
1285   if (NextVA.isRegLoc())
1286     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1287   else {
1288     assert(NextVA.isMemLoc());
1289     if (StackPtr.getNode() == 0)
1290       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1291
1292     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1293                                            dl, DAG, NextVA,
1294                                            Flags));
1295   }
1296 }
1297
1298 /// LowerCall - Lowering a call into a callseq_start <-
1299 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1300 /// nodes.
1301 SDValue
1302 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1303                              SmallVectorImpl<SDValue> &InVals) const {
1304   SelectionDAG &DAG                     = CLI.DAG;
1305   DebugLoc &dl                          = CLI.DL;
1306   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1307   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1308   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1309   SDValue Chain                         = CLI.Chain;
1310   SDValue Callee                        = CLI.Callee;
1311   bool &isTailCall                      = CLI.IsTailCall;
1312   CallingConv::ID CallConv              = CLI.CallConv;
1313   bool doesNotRet                       = CLI.DoesNotReturn;
1314   bool isVarArg                         = CLI.IsVarArg;
1315
1316   MachineFunction &MF = DAG.getMachineFunction();
1317   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1318   bool IsSibCall = false;
1319   // Disable tail calls if they're not supported.
1320   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1321     isTailCall = false;
1322   if (isTailCall) {
1323     // Check if it's really possible to do a tail call.
1324     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1325                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1326                                                    Outs, OutVals, Ins, DAG);
1327     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1328     // detected sibcalls.
1329     if (isTailCall) {
1330       ++NumTailCalls;
1331       IsSibCall = true;
1332     }
1333   }
1334
1335   // Analyze operands of the call, assigning locations to each operand.
1336   SmallVector<CCValAssign, 16> ArgLocs;
1337   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1338                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1339   CCInfo.AnalyzeCallOperands(Outs,
1340                              CCAssignFnForNode(CallConv, /* Return*/ false,
1341                                                isVarArg));
1342
1343   // Get a count of how many bytes are to be pushed on the stack.
1344   unsigned NumBytes = CCInfo.getNextStackOffset();
1345
1346   // For tail calls, memory operands are available in our caller's stack.
1347   if (IsSibCall)
1348     NumBytes = 0;
1349
1350   // Adjust the stack pointer for the new arguments...
1351   // These operations are automatically eliminated by the prolog/epilog pass
1352   if (!IsSibCall)
1353     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1354
1355   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1356
1357   RegsToPassVector RegsToPass;
1358   SmallVector<SDValue, 8> MemOpChains;
1359
1360   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1361   // of tail call optimization, arguments are handled later.
1362   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1363        i != e;
1364        ++i, ++realArgIdx) {
1365     CCValAssign &VA = ArgLocs[i];
1366     SDValue Arg = OutVals[realArgIdx];
1367     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1368     bool isByVal = Flags.isByVal();
1369
1370     // Promote the value if needed.
1371     switch (VA.getLocInfo()) {
1372     default: llvm_unreachable("Unknown loc info!");
1373     case CCValAssign::Full: break;
1374     case CCValAssign::SExt:
1375       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1376       break;
1377     case CCValAssign::ZExt:
1378       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1379       break;
1380     case CCValAssign::AExt:
1381       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1382       break;
1383     case CCValAssign::BCvt:
1384       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1385       break;
1386     }
1387
1388     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1389     if (VA.needsCustom()) {
1390       if (VA.getLocVT() == MVT::v2f64) {
1391         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1392                                   DAG.getConstant(0, MVT::i32));
1393         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1394                                   DAG.getConstant(1, MVT::i32));
1395
1396         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1397                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1398
1399         VA = ArgLocs[++i]; // skip ahead to next loc
1400         if (VA.isRegLoc()) {
1401           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1402                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1403         } else {
1404           assert(VA.isMemLoc());
1405
1406           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1407                                                  dl, DAG, VA, Flags));
1408         }
1409       } else {
1410         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1411                          StackPtr, MemOpChains, Flags);
1412       }
1413     } else if (VA.isRegLoc()) {
1414       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1415     } else if (isByVal) {
1416       assert(VA.isMemLoc());
1417       unsigned offset = 0;
1418
1419       // True if this byval aggregate will be split between registers
1420       // and memory.
1421       if (CCInfo.isFirstByValRegValid()) {
1422         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1423         unsigned int i, j;
1424         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1425           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1426           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1427           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1428                                      MachinePointerInfo(),
1429                                      false, false, false, 0);
1430           MemOpChains.push_back(Load.getValue(1));
1431           RegsToPass.push_back(std::make_pair(j, Load));
1432         }
1433         offset = ARM::R4 - CCInfo.getFirstByValReg();
1434         CCInfo.clearFirstByValReg();
1435       }
1436
1437       if (Flags.getByValSize() - 4*offset > 0) {
1438         unsigned LocMemOffset = VA.getLocMemOffset();
1439         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1440         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1441                                   StkPtrOff);
1442         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1443         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1444         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1445                                            MVT::i32);
1446         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1447
1448         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1449         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1450         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1451                                           Ops, array_lengthof(Ops)));
1452       }
1453     } else if (!IsSibCall) {
1454       assert(VA.isMemLoc());
1455
1456       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1457                                              dl, DAG, VA, Flags));
1458     }
1459   }
1460
1461   if (!MemOpChains.empty())
1462     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1463                         &MemOpChains[0], MemOpChains.size());
1464
1465   // Build a sequence of copy-to-reg nodes chained together with token chain
1466   // and flag operands which copy the outgoing args into the appropriate regs.
1467   SDValue InFlag;
1468   // Tail call byval lowering might overwrite argument registers so in case of
1469   // tail call optimization the copies to registers are lowered later.
1470   if (!isTailCall)
1471     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1472       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1473                                RegsToPass[i].second, InFlag);
1474       InFlag = Chain.getValue(1);
1475     }
1476
1477   // For tail calls lower the arguments to the 'real' stack slot.
1478   if (isTailCall) {
1479     // Force all the incoming stack arguments to be loaded from the stack
1480     // before any new outgoing arguments are stored to the stack, because the
1481     // outgoing stack slots may alias the incoming argument stack slots, and
1482     // the alias isn't otherwise explicit. This is slightly more conservative
1483     // than necessary, because it means that each store effectively depends
1484     // on every argument instead of just those arguments it would clobber.
1485
1486     // Do not flag preceding copytoreg stuff together with the following stuff.
1487     InFlag = SDValue();
1488     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1489       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1490                                RegsToPass[i].second, InFlag);
1491       InFlag = Chain.getValue(1);
1492     }
1493     InFlag =SDValue();
1494   }
1495
1496   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1497   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1498   // node so that legalize doesn't hack it.
1499   bool isDirect = false;
1500   bool isARMFunc = false;
1501   bool isLocalARMFunc = false;
1502   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1503
1504   if (EnableARMLongCalls) {
1505     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1506             && "long-calls with non-static relocation model!");
1507     // Handle a global address or an external symbol. If it's not one of
1508     // those, the target's already in a register, so we don't need to do
1509     // anything extra.
1510     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1511       const GlobalValue *GV = G->getGlobal();
1512       // Create a constant pool entry for the callee address
1513       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1514       ARMConstantPoolValue *CPV =
1515         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1516
1517       // Get the address of the callee into a register
1518       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1519       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1520       Callee = DAG.getLoad(getPointerTy(), dl,
1521                            DAG.getEntryNode(), CPAddr,
1522                            MachinePointerInfo::getConstantPool(),
1523                            false, false, false, 0);
1524     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1525       const char *Sym = S->getSymbol();
1526
1527       // Create a constant pool entry for the callee address
1528       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1529       ARMConstantPoolValue *CPV =
1530         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1531                                       ARMPCLabelIndex, 0);
1532       // Get the address of the callee into a register
1533       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1534       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1535       Callee = DAG.getLoad(getPointerTy(), dl,
1536                            DAG.getEntryNode(), CPAddr,
1537                            MachinePointerInfo::getConstantPool(),
1538                            false, false, false, 0);
1539     }
1540   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1541     const GlobalValue *GV = G->getGlobal();
1542     isDirect = true;
1543     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1544     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1545                    getTargetMachine().getRelocationModel() != Reloc::Static;
1546     isARMFunc = !Subtarget->isThumb() || isStub;
1547     // ARM call to a local ARM function is predicable.
1548     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1549     // tBX takes a register source operand.
1550     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1551       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1552       ARMConstantPoolValue *CPV =
1553         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1554       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1555       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1556       Callee = DAG.getLoad(getPointerTy(), dl,
1557                            DAG.getEntryNode(), CPAddr,
1558                            MachinePointerInfo::getConstantPool(),
1559                            false, false, false, 0);
1560       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1561       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1562                            getPointerTy(), Callee, PICLabel);
1563     } else {
1564       // On ELF targets for PIC code, direct calls should go through the PLT
1565       unsigned OpFlags = 0;
1566       if (Subtarget->isTargetELF() &&
1567                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1568         OpFlags = ARMII::MO_PLT;
1569       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1570     }
1571   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1572     isDirect = true;
1573     bool isStub = Subtarget->isTargetDarwin() &&
1574                   getTargetMachine().getRelocationModel() != Reloc::Static;
1575     isARMFunc = !Subtarget->isThumb() || isStub;
1576     // tBX takes a register source operand.
1577     const char *Sym = S->getSymbol();
1578     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1579       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1580       ARMConstantPoolValue *CPV =
1581         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1582                                       ARMPCLabelIndex, 4);
1583       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1584       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1585       Callee = DAG.getLoad(getPointerTy(), dl,
1586                            DAG.getEntryNode(), CPAddr,
1587                            MachinePointerInfo::getConstantPool(),
1588                            false, false, false, 0);
1589       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1590       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1591                            getPointerTy(), Callee, PICLabel);
1592     } else {
1593       unsigned OpFlags = 0;
1594       // On ELF targets for PIC code, direct calls should go through the PLT
1595       if (Subtarget->isTargetELF() &&
1596                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1597         OpFlags = ARMII::MO_PLT;
1598       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1599     }
1600   }
1601
1602   // FIXME: handle tail calls differently.
1603   unsigned CallOpc;
1604   bool HasMinSizeAttr = MF.getFunction()->getFnAttributes().
1605     hasAttribute(Attributes::MinSize);
1606   if (Subtarget->isThumb()) {
1607     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1608       CallOpc = ARMISD::CALL_NOLINK;
1609     else
1610       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1611   } else {
1612     if (!isDirect && !Subtarget->hasV5TOps())
1613       CallOpc = ARMISD::CALL_NOLINK;
1614     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1615                // Emit regular call when code size is the priority
1616                !HasMinSizeAttr)
1617       // "mov lr, pc; b _foo" to avoid confusing the RSP
1618       CallOpc = ARMISD::CALL_NOLINK;
1619     else
1620       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1621   }
1622
1623   std::vector<SDValue> Ops;
1624   Ops.push_back(Chain);
1625   Ops.push_back(Callee);
1626
1627   // Add argument registers to the end of the list so that they are known live
1628   // into the call.
1629   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1630     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1631                                   RegsToPass[i].second.getValueType()));
1632
1633   // Add a register mask operand representing the call-preserved registers.
1634   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1635   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1636   assert(Mask && "Missing call preserved mask for calling convention");
1637   Ops.push_back(DAG.getRegisterMask(Mask));
1638
1639   if (InFlag.getNode())
1640     Ops.push_back(InFlag);
1641
1642   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1643   if (isTailCall)
1644     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1645
1646   // Returns a chain and a flag for retval copy to use.
1647   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1648   InFlag = Chain.getValue(1);
1649
1650   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1651                              DAG.getIntPtrConstant(0, true), InFlag);
1652   if (!Ins.empty())
1653     InFlag = Chain.getValue(1);
1654
1655   // Handle result values, copying them out of physregs into vregs that we
1656   // return.
1657   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1658                          dl, DAG, InVals);
1659 }
1660
1661 /// HandleByVal - Every parameter *after* a byval parameter is passed
1662 /// on the stack.  Remember the next parameter register to allocate,
1663 /// and then confiscate the rest of the parameter registers to insure
1664 /// this.
1665 void
1666 ARMTargetLowering::HandleByVal(
1667     CCState *State, unsigned &size, unsigned Align) const {
1668   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1669   assert((State->getCallOrPrologue() == Prologue ||
1670           State->getCallOrPrologue() == Call) &&
1671          "unhandled ParmContext");
1672   if ((!State->isFirstByValRegValid()) &&
1673       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1674     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1675       unsigned AlignInRegs = Align / 4;
1676       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1677       for (unsigned i = 0; i < Waste; ++i)
1678         reg = State->AllocateReg(GPRArgRegs, 4);
1679     }
1680     if (reg != 0) {
1681       State->setFirstByValReg(reg);
1682       // At a call site, a byval parameter that is split between
1683       // registers and memory needs its size truncated here.  In a
1684       // function prologue, such byval parameters are reassembled in
1685       // memory, and are not truncated.
1686       if (State->getCallOrPrologue() == Call) {
1687         unsigned excess = 4 * (ARM::R4 - reg);
1688         assert(size >= excess && "expected larger existing stack allocation");
1689         size -= excess;
1690       }
1691     }
1692   }
1693   // Confiscate any remaining parameter registers to preclude their
1694   // assignment to subsequent parameters.
1695   while (State->AllocateReg(GPRArgRegs, 4))
1696     ;
1697 }
1698
1699 /// MatchingStackOffset - Return true if the given stack call argument is
1700 /// already available in the same position (relatively) of the caller's
1701 /// incoming argument stack.
1702 static
1703 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1704                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1705                          const TargetInstrInfo *TII) {
1706   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1707   int FI = INT_MAX;
1708   if (Arg.getOpcode() == ISD::CopyFromReg) {
1709     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1710     if (!TargetRegisterInfo::isVirtualRegister(VR))
1711       return false;
1712     MachineInstr *Def = MRI->getVRegDef(VR);
1713     if (!Def)
1714       return false;
1715     if (!Flags.isByVal()) {
1716       if (!TII->isLoadFromStackSlot(Def, FI))
1717         return false;
1718     } else {
1719       return false;
1720     }
1721   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1722     if (Flags.isByVal())
1723       // ByVal argument is passed in as a pointer but it's now being
1724       // dereferenced. e.g.
1725       // define @foo(%struct.X* %A) {
1726       //   tail call @bar(%struct.X* byval %A)
1727       // }
1728       return false;
1729     SDValue Ptr = Ld->getBasePtr();
1730     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1731     if (!FINode)
1732       return false;
1733     FI = FINode->getIndex();
1734   } else
1735     return false;
1736
1737   assert(FI != INT_MAX);
1738   if (!MFI->isFixedObjectIndex(FI))
1739     return false;
1740   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1741 }
1742
1743 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1744 /// for tail call optimization. Targets which want to do tail call
1745 /// optimization should implement this function.
1746 bool
1747 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1748                                                      CallingConv::ID CalleeCC,
1749                                                      bool isVarArg,
1750                                                      bool isCalleeStructRet,
1751                                                      bool isCallerStructRet,
1752                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1753                                     const SmallVectorImpl<SDValue> &OutVals,
1754                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1755                                                      SelectionDAG& DAG) const {
1756   const Function *CallerF = DAG.getMachineFunction().getFunction();
1757   CallingConv::ID CallerCC = CallerF->getCallingConv();
1758   bool CCMatch = CallerCC == CalleeCC;
1759
1760   // Look for obvious safe cases to perform tail call optimization that do not
1761   // require ABI changes. This is what gcc calls sibcall.
1762
1763   // Do not sibcall optimize vararg calls unless the call site is not passing
1764   // any arguments.
1765   if (isVarArg && !Outs.empty())
1766     return false;
1767
1768   // Also avoid sibcall optimization if either caller or callee uses struct
1769   // return semantics.
1770   if (isCalleeStructRet || isCallerStructRet)
1771     return false;
1772
1773   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1774   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1775   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1776   // support in the assembler and linker to be used. This would need to be
1777   // fixed to fully support tail calls in Thumb1.
1778   //
1779   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1780   // LR.  This means if we need to reload LR, it takes an extra instructions,
1781   // which outweighs the value of the tail call; but here we don't know yet
1782   // whether LR is going to be used.  Probably the right approach is to
1783   // generate the tail call here and turn it back into CALL/RET in
1784   // emitEpilogue if LR is used.
1785
1786   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1787   // but we need to make sure there are enough registers; the only valid
1788   // registers are the 4 used for parameters.  We don't currently do this
1789   // case.
1790   if (Subtarget->isThumb1Only())
1791     return false;
1792
1793   // If the calling conventions do not match, then we'd better make sure the
1794   // results are returned in the same way as what the caller expects.
1795   if (!CCMatch) {
1796     SmallVector<CCValAssign, 16> RVLocs1;
1797     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1798                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1799     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1800
1801     SmallVector<CCValAssign, 16> RVLocs2;
1802     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1803                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1804     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1805
1806     if (RVLocs1.size() != RVLocs2.size())
1807       return false;
1808     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1809       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1810         return false;
1811       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1812         return false;
1813       if (RVLocs1[i].isRegLoc()) {
1814         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1815           return false;
1816       } else {
1817         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1818           return false;
1819       }
1820     }
1821   }
1822
1823   // If Caller's vararg or byval argument has been split between registers and
1824   // stack, do not perform tail call, since part of the argument is in caller's
1825   // local frame.
1826   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1827                                       getInfo<ARMFunctionInfo>();
1828   if (AFI_Caller->getVarArgsRegSaveSize())
1829     return false;
1830
1831   // If the callee takes no arguments then go on to check the results of the
1832   // call.
1833   if (!Outs.empty()) {
1834     // Check if stack adjustment is needed. For now, do not do this if any
1835     // argument is passed on the stack.
1836     SmallVector<CCValAssign, 16> ArgLocs;
1837     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1838                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1839     CCInfo.AnalyzeCallOperands(Outs,
1840                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1841     if (CCInfo.getNextStackOffset()) {
1842       MachineFunction &MF = DAG.getMachineFunction();
1843
1844       // Check if the arguments are already laid out in the right way as
1845       // the caller's fixed stack objects.
1846       MachineFrameInfo *MFI = MF.getFrameInfo();
1847       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1848       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1849       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1850            i != e;
1851            ++i, ++realArgIdx) {
1852         CCValAssign &VA = ArgLocs[i];
1853         EVT RegVT = VA.getLocVT();
1854         SDValue Arg = OutVals[realArgIdx];
1855         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1856         if (VA.getLocInfo() == CCValAssign::Indirect)
1857           return false;
1858         if (VA.needsCustom()) {
1859           // f64 and vector types are split into multiple registers or
1860           // register/stack-slot combinations.  The types will not match
1861           // the registers; give up on memory f64 refs until we figure
1862           // out what to do about this.
1863           if (!VA.isRegLoc())
1864             return false;
1865           if (!ArgLocs[++i].isRegLoc())
1866             return false;
1867           if (RegVT == MVT::v2f64) {
1868             if (!ArgLocs[++i].isRegLoc())
1869               return false;
1870             if (!ArgLocs[++i].isRegLoc())
1871               return false;
1872           }
1873         } else if (!VA.isRegLoc()) {
1874           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1875                                    MFI, MRI, TII))
1876             return false;
1877         }
1878       }
1879     }
1880   }
1881
1882   return true;
1883 }
1884
1885 SDValue
1886 ARMTargetLowering::LowerReturn(SDValue Chain,
1887                                CallingConv::ID CallConv, bool isVarArg,
1888                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1889                                const SmallVectorImpl<SDValue> &OutVals,
1890                                DebugLoc dl, SelectionDAG &DAG) const {
1891
1892   // CCValAssign - represent the assignment of the return value to a location.
1893   SmallVector<CCValAssign, 16> RVLocs;
1894
1895   // CCState - Info about the registers and stack slots.
1896   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1897                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1898
1899   // Analyze outgoing return values.
1900   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1901                                                isVarArg));
1902
1903   // If this is the first return lowered for this function, add
1904   // the regs to the liveout set for the function.
1905   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1906     for (unsigned i = 0; i != RVLocs.size(); ++i)
1907       if (RVLocs[i].isRegLoc())
1908         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1909   }
1910
1911   SDValue Flag;
1912
1913   // Copy the result values into the output registers.
1914   for (unsigned i = 0, realRVLocIdx = 0;
1915        i != RVLocs.size();
1916        ++i, ++realRVLocIdx) {
1917     CCValAssign &VA = RVLocs[i];
1918     assert(VA.isRegLoc() && "Can only return in registers!");
1919
1920     SDValue Arg = OutVals[realRVLocIdx];
1921
1922     switch (VA.getLocInfo()) {
1923     default: llvm_unreachable("Unknown loc info!");
1924     case CCValAssign::Full: break;
1925     case CCValAssign::BCvt:
1926       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1927       break;
1928     }
1929
1930     if (VA.needsCustom()) {
1931       if (VA.getLocVT() == MVT::v2f64) {
1932         // Extract the first half and return it in two registers.
1933         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1934                                    DAG.getConstant(0, MVT::i32));
1935         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1936                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1937
1938         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1939         Flag = Chain.getValue(1);
1940         VA = RVLocs[++i]; // skip ahead to next loc
1941         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1942                                  HalfGPRs.getValue(1), Flag);
1943         Flag = Chain.getValue(1);
1944         VA = RVLocs[++i]; // skip ahead to next loc
1945
1946         // Extract the 2nd half and fall through to handle it as an f64 value.
1947         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1948                           DAG.getConstant(1, MVT::i32));
1949       }
1950       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1951       // available.
1952       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1953                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1954       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1955       Flag = Chain.getValue(1);
1956       VA = RVLocs[++i]; // skip ahead to next loc
1957       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1958                                Flag);
1959     } else
1960       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1961
1962     // Guarantee that all emitted copies are
1963     // stuck together, avoiding something bad.
1964     Flag = Chain.getValue(1);
1965   }
1966
1967   SDValue result;
1968   if (Flag.getNode())
1969     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1970   else // Return Void
1971     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1972
1973   return result;
1974 }
1975
1976 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1977   if (N->getNumValues() != 1)
1978     return false;
1979   if (!N->hasNUsesOfValue(1, 0))
1980     return false;
1981
1982   SDValue TCChain = Chain;
1983   SDNode *Copy = *N->use_begin();
1984   if (Copy->getOpcode() == ISD::CopyToReg) {
1985     // If the copy has a glue operand, we conservatively assume it isn't safe to
1986     // perform a tail call.
1987     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1988       return false;
1989     TCChain = Copy->getOperand(0);
1990   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1991     SDNode *VMov = Copy;
1992     // f64 returned in a pair of GPRs.
1993     SmallPtrSet<SDNode*, 2> Copies;
1994     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1995          UI != UE; ++UI) {
1996       if (UI->getOpcode() != ISD::CopyToReg)
1997         return false;
1998       Copies.insert(*UI);
1999     }
2000     if (Copies.size() > 2)
2001       return false;
2002
2003     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2004          UI != UE; ++UI) {
2005       SDValue UseChain = UI->getOperand(0);
2006       if (Copies.count(UseChain.getNode()))
2007         // Second CopyToReg
2008         Copy = *UI;
2009       else
2010         // First CopyToReg
2011         TCChain = UseChain;
2012     }
2013   } else if (Copy->getOpcode() == ISD::BITCAST) {
2014     // f32 returned in a single GPR.
2015     if (!Copy->hasOneUse())
2016       return false;
2017     Copy = *Copy->use_begin();
2018     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2019       return false;
2020     Chain = Copy->getOperand(0);
2021   } else {
2022     return false;
2023   }
2024
2025   bool HasRet = false;
2026   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2027        UI != UE; ++UI) {
2028     if (UI->getOpcode() != ARMISD::RET_FLAG)
2029       return false;
2030     HasRet = true;
2031   }
2032
2033   if (!HasRet)
2034     return false;
2035
2036   Chain = TCChain;
2037   return true;
2038 }
2039
2040 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2041   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2042     return false;
2043
2044   if (!CI->isTailCall())
2045     return false;
2046
2047   return !Subtarget->isThumb1Only();
2048 }
2049
2050 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2051 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2052 // one of the above mentioned nodes. It has to be wrapped because otherwise
2053 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2054 // be used to form addressing mode. These wrapped nodes will be selected
2055 // into MOVi.
2056 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2057   EVT PtrVT = Op.getValueType();
2058   // FIXME there is no actual debug info here
2059   DebugLoc dl = Op.getDebugLoc();
2060   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2061   SDValue Res;
2062   if (CP->isMachineConstantPoolEntry())
2063     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2064                                     CP->getAlignment());
2065   else
2066     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2067                                     CP->getAlignment());
2068   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2069 }
2070
2071 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2072   return MachineJumpTableInfo::EK_Inline;
2073 }
2074
2075 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2076                                              SelectionDAG &DAG) const {
2077   MachineFunction &MF = DAG.getMachineFunction();
2078   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2079   unsigned ARMPCLabelIndex = 0;
2080   DebugLoc DL = Op.getDebugLoc();
2081   EVT PtrVT = getPointerTy();
2082   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2083   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2084   SDValue CPAddr;
2085   if (RelocM == Reloc::Static) {
2086     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2087   } else {
2088     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2089     ARMPCLabelIndex = AFI->createPICLabelUId();
2090     ARMConstantPoolValue *CPV =
2091       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2092                                       ARMCP::CPBlockAddress, PCAdj);
2093     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2094   }
2095   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2096   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2097                                MachinePointerInfo::getConstantPool(),
2098                                false, false, false, 0);
2099   if (RelocM == Reloc::Static)
2100     return Result;
2101   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2102   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2103 }
2104
2105 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2106 SDValue
2107 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2108                                                  SelectionDAG &DAG) const {
2109   DebugLoc dl = GA->getDebugLoc();
2110   EVT PtrVT = getPointerTy();
2111   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2112   MachineFunction &MF = DAG.getMachineFunction();
2113   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2114   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2115   ARMConstantPoolValue *CPV =
2116     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2117                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2118   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2119   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2120   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2121                          MachinePointerInfo::getConstantPool(),
2122                          false, false, false, 0);
2123   SDValue Chain = Argument.getValue(1);
2124
2125   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2126   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2127
2128   // call __tls_get_addr.
2129   ArgListTy Args;
2130   ArgListEntry Entry;
2131   Entry.Node = Argument;
2132   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2133   Args.push_back(Entry);
2134   // FIXME: is there useful debug info available here?
2135   TargetLowering::CallLoweringInfo CLI(Chain,
2136                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2137                 false, false, false, false,
2138                 0, CallingConv::C, /*isTailCall=*/false,
2139                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2140                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2141   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2142   return CallResult.first;
2143 }
2144
2145 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2146 // "local exec" model.
2147 SDValue
2148 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2149                                         SelectionDAG &DAG,
2150                                         TLSModel::Model model) const {
2151   const GlobalValue *GV = GA->getGlobal();
2152   DebugLoc dl = GA->getDebugLoc();
2153   SDValue Offset;
2154   SDValue Chain = DAG.getEntryNode();
2155   EVT PtrVT = getPointerTy();
2156   // Get the Thread Pointer
2157   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2158
2159   if (model == TLSModel::InitialExec) {
2160     MachineFunction &MF = DAG.getMachineFunction();
2161     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2162     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2163     // Initial exec model.
2164     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2165     ARMConstantPoolValue *CPV =
2166       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2167                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2168                                       true);
2169     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2170     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2171     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2172                          MachinePointerInfo::getConstantPool(),
2173                          false, false, false, 0);
2174     Chain = Offset.getValue(1);
2175
2176     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2177     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2178
2179     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2180                          MachinePointerInfo::getConstantPool(),
2181                          false, false, false, 0);
2182   } else {
2183     // local exec model
2184     assert(model == TLSModel::LocalExec);
2185     ARMConstantPoolValue *CPV =
2186       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2187     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2188     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2189     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2190                          MachinePointerInfo::getConstantPool(),
2191                          false, false, false, 0);
2192   }
2193
2194   // The address of the thread local variable is the add of the thread
2195   // pointer with the offset of the variable.
2196   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2197 }
2198
2199 SDValue
2200 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2201   // TODO: implement the "local dynamic" model
2202   assert(Subtarget->isTargetELF() &&
2203          "TLS not implemented for non-ELF targets");
2204   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2205
2206   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2207
2208   switch (model) {
2209     case TLSModel::GeneralDynamic:
2210     case TLSModel::LocalDynamic:
2211       return LowerToTLSGeneralDynamicModel(GA, DAG);
2212     case TLSModel::InitialExec:
2213     case TLSModel::LocalExec:
2214       return LowerToTLSExecModels(GA, DAG, model);
2215   }
2216   llvm_unreachable("bogus TLS model");
2217 }
2218
2219 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2220                                                  SelectionDAG &DAG) const {
2221   EVT PtrVT = getPointerTy();
2222   DebugLoc dl = Op.getDebugLoc();
2223   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2224   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2225   if (RelocM == Reloc::PIC_) {
2226     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2227     ARMConstantPoolValue *CPV =
2228       ARMConstantPoolConstant::Create(GV,
2229                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2230     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2231     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2232     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2233                                  CPAddr,
2234                                  MachinePointerInfo::getConstantPool(),
2235                                  false, false, false, 0);
2236     SDValue Chain = Result.getValue(1);
2237     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2238     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2239     if (!UseGOTOFF)
2240       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2241                            MachinePointerInfo::getGOT(),
2242                            false, false, false, 0);
2243     return Result;
2244   }
2245
2246   // If we have T2 ops, we can materialize the address directly via movt/movw
2247   // pair. This is always cheaper.
2248   if (Subtarget->useMovt()) {
2249     ++NumMovwMovt;
2250     // FIXME: Once remat is capable of dealing with instructions with register
2251     // operands, expand this into two nodes.
2252     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2253                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2254   } else {
2255     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2256     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2257     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2258                        MachinePointerInfo::getConstantPool(),
2259                        false, false, false, 0);
2260   }
2261 }
2262
2263 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2264                                                     SelectionDAG &DAG) const {
2265   EVT PtrVT = getPointerTy();
2266   DebugLoc dl = Op.getDebugLoc();
2267   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2268   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2269   MachineFunction &MF = DAG.getMachineFunction();
2270   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2271
2272   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2273   // update ARMFastISel::ARMMaterializeGV.
2274   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2275     ++NumMovwMovt;
2276     // FIXME: Once remat is capable of dealing with instructions with register
2277     // operands, expand this into two nodes.
2278     if (RelocM == Reloc::Static)
2279       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2280                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2281
2282     unsigned Wrapper = (RelocM == Reloc::PIC_)
2283       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2284     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2285                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2286     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2287       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2288                            MachinePointerInfo::getGOT(),
2289                            false, false, false, 0);
2290     return Result;
2291   }
2292
2293   unsigned ARMPCLabelIndex = 0;
2294   SDValue CPAddr;
2295   if (RelocM == Reloc::Static) {
2296     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2297   } else {
2298     ARMPCLabelIndex = AFI->createPICLabelUId();
2299     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2300     ARMConstantPoolValue *CPV =
2301       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2302                                       PCAdj);
2303     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2304   }
2305   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2306
2307   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2308                                MachinePointerInfo::getConstantPool(),
2309                                false, false, false, 0);
2310   SDValue Chain = Result.getValue(1);
2311
2312   if (RelocM == Reloc::PIC_) {
2313     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2314     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2315   }
2316
2317   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2318     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2319                          false, false, false, 0);
2320
2321   return Result;
2322 }
2323
2324 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2325                                                     SelectionDAG &DAG) const {
2326   assert(Subtarget->isTargetELF() &&
2327          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2328   MachineFunction &MF = DAG.getMachineFunction();
2329   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2330   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2331   EVT PtrVT = getPointerTy();
2332   DebugLoc dl = Op.getDebugLoc();
2333   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2334   ARMConstantPoolValue *CPV =
2335     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2336                                   ARMPCLabelIndex, PCAdj);
2337   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2338   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2339   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2340                                MachinePointerInfo::getConstantPool(),
2341                                false, false, false, 0);
2342   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2343   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2344 }
2345
2346 SDValue
2347 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2348   DebugLoc dl = Op.getDebugLoc();
2349   SDValue Val = DAG.getConstant(0, MVT::i32);
2350   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2351                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2352                      Op.getOperand(1), Val);
2353 }
2354
2355 SDValue
2356 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2357   DebugLoc dl = Op.getDebugLoc();
2358   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2359                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2360 }
2361
2362 SDValue
2363 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2364                                           const ARMSubtarget *Subtarget) const {
2365   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2366   DebugLoc dl = Op.getDebugLoc();
2367   switch (IntNo) {
2368   default: return SDValue();    // Don't custom lower most intrinsics.
2369   case Intrinsic::arm_thread_pointer: {
2370     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2371     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2372   }
2373   case Intrinsic::eh_sjlj_lsda: {
2374     MachineFunction &MF = DAG.getMachineFunction();
2375     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2376     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2377     EVT PtrVT = getPointerTy();
2378     DebugLoc dl = Op.getDebugLoc();
2379     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2380     SDValue CPAddr;
2381     unsigned PCAdj = (RelocM != Reloc::PIC_)
2382       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2383     ARMConstantPoolValue *CPV =
2384       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2385                                       ARMCP::CPLSDA, PCAdj);
2386     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2387     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2388     SDValue Result =
2389       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2390                   MachinePointerInfo::getConstantPool(),
2391                   false, false, false, 0);
2392
2393     if (RelocM == Reloc::PIC_) {
2394       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2395       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2396     }
2397     return Result;
2398   }
2399   case Intrinsic::arm_neon_vmulls:
2400   case Intrinsic::arm_neon_vmullu: {
2401     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2402       ? ARMISD::VMULLs : ARMISD::VMULLu;
2403     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2404                        Op.getOperand(1), Op.getOperand(2));
2405   }
2406   }
2407 }
2408
2409 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2410                                const ARMSubtarget *Subtarget) {
2411   DebugLoc dl = Op.getDebugLoc();
2412   if (!Subtarget->hasDataBarrier()) {
2413     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2414     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2415     // here.
2416     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2417            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2418     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2419                        DAG.getConstant(0, MVT::i32));
2420   }
2421
2422   SDValue Op5 = Op.getOperand(5);
2423   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2424   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2425   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2426   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2427
2428   ARM_MB::MemBOpt DMBOpt;
2429   if (isDeviceBarrier)
2430     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2431   else
2432     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2433   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2434                      DAG.getConstant(DMBOpt, MVT::i32));
2435 }
2436
2437
2438 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2439                                  const ARMSubtarget *Subtarget) {
2440   // FIXME: handle "fence singlethread" more efficiently.
2441   DebugLoc dl = Op.getDebugLoc();
2442   if (!Subtarget->hasDataBarrier()) {
2443     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2444     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2445     // here.
2446     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2447            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2448     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2449                        DAG.getConstant(0, MVT::i32));
2450   }
2451
2452   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2453                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2454 }
2455
2456 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2457                              const ARMSubtarget *Subtarget) {
2458   // ARM pre v5TE and Thumb1 does not have preload instructions.
2459   if (!(Subtarget->isThumb2() ||
2460         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2461     // Just preserve the chain.
2462     return Op.getOperand(0);
2463
2464   DebugLoc dl = Op.getDebugLoc();
2465   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2466   if (!isRead &&
2467       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2468     // ARMv7 with MP extension has PLDW.
2469     return Op.getOperand(0);
2470
2471   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2472   if (Subtarget->isThumb()) {
2473     // Invert the bits.
2474     isRead = ~isRead & 1;
2475     isData = ~isData & 1;
2476   }
2477
2478   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2479                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2480                      DAG.getConstant(isData, MVT::i32));
2481 }
2482
2483 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2484   MachineFunction &MF = DAG.getMachineFunction();
2485   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2486
2487   // vastart just stores the address of the VarArgsFrameIndex slot into the
2488   // memory location argument.
2489   DebugLoc dl = Op.getDebugLoc();
2490   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2491   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2492   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2493   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2494                       MachinePointerInfo(SV), false, false, 0);
2495 }
2496
2497 SDValue
2498 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2499                                         SDValue &Root, SelectionDAG &DAG,
2500                                         DebugLoc dl) const {
2501   MachineFunction &MF = DAG.getMachineFunction();
2502   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2503
2504   const TargetRegisterClass *RC;
2505   if (AFI->isThumb1OnlyFunction())
2506     RC = &ARM::tGPRRegClass;
2507   else
2508     RC = &ARM::GPRRegClass;
2509
2510   // Transform the arguments stored in physical registers into virtual ones.
2511   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2512   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2513
2514   SDValue ArgValue2;
2515   if (NextVA.isMemLoc()) {
2516     MachineFrameInfo *MFI = MF.getFrameInfo();
2517     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2518
2519     // Create load node to retrieve arguments from the stack.
2520     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2521     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2522                             MachinePointerInfo::getFixedStack(FI),
2523                             false, false, false, 0);
2524   } else {
2525     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2526     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2527   }
2528
2529   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2530 }
2531
2532 void
2533 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2534                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2535   const {
2536   unsigned NumGPRs;
2537   if (CCInfo.isFirstByValRegValid())
2538     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2539   else {
2540     unsigned int firstUnalloced;
2541     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2542                                                 sizeof(GPRArgRegs) /
2543                                                 sizeof(GPRArgRegs[0]));
2544     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2545   }
2546
2547   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2548   VARegSize = NumGPRs * 4;
2549   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2550 }
2551
2552 // The remaining GPRs hold either the beginning of variable-argument
2553 // data, or the beginning of an aggregate passed by value (usuall
2554 // byval).  Either way, we allocate stack slots adjacent to the data
2555 // provided by our caller, and store the unallocated registers there.
2556 // If this is a variadic function, the va_list pointer will begin with
2557 // these values; otherwise, this reassembles a (byval) structure that
2558 // was split between registers and memory.
2559 void
2560 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2561                                         DebugLoc dl, SDValue &Chain,
2562                                         const Value *OrigArg,
2563                                         unsigned OffsetFromOrigArg,
2564                                         unsigned ArgOffset,
2565                                         bool ForceMutable) const {
2566   MachineFunction &MF = DAG.getMachineFunction();
2567   MachineFrameInfo *MFI = MF.getFrameInfo();
2568   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2569   unsigned firstRegToSaveIndex;
2570   if (CCInfo.isFirstByValRegValid())
2571     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2572   else {
2573     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2574       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2575   }
2576
2577   unsigned VARegSize, VARegSaveSize;
2578   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2579   if (VARegSaveSize) {
2580     // If this function is vararg, store any remaining integer argument regs
2581     // to their spots on the stack so that they may be loaded by deferencing
2582     // the result of va_next.
2583     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2584     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2585                                                      ArgOffset + VARegSaveSize
2586                                                      - VARegSize,
2587                                                      false));
2588     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2589                                     getPointerTy());
2590
2591     SmallVector<SDValue, 4> MemOps;
2592     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2593       const TargetRegisterClass *RC;
2594       if (AFI->isThumb1OnlyFunction())
2595         RC = &ARM::tGPRRegClass;
2596       else
2597         RC = &ARM::GPRRegClass;
2598
2599       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2600       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2601       SDValue Store =
2602         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2603                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2604                      false, false, 0);
2605       MemOps.push_back(Store);
2606       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2607                         DAG.getConstant(4, getPointerTy()));
2608     }
2609     if (!MemOps.empty())
2610       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2611                           &MemOps[0], MemOps.size());
2612   } else
2613     // This will point to the next argument passed via stack.
2614     AFI->setVarArgsFrameIndex(
2615         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2616 }
2617
2618 SDValue
2619 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2620                                         CallingConv::ID CallConv, bool isVarArg,
2621                                         const SmallVectorImpl<ISD::InputArg>
2622                                           &Ins,
2623                                         DebugLoc dl, SelectionDAG &DAG,
2624                                         SmallVectorImpl<SDValue> &InVals)
2625                                           const {
2626   MachineFunction &MF = DAG.getMachineFunction();
2627   MachineFrameInfo *MFI = MF.getFrameInfo();
2628
2629   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2630
2631   // Assign locations to all of the incoming arguments.
2632   SmallVector<CCValAssign, 16> ArgLocs;
2633   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2634                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2635   CCInfo.AnalyzeFormalArguments(Ins,
2636                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2637                                                   isVarArg));
2638   
2639   SmallVector<SDValue, 16> ArgValues;
2640   int lastInsIndex = -1;
2641   SDValue ArgValue;
2642   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2643   unsigned CurArgIdx = 0;
2644   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2645     CCValAssign &VA = ArgLocs[i];
2646     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2647     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2648     // Arguments stored in registers.
2649     if (VA.isRegLoc()) {
2650       EVT RegVT = VA.getLocVT();
2651
2652       if (VA.needsCustom()) {
2653         // f64 and vector types are split up into multiple registers or
2654         // combinations of registers and stack slots.
2655         if (VA.getLocVT() == MVT::v2f64) {
2656           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2657                                                    Chain, DAG, dl);
2658           VA = ArgLocs[++i]; // skip ahead to next loc
2659           SDValue ArgValue2;
2660           if (VA.isMemLoc()) {
2661             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2662             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2663             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2664                                     MachinePointerInfo::getFixedStack(FI),
2665                                     false, false, false, 0);
2666           } else {
2667             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2668                                              Chain, DAG, dl);
2669           }
2670           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2671           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2672                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2673           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2674                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2675         } else
2676           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2677
2678       } else {
2679         const TargetRegisterClass *RC;
2680
2681         if (RegVT == MVT::f32)
2682           RC = &ARM::SPRRegClass;
2683         else if (RegVT == MVT::f64)
2684           RC = &ARM::DPRRegClass;
2685         else if (RegVT == MVT::v2f64)
2686           RC = &ARM::QPRRegClass;
2687         else if (RegVT == MVT::i32)
2688           RC = AFI->isThumb1OnlyFunction() ?
2689             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2690             (const TargetRegisterClass*)&ARM::GPRRegClass;
2691         else
2692           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2693
2694         // Transform the arguments in physical registers into virtual ones.
2695         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2696         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2697       }
2698
2699       // If this is an 8 or 16-bit value, it is really passed promoted
2700       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2701       // truncate to the right size.
2702       switch (VA.getLocInfo()) {
2703       default: llvm_unreachable("Unknown loc info!");
2704       case CCValAssign::Full: break;
2705       case CCValAssign::BCvt:
2706         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2707         break;
2708       case CCValAssign::SExt:
2709         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2710                                DAG.getValueType(VA.getValVT()));
2711         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2712         break;
2713       case CCValAssign::ZExt:
2714         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2715                                DAG.getValueType(VA.getValVT()));
2716         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2717         break;
2718       }
2719
2720       InVals.push_back(ArgValue);
2721
2722     } else { // VA.isRegLoc()
2723
2724       // sanity check
2725       assert(VA.isMemLoc());
2726       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2727
2728       int index = ArgLocs[i].getValNo();
2729
2730       // Some Ins[] entries become multiple ArgLoc[] entries.
2731       // Process them only once.
2732       if (index != lastInsIndex)
2733         {
2734           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2735           // FIXME: For now, all byval parameter objects are marked mutable.
2736           // This can be changed with more analysis.
2737           // In case of tail call optimization mark all arguments mutable.
2738           // Since they could be overwritten by lowering of arguments in case of
2739           // a tail call.
2740           if (Flags.isByVal()) {
2741             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2742             if (!AFI->getVarArgsFrameIndex()) {
2743               VarArgStyleRegisters(CCInfo, DAG,
2744                                    dl, Chain, CurOrigArg,
2745                                    Ins[VA.getValNo()].PartOffset,
2746                                    VA.getLocMemOffset(),
2747                                    true /*force mutable frames*/);
2748               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2749               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2750             } else {
2751               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2752                                               VA.getLocMemOffset(), false);
2753               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2754             }
2755           } else {
2756             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2757                                             VA.getLocMemOffset(), true);
2758
2759             // Create load nodes to retrieve arguments from the stack.
2760             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2761             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2762                                          MachinePointerInfo::getFixedStack(FI),
2763                                          false, false, false, 0));
2764           }
2765           lastInsIndex = index;
2766         }
2767     }
2768   }
2769
2770   // varargs
2771   if (isVarArg)
2772     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2773                          CCInfo.getNextStackOffset());
2774
2775   return Chain;
2776 }
2777
2778 /// isFloatingPointZero - Return true if this is +0.0.
2779 static bool isFloatingPointZero(SDValue Op) {
2780   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2781     return CFP->getValueAPF().isPosZero();
2782   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2783     // Maybe this has already been legalized into the constant pool?
2784     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2785       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2786       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2787         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2788           return CFP->getValueAPF().isPosZero();
2789     }
2790   }
2791   return false;
2792 }
2793
2794 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2795 /// the given operands.
2796 SDValue
2797 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2798                              SDValue &ARMcc, SelectionDAG &DAG,
2799                              DebugLoc dl) const {
2800   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2801     unsigned C = RHSC->getZExtValue();
2802     if (!isLegalICmpImmediate(C)) {
2803       // Constant does not fit, try adjusting it by one?
2804       switch (CC) {
2805       default: break;
2806       case ISD::SETLT:
2807       case ISD::SETGE:
2808         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2809           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2810           RHS = DAG.getConstant(C-1, MVT::i32);
2811         }
2812         break;
2813       case ISD::SETULT:
2814       case ISD::SETUGE:
2815         if (C != 0 && isLegalICmpImmediate(C-1)) {
2816           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2817           RHS = DAG.getConstant(C-1, MVT::i32);
2818         }
2819         break;
2820       case ISD::SETLE:
2821       case ISD::SETGT:
2822         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2823           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2824           RHS = DAG.getConstant(C+1, MVT::i32);
2825         }
2826         break;
2827       case ISD::SETULE:
2828       case ISD::SETUGT:
2829         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2830           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2831           RHS = DAG.getConstant(C+1, MVT::i32);
2832         }
2833         break;
2834       }
2835     }
2836   }
2837
2838   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2839   ARMISD::NodeType CompareType;
2840   switch (CondCode) {
2841   default:
2842     CompareType = ARMISD::CMP;
2843     break;
2844   case ARMCC::EQ:
2845   case ARMCC::NE:
2846     // Uses only Z Flag
2847     CompareType = ARMISD::CMPZ;
2848     break;
2849   }
2850   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2851   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2852 }
2853
2854 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2855 SDValue
2856 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2857                              DebugLoc dl) const {
2858   SDValue Cmp;
2859   if (!isFloatingPointZero(RHS))
2860     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2861   else
2862     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2863   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2864 }
2865
2866 /// duplicateCmp - Glue values can have only one use, so this function
2867 /// duplicates a comparison node.
2868 SDValue
2869 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2870   unsigned Opc = Cmp.getOpcode();
2871   DebugLoc DL = Cmp.getDebugLoc();
2872   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2873     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2874
2875   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2876   Cmp = Cmp.getOperand(0);
2877   Opc = Cmp.getOpcode();
2878   if (Opc == ARMISD::CMPFP)
2879     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2880   else {
2881     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2882     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2883   }
2884   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2885 }
2886
2887 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2888   SDValue Cond = Op.getOperand(0);
2889   SDValue SelectTrue = Op.getOperand(1);
2890   SDValue SelectFalse = Op.getOperand(2);
2891   DebugLoc dl = Op.getDebugLoc();
2892
2893   // Convert:
2894   //
2895   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2896   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2897   //
2898   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2899     const ConstantSDNode *CMOVTrue =
2900       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2901     const ConstantSDNode *CMOVFalse =
2902       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2903
2904     if (CMOVTrue && CMOVFalse) {
2905       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2906       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2907
2908       SDValue True;
2909       SDValue False;
2910       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2911         True = SelectTrue;
2912         False = SelectFalse;
2913       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2914         True = SelectFalse;
2915         False = SelectTrue;
2916       }
2917
2918       if (True.getNode() && False.getNode()) {
2919         EVT VT = Op.getValueType();
2920         SDValue ARMcc = Cond.getOperand(2);
2921         SDValue CCR = Cond.getOperand(3);
2922         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2923         assert(True.getValueType() == VT);
2924         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2925       }
2926     }
2927   }
2928
2929   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2930   // undefined bits before doing a full-word comparison with zero.
2931   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2932                      DAG.getConstant(1, Cond.getValueType()));
2933
2934   return DAG.getSelectCC(dl, Cond,
2935                          DAG.getConstant(0, Cond.getValueType()),
2936                          SelectTrue, SelectFalse, ISD::SETNE);
2937 }
2938
2939 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2940   EVT VT = Op.getValueType();
2941   SDValue LHS = Op.getOperand(0);
2942   SDValue RHS = Op.getOperand(1);
2943   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2944   SDValue TrueVal = Op.getOperand(2);
2945   SDValue FalseVal = Op.getOperand(3);
2946   DebugLoc dl = Op.getDebugLoc();
2947
2948   if (LHS.getValueType() == MVT::i32) {
2949     SDValue ARMcc;
2950     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2951     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2952     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2953   }
2954
2955   ARMCC::CondCodes CondCode, CondCode2;
2956   FPCCToARMCC(CC, CondCode, CondCode2);
2957
2958   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2959   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2960   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2961   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2962                                ARMcc, CCR, Cmp);
2963   if (CondCode2 != ARMCC::AL) {
2964     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2965     // FIXME: Needs another CMP because flag can have but one use.
2966     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2967     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2968                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2969   }
2970   return Result;
2971 }
2972
2973 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2974 /// to morph to an integer compare sequence.
2975 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2976                            const ARMSubtarget *Subtarget) {
2977   SDNode *N = Op.getNode();
2978   if (!N->hasOneUse())
2979     // Otherwise it requires moving the value from fp to integer registers.
2980     return false;
2981   if (!N->getNumValues())
2982     return false;
2983   EVT VT = Op.getValueType();
2984   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2985     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2986     // vmrs are very slow, e.g. cortex-a8.
2987     return false;
2988
2989   if (isFloatingPointZero(Op)) {
2990     SeenZero = true;
2991     return true;
2992   }
2993   return ISD::isNormalLoad(N);
2994 }
2995
2996 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2997   if (isFloatingPointZero(Op))
2998     return DAG.getConstant(0, MVT::i32);
2999
3000   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3001     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3002                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3003                        Ld->isVolatile(), Ld->isNonTemporal(),
3004                        Ld->isInvariant(), Ld->getAlignment());
3005
3006   llvm_unreachable("Unknown VFP cmp argument!");
3007 }
3008
3009 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3010                            SDValue &RetVal1, SDValue &RetVal2) {
3011   if (isFloatingPointZero(Op)) {
3012     RetVal1 = DAG.getConstant(0, MVT::i32);
3013     RetVal2 = DAG.getConstant(0, MVT::i32);
3014     return;
3015   }
3016
3017   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3018     SDValue Ptr = Ld->getBasePtr();
3019     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3020                           Ld->getChain(), Ptr,
3021                           Ld->getPointerInfo(),
3022                           Ld->isVolatile(), Ld->isNonTemporal(),
3023                           Ld->isInvariant(), Ld->getAlignment());
3024
3025     EVT PtrType = Ptr.getValueType();
3026     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3027     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3028                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3029     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3030                           Ld->getChain(), NewPtr,
3031                           Ld->getPointerInfo().getWithOffset(4),
3032                           Ld->isVolatile(), Ld->isNonTemporal(),
3033                           Ld->isInvariant(), NewAlign);
3034     return;
3035   }
3036
3037   llvm_unreachable("Unknown VFP cmp argument!");
3038 }
3039
3040 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3041 /// f32 and even f64 comparisons to integer ones.
3042 SDValue
3043 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3044   SDValue Chain = Op.getOperand(0);
3045   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3046   SDValue LHS = Op.getOperand(2);
3047   SDValue RHS = Op.getOperand(3);
3048   SDValue Dest = Op.getOperand(4);
3049   DebugLoc dl = Op.getDebugLoc();
3050
3051   bool LHSSeenZero = false;
3052   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3053   bool RHSSeenZero = false;
3054   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3055   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3056     // If unsafe fp math optimization is enabled and there are no other uses of
3057     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3058     // to an integer comparison.
3059     if (CC == ISD::SETOEQ)
3060       CC = ISD::SETEQ;
3061     else if (CC == ISD::SETUNE)
3062       CC = ISD::SETNE;
3063
3064     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3065     SDValue ARMcc;
3066     if (LHS.getValueType() == MVT::f32) {
3067       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3068                         bitcastf32Toi32(LHS, DAG), Mask);
3069       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3070                         bitcastf32Toi32(RHS, DAG), Mask);
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     SDValue LHS1, LHS2;
3078     SDValue RHS1, RHS2;
3079     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3080     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3081     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3082     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3083     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3084     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3085     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3086     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3087     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3088   }
3089
3090   return SDValue();
3091 }
3092
3093 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3094   SDValue Chain = Op.getOperand(0);
3095   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3096   SDValue LHS = Op.getOperand(2);
3097   SDValue RHS = Op.getOperand(3);
3098   SDValue Dest = Op.getOperand(4);
3099   DebugLoc dl = Op.getDebugLoc();
3100
3101   if (LHS.getValueType() == MVT::i32) {
3102     SDValue ARMcc;
3103     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3104     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3105     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3106                        Chain, Dest, ARMcc, CCR, Cmp);
3107   }
3108
3109   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3110
3111   if (getTargetMachine().Options.UnsafeFPMath &&
3112       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3113        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3114     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3115     if (Result.getNode())
3116       return Result;
3117   }
3118
3119   ARMCC::CondCodes CondCode, CondCode2;
3120   FPCCToARMCC(CC, CondCode, CondCode2);
3121
3122   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3123   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3124   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3125   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3126   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3127   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3128   if (CondCode2 != ARMCC::AL) {
3129     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3130     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3131     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3132   }
3133   return Res;
3134 }
3135
3136 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3137   SDValue Chain = Op.getOperand(0);
3138   SDValue Table = Op.getOperand(1);
3139   SDValue Index = Op.getOperand(2);
3140   DebugLoc dl = Op.getDebugLoc();
3141
3142   EVT PTy = getPointerTy();
3143   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3144   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3145   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3146   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3147   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3148   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3149   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3150   if (Subtarget->isThumb2()) {
3151     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3152     // which does another jump to the destination. This also makes it easier
3153     // to translate it to TBB / TBH later.
3154     // FIXME: This might not work if the function is extremely large.
3155     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3156                        Addr, Op.getOperand(2), JTI, UId);
3157   }
3158   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3159     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3160                        MachinePointerInfo::getJumpTable(),
3161                        false, false, false, 0);
3162     Chain = Addr.getValue(1);
3163     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3164     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3165   } else {
3166     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3167                        MachinePointerInfo::getJumpTable(),
3168                        false, false, false, 0);
3169     Chain = Addr.getValue(1);
3170     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3171   }
3172 }
3173
3174 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3175   EVT VT = Op.getValueType();
3176   DebugLoc dl = Op.getDebugLoc();
3177
3178   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3179     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3180       return Op;
3181     return DAG.UnrollVectorOp(Op.getNode());
3182   }
3183
3184   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3185          "Invalid type for custom lowering!");
3186   if (VT != MVT::v4i16)
3187     return DAG.UnrollVectorOp(Op.getNode());
3188
3189   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3190   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3191 }
3192
3193 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3194   EVT VT = Op.getValueType();
3195   if (VT.isVector())
3196     return LowerVectorFP_TO_INT(Op, DAG);
3197
3198   DebugLoc dl = Op.getDebugLoc();
3199   unsigned Opc;
3200
3201   switch (Op.getOpcode()) {
3202   default: llvm_unreachable("Invalid opcode!");
3203   case ISD::FP_TO_SINT:
3204     Opc = ARMISD::FTOSI;
3205     break;
3206   case ISD::FP_TO_UINT:
3207     Opc = ARMISD::FTOUI;
3208     break;
3209   }
3210   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3211   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3212 }
3213
3214 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3215   EVT VT = Op.getValueType();
3216   DebugLoc dl = Op.getDebugLoc();
3217
3218   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3219     if (VT.getVectorElementType() == MVT::f32)
3220       return Op;
3221     return DAG.UnrollVectorOp(Op.getNode());
3222   }
3223
3224   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3225          "Invalid type for custom lowering!");
3226   if (VT != MVT::v4f32)
3227     return DAG.UnrollVectorOp(Op.getNode());
3228
3229   unsigned CastOpc;
3230   unsigned Opc;
3231   switch (Op.getOpcode()) {
3232   default: llvm_unreachable("Invalid opcode!");
3233   case ISD::SINT_TO_FP:
3234     CastOpc = ISD::SIGN_EXTEND;
3235     Opc = ISD::SINT_TO_FP;
3236     break;
3237   case ISD::UINT_TO_FP:
3238     CastOpc = ISD::ZERO_EXTEND;
3239     Opc = ISD::UINT_TO_FP;
3240     break;
3241   }
3242
3243   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3244   return DAG.getNode(Opc, dl, VT, Op);
3245 }
3246
3247 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3248   EVT VT = Op.getValueType();
3249   if (VT.isVector())
3250     return LowerVectorINT_TO_FP(Op, DAG);
3251
3252   DebugLoc dl = Op.getDebugLoc();
3253   unsigned Opc;
3254
3255   switch (Op.getOpcode()) {
3256   default: llvm_unreachable("Invalid opcode!");
3257   case ISD::SINT_TO_FP:
3258     Opc = ARMISD::SITOF;
3259     break;
3260   case ISD::UINT_TO_FP:
3261     Opc = ARMISD::UITOF;
3262     break;
3263   }
3264
3265   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3266   return DAG.getNode(Opc, dl, VT, Op);
3267 }
3268
3269 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3270   // Implement fcopysign with a fabs and a conditional fneg.
3271   SDValue Tmp0 = Op.getOperand(0);
3272   SDValue Tmp1 = Op.getOperand(1);
3273   DebugLoc dl = Op.getDebugLoc();
3274   EVT VT = Op.getValueType();
3275   EVT SrcVT = Tmp1.getValueType();
3276   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3277     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3278   bool UseNEON = !InGPR && Subtarget->hasNEON();
3279
3280   if (UseNEON) {
3281     // Use VBSL to copy the sign bit.
3282     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3283     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3284                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3285     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3286     if (VT == MVT::f64)
3287       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3288                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3289                          DAG.getConstant(32, MVT::i32));
3290     else /*if (VT == MVT::f32)*/
3291       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3292     if (SrcVT == MVT::f32) {
3293       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3294       if (VT == MVT::f64)
3295         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3296                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3297                            DAG.getConstant(32, MVT::i32));
3298     } else if (VT == MVT::f32)
3299       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3300                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3301                          DAG.getConstant(32, MVT::i32));
3302     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3303     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3304
3305     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3306                                             MVT::i32);
3307     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3308     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3309                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3310
3311     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3312                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3313                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3314     if (VT == MVT::f32) {
3315       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3316       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3317                         DAG.getConstant(0, MVT::i32));
3318     } else {
3319       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3320     }
3321
3322     return Res;
3323   }
3324
3325   // Bitcast operand 1 to i32.
3326   if (SrcVT == MVT::f64)
3327     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3328                        &Tmp1, 1).getValue(1);
3329   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3330
3331   // Or in the signbit with integer operations.
3332   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3333   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3334   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3335   if (VT == MVT::f32) {
3336     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3337                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3338     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3339                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3340   }
3341
3342   // f64: Or the high part with signbit and then combine two parts.
3343   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3344                      &Tmp0, 1);
3345   SDValue Lo = Tmp0.getValue(0);
3346   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3347   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3348   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3349 }
3350
3351 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3352   MachineFunction &MF = DAG.getMachineFunction();
3353   MachineFrameInfo *MFI = MF.getFrameInfo();
3354   MFI->setReturnAddressIsTaken(true);
3355
3356   EVT VT = Op.getValueType();
3357   DebugLoc dl = Op.getDebugLoc();
3358   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3359   if (Depth) {
3360     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3361     SDValue Offset = DAG.getConstant(4, MVT::i32);
3362     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3363                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3364                        MachinePointerInfo(), false, false, false, 0);
3365   }
3366
3367   // Return LR, which contains the return address. Mark it an implicit live-in.
3368   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3369   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3370 }
3371
3372 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3373   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3374   MFI->setFrameAddressIsTaken(true);
3375
3376   EVT VT = Op.getValueType();
3377   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3378   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3379   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3380     ? ARM::R7 : ARM::R11;
3381   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3382   while (Depth--)
3383     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3384                             MachinePointerInfo(),
3385                             false, false, false, 0);
3386   return FrameAddr;
3387 }
3388
3389 /// ExpandBITCAST - If the target supports VFP, this function is called to
3390 /// expand a bit convert where either the source or destination type is i64 to
3391 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3392 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3393 /// vectors), since the legalizer won't know what to do with that.
3394 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3396   DebugLoc dl = N->getDebugLoc();
3397   SDValue Op = N->getOperand(0);
3398
3399   // This function is only supposed to be called for i64 types, either as the
3400   // source or destination of the bit convert.
3401   EVT SrcVT = Op.getValueType();
3402   EVT DstVT = N->getValueType(0);
3403   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3404          "ExpandBITCAST called for non-i64 type");
3405
3406   // Turn i64->f64 into VMOVDRR.
3407   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3408     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3409                              DAG.getConstant(0, MVT::i32));
3410     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3411                              DAG.getConstant(1, MVT::i32));
3412     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3413                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3414   }
3415
3416   // Turn f64->i64 into VMOVRRD.
3417   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3418     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3419                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3420     // Merge the pieces into a single i64 value.
3421     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3422   }
3423
3424   return SDValue();
3425 }
3426
3427 /// getZeroVector - Returns a vector of specified type with all zero elements.
3428 /// Zero vectors are used to represent vector negation and in those cases
3429 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3430 /// not support i64 elements, so sometimes the zero vectors will need to be
3431 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3432 /// zero vector.
3433 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3434   assert(VT.isVector() && "Expected a vector type");
3435   // The canonical modified immediate encoding of a zero vector is....0!
3436   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3437   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3438   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3439   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3440 }
3441
3442 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3443 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3444 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3445                                                 SelectionDAG &DAG) const {
3446   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3447   EVT VT = Op.getValueType();
3448   unsigned VTBits = VT.getSizeInBits();
3449   DebugLoc dl = Op.getDebugLoc();
3450   SDValue ShOpLo = Op.getOperand(0);
3451   SDValue ShOpHi = Op.getOperand(1);
3452   SDValue ShAmt  = Op.getOperand(2);
3453   SDValue ARMcc;
3454   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3455
3456   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3457
3458   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3459                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3460   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3461   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3462                                    DAG.getConstant(VTBits, MVT::i32));
3463   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3464   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3465   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3466
3467   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3468   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3469                           ARMcc, DAG, dl);
3470   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3471   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3472                            CCR, Cmp);
3473
3474   SDValue Ops[2] = { Lo, Hi };
3475   return DAG.getMergeValues(Ops, 2, dl);
3476 }
3477
3478 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3479 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3480 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3481                                                SelectionDAG &DAG) const {
3482   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3483   EVT VT = Op.getValueType();
3484   unsigned VTBits = VT.getSizeInBits();
3485   DebugLoc dl = Op.getDebugLoc();
3486   SDValue ShOpLo = Op.getOperand(0);
3487   SDValue ShOpHi = Op.getOperand(1);
3488   SDValue ShAmt  = Op.getOperand(2);
3489   SDValue ARMcc;
3490
3491   assert(Op.getOpcode() == ISD::SHL_PARTS);
3492   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3493                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3494   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3495   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3496                                    DAG.getConstant(VTBits, MVT::i32));
3497   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3498   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3499
3500   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3501   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3502   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3503                           ARMcc, DAG, dl);
3504   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3505   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3506                            CCR, Cmp);
3507
3508   SDValue Ops[2] = { Lo, Hi };
3509   return DAG.getMergeValues(Ops, 2, dl);
3510 }
3511
3512 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3513                                             SelectionDAG &DAG) const {
3514   // The rounding mode is in bits 23:22 of the FPSCR.
3515   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3516   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3517   // so that the shift + and get folded into a bitfield extract.
3518   DebugLoc dl = Op.getDebugLoc();
3519   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3520                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3521                                               MVT::i32));
3522   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3523                                   DAG.getConstant(1U << 22, MVT::i32));
3524   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3525                               DAG.getConstant(22, MVT::i32));
3526   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3527                      DAG.getConstant(3, MVT::i32));
3528 }
3529
3530 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3531                          const ARMSubtarget *ST) {
3532   EVT VT = N->getValueType(0);
3533   DebugLoc dl = N->getDebugLoc();
3534
3535   if (!ST->hasV6T2Ops())
3536     return SDValue();
3537
3538   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3539   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3540 }
3541
3542 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3543                           const ARMSubtarget *ST) {
3544   EVT VT = N->getValueType(0);
3545   DebugLoc dl = N->getDebugLoc();
3546
3547   if (!VT.isVector())
3548     return SDValue();
3549
3550   // Lower vector shifts on NEON to use VSHL.
3551   assert(ST->hasNEON() && "unexpected vector shift");
3552
3553   // Left shifts translate directly to the vshiftu intrinsic.
3554   if (N->getOpcode() == ISD::SHL)
3555     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3556                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3557                        N->getOperand(0), N->getOperand(1));
3558
3559   assert((N->getOpcode() == ISD::SRA ||
3560           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3561
3562   // NEON uses the same intrinsics for both left and right shifts.  For
3563   // right shifts, the shift amounts are negative, so negate the vector of
3564   // shift amounts.
3565   EVT ShiftVT = N->getOperand(1).getValueType();
3566   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3567                                      getZeroVector(ShiftVT, DAG, dl),
3568                                      N->getOperand(1));
3569   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3570                              Intrinsic::arm_neon_vshifts :
3571                              Intrinsic::arm_neon_vshiftu);
3572   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3573                      DAG.getConstant(vshiftInt, MVT::i32),
3574                      N->getOperand(0), NegatedCount);
3575 }
3576
3577 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3578                                 const ARMSubtarget *ST) {
3579   EVT VT = N->getValueType(0);
3580   DebugLoc dl = N->getDebugLoc();
3581
3582   // We can get here for a node like i32 = ISD::SHL i32, i64
3583   if (VT != MVT::i64)
3584     return SDValue();
3585
3586   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3587          "Unknown shift to lower!");
3588
3589   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3590   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3591       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3592     return SDValue();
3593
3594   // If we are in thumb mode, we don't have RRX.
3595   if (ST->isThumb1Only()) return SDValue();
3596
3597   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3598   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3599                            DAG.getConstant(0, MVT::i32));
3600   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3601                            DAG.getConstant(1, MVT::i32));
3602
3603   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3604   // captures the result into a carry flag.
3605   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3606   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3607
3608   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3609   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3610
3611   // Merge the pieces into a single i64 value.
3612  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3613 }
3614
3615 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3616   SDValue TmpOp0, TmpOp1;
3617   bool Invert = false;
3618   bool Swap = false;
3619   unsigned Opc = 0;
3620
3621   SDValue Op0 = Op.getOperand(0);
3622   SDValue Op1 = Op.getOperand(1);
3623   SDValue CC = Op.getOperand(2);
3624   EVT VT = Op.getValueType();
3625   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3626   DebugLoc dl = Op.getDebugLoc();
3627
3628   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3629     switch (SetCCOpcode) {
3630     default: llvm_unreachable("Illegal FP comparison");
3631     case ISD::SETUNE:
3632     case ISD::SETNE:  Invert = true; // Fallthrough
3633     case ISD::SETOEQ:
3634     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3635     case ISD::SETOLT:
3636     case ISD::SETLT: Swap = true; // Fallthrough
3637     case ISD::SETOGT:
3638     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3639     case ISD::SETOLE:
3640     case ISD::SETLE:  Swap = true; // Fallthrough
3641     case ISD::SETOGE:
3642     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3643     case ISD::SETUGE: Swap = true; // Fallthrough
3644     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3645     case ISD::SETUGT: Swap = true; // Fallthrough
3646     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3647     case ISD::SETUEQ: Invert = true; // Fallthrough
3648     case ISD::SETONE:
3649       // Expand this to (OLT | OGT).
3650       TmpOp0 = Op0;
3651       TmpOp1 = Op1;
3652       Opc = ISD::OR;
3653       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3654       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3655       break;
3656     case ISD::SETUO: Invert = true; // Fallthrough
3657     case ISD::SETO:
3658       // Expand this to (OLT | OGE).
3659       TmpOp0 = Op0;
3660       TmpOp1 = Op1;
3661       Opc = ISD::OR;
3662       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3663       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3664       break;
3665     }
3666   } else {
3667     // Integer comparisons.
3668     switch (SetCCOpcode) {
3669     default: llvm_unreachable("Illegal integer comparison");
3670     case ISD::SETNE:  Invert = true;
3671     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3672     case ISD::SETLT:  Swap = true;
3673     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3674     case ISD::SETLE:  Swap = true;
3675     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3676     case ISD::SETULT: Swap = true;
3677     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3678     case ISD::SETULE: Swap = true;
3679     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3680     }
3681
3682     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3683     if (Opc == ARMISD::VCEQ) {
3684
3685       SDValue AndOp;
3686       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3687         AndOp = Op0;
3688       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3689         AndOp = Op1;
3690
3691       // Ignore bitconvert.
3692       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3693         AndOp = AndOp.getOperand(0);
3694
3695       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3696         Opc = ARMISD::VTST;
3697         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3698         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3699         Invert = !Invert;
3700       }
3701     }
3702   }
3703
3704   if (Swap)
3705     std::swap(Op0, Op1);
3706
3707   // If one of the operands is a constant vector zero, attempt to fold the
3708   // comparison to a specialized compare-against-zero form.
3709   SDValue SingleOp;
3710   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3711     SingleOp = Op0;
3712   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3713     if (Opc == ARMISD::VCGE)
3714       Opc = ARMISD::VCLEZ;
3715     else if (Opc == ARMISD::VCGT)
3716       Opc = ARMISD::VCLTZ;
3717     SingleOp = Op1;
3718   }
3719
3720   SDValue Result;
3721   if (SingleOp.getNode()) {
3722     switch (Opc) {
3723     case ARMISD::VCEQ:
3724       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3725     case ARMISD::VCGE:
3726       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3727     case ARMISD::VCLEZ:
3728       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3729     case ARMISD::VCGT:
3730       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3731     case ARMISD::VCLTZ:
3732       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3733     default:
3734       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3735     }
3736   } else {
3737      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3738   }
3739
3740   if (Invert)
3741     Result = DAG.getNOT(dl, Result, VT);
3742
3743   return Result;
3744 }
3745
3746 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3747 /// valid vector constant for a NEON instruction with a "modified immediate"
3748 /// operand (e.g., VMOV).  If so, return the encoded value.
3749 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3750                                  unsigned SplatBitSize, SelectionDAG &DAG,
3751                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3752   unsigned OpCmode, Imm;
3753
3754   // SplatBitSize is set to the smallest size that splats the vector, so a
3755   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3756   // immediate instructions others than VMOV do not support the 8-bit encoding
3757   // of a zero vector, and the default encoding of zero is supposed to be the
3758   // 32-bit version.
3759   if (SplatBits == 0)
3760     SplatBitSize = 32;
3761
3762   switch (SplatBitSize) {
3763   case 8:
3764     if (type != VMOVModImm)
3765       return SDValue();
3766     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3767     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3768     OpCmode = 0xe;
3769     Imm = SplatBits;
3770     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3771     break;
3772
3773   case 16:
3774     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3775     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3776     if ((SplatBits & ~0xff) == 0) {
3777       // Value = 0x00nn: Op=x, Cmode=100x.
3778       OpCmode = 0x8;
3779       Imm = SplatBits;
3780       break;
3781     }
3782     if ((SplatBits & ~0xff00) == 0) {
3783       // Value = 0xnn00: Op=x, Cmode=101x.
3784       OpCmode = 0xa;
3785       Imm = SplatBits >> 8;
3786       break;
3787     }
3788     return SDValue();
3789
3790   case 32:
3791     // NEON's 32-bit VMOV supports splat values where:
3792     // * only one byte is nonzero, or
3793     // * the least significant byte is 0xff and the second byte is nonzero, or
3794     // * the least significant 2 bytes are 0xff and the third is nonzero.
3795     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3796     if ((SplatBits & ~0xff) == 0) {
3797       // Value = 0x000000nn: Op=x, Cmode=000x.
3798       OpCmode = 0;
3799       Imm = SplatBits;
3800       break;
3801     }
3802     if ((SplatBits & ~0xff00) == 0) {
3803       // Value = 0x0000nn00: Op=x, Cmode=001x.
3804       OpCmode = 0x2;
3805       Imm = SplatBits >> 8;
3806       break;
3807     }
3808     if ((SplatBits & ~0xff0000) == 0) {
3809       // Value = 0x00nn0000: Op=x, Cmode=010x.
3810       OpCmode = 0x4;
3811       Imm = SplatBits >> 16;
3812       break;
3813     }
3814     if ((SplatBits & ~0xff000000) == 0) {
3815       // Value = 0xnn000000: Op=x, Cmode=011x.
3816       OpCmode = 0x6;
3817       Imm = SplatBits >> 24;
3818       break;
3819     }
3820
3821     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3822     if (type == OtherModImm) return SDValue();
3823
3824     if ((SplatBits & ~0xffff) == 0 &&
3825         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3826       // Value = 0x0000nnff: Op=x, Cmode=1100.
3827       OpCmode = 0xc;
3828       Imm = SplatBits >> 8;
3829       SplatBits |= 0xff;
3830       break;
3831     }
3832
3833     if ((SplatBits & ~0xffffff) == 0 &&
3834         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3835       // Value = 0x00nnffff: Op=x, Cmode=1101.
3836       OpCmode = 0xd;
3837       Imm = SplatBits >> 16;
3838       SplatBits |= 0xffff;
3839       break;
3840     }
3841
3842     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3843     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3844     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3845     // and fall through here to test for a valid 64-bit splat.  But, then the
3846     // caller would also need to check and handle the change in size.
3847     return SDValue();
3848
3849   case 64: {
3850     if (type != VMOVModImm)
3851       return SDValue();
3852     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3853     uint64_t BitMask = 0xff;
3854     uint64_t Val = 0;
3855     unsigned ImmMask = 1;
3856     Imm = 0;
3857     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3858       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3859         Val |= BitMask;
3860         Imm |= ImmMask;
3861       } else if ((SplatBits & BitMask) != 0) {
3862         return SDValue();
3863       }
3864       BitMask <<= 8;
3865       ImmMask <<= 1;
3866     }
3867     // Op=1, Cmode=1110.
3868     OpCmode = 0x1e;
3869     SplatBits = Val;
3870     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3871     break;
3872   }
3873
3874   default:
3875     llvm_unreachable("unexpected size for isNEONModifiedImm");
3876   }
3877
3878   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3879   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3880 }
3881
3882 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3883                                            const ARMSubtarget *ST) const {
3884   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3885     return SDValue();
3886
3887   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3888   assert(Op.getValueType() == MVT::f32 &&
3889          "ConstantFP custom lowering should only occur for f32.");
3890
3891   // Try splatting with a VMOV.f32...
3892   APFloat FPVal = CFP->getValueAPF();
3893   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3894   if (ImmVal != -1) {
3895     DebugLoc DL = Op.getDebugLoc();
3896     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3897     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3898                                       NewVal);
3899     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3900                        DAG.getConstant(0, MVT::i32));
3901   }
3902
3903   // If that fails, try a VMOV.i32
3904   EVT VMovVT;
3905   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3906   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3907                                      VMOVModImm);
3908   if (NewVal != SDValue()) {
3909     DebugLoc DL = Op.getDebugLoc();
3910     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3911                                       NewVal);
3912     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3913                                        VecConstant);
3914     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3915                        DAG.getConstant(0, MVT::i32));
3916   }
3917
3918   // Finally, try a VMVN.i32
3919   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3920                              VMVNModImm);
3921   if (NewVal != SDValue()) {
3922     DebugLoc DL = Op.getDebugLoc();
3923     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3924     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3925                                        VecConstant);
3926     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3927                        DAG.getConstant(0, MVT::i32));
3928   }
3929
3930   return SDValue();
3931 }
3932
3933 // check if an VEXT instruction can handle the shuffle mask when the
3934 // vector sources of the shuffle are the same.
3935 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3936   unsigned NumElts = VT.getVectorNumElements();
3937
3938   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3939   if (M[0] < 0)
3940     return false;
3941
3942   Imm = M[0];
3943
3944   // If this is a VEXT shuffle, the immediate value is the index of the first
3945   // element.  The other shuffle indices must be the successive elements after
3946   // the first one.
3947   unsigned ExpectedElt = Imm;
3948   for (unsigned i = 1; i < NumElts; ++i) {
3949     // Increment the expected index.  If it wraps around, just follow it
3950     // back to index zero and keep going.
3951     ++ExpectedElt;
3952     if (ExpectedElt == NumElts)
3953       ExpectedElt = 0;
3954
3955     if (M[i] < 0) continue; // ignore UNDEF indices
3956     if (ExpectedElt != static_cast<unsigned>(M[i]))
3957       return false;
3958   }
3959
3960   return true;
3961 }
3962
3963
3964 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3965                        bool &ReverseVEXT, unsigned &Imm) {
3966   unsigned NumElts = VT.getVectorNumElements();
3967   ReverseVEXT = false;
3968
3969   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3970   if (M[0] < 0)
3971     return false;
3972
3973   Imm = M[0];
3974
3975   // If this is a VEXT shuffle, the immediate value is the index of the first
3976   // element.  The other shuffle indices must be the successive elements after
3977   // the first one.
3978   unsigned ExpectedElt = Imm;
3979   for (unsigned i = 1; i < NumElts; ++i) {
3980     // Increment the expected index.  If it wraps around, it may still be
3981     // a VEXT but the source vectors must be swapped.
3982     ExpectedElt += 1;
3983     if (ExpectedElt == NumElts * 2) {
3984       ExpectedElt = 0;
3985       ReverseVEXT = true;
3986     }
3987
3988     if (M[i] < 0) continue; // ignore UNDEF indices
3989     if (ExpectedElt != static_cast<unsigned>(M[i]))
3990       return false;
3991   }
3992
3993   // Adjust the index value if the source operands will be swapped.
3994   if (ReverseVEXT)
3995     Imm -= NumElts;
3996
3997   return true;
3998 }
3999
4000 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4001 /// instruction with the specified blocksize.  (The order of the elements
4002 /// within each block of the vector is reversed.)
4003 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4004   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4005          "Only possible block sizes for VREV are: 16, 32, 64");
4006
4007   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4008   if (EltSz == 64)
4009     return false;
4010
4011   unsigned NumElts = VT.getVectorNumElements();
4012   unsigned BlockElts = M[0] + 1;
4013   // If the first shuffle index is UNDEF, be optimistic.
4014   if (M[0] < 0)
4015     BlockElts = BlockSize / EltSz;
4016
4017   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4018     return false;
4019
4020   for (unsigned i = 0; i < NumElts; ++i) {
4021     if (M[i] < 0) continue; // ignore UNDEF indices
4022     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4023       return false;
4024   }
4025
4026   return true;
4027 }
4028
4029 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4030   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4031   // range, then 0 is placed into the resulting vector. So pretty much any mask
4032   // of 8 elements can work here.
4033   return VT == MVT::v8i8 && M.size() == 8;
4034 }
4035
4036 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4037   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4038   if (EltSz == 64)
4039     return false;
4040
4041   unsigned NumElts = VT.getVectorNumElements();
4042   WhichResult = (M[0] == 0 ? 0 : 1);
4043   for (unsigned i = 0; i < NumElts; i += 2) {
4044     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4045         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4046       return false;
4047   }
4048   return true;
4049 }
4050
4051 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4052 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4053 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4054 static bool isVTRN_v_undef_Mask(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   for (unsigned i = 0; i < NumElts; i += 2) {
4062     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4063         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4064       return false;
4065   }
4066   return true;
4067 }
4068
4069 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4070   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4071   if (EltSz == 64)
4072     return false;
4073
4074   unsigned NumElts = VT.getVectorNumElements();
4075   WhichResult = (M[0] == 0 ? 0 : 1);
4076   for (unsigned i = 0; i != NumElts; ++i) {
4077     if (M[i] < 0) continue; // ignore UNDEF indices
4078     if ((unsigned) M[i] != 2 * i + WhichResult)
4079       return false;
4080   }
4081
4082   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4083   if (VT.is64BitVector() && EltSz == 32)
4084     return false;
4085
4086   return true;
4087 }
4088
4089 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4090 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4091 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4092 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4093   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4094   if (EltSz == 64)
4095     return false;
4096
4097   unsigned Half = VT.getVectorNumElements() / 2;
4098   WhichResult = (M[0] == 0 ? 0 : 1);
4099   for (unsigned j = 0; j != 2; ++j) {
4100     unsigned Idx = WhichResult;
4101     for (unsigned i = 0; i != Half; ++i) {
4102       int MIdx = M[i + j * Half];
4103       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4104         return false;
4105       Idx += 2;
4106     }
4107   }
4108
4109   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4110   if (VT.is64BitVector() && EltSz == 32)
4111     return false;
4112
4113   return true;
4114 }
4115
4116 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4117   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4118   if (EltSz == 64)
4119     return false;
4120
4121   unsigned NumElts = VT.getVectorNumElements();
4122   WhichResult = (M[0] == 0 ? 0 : 1);
4123   unsigned Idx = WhichResult * NumElts / 2;
4124   for (unsigned i = 0; i != NumElts; i += 2) {
4125     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4126         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4127       return false;
4128     Idx += 1;
4129   }
4130
4131   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4132   if (VT.is64BitVector() && EltSz == 32)
4133     return false;
4134
4135   return true;
4136 }
4137
4138 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4139 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4140 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4141 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4142   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4143   if (EltSz == 64)
4144     return false;
4145
4146   unsigned NumElts = VT.getVectorNumElements();
4147   WhichResult = (M[0] == 0 ? 0 : 1);
4148   unsigned Idx = WhichResult * NumElts / 2;
4149   for (unsigned i = 0; i != NumElts; i += 2) {
4150     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4151         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4152       return false;
4153     Idx += 1;
4154   }
4155
4156   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4157   if (VT.is64BitVector() && EltSz == 32)
4158     return false;
4159
4160   return true;
4161 }
4162
4163 // If N is an integer constant that can be moved into a register in one
4164 // instruction, return an SDValue of such a constant (will become a MOV
4165 // instruction).  Otherwise return null.
4166 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4167                                      const ARMSubtarget *ST, DebugLoc dl) {
4168   uint64_t Val;
4169   if (!isa<ConstantSDNode>(N))
4170     return SDValue();
4171   Val = cast<ConstantSDNode>(N)->getZExtValue();
4172
4173   if (ST->isThumb1Only()) {
4174     if (Val <= 255 || ~Val <= 255)
4175       return DAG.getConstant(Val, MVT::i32);
4176   } else {
4177     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4178       return DAG.getConstant(Val, MVT::i32);
4179   }
4180   return SDValue();
4181 }
4182
4183 // If this is a case we can't handle, return null and let the default
4184 // expansion code take care of it.
4185 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4186                                              const ARMSubtarget *ST) const {
4187   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4188   DebugLoc dl = Op.getDebugLoc();
4189   EVT VT = Op.getValueType();
4190
4191   APInt SplatBits, SplatUndef;
4192   unsigned SplatBitSize;
4193   bool HasAnyUndefs;
4194   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4195     if (SplatBitSize <= 64) {
4196       // Check if an immediate VMOV works.
4197       EVT VmovVT;
4198       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4199                                       SplatUndef.getZExtValue(), SplatBitSize,
4200                                       DAG, VmovVT, VT.is128BitVector(),
4201                                       VMOVModImm);
4202       if (Val.getNode()) {
4203         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4204         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4205       }
4206
4207       // Try an immediate VMVN.
4208       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4209       Val = isNEONModifiedImm(NegatedImm,
4210                                       SplatUndef.getZExtValue(), SplatBitSize,
4211                                       DAG, VmovVT, VT.is128BitVector(),
4212                                       VMVNModImm);
4213       if (Val.getNode()) {
4214         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4215         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4216       }
4217
4218       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4219       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4220         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4221         if (ImmVal != -1) {
4222           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4223           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4224         }
4225       }
4226     }
4227   }
4228
4229   // Scan through the operands to see if only one value is used.
4230   //
4231   // As an optimisation, even if more than one value is used it may be more
4232   // profitable to splat with one value then change some lanes.
4233   //
4234   // Heuristically we decide to do this if the vector has a "dominant" value,
4235   // defined as splatted to more than half of the lanes.
4236   unsigned NumElts = VT.getVectorNumElements();
4237   bool isOnlyLowElement = true;
4238   bool usesOnlyOneValue = true;
4239   bool hasDominantValue = false;
4240   bool isConstant = true;
4241
4242   // Map of the number of times a particular SDValue appears in the
4243   // element list.
4244   DenseMap<SDValue, unsigned> ValueCounts;
4245   SDValue Value;
4246   for (unsigned i = 0; i < NumElts; ++i) {
4247     SDValue V = Op.getOperand(i);
4248     if (V.getOpcode() == ISD::UNDEF)
4249       continue;
4250     if (i > 0)
4251       isOnlyLowElement = false;
4252     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4253       isConstant = false;
4254
4255     ValueCounts.insert(std::make_pair(V, 0));
4256     unsigned &Count = ValueCounts[V];
4257     
4258     // Is this value dominant? (takes up more than half of the lanes)
4259     if (++Count > (NumElts / 2)) {
4260       hasDominantValue = true;
4261       Value = V;
4262     }
4263   }
4264   if (ValueCounts.size() != 1)
4265     usesOnlyOneValue = false;
4266   if (!Value.getNode() && ValueCounts.size() > 0)
4267     Value = ValueCounts.begin()->first;
4268
4269   if (ValueCounts.size() == 0)
4270     return DAG.getUNDEF(VT);
4271
4272   if (isOnlyLowElement)
4273     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4274
4275   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4276
4277   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4278   // i32 and try again.
4279   if (hasDominantValue && EltSize <= 32) {
4280     if (!isConstant) {
4281       SDValue N;
4282
4283       // If we are VDUPing a value that comes directly from a vector, that will
4284       // cause an unnecessary move to and from a GPR, where instead we could
4285       // just use VDUPLANE.
4286       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4287         // We need to create a new undef vector to use for the VDUPLANE if the
4288         // size of the vector from which we get the value is different than the
4289         // size of the vector that we need to create. We will insert the element
4290         // such that the register coalescer will remove unnecessary copies.
4291         if (VT != Value->getOperand(0).getValueType()) {
4292           ConstantSDNode *constIndex;
4293           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4294           assert(constIndex && "The index is not a constant!");
4295           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4296                              VT.getVectorNumElements();
4297           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4298                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4299                         Value, DAG.getConstant(index, MVT::i32)),
4300                            DAG.getConstant(index, MVT::i32));
4301         } else {
4302           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4303                         Value->getOperand(0), Value->getOperand(1));
4304         }
4305       }
4306       else
4307         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4308
4309       if (!usesOnlyOneValue) {
4310         // The dominant value was splatted as 'N', but we now have to insert
4311         // all differing elements.
4312         for (unsigned I = 0; I < NumElts; ++I) {
4313           if (Op.getOperand(I) == Value)
4314             continue;
4315           SmallVector<SDValue, 3> Ops;
4316           Ops.push_back(N);
4317           Ops.push_back(Op.getOperand(I));
4318           Ops.push_back(DAG.getConstant(I, MVT::i32));
4319           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4320         }
4321       }
4322       return N;
4323     }
4324     if (VT.getVectorElementType().isFloatingPoint()) {
4325       SmallVector<SDValue, 8> Ops;
4326       for (unsigned i = 0; i < NumElts; ++i)
4327         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4328                                   Op.getOperand(i)));
4329       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4330       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4331       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4332       if (Val.getNode())
4333         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4334     }
4335     if (usesOnlyOneValue) {
4336       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4337       if (isConstant && Val.getNode())
4338         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4339     }
4340   }
4341
4342   // If all elements are constants and the case above didn't get hit, fall back
4343   // to the default expansion, which will generate a load from the constant
4344   // pool.
4345   if (isConstant)
4346     return SDValue();
4347
4348   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4349   if (NumElts >= 4) {
4350     SDValue shuffle = ReconstructShuffle(Op, DAG);
4351     if (shuffle != SDValue())
4352       return shuffle;
4353   }
4354
4355   // Vectors with 32- or 64-bit elements can be built by directly assigning
4356   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4357   // will be legalized.
4358   if (EltSize >= 32) {
4359     // Do the expansion with floating-point types, since that is what the VFP
4360     // registers are defined to use, and since i64 is not legal.
4361     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4362     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4363     SmallVector<SDValue, 8> Ops;
4364     for (unsigned i = 0; i < NumElts; ++i)
4365       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4366     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4367     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4368   }
4369
4370   return SDValue();
4371 }
4372
4373 // Gather data to see if the operation can be modelled as a
4374 // shuffle in combination with VEXTs.
4375 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4376                                               SelectionDAG &DAG) const {
4377   DebugLoc dl = Op.getDebugLoc();
4378   EVT VT = Op.getValueType();
4379   unsigned NumElts = VT.getVectorNumElements();
4380
4381   SmallVector<SDValue, 2> SourceVecs;
4382   SmallVector<unsigned, 2> MinElts;
4383   SmallVector<unsigned, 2> MaxElts;
4384
4385   for (unsigned i = 0; i < NumElts; ++i) {
4386     SDValue V = Op.getOperand(i);
4387     if (V.getOpcode() == ISD::UNDEF)
4388       continue;
4389     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4390       // A shuffle can only come from building a vector from various
4391       // elements of other vectors.
4392       return SDValue();
4393     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4394                VT.getVectorElementType()) {
4395       // This code doesn't know how to handle shuffles where the vector
4396       // element types do not match (this happens because type legalization
4397       // promotes the return type of EXTRACT_VECTOR_ELT).
4398       // FIXME: It might be appropriate to extend this code to handle
4399       // mismatched types.
4400       return SDValue();
4401     }
4402
4403     // Record this extraction against the appropriate vector if possible...
4404     SDValue SourceVec = V.getOperand(0);
4405     // If the element number isn't a constant, we can't effectively
4406     // analyze what's going on.
4407     if (!isa<ConstantSDNode>(V.getOperand(1)))
4408       return SDValue();
4409     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4410     bool FoundSource = false;
4411     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4412       if (SourceVecs[j] == SourceVec) {
4413         if (MinElts[j] > EltNo)
4414           MinElts[j] = EltNo;
4415         if (MaxElts[j] < EltNo)
4416           MaxElts[j] = EltNo;
4417         FoundSource = true;
4418         break;
4419       }
4420     }
4421
4422     // Or record a new source if not...
4423     if (!FoundSource) {
4424       SourceVecs.push_back(SourceVec);
4425       MinElts.push_back(EltNo);
4426       MaxElts.push_back(EltNo);
4427     }
4428   }
4429
4430   // Currently only do something sane when at most two source vectors
4431   // involved.
4432   if (SourceVecs.size() > 2)
4433     return SDValue();
4434
4435   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4436   int VEXTOffsets[2] = {0, 0};
4437
4438   // This loop extracts the usage patterns of the source vectors
4439   // and prepares appropriate SDValues for a shuffle if possible.
4440   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4441     if (SourceVecs[i].getValueType() == VT) {
4442       // No VEXT necessary
4443       ShuffleSrcs[i] = SourceVecs[i];
4444       VEXTOffsets[i] = 0;
4445       continue;
4446     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4447       // It probably isn't worth padding out a smaller vector just to
4448       // break it down again in a shuffle.
4449       return SDValue();
4450     }
4451
4452     // Since only 64-bit and 128-bit vectors are legal on ARM and
4453     // we've eliminated the other cases...
4454     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4455            "unexpected vector sizes in ReconstructShuffle");
4456
4457     if (MaxElts[i] - MinElts[i] >= NumElts) {
4458       // Span too large for a VEXT to cope
4459       return SDValue();
4460     }
4461
4462     if (MinElts[i] >= NumElts) {
4463       // The extraction can just take the second half
4464       VEXTOffsets[i] = NumElts;
4465       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4466                                    SourceVecs[i],
4467                                    DAG.getIntPtrConstant(NumElts));
4468     } else if (MaxElts[i] < NumElts) {
4469       // The extraction can just take the first half
4470       VEXTOffsets[i] = 0;
4471       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4472                                    SourceVecs[i],
4473                                    DAG.getIntPtrConstant(0));
4474     } else {
4475       // An actual VEXT is needed
4476       VEXTOffsets[i] = MinElts[i];
4477       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4478                                      SourceVecs[i],
4479                                      DAG.getIntPtrConstant(0));
4480       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4481                                      SourceVecs[i],
4482                                      DAG.getIntPtrConstant(NumElts));
4483       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4484                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4485     }
4486   }
4487
4488   SmallVector<int, 8> Mask;
4489
4490   for (unsigned i = 0; i < NumElts; ++i) {
4491     SDValue Entry = Op.getOperand(i);
4492     if (Entry.getOpcode() == ISD::UNDEF) {
4493       Mask.push_back(-1);
4494       continue;
4495     }
4496
4497     SDValue ExtractVec = Entry.getOperand(0);
4498     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4499                                           .getOperand(1))->getSExtValue();
4500     if (ExtractVec == SourceVecs[0]) {
4501       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4502     } else {
4503       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4504     }
4505   }
4506
4507   // Final check before we try to produce nonsense...
4508   if (isShuffleMaskLegal(Mask, VT))
4509     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4510                                 &Mask[0]);
4511
4512   return SDValue();
4513 }
4514
4515 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4516 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4517 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4518 /// are assumed to be legal.
4519 bool
4520 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4521                                       EVT VT) const {
4522   if (VT.getVectorNumElements() == 4 &&
4523       (VT.is128BitVector() || VT.is64BitVector())) {
4524     unsigned PFIndexes[4];
4525     for (unsigned i = 0; i != 4; ++i) {
4526       if (M[i] < 0)
4527         PFIndexes[i] = 8;
4528       else
4529         PFIndexes[i] = M[i];
4530     }
4531
4532     // Compute the index in the perfect shuffle table.
4533     unsigned PFTableIndex =
4534       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4535     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4536     unsigned Cost = (PFEntry >> 30);
4537
4538     if (Cost <= 4)
4539       return true;
4540   }
4541
4542   bool ReverseVEXT;
4543   unsigned Imm, WhichResult;
4544
4545   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4546   return (EltSize >= 32 ||
4547           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4548           isVREVMask(M, VT, 64) ||
4549           isVREVMask(M, VT, 32) ||
4550           isVREVMask(M, VT, 16) ||
4551           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4552           isVTBLMask(M, VT) ||
4553           isVTRNMask(M, VT, WhichResult) ||
4554           isVUZPMask(M, VT, WhichResult) ||
4555           isVZIPMask(M, VT, WhichResult) ||
4556           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4557           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4558           isVZIP_v_undef_Mask(M, VT, WhichResult));
4559 }
4560
4561 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4562 /// the specified operations to build the shuffle.
4563 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4564                                       SDValue RHS, SelectionDAG &DAG,
4565                                       DebugLoc dl) {
4566   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4567   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4568   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4569
4570   enum {
4571     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4572     OP_VREV,
4573     OP_VDUP0,
4574     OP_VDUP1,
4575     OP_VDUP2,
4576     OP_VDUP3,
4577     OP_VEXT1,
4578     OP_VEXT2,
4579     OP_VEXT3,
4580     OP_VUZPL, // VUZP, left result
4581     OP_VUZPR, // VUZP, right result
4582     OP_VZIPL, // VZIP, left result
4583     OP_VZIPR, // VZIP, right result
4584     OP_VTRNL, // VTRN, left result
4585     OP_VTRNR  // VTRN, right result
4586   };
4587
4588   if (OpNum == OP_COPY) {
4589     if (LHSID == (1*9+2)*9+3) return LHS;
4590     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4591     return RHS;
4592   }
4593
4594   SDValue OpLHS, OpRHS;
4595   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4596   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4597   EVT VT = OpLHS.getValueType();
4598
4599   switch (OpNum) {
4600   default: llvm_unreachable("Unknown shuffle opcode!");
4601   case OP_VREV:
4602     // VREV divides the vector in half and swaps within the half.
4603     if (VT.getVectorElementType() == MVT::i32 ||
4604         VT.getVectorElementType() == MVT::f32)
4605       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4606     // vrev <4 x i16> -> VREV32
4607     if (VT.getVectorElementType() == MVT::i16)
4608       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4609     // vrev <4 x i8> -> VREV16
4610     assert(VT.getVectorElementType() == MVT::i8);
4611     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4612   case OP_VDUP0:
4613   case OP_VDUP1:
4614   case OP_VDUP2:
4615   case OP_VDUP3:
4616     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4617                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4618   case OP_VEXT1:
4619   case OP_VEXT2:
4620   case OP_VEXT3:
4621     return DAG.getNode(ARMISD::VEXT, dl, VT,
4622                        OpLHS, OpRHS,
4623                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4624   case OP_VUZPL:
4625   case OP_VUZPR:
4626     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4627                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4628   case OP_VZIPL:
4629   case OP_VZIPR:
4630     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4631                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4632   case OP_VTRNL:
4633   case OP_VTRNR:
4634     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4635                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4636   }
4637 }
4638
4639 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4640                                        ArrayRef<int> ShuffleMask,
4641                                        SelectionDAG &DAG) {
4642   // Check to see if we can use the VTBL instruction.
4643   SDValue V1 = Op.getOperand(0);
4644   SDValue V2 = Op.getOperand(1);
4645   DebugLoc DL = Op.getDebugLoc();
4646
4647   SmallVector<SDValue, 8> VTBLMask;
4648   for (ArrayRef<int>::iterator
4649          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4650     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4651
4652   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4653     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4654                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4655                                    &VTBLMask[0], 8));
4656
4657   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4658                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4659                                  &VTBLMask[0], 8));
4660 }
4661
4662 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4663   SDValue V1 = Op.getOperand(0);
4664   SDValue V2 = Op.getOperand(1);
4665   DebugLoc dl = Op.getDebugLoc();
4666   EVT VT = Op.getValueType();
4667   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4668
4669   // Convert shuffles that are directly supported on NEON to target-specific
4670   // DAG nodes, instead of keeping them as shuffles and matching them again
4671   // during code selection.  This is more efficient and avoids the possibility
4672   // of inconsistencies between legalization and selection.
4673   // FIXME: floating-point vectors should be canonicalized to integer vectors
4674   // of the same time so that they get CSEd properly.
4675   ArrayRef<int> ShuffleMask = SVN->getMask();
4676
4677   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4678   if (EltSize <= 32) {
4679     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4680       int Lane = SVN->getSplatIndex();
4681       // If this is undef splat, generate it via "just" vdup, if possible.
4682       if (Lane == -1) Lane = 0;
4683
4684       // Test if V1 is a SCALAR_TO_VECTOR.
4685       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4686         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4687       }
4688       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4689       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4690       // reaches it).
4691       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4692           !isa<ConstantSDNode>(V1.getOperand(0))) {
4693         bool IsScalarToVector = true;
4694         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4695           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4696             IsScalarToVector = false;
4697             break;
4698           }
4699         if (IsScalarToVector)
4700           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4701       }
4702       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4703                          DAG.getConstant(Lane, MVT::i32));
4704     }
4705
4706     bool ReverseVEXT;
4707     unsigned Imm;
4708     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4709       if (ReverseVEXT)
4710         std::swap(V1, V2);
4711       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4712                          DAG.getConstant(Imm, MVT::i32));
4713     }
4714
4715     if (isVREVMask(ShuffleMask, VT, 64))
4716       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4717     if (isVREVMask(ShuffleMask, VT, 32))
4718       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4719     if (isVREVMask(ShuffleMask, VT, 16))
4720       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4721
4722     if (V2->getOpcode() == ISD::UNDEF &&
4723         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4724       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4725                          DAG.getConstant(Imm, MVT::i32));
4726     }
4727
4728     // Check for Neon shuffles that modify both input vectors in place.
4729     // If both results are used, i.e., if there are two shuffles with the same
4730     // source operands and with masks corresponding to both results of one of
4731     // these operations, DAG memoization will ensure that a single node is
4732     // used for both shuffles.
4733     unsigned WhichResult;
4734     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4735       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4736                          V1, V2).getValue(WhichResult);
4737     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4738       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4739                          V1, V2).getValue(WhichResult);
4740     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4741       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4742                          V1, V2).getValue(WhichResult);
4743
4744     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4745       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4746                          V1, V1).getValue(WhichResult);
4747     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4748       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4749                          V1, V1).getValue(WhichResult);
4750     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4751       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4752                          V1, V1).getValue(WhichResult);
4753   }
4754
4755   // If the shuffle is not directly supported and it has 4 elements, use
4756   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4757   unsigned NumElts = VT.getVectorNumElements();
4758   if (NumElts == 4) {
4759     unsigned PFIndexes[4];
4760     for (unsigned i = 0; i != 4; ++i) {
4761       if (ShuffleMask[i] < 0)
4762         PFIndexes[i] = 8;
4763       else
4764         PFIndexes[i] = ShuffleMask[i];
4765     }
4766
4767     // Compute the index in the perfect shuffle table.
4768     unsigned PFTableIndex =
4769       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4770     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4771     unsigned Cost = (PFEntry >> 30);
4772
4773     if (Cost <= 4)
4774       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4775   }
4776
4777   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4778   if (EltSize >= 32) {
4779     // Do the expansion with floating-point types, since that is what the VFP
4780     // registers are defined to use, and since i64 is not legal.
4781     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4782     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4783     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4784     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4785     SmallVector<SDValue, 8> Ops;
4786     for (unsigned i = 0; i < NumElts; ++i) {
4787       if (ShuffleMask[i] < 0)
4788         Ops.push_back(DAG.getUNDEF(EltVT));
4789       else
4790         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4791                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4792                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4793                                                   MVT::i32)));
4794     }
4795     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4796     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4797   }
4798
4799   if (VT == MVT::v8i8) {
4800     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4801     if (NewOp.getNode())
4802       return NewOp;
4803   }
4804
4805   return SDValue();
4806 }
4807
4808 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4809   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4810   SDValue Lane = Op.getOperand(2);
4811   if (!isa<ConstantSDNode>(Lane))
4812     return SDValue();
4813
4814   return Op;
4815 }
4816
4817 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4818   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4819   SDValue Lane = Op.getOperand(1);
4820   if (!isa<ConstantSDNode>(Lane))
4821     return SDValue();
4822
4823   SDValue Vec = Op.getOperand(0);
4824   if (Op.getValueType() == MVT::i32 &&
4825       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4826     DebugLoc dl = Op.getDebugLoc();
4827     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4828   }
4829
4830   return Op;
4831 }
4832
4833 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4834   // The only time a CONCAT_VECTORS operation can have legal types is when
4835   // two 64-bit vectors are concatenated to a 128-bit vector.
4836   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4837          "unexpected CONCAT_VECTORS");
4838   DebugLoc dl = Op.getDebugLoc();
4839   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4840   SDValue Op0 = Op.getOperand(0);
4841   SDValue Op1 = Op.getOperand(1);
4842   if (Op0.getOpcode() != ISD::UNDEF)
4843     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4844                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4845                       DAG.getIntPtrConstant(0));
4846   if (Op1.getOpcode() != ISD::UNDEF)
4847     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4848                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4849                       DAG.getIntPtrConstant(1));
4850   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4851 }
4852
4853 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4854 /// element has been zero/sign-extended, depending on the isSigned parameter,
4855 /// from an integer type half its size.
4856 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4857                                    bool isSigned) {
4858   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4859   EVT VT = N->getValueType(0);
4860   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4861     SDNode *BVN = N->getOperand(0).getNode();
4862     if (BVN->getValueType(0) != MVT::v4i32 ||
4863         BVN->getOpcode() != ISD::BUILD_VECTOR)
4864       return false;
4865     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4866     unsigned HiElt = 1 - LoElt;
4867     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4868     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4869     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4870     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4871     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4872       return false;
4873     if (isSigned) {
4874       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4875           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4876         return true;
4877     } else {
4878       if (Hi0->isNullValue() && Hi1->isNullValue())
4879         return true;
4880     }
4881     return false;
4882   }
4883
4884   if (N->getOpcode() != ISD::BUILD_VECTOR)
4885     return false;
4886
4887   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4888     SDNode *Elt = N->getOperand(i).getNode();
4889     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4890       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4891       unsigned HalfSize = EltSize / 2;
4892       if (isSigned) {
4893         if (!isIntN(HalfSize, C->getSExtValue()))
4894           return false;
4895       } else {
4896         if (!isUIntN(HalfSize, C->getZExtValue()))
4897           return false;
4898       }
4899       continue;
4900     }
4901     return false;
4902   }
4903
4904   return true;
4905 }
4906
4907 /// isSignExtended - Check if a node is a vector value that is sign-extended
4908 /// or a constant BUILD_VECTOR with sign-extended elements.
4909 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4910   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4911     return true;
4912   if (isExtendedBUILD_VECTOR(N, DAG, true))
4913     return true;
4914   return false;
4915 }
4916
4917 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4918 /// or a constant BUILD_VECTOR with zero-extended elements.
4919 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4920   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4921     return true;
4922   if (isExtendedBUILD_VECTOR(N, DAG, false))
4923     return true;
4924   return false;
4925 }
4926
4927 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4928 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4929 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4930   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4931     return N->getOperand(0);
4932   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4933     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4934                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4935                        LD->isNonTemporal(), LD->isInvariant(),
4936                        LD->getAlignment());
4937   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4938   // have been legalized as a BITCAST from v4i32.
4939   if (N->getOpcode() == ISD::BITCAST) {
4940     SDNode *BVN = N->getOperand(0).getNode();
4941     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4942            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4943     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4944     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4945                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4946   }
4947   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4948   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4949   EVT VT = N->getValueType(0);
4950   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4951   unsigned NumElts = VT.getVectorNumElements();
4952   MVT TruncVT = MVT::getIntegerVT(EltSize);
4953   SmallVector<SDValue, 8> Ops;
4954   for (unsigned i = 0; i != NumElts; ++i) {
4955     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4956     const APInt &CInt = C->getAPIntValue();
4957     // Element types smaller than 32 bits are not legal, so use i32 elements.
4958     // The values are implicitly truncated so sext vs. zext doesn't matter.
4959     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4960   }
4961   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4962                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4963 }
4964
4965 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4966   unsigned Opcode = N->getOpcode();
4967   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4968     SDNode *N0 = N->getOperand(0).getNode();
4969     SDNode *N1 = N->getOperand(1).getNode();
4970     return N0->hasOneUse() && N1->hasOneUse() &&
4971       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4972   }
4973   return false;
4974 }
4975
4976 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4977   unsigned Opcode = N->getOpcode();
4978   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4979     SDNode *N0 = N->getOperand(0).getNode();
4980     SDNode *N1 = N->getOperand(1).getNode();
4981     return N0->hasOneUse() && N1->hasOneUse() &&
4982       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4983   }
4984   return false;
4985 }
4986
4987 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4988   // Multiplications are only custom-lowered for 128-bit vectors so that
4989   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4990   EVT VT = Op.getValueType();
4991   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4992   SDNode *N0 = Op.getOperand(0).getNode();
4993   SDNode *N1 = Op.getOperand(1).getNode();
4994   unsigned NewOpc = 0;
4995   bool isMLA = false;
4996   bool isN0SExt = isSignExtended(N0, DAG);
4997   bool isN1SExt = isSignExtended(N1, DAG);
4998   if (isN0SExt && isN1SExt)
4999     NewOpc = ARMISD::VMULLs;
5000   else {
5001     bool isN0ZExt = isZeroExtended(N0, DAG);
5002     bool isN1ZExt = isZeroExtended(N1, DAG);
5003     if (isN0ZExt && isN1ZExt)
5004       NewOpc = ARMISD::VMULLu;
5005     else if (isN1SExt || isN1ZExt) {
5006       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5007       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5008       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5009         NewOpc = ARMISD::VMULLs;
5010         isMLA = true;
5011       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5012         NewOpc = ARMISD::VMULLu;
5013         isMLA = true;
5014       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5015         std::swap(N0, N1);
5016         NewOpc = ARMISD::VMULLu;
5017         isMLA = true;
5018       }
5019     }
5020
5021     if (!NewOpc) {
5022       if (VT == MVT::v2i64)
5023         // Fall through to expand this.  It is not legal.
5024         return SDValue();
5025       else
5026         // Other vector multiplications are legal.
5027         return Op;
5028     }
5029   }
5030
5031   // Legalize to a VMULL instruction.
5032   DebugLoc DL = Op.getDebugLoc();
5033   SDValue Op0;
5034   SDValue Op1 = SkipExtension(N1, DAG);
5035   if (!isMLA) {
5036     Op0 = SkipExtension(N0, DAG);
5037     assert(Op0.getValueType().is64BitVector() &&
5038            Op1.getValueType().is64BitVector() &&
5039            "unexpected types for extended operands to VMULL");
5040     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5041   }
5042
5043   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5044   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5045   //   vmull q0, d4, d6
5046   //   vmlal q0, d5, d6
5047   // is faster than
5048   //   vaddl q0, d4, d5
5049   //   vmovl q1, d6
5050   //   vmul  q0, q0, q1
5051   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
5052   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
5053   EVT Op1VT = Op1.getValueType();
5054   return DAG.getNode(N0->getOpcode(), DL, VT,
5055                      DAG.getNode(NewOpc, DL, VT,
5056                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5057                      DAG.getNode(NewOpc, DL, VT,
5058                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5059 }
5060
5061 static SDValue
5062 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5063   // Convert to float
5064   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5065   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5066   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5067   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5068   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5069   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5070   // Get reciprocal estimate.
5071   // float4 recip = vrecpeq_f32(yf);
5072   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5073                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5074   // Because char has a smaller range than uchar, we can actually get away
5075   // without any newton steps.  This requires that we use a weird bias
5076   // of 0xb000, however (again, this has been exhaustively tested).
5077   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5078   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5079   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5080   Y = DAG.getConstant(0xb000, MVT::i32);
5081   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5082   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5083   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5084   // Convert back to short.
5085   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5086   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5087   return X;
5088 }
5089
5090 static SDValue
5091 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5092   SDValue N2;
5093   // Convert to float.
5094   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5095   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5096   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5097   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5098   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5099   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5100
5101   // Use reciprocal estimate and one refinement step.
5102   // float4 recip = vrecpeq_f32(yf);
5103   // recip *= vrecpsq_f32(yf, recip);
5104   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5105                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5106   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5107                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5108                    N1, N2);
5109   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5110   // Because short has a smaller range than ushort, we can actually get away
5111   // with only a single newton step.  This requires that we use a weird bias
5112   // of 89, however (again, this has been exhaustively tested).
5113   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5114   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5115   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5116   N1 = DAG.getConstant(0x89, MVT::i32);
5117   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5118   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5119   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5120   // Convert back to integer and return.
5121   // return vmovn_s32(vcvt_s32_f32(result));
5122   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5123   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5124   return N0;
5125 }
5126
5127 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5128   EVT VT = Op.getValueType();
5129   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5130          "unexpected type for custom-lowering ISD::SDIV");
5131
5132   DebugLoc dl = Op.getDebugLoc();
5133   SDValue N0 = Op.getOperand(0);
5134   SDValue N1 = Op.getOperand(1);
5135   SDValue N2, N3;
5136
5137   if (VT == MVT::v8i8) {
5138     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5139     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5140
5141     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5142                      DAG.getIntPtrConstant(4));
5143     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5144                      DAG.getIntPtrConstant(4));
5145     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5146                      DAG.getIntPtrConstant(0));
5147     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5148                      DAG.getIntPtrConstant(0));
5149
5150     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5151     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5152
5153     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5154     N0 = LowerCONCAT_VECTORS(N0, DAG);
5155
5156     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5157     return N0;
5158   }
5159   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5160 }
5161
5162 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5163   EVT VT = Op.getValueType();
5164   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5165          "unexpected type for custom-lowering ISD::UDIV");
5166
5167   DebugLoc dl = Op.getDebugLoc();
5168   SDValue N0 = Op.getOperand(0);
5169   SDValue N1 = Op.getOperand(1);
5170   SDValue N2, N3;
5171
5172   if (VT == MVT::v8i8) {
5173     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5174     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5175
5176     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5177                      DAG.getIntPtrConstant(4));
5178     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5179                      DAG.getIntPtrConstant(4));
5180     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5181                      DAG.getIntPtrConstant(0));
5182     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5183                      DAG.getIntPtrConstant(0));
5184
5185     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5186     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5187
5188     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5189     N0 = LowerCONCAT_VECTORS(N0, DAG);
5190
5191     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5192                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5193                      N0);
5194     return N0;
5195   }
5196
5197   // v4i16 sdiv ... Convert to float.
5198   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5199   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5200   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5201   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5202   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5203   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5204
5205   // Use reciprocal estimate and two refinement steps.
5206   // float4 recip = vrecpeq_f32(yf);
5207   // recip *= vrecpsq_f32(yf, recip);
5208   // recip *= vrecpsq_f32(yf, recip);
5209   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5210                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5211   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5212                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5213                    BN1, N2);
5214   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5215   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5216                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5217                    BN1, N2);
5218   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5219   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5220   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5221   // and that it will never cause us to return an answer too large).
5222   // float4 result = as_float4(as_int4(xf*recip) + 2);
5223   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5224   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5225   N1 = DAG.getConstant(2, MVT::i32);
5226   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5227   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5228   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5229   // Convert back to integer and return.
5230   // return vmovn_u32(vcvt_s32_f32(result));
5231   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5232   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5233   return N0;
5234 }
5235
5236 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5237   EVT VT = Op.getNode()->getValueType(0);
5238   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5239
5240   unsigned Opc;
5241   bool ExtraOp = false;
5242   switch (Op.getOpcode()) {
5243   default: llvm_unreachable("Invalid code");
5244   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5245   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5246   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5247   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5248   }
5249
5250   if (!ExtraOp)
5251     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5252                        Op.getOperand(1));
5253   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5254                      Op.getOperand(1), Op.getOperand(2));
5255 }
5256
5257 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5258   // Monotonic load/store is legal for all targets
5259   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5260     return Op;
5261
5262   // Aquire/Release load/store is not legal for targets without a
5263   // dmb or equivalent available.
5264   return SDValue();
5265 }
5266
5267
5268 static void
5269 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5270                     SelectionDAG &DAG, unsigned NewOp) {
5271   DebugLoc dl = Node->getDebugLoc();
5272   assert (Node->getValueType(0) == MVT::i64 &&
5273           "Only know how to expand i64 atomics");
5274
5275   SmallVector<SDValue, 6> Ops;
5276   Ops.push_back(Node->getOperand(0)); // Chain
5277   Ops.push_back(Node->getOperand(1)); // Ptr
5278   // Low part of Val1
5279   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5280                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5281   // High part of Val1
5282   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5283                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5284   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5285     // High part of Val1
5286     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5287                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5288     // High part of Val2
5289     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5290                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5291   }
5292   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5293   SDValue Result =
5294     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5295                             cast<MemSDNode>(Node)->getMemOperand());
5296   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5297   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5298   Results.push_back(Result.getValue(2));
5299 }
5300
5301 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5302   switch (Op.getOpcode()) {
5303   default: llvm_unreachable("Don't know how to custom lower this!");
5304   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5305   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5306   case ISD::GlobalAddress:
5307     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5308       LowerGlobalAddressELF(Op, DAG);
5309   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5310   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5311   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5312   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5313   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5314   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5315   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5316   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5317   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5318   case ISD::SINT_TO_FP:
5319   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5320   case ISD::FP_TO_SINT:
5321   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5322   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5323   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5324   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5325   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5326   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5327   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5328   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5329                                                                Subtarget);
5330   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5331   case ISD::SHL:
5332   case ISD::SRL:
5333   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5334   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5335   case ISD::SRL_PARTS:
5336   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5337   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5338   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5339   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5340   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5341   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5342   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5343   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5344   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5345   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5346   case ISD::MUL:           return LowerMUL(Op, DAG);
5347   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5348   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5349   case ISD::ADDC:
5350   case ISD::ADDE:
5351   case ISD::SUBC:
5352   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5353   case ISD::ATOMIC_LOAD:
5354   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5355   }
5356 }
5357
5358 /// ReplaceNodeResults - Replace the results of node with an illegal result
5359 /// type with new values built out of custom code.
5360 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5361                                            SmallVectorImpl<SDValue>&Results,
5362                                            SelectionDAG &DAG) const {
5363   SDValue Res;
5364   switch (N->getOpcode()) {
5365   default:
5366     llvm_unreachable("Don't know how to custom expand this!");
5367   case ISD::BITCAST:
5368     Res = ExpandBITCAST(N, DAG);
5369     break;
5370   case ISD::SRL:
5371   case ISD::SRA:
5372     Res = Expand64BitShift(N, DAG, Subtarget);
5373     break;
5374   case ISD::ATOMIC_LOAD_ADD:
5375     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5376     return;
5377   case ISD::ATOMIC_LOAD_AND:
5378     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5379     return;
5380   case ISD::ATOMIC_LOAD_NAND:
5381     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5382     return;
5383   case ISD::ATOMIC_LOAD_OR:
5384     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5385     return;
5386   case ISD::ATOMIC_LOAD_SUB:
5387     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5388     return;
5389   case ISD::ATOMIC_LOAD_XOR:
5390     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5391     return;
5392   case ISD::ATOMIC_SWAP:
5393     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5394     return;
5395   case ISD::ATOMIC_CMP_SWAP:
5396     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5397     return;
5398   }
5399   if (Res.getNode())
5400     Results.push_back(Res);
5401 }
5402
5403 //===----------------------------------------------------------------------===//
5404 //                           ARM Scheduler Hooks
5405 //===----------------------------------------------------------------------===//
5406
5407 MachineBasicBlock *
5408 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5409                                      MachineBasicBlock *BB,
5410                                      unsigned Size) const {
5411   unsigned dest    = MI->getOperand(0).getReg();
5412   unsigned ptr     = MI->getOperand(1).getReg();
5413   unsigned oldval  = MI->getOperand(2).getReg();
5414   unsigned newval  = MI->getOperand(3).getReg();
5415   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5416   DebugLoc dl = MI->getDebugLoc();
5417   bool isThumb2 = Subtarget->isThumb2();
5418
5419   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5420   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5421     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5422     (const TargetRegisterClass*)&ARM::GPRRegClass);
5423
5424   if (isThumb2) {
5425     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5426     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5427     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5428   }
5429
5430   unsigned ldrOpc, strOpc;
5431   switch (Size) {
5432   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5433   case 1:
5434     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5435     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5436     break;
5437   case 2:
5438     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5439     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5440     break;
5441   case 4:
5442     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5443     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5444     break;
5445   }
5446
5447   MachineFunction *MF = BB->getParent();
5448   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5449   MachineFunction::iterator It = BB;
5450   ++It; // insert the new blocks after the current block
5451
5452   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5453   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5454   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5455   MF->insert(It, loop1MBB);
5456   MF->insert(It, loop2MBB);
5457   MF->insert(It, exitMBB);
5458
5459   // Transfer the remainder of BB and its successor edges to exitMBB.
5460   exitMBB->splice(exitMBB->begin(), BB,
5461                   llvm::next(MachineBasicBlock::iterator(MI)),
5462                   BB->end());
5463   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5464
5465   //  thisMBB:
5466   //   ...
5467   //   fallthrough --> loop1MBB
5468   BB->addSuccessor(loop1MBB);
5469
5470   // loop1MBB:
5471   //   ldrex dest, [ptr]
5472   //   cmp dest, oldval
5473   //   bne exitMBB
5474   BB = loop1MBB;
5475   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5476   if (ldrOpc == ARM::t2LDREX)
5477     MIB.addImm(0);
5478   AddDefaultPred(MIB);
5479   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5480                  .addReg(dest).addReg(oldval));
5481   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5482     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5483   BB->addSuccessor(loop2MBB);
5484   BB->addSuccessor(exitMBB);
5485
5486   // loop2MBB:
5487   //   strex scratch, newval, [ptr]
5488   //   cmp scratch, #0
5489   //   bne loop1MBB
5490   BB = loop2MBB;
5491   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5492   if (strOpc == ARM::t2STREX)
5493     MIB.addImm(0);
5494   AddDefaultPred(MIB);
5495   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5496                  .addReg(scratch).addImm(0));
5497   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5498     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5499   BB->addSuccessor(loop1MBB);
5500   BB->addSuccessor(exitMBB);
5501
5502   //  exitMBB:
5503   //   ...
5504   BB = exitMBB;
5505
5506   MI->eraseFromParent();   // The instruction is gone now.
5507
5508   return BB;
5509 }
5510
5511 MachineBasicBlock *
5512 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5513                                     unsigned Size, unsigned BinOpcode) const {
5514   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5515   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5516
5517   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5518   MachineFunction *MF = BB->getParent();
5519   MachineFunction::iterator It = BB;
5520   ++It;
5521
5522   unsigned dest = MI->getOperand(0).getReg();
5523   unsigned ptr = MI->getOperand(1).getReg();
5524   unsigned incr = MI->getOperand(2).getReg();
5525   DebugLoc dl = MI->getDebugLoc();
5526   bool isThumb2 = Subtarget->isThumb2();
5527
5528   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5529   if (isThumb2) {
5530     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5531     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5532   }
5533
5534   unsigned ldrOpc, strOpc;
5535   switch (Size) {
5536   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5537   case 1:
5538     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5539     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5540     break;
5541   case 2:
5542     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5543     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5544     break;
5545   case 4:
5546     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5547     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5548     break;
5549   }
5550
5551   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5552   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5553   MF->insert(It, loopMBB);
5554   MF->insert(It, exitMBB);
5555
5556   // Transfer the remainder of BB and its successor edges to exitMBB.
5557   exitMBB->splice(exitMBB->begin(), BB,
5558                   llvm::next(MachineBasicBlock::iterator(MI)),
5559                   BB->end());
5560   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5561
5562   const TargetRegisterClass *TRC = isThumb2 ?
5563     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5564     (const TargetRegisterClass*)&ARM::GPRRegClass;
5565   unsigned scratch = MRI.createVirtualRegister(TRC);
5566   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5567
5568   //  thisMBB:
5569   //   ...
5570   //   fallthrough --> loopMBB
5571   BB->addSuccessor(loopMBB);
5572
5573   //  loopMBB:
5574   //   ldrex dest, ptr
5575   //   <binop> scratch2, dest, incr
5576   //   strex scratch, scratch2, ptr
5577   //   cmp scratch, #0
5578   //   bne- loopMBB
5579   //   fallthrough --> exitMBB
5580   BB = loopMBB;
5581   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5582   if (ldrOpc == ARM::t2LDREX)
5583     MIB.addImm(0);
5584   AddDefaultPred(MIB);
5585   if (BinOpcode) {
5586     // operand order needs to go the other way for NAND
5587     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5588       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5589                      addReg(incr).addReg(dest)).addReg(0);
5590     else
5591       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5592                      addReg(dest).addReg(incr)).addReg(0);
5593   }
5594
5595   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5596   if (strOpc == ARM::t2STREX)
5597     MIB.addImm(0);
5598   AddDefaultPred(MIB);
5599   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5600                  .addReg(scratch).addImm(0));
5601   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5602     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5603
5604   BB->addSuccessor(loopMBB);
5605   BB->addSuccessor(exitMBB);
5606
5607   //  exitMBB:
5608   //   ...
5609   BB = exitMBB;
5610
5611   MI->eraseFromParent();   // The instruction is gone now.
5612
5613   return BB;
5614 }
5615
5616 MachineBasicBlock *
5617 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5618                                           MachineBasicBlock *BB,
5619                                           unsigned Size,
5620                                           bool signExtend,
5621                                           ARMCC::CondCodes Cond) const {
5622   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5623
5624   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5625   MachineFunction *MF = BB->getParent();
5626   MachineFunction::iterator It = BB;
5627   ++It;
5628
5629   unsigned dest = MI->getOperand(0).getReg();
5630   unsigned ptr = MI->getOperand(1).getReg();
5631   unsigned incr = MI->getOperand(2).getReg();
5632   unsigned oldval = dest;
5633   DebugLoc dl = MI->getDebugLoc();
5634   bool isThumb2 = Subtarget->isThumb2();
5635
5636   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5637   if (isThumb2) {
5638     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5639     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5640   }
5641
5642   unsigned ldrOpc, strOpc, extendOpc;
5643   switch (Size) {
5644   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5645   case 1:
5646     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5647     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5648     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5649     break;
5650   case 2:
5651     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5652     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5653     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5654     break;
5655   case 4:
5656     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5657     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5658     extendOpc = 0;
5659     break;
5660   }
5661
5662   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5663   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5664   MF->insert(It, loopMBB);
5665   MF->insert(It, exitMBB);
5666
5667   // Transfer the remainder of BB and its successor edges to exitMBB.
5668   exitMBB->splice(exitMBB->begin(), BB,
5669                   llvm::next(MachineBasicBlock::iterator(MI)),
5670                   BB->end());
5671   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5672
5673   const TargetRegisterClass *TRC = isThumb2 ?
5674     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5675     (const TargetRegisterClass*)&ARM::GPRRegClass;
5676   unsigned scratch = MRI.createVirtualRegister(TRC);
5677   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5678
5679   //  thisMBB:
5680   //   ...
5681   //   fallthrough --> loopMBB
5682   BB->addSuccessor(loopMBB);
5683
5684   //  loopMBB:
5685   //   ldrex dest, ptr
5686   //   (sign extend dest, if required)
5687   //   cmp dest, incr
5688   //   cmov.cond scratch2, incr, dest
5689   //   strex scratch, scratch2, ptr
5690   //   cmp scratch, #0
5691   //   bne- loopMBB
5692   //   fallthrough --> exitMBB
5693   BB = loopMBB;
5694   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5695   if (ldrOpc == ARM::t2LDREX)
5696     MIB.addImm(0);
5697   AddDefaultPred(MIB);
5698
5699   // Sign extend the value, if necessary.
5700   if (signExtend && extendOpc) {
5701     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5702     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5703                      .addReg(dest)
5704                      .addImm(0));
5705   }
5706
5707   // Build compare and cmov instructions.
5708   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5709                  .addReg(oldval).addReg(incr));
5710   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5711          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5712
5713   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5714   if (strOpc == ARM::t2STREX)
5715     MIB.addImm(0);
5716   AddDefaultPred(MIB);
5717   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5718                  .addReg(scratch).addImm(0));
5719   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5720     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5721
5722   BB->addSuccessor(loopMBB);
5723   BB->addSuccessor(exitMBB);
5724
5725   //  exitMBB:
5726   //   ...
5727   BB = exitMBB;
5728
5729   MI->eraseFromParent();   // The instruction is gone now.
5730
5731   return BB;
5732 }
5733
5734 MachineBasicBlock *
5735 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5736                                       unsigned Op1, unsigned Op2,
5737                                       bool NeedsCarry, bool IsCmpxchg) const {
5738   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5739   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5740
5741   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5742   MachineFunction *MF = BB->getParent();
5743   MachineFunction::iterator It = BB;
5744   ++It;
5745
5746   unsigned destlo = MI->getOperand(0).getReg();
5747   unsigned desthi = MI->getOperand(1).getReg();
5748   unsigned ptr = MI->getOperand(2).getReg();
5749   unsigned vallo = MI->getOperand(3).getReg();
5750   unsigned valhi = MI->getOperand(4).getReg();
5751   DebugLoc dl = MI->getDebugLoc();
5752   bool isThumb2 = Subtarget->isThumb2();
5753
5754   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5755   if (isThumb2) {
5756     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5757     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5758     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5759   }
5760
5761   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5762   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5763
5764   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5765   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5766   if (IsCmpxchg) {
5767     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5768     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5769   }
5770   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5771   MF->insert(It, loopMBB);
5772   if (IsCmpxchg) {
5773     MF->insert(It, contBB);
5774     MF->insert(It, cont2BB);
5775   }
5776   MF->insert(It, exitMBB);
5777
5778   // Transfer the remainder of BB and its successor edges to exitMBB.
5779   exitMBB->splice(exitMBB->begin(), BB,
5780                   llvm::next(MachineBasicBlock::iterator(MI)),
5781                   BB->end());
5782   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5783
5784   const TargetRegisterClass *TRC = isThumb2 ?
5785     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5786     (const TargetRegisterClass*)&ARM::GPRRegClass;
5787   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5788
5789   //  thisMBB:
5790   //   ...
5791   //   fallthrough --> loopMBB
5792   BB->addSuccessor(loopMBB);
5793
5794   //  loopMBB:
5795   //   ldrexd r2, r3, ptr
5796   //   <binopa> r0, r2, incr
5797   //   <binopb> r1, r3, incr
5798   //   strexd storesuccess, r0, r1, ptr
5799   //   cmp storesuccess, #0
5800   //   bne- loopMBB
5801   //   fallthrough --> exitMBB
5802   //
5803   // Note that the registers are explicitly specified because there is not any
5804   // way to force the register allocator to allocate a register pair.
5805   //
5806   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5807   // need to properly enforce the restriction that the two output registers
5808   // for ldrexd must be different.
5809   BB = loopMBB;
5810   // Load
5811   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5812                  .addReg(ARM::R2, RegState::Define)
5813                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5814   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5815   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5816   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5817
5818   if (IsCmpxchg) {
5819     // Add early exit
5820     for (unsigned i = 0; i < 2; i++) {
5821       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5822                                                          ARM::CMPrr))
5823                      .addReg(i == 0 ? destlo : desthi)
5824                      .addReg(i == 0 ? vallo : valhi));
5825       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5826         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5827       BB->addSuccessor(exitMBB);
5828       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5829       BB = (i == 0 ? contBB : cont2BB);
5830     }
5831
5832     // Copy to physregs for strexd
5833     unsigned setlo = MI->getOperand(5).getReg();
5834     unsigned sethi = MI->getOperand(6).getReg();
5835     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5836     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5837   } else if (Op1) {
5838     // Perform binary operation
5839     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5840                    .addReg(destlo).addReg(vallo))
5841         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5842     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5843                    .addReg(desthi).addReg(valhi)).addReg(0);
5844   } else {
5845     // Copy to physregs for strexd
5846     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5847     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5848   }
5849
5850   // Store
5851   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5852                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5853   // Cmp+jump
5854   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5855                  .addReg(storesuccess).addImm(0));
5856   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5857     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5858
5859   BB->addSuccessor(loopMBB);
5860   BB->addSuccessor(exitMBB);
5861
5862   //  exitMBB:
5863   //   ...
5864   BB = exitMBB;
5865
5866   MI->eraseFromParent();   // The instruction is gone now.
5867
5868   return BB;
5869 }
5870
5871 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5872 /// registers the function context.
5873 void ARMTargetLowering::
5874 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5875                        MachineBasicBlock *DispatchBB, int FI) const {
5876   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5877   DebugLoc dl = MI->getDebugLoc();
5878   MachineFunction *MF = MBB->getParent();
5879   MachineRegisterInfo *MRI = &MF->getRegInfo();
5880   MachineConstantPool *MCP = MF->getConstantPool();
5881   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5882   const Function *F = MF->getFunction();
5883
5884   bool isThumb = Subtarget->isThumb();
5885   bool isThumb2 = Subtarget->isThumb2();
5886
5887   unsigned PCLabelId = AFI->createPICLabelUId();
5888   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5889   ARMConstantPoolValue *CPV =
5890     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5891   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5892
5893   const TargetRegisterClass *TRC = isThumb ?
5894     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5895     (const TargetRegisterClass*)&ARM::GPRRegClass;
5896
5897   // Grab constant pool and fixed stack memory operands.
5898   MachineMemOperand *CPMMO =
5899     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5900                              MachineMemOperand::MOLoad, 4, 4);
5901
5902   MachineMemOperand *FIMMOSt =
5903     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5904                              MachineMemOperand::MOStore, 4, 4);
5905
5906   // Load the address of the dispatch MBB into the jump buffer.
5907   if (isThumb2) {
5908     // Incoming value: jbuf
5909     //   ldr.n  r5, LCPI1_1
5910     //   orr    r5, r5, #1
5911     //   add    r5, pc
5912     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5913     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5914     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5915                    .addConstantPoolIndex(CPI)
5916                    .addMemOperand(CPMMO));
5917     // Set the low bit because of thumb mode.
5918     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5919     AddDefaultCC(
5920       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5921                      .addReg(NewVReg1, RegState::Kill)
5922                      .addImm(0x01)));
5923     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5924     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5925       .addReg(NewVReg2, RegState::Kill)
5926       .addImm(PCLabelId);
5927     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5928                    .addReg(NewVReg3, RegState::Kill)
5929                    .addFrameIndex(FI)
5930                    .addImm(36)  // &jbuf[1] :: pc
5931                    .addMemOperand(FIMMOSt));
5932   } else if (isThumb) {
5933     // Incoming value: jbuf
5934     //   ldr.n  r1, LCPI1_4
5935     //   add    r1, pc
5936     //   mov    r2, #1
5937     //   orrs   r1, r2
5938     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5939     //   str    r1, [r2]
5940     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5941     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5942                    .addConstantPoolIndex(CPI)
5943                    .addMemOperand(CPMMO));
5944     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5945     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5946       .addReg(NewVReg1, RegState::Kill)
5947       .addImm(PCLabelId);
5948     // Set the low bit because of thumb mode.
5949     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5950     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5951                    .addReg(ARM::CPSR, RegState::Define)
5952                    .addImm(1));
5953     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5954     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5955                    .addReg(ARM::CPSR, RegState::Define)
5956                    .addReg(NewVReg2, RegState::Kill)
5957                    .addReg(NewVReg3, RegState::Kill));
5958     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5959     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5960                    .addFrameIndex(FI)
5961                    .addImm(36)); // &jbuf[1] :: pc
5962     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5963                    .addReg(NewVReg4, RegState::Kill)
5964                    .addReg(NewVReg5, RegState::Kill)
5965                    .addImm(0)
5966                    .addMemOperand(FIMMOSt));
5967   } else {
5968     // Incoming value: jbuf
5969     //   ldr  r1, LCPI1_1
5970     //   add  r1, pc, r1
5971     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5972     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5973     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5974                    .addConstantPoolIndex(CPI)
5975                    .addImm(0)
5976                    .addMemOperand(CPMMO));
5977     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5978     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5979                    .addReg(NewVReg1, RegState::Kill)
5980                    .addImm(PCLabelId));
5981     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5982                    .addReg(NewVReg2, RegState::Kill)
5983                    .addFrameIndex(FI)
5984                    .addImm(36)  // &jbuf[1] :: pc
5985                    .addMemOperand(FIMMOSt));
5986   }
5987 }
5988
5989 MachineBasicBlock *ARMTargetLowering::
5990 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5991   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5992   DebugLoc dl = MI->getDebugLoc();
5993   MachineFunction *MF = MBB->getParent();
5994   MachineRegisterInfo *MRI = &MF->getRegInfo();
5995   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5996   MachineFrameInfo *MFI = MF->getFrameInfo();
5997   int FI = MFI->getFunctionContextIndex();
5998
5999   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6000     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6001     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6002
6003   // Get a mapping of the call site numbers to all of the landing pads they're
6004   // associated with.
6005   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6006   unsigned MaxCSNum = 0;
6007   MachineModuleInfo &MMI = MF->getMMI();
6008   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6009        ++BB) {
6010     if (!BB->isLandingPad()) continue;
6011
6012     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6013     // pad.
6014     for (MachineBasicBlock::iterator
6015            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6016       if (!II->isEHLabel()) continue;
6017
6018       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6019       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6020
6021       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6022       for (SmallVectorImpl<unsigned>::iterator
6023              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6024            CSI != CSE; ++CSI) {
6025         CallSiteNumToLPad[*CSI].push_back(BB);
6026         MaxCSNum = std::max(MaxCSNum, *CSI);
6027       }
6028       break;
6029     }
6030   }
6031
6032   // Get an ordered list of the machine basic blocks for the jump table.
6033   std::vector<MachineBasicBlock*> LPadList;
6034   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6035   LPadList.reserve(CallSiteNumToLPad.size());
6036   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6037     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6038     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6039            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6040       LPadList.push_back(*II);
6041       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6042     }
6043   }
6044
6045   assert(!LPadList.empty() &&
6046          "No landing pad destinations for the dispatch jump table!");
6047
6048   // Create the jump table and associated information.
6049   MachineJumpTableInfo *JTI =
6050     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6051   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6052   unsigned UId = AFI->createJumpTableUId();
6053
6054   // Create the MBBs for the dispatch code.
6055
6056   // Shove the dispatch's address into the return slot in the function context.
6057   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6058   DispatchBB->setIsLandingPad();
6059
6060   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6061   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6062   DispatchBB->addSuccessor(TrapBB);
6063
6064   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6065   DispatchBB->addSuccessor(DispContBB);
6066
6067   // Insert and MBBs.
6068   MF->insert(MF->end(), DispatchBB);
6069   MF->insert(MF->end(), DispContBB);
6070   MF->insert(MF->end(), TrapBB);
6071
6072   // Insert code into the entry block that creates and registers the function
6073   // context.
6074   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6075
6076   MachineMemOperand *FIMMOLd =
6077     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6078                              MachineMemOperand::MOLoad |
6079                              MachineMemOperand::MOVolatile, 4, 4);
6080
6081   MachineInstrBuilder MIB;
6082   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6083
6084   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6085   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6086
6087   // Add a register mask with no preserved registers.  This results in all
6088   // registers being marked as clobbered.
6089   MIB.addRegMask(RI.getNoPreservedMask());
6090
6091   unsigned NumLPads = LPadList.size();
6092   if (Subtarget->isThumb2()) {
6093     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6094     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6095                    .addFrameIndex(FI)
6096                    .addImm(4)
6097                    .addMemOperand(FIMMOLd));
6098
6099     if (NumLPads < 256) {
6100       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6101                      .addReg(NewVReg1)
6102                      .addImm(LPadList.size()));
6103     } else {
6104       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6105       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6106                      .addImm(NumLPads & 0xFFFF));
6107
6108       unsigned VReg2 = VReg1;
6109       if ((NumLPads & 0xFFFF0000) != 0) {
6110         VReg2 = MRI->createVirtualRegister(TRC);
6111         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6112                        .addReg(VReg1)
6113                        .addImm(NumLPads >> 16));
6114       }
6115
6116       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6117                      .addReg(NewVReg1)
6118                      .addReg(VReg2));
6119     }
6120
6121     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6122       .addMBB(TrapBB)
6123       .addImm(ARMCC::HI)
6124       .addReg(ARM::CPSR);
6125
6126     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6127     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6128                    .addJumpTableIndex(MJTI)
6129                    .addImm(UId));
6130
6131     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6132     AddDefaultCC(
6133       AddDefaultPred(
6134         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6135         .addReg(NewVReg3, RegState::Kill)
6136         .addReg(NewVReg1)
6137         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6138
6139     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6140       .addReg(NewVReg4, RegState::Kill)
6141       .addReg(NewVReg1)
6142       .addJumpTableIndex(MJTI)
6143       .addImm(UId);
6144   } else if (Subtarget->isThumb()) {
6145     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6146     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6147                    .addFrameIndex(FI)
6148                    .addImm(1)
6149                    .addMemOperand(FIMMOLd));
6150
6151     if (NumLPads < 256) {
6152       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6153                      .addReg(NewVReg1)
6154                      .addImm(NumLPads));
6155     } else {
6156       MachineConstantPool *ConstantPool = MF->getConstantPool();
6157       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6158       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6159
6160       // MachineConstantPool wants an explicit alignment.
6161       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6162       if (Align == 0)
6163         Align = getDataLayout()->getTypeAllocSize(C->getType());
6164       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6165
6166       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6167       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6168                      .addReg(VReg1, RegState::Define)
6169                      .addConstantPoolIndex(Idx));
6170       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6171                      .addReg(NewVReg1)
6172                      .addReg(VReg1));
6173     }
6174
6175     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6176       .addMBB(TrapBB)
6177       .addImm(ARMCC::HI)
6178       .addReg(ARM::CPSR);
6179
6180     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6181     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6182                    .addReg(ARM::CPSR, RegState::Define)
6183                    .addReg(NewVReg1)
6184                    .addImm(2));
6185
6186     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6187     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6188                    .addJumpTableIndex(MJTI)
6189                    .addImm(UId));
6190
6191     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6192     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6193                    .addReg(ARM::CPSR, RegState::Define)
6194                    .addReg(NewVReg2, RegState::Kill)
6195                    .addReg(NewVReg3));
6196
6197     MachineMemOperand *JTMMOLd =
6198       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6199                                MachineMemOperand::MOLoad, 4, 4);
6200
6201     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6202     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6203                    .addReg(NewVReg4, RegState::Kill)
6204                    .addImm(0)
6205                    .addMemOperand(JTMMOLd));
6206
6207     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6208     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6209                    .addReg(ARM::CPSR, RegState::Define)
6210                    .addReg(NewVReg5, RegState::Kill)
6211                    .addReg(NewVReg3));
6212
6213     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6214       .addReg(NewVReg6, RegState::Kill)
6215       .addJumpTableIndex(MJTI)
6216       .addImm(UId);
6217   } else {
6218     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6219     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6220                    .addFrameIndex(FI)
6221                    .addImm(4)
6222                    .addMemOperand(FIMMOLd));
6223
6224     if (NumLPads < 256) {
6225       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6226                      .addReg(NewVReg1)
6227                      .addImm(NumLPads));
6228     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6229       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6230       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6231                      .addImm(NumLPads & 0xFFFF));
6232
6233       unsigned VReg2 = VReg1;
6234       if ((NumLPads & 0xFFFF0000) != 0) {
6235         VReg2 = MRI->createVirtualRegister(TRC);
6236         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6237                        .addReg(VReg1)
6238                        .addImm(NumLPads >> 16));
6239       }
6240
6241       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6242                      .addReg(NewVReg1)
6243                      .addReg(VReg2));
6244     } else {
6245       MachineConstantPool *ConstantPool = MF->getConstantPool();
6246       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6247       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6248
6249       // MachineConstantPool wants an explicit alignment.
6250       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6251       if (Align == 0)
6252         Align = getDataLayout()->getTypeAllocSize(C->getType());
6253       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6254
6255       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6256       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6257                      .addReg(VReg1, RegState::Define)
6258                      .addConstantPoolIndex(Idx)
6259                      .addImm(0));
6260       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6261                      .addReg(NewVReg1)
6262                      .addReg(VReg1, RegState::Kill));
6263     }
6264
6265     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6266       .addMBB(TrapBB)
6267       .addImm(ARMCC::HI)
6268       .addReg(ARM::CPSR);
6269
6270     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6271     AddDefaultCC(
6272       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6273                      .addReg(NewVReg1)
6274                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6275     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6276     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6277                    .addJumpTableIndex(MJTI)
6278                    .addImm(UId));
6279
6280     MachineMemOperand *JTMMOLd =
6281       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6282                                MachineMemOperand::MOLoad, 4, 4);
6283     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6284     AddDefaultPred(
6285       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6286       .addReg(NewVReg3, RegState::Kill)
6287       .addReg(NewVReg4)
6288       .addImm(0)
6289       .addMemOperand(JTMMOLd));
6290
6291     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6292       .addReg(NewVReg5, RegState::Kill)
6293       .addReg(NewVReg4)
6294       .addJumpTableIndex(MJTI)
6295       .addImm(UId);
6296   }
6297
6298   // Add the jump table entries as successors to the MBB.
6299   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6300   for (std::vector<MachineBasicBlock*>::iterator
6301          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6302     MachineBasicBlock *CurMBB = *I;
6303     if (SeenMBBs.insert(CurMBB))
6304       DispContBB->addSuccessor(CurMBB);
6305   }
6306
6307   // N.B. the order the invoke BBs are processed in doesn't matter here.
6308   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6309   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6310   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6311          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6312     MachineBasicBlock *BB = *I;
6313
6314     // Remove the landing pad successor from the invoke block and replace it
6315     // with the new dispatch block.
6316     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6317                                                   BB->succ_end());
6318     while (!Successors.empty()) {
6319       MachineBasicBlock *SMBB = Successors.pop_back_val();
6320       if (SMBB->isLandingPad()) {
6321         BB->removeSuccessor(SMBB);
6322         MBBLPads.push_back(SMBB);
6323       }
6324     }
6325
6326     BB->addSuccessor(DispatchBB);
6327
6328     // Find the invoke call and mark all of the callee-saved registers as
6329     // 'implicit defined' so that they're spilled. This prevents code from
6330     // moving instructions to before the EH block, where they will never be
6331     // executed.
6332     for (MachineBasicBlock::reverse_iterator
6333            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6334       if (!II->isCall()) continue;
6335
6336       DenseMap<unsigned, bool> DefRegs;
6337       for (MachineInstr::mop_iterator
6338              OI = II->operands_begin(), OE = II->operands_end();
6339            OI != OE; ++OI) {
6340         if (!OI->isReg()) continue;
6341         DefRegs[OI->getReg()] = true;
6342       }
6343
6344       MachineInstrBuilder MIB(&*II);
6345
6346       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6347         unsigned Reg = SavedRegs[i];
6348         if (Subtarget->isThumb2() &&
6349             !ARM::tGPRRegClass.contains(Reg) &&
6350             !ARM::hGPRRegClass.contains(Reg))
6351           continue;
6352         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6353           continue;
6354         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6355           continue;
6356         if (!DefRegs[Reg])
6357           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6358       }
6359
6360       break;
6361     }
6362   }
6363
6364   // Mark all former landing pads as non-landing pads. The dispatch is the only
6365   // landing pad now.
6366   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6367          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6368     (*I)->setIsLandingPad(false);
6369
6370   // The instruction is gone now.
6371   MI->eraseFromParent();
6372
6373   return MBB;
6374 }
6375
6376 static
6377 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6378   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6379        E = MBB->succ_end(); I != E; ++I)
6380     if (*I != Succ)
6381       return *I;
6382   llvm_unreachable("Expecting a BB with two successors!");
6383 }
6384
6385 MachineBasicBlock *ARMTargetLowering::
6386 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6387   // This pseudo instruction has 3 operands: dst, src, size
6388   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6389   // Otherwise, we will generate unrolled scalar copies.
6390   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6391   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6392   MachineFunction::iterator It = BB;
6393   ++It;
6394
6395   unsigned dest = MI->getOperand(0).getReg();
6396   unsigned src = MI->getOperand(1).getReg();
6397   unsigned SizeVal = MI->getOperand(2).getImm();
6398   unsigned Align = MI->getOperand(3).getImm();
6399   DebugLoc dl = MI->getDebugLoc();
6400
6401   bool isThumb2 = Subtarget->isThumb2();
6402   MachineFunction *MF = BB->getParent();
6403   MachineRegisterInfo &MRI = MF->getRegInfo();
6404   unsigned ldrOpc, strOpc, UnitSize = 0;
6405
6406   const TargetRegisterClass *TRC = isThumb2 ?
6407     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6408     (const TargetRegisterClass*)&ARM::GPRRegClass;
6409   const TargetRegisterClass *TRC_Vec = 0;
6410
6411   if (Align & 1) {
6412     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6413     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6414     UnitSize = 1;
6415   } else if (Align & 2) {
6416     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6417     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6418     UnitSize = 2;
6419   } else {
6420     // Check whether we can use NEON instructions.
6421     if (!MF->getFunction()->getFnAttributes().
6422           hasAttribute(Attributes::NoImplicitFloat) &&
6423         Subtarget->hasNEON()) {
6424       if ((Align % 16 == 0) && SizeVal >= 16) {
6425         ldrOpc = ARM::VLD1q32wb_fixed;
6426         strOpc = ARM::VST1q32wb_fixed;
6427         UnitSize = 16;
6428         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6429       }
6430       else if ((Align % 8 == 0) && SizeVal >= 8) {
6431         ldrOpc = ARM::VLD1d32wb_fixed;
6432         strOpc = ARM::VST1d32wb_fixed;
6433         UnitSize = 8;
6434         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6435       }
6436     }
6437     // Can't use NEON instructions.
6438     if (UnitSize == 0) {
6439       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6440       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6441       UnitSize = 4;
6442     }
6443   }
6444
6445   unsigned BytesLeft = SizeVal % UnitSize;
6446   unsigned LoopSize = SizeVal - BytesLeft;
6447
6448   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6449     // Use LDR and STR to copy.
6450     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6451     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6452     unsigned srcIn = src;
6453     unsigned destIn = dest;
6454     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6455       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6456       unsigned srcOut = MRI.createVirtualRegister(TRC);
6457       unsigned destOut = MRI.createVirtualRegister(TRC);
6458       if (UnitSize >= 8) {
6459         AddDefaultPred(BuildMI(*BB, MI, dl,
6460           TII->get(ldrOpc), scratch)
6461           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6462
6463         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6464           .addReg(destIn).addImm(0).addReg(scratch));
6465       } else if (isThumb2) {
6466         AddDefaultPred(BuildMI(*BB, MI, dl,
6467           TII->get(ldrOpc), scratch)
6468           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6469
6470         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6471           .addReg(scratch).addReg(destIn)
6472           .addImm(UnitSize));
6473       } else {
6474         AddDefaultPred(BuildMI(*BB, MI, dl,
6475           TII->get(ldrOpc), scratch)
6476           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6477           .addImm(UnitSize));
6478
6479         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6480           .addReg(scratch).addReg(destIn)
6481           .addReg(0).addImm(UnitSize));
6482       }
6483       srcIn = srcOut;
6484       destIn = destOut;
6485     }
6486
6487     // Handle the leftover bytes with LDRB and STRB.
6488     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6489     // [destOut] = STRB_POST(scratch, destIn, 1)
6490     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6491     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6492     for (unsigned i = 0; i < BytesLeft; i++) {
6493       unsigned scratch = MRI.createVirtualRegister(TRC);
6494       unsigned srcOut = MRI.createVirtualRegister(TRC);
6495       unsigned destOut = MRI.createVirtualRegister(TRC);
6496       if (isThumb2) {
6497         AddDefaultPred(BuildMI(*BB, MI, dl,
6498           TII->get(ldrOpc),scratch)
6499           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6500
6501         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6502           .addReg(scratch).addReg(destIn)
6503           .addReg(0).addImm(1));
6504       } else {
6505         AddDefaultPred(BuildMI(*BB, MI, dl,
6506           TII->get(ldrOpc),scratch)
6507           .addReg(srcOut, RegState::Define).addReg(srcIn)
6508           .addReg(0).addImm(1));
6509
6510         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6511           .addReg(scratch).addReg(destIn)
6512           .addReg(0).addImm(1));
6513       }
6514       srcIn = srcOut;
6515       destIn = destOut;
6516     }
6517     MI->eraseFromParent();   // The instruction is gone now.
6518     return BB;
6519   }
6520
6521   // Expand the pseudo op to a loop.
6522   // thisMBB:
6523   //   ...
6524   //   movw varEnd, # --> with thumb2
6525   //   movt varEnd, #
6526   //   ldrcp varEnd, idx --> without thumb2
6527   //   fallthrough --> loopMBB
6528   // loopMBB:
6529   //   PHI varPhi, varEnd, varLoop
6530   //   PHI srcPhi, src, srcLoop
6531   //   PHI destPhi, dst, destLoop
6532   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6533   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6534   //   subs varLoop, varPhi, #UnitSize
6535   //   bne loopMBB
6536   //   fallthrough --> exitMBB
6537   // exitMBB:
6538   //   epilogue to handle left-over bytes
6539   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6540   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6541   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6542   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6543   MF->insert(It, loopMBB);
6544   MF->insert(It, exitMBB);
6545
6546   // Transfer the remainder of BB and its successor edges to exitMBB.
6547   exitMBB->splice(exitMBB->begin(), BB,
6548                   llvm::next(MachineBasicBlock::iterator(MI)),
6549                   BB->end());
6550   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6551
6552   // Load an immediate to varEnd.
6553   unsigned varEnd = MRI.createVirtualRegister(TRC);
6554   if (isThumb2) {
6555     unsigned VReg1 = varEnd;
6556     if ((LoopSize & 0xFFFF0000) != 0)
6557       VReg1 = MRI.createVirtualRegister(TRC);
6558     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6559                    .addImm(LoopSize & 0xFFFF));
6560
6561     if ((LoopSize & 0xFFFF0000) != 0)
6562       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6563                      .addReg(VReg1)
6564                      .addImm(LoopSize >> 16));
6565   } else {
6566     MachineConstantPool *ConstantPool = MF->getConstantPool();
6567     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6568     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6569
6570     // MachineConstantPool wants an explicit alignment.
6571     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6572     if (Align == 0)
6573       Align = getDataLayout()->getTypeAllocSize(C->getType());
6574     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6575
6576     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6577                    .addReg(varEnd, RegState::Define)
6578                    .addConstantPoolIndex(Idx)
6579                    .addImm(0));
6580   }
6581   BB->addSuccessor(loopMBB);
6582
6583   // Generate the loop body:
6584   //   varPhi = PHI(varLoop, varEnd)
6585   //   srcPhi = PHI(srcLoop, src)
6586   //   destPhi = PHI(destLoop, dst)
6587   MachineBasicBlock *entryBB = BB;
6588   BB = loopMBB;
6589   unsigned varLoop = MRI.createVirtualRegister(TRC);
6590   unsigned varPhi = MRI.createVirtualRegister(TRC);
6591   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6592   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6593   unsigned destLoop = MRI.createVirtualRegister(TRC);
6594   unsigned destPhi = MRI.createVirtualRegister(TRC);
6595
6596   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6597     .addReg(varLoop).addMBB(loopMBB)
6598     .addReg(varEnd).addMBB(entryBB);
6599   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6600     .addReg(srcLoop).addMBB(loopMBB)
6601     .addReg(src).addMBB(entryBB);
6602   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6603     .addReg(destLoop).addMBB(loopMBB)
6604     .addReg(dest).addMBB(entryBB);
6605
6606   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6607   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6608   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6609   if (UnitSize >= 8) {
6610     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6611       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6612
6613     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6614       .addReg(destPhi).addImm(0).addReg(scratch));
6615   } else if (isThumb2) {
6616     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6617       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6618
6619     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6620       .addReg(scratch).addReg(destPhi)
6621       .addImm(UnitSize));
6622   } else {
6623     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6624       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6625       .addImm(UnitSize));
6626
6627     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6628       .addReg(scratch).addReg(destPhi)
6629       .addReg(0).addImm(UnitSize));
6630   }
6631
6632   // Decrement loop variable by UnitSize.
6633   MachineInstrBuilder MIB = BuildMI(BB, dl,
6634     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6635   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6636   MIB->getOperand(5).setReg(ARM::CPSR);
6637   MIB->getOperand(5).setIsDef(true);
6638
6639   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6640     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6641
6642   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6643   BB->addSuccessor(loopMBB);
6644   BB->addSuccessor(exitMBB);
6645
6646   // Add epilogue to handle BytesLeft.
6647   BB = exitMBB;
6648   MachineInstr *StartOfExit = exitMBB->begin();
6649   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6650   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6651
6652   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6653   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6654   unsigned srcIn = srcLoop;
6655   unsigned destIn = destLoop;
6656   for (unsigned i = 0; i < BytesLeft; i++) {
6657     unsigned scratch = MRI.createVirtualRegister(TRC);
6658     unsigned srcOut = MRI.createVirtualRegister(TRC);
6659     unsigned destOut = MRI.createVirtualRegister(TRC);
6660     if (isThumb2) {
6661       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6662         TII->get(ldrOpc),scratch)
6663         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6664
6665       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6666         .addReg(scratch).addReg(destIn)
6667         .addImm(1));
6668     } else {
6669       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6670         TII->get(ldrOpc),scratch)
6671         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6672
6673       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6674         .addReg(scratch).addReg(destIn)
6675         .addReg(0).addImm(1));
6676     }
6677     srcIn = srcOut;
6678     destIn = destOut;
6679   }
6680
6681   MI->eraseFromParent();   // The instruction is gone now.
6682   return BB;
6683 }
6684
6685 MachineBasicBlock *
6686 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6687                                                MachineBasicBlock *BB) const {
6688   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6689   DebugLoc dl = MI->getDebugLoc();
6690   bool isThumb2 = Subtarget->isThumb2();
6691   switch (MI->getOpcode()) {
6692   default: {
6693     MI->dump();
6694     llvm_unreachable("Unexpected instr type to insert");
6695   }
6696   // The Thumb2 pre-indexed stores have the same MI operands, they just
6697   // define them differently in the .td files from the isel patterns, so
6698   // they need pseudos.
6699   case ARM::t2STR_preidx:
6700     MI->setDesc(TII->get(ARM::t2STR_PRE));
6701     return BB;
6702   case ARM::t2STRB_preidx:
6703     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6704     return BB;
6705   case ARM::t2STRH_preidx:
6706     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6707     return BB;
6708
6709   case ARM::STRi_preidx:
6710   case ARM::STRBi_preidx: {
6711     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6712       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6713     // Decode the offset.
6714     unsigned Offset = MI->getOperand(4).getImm();
6715     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6716     Offset = ARM_AM::getAM2Offset(Offset);
6717     if (isSub)
6718       Offset = -Offset;
6719
6720     MachineMemOperand *MMO = *MI->memoperands_begin();
6721     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6722       .addOperand(MI->getOperand(0))  // Rn_wb
6723       .addOperand(MI->getOperand(1))  // Rt
6724       .addOperand(MI->getOperand(2))  // Rn
6725       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6726       .addOperand(MI->getOperand(5))  // pred
6727       .addOperand(MI->getOperand(6))
6728       .addMemOperand(MMO);
6729     MI->eraseFromParent();
6730     return BB;
6731   }
6732   case ARM::STRr_preidx:
6733   case ARM::STRBr_preidx:
6734   case ARM::STRH_preidx: {
6735     unsigned NewOpc;
6736     switch (MI->getOpcode()) {
6737     default: llvm_unreachable("unexpected opcode!");
6738     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6739     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6740     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6741     }
6742     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6743     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6744       MIB.addOperand(MI->getOperand(i));
6745     MI->eraseFromParent();
6746     return BB;
6747   }
6748   case ARM::ATOMIC_LOAD_ADD_I8:
6749      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6750   case ARM::ATOMIC_LOAD_ADD_I16:
6751      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6752   case ARM::ATOMIC_LOAD_ADD_I32:
6753      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6754
6755   case ARM::ATOMIC_LOAD_AND_I8:
6756      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6757   case ARM::ATOMIC_LOAD_AND_I16:
6758      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6759   case ARM::ATOMIC_LOAD_AND_I32:
6760      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6761
6762   case ARM::ATOMIC_LOAD_OR_I8:
6763      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6764   case ARM::ATOMIC_LOAD_OR_I16:
6765      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6766   case ARM::ATOMIC_LOAD_OR_I32:
6767      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6768
6769   case ARM::ATOMIC_LOAD_XOR_I8:
6770      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6771   case ARM::ATOMIC_LOAD_XOR_I16:
6772      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6773   case ARM::ATOMIC_LOAD_XOR_I32:
6774      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6775
6776   case ARM::ATOMIC_LOAD_NAND_I8:
6777      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6778   case ARM::ATOMIC_LOAD_NAND_I16:
6779      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6780   case ARM::ATOMIC_LOAD_NAND_I32:
6781      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6782
6783   case ARM::ATOMIC_LOAD_SUB_I8:
6784      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6785   case ARM::ATOMIC_LOAD_SUB_I16:
6786      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6787   case ARM::ATOMIC_LOAD_SUB_I32:
6788      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6789
6790   case ARM::ATOMIC_LOAD_MIN_I8:
6791      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6792   case ARM::ATOMIC_LOAD_MIN_I16:
6793      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6794   case ARM::ATOMIC_LOAD_MIN_I32:
6795      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6796
6797   case ARM::ATOMIC_LOAD_MAX_I8:
6798      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6799   case ARM::ATOMIC_LOAD_MAX_I16:
6800      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6801   case ARM::ATOMIC_LOAD_MAX_I32:
6802      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6803
6804   case ARM::ATOMIC_LOAD_UMIN_I8:
6805      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6806   case ARM::ATOMIC_LOAD_UMIN_I16:
6807      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6808   case ARM::ATOMIC_LOAD_UMIN_I32:
6809      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6810
6811   case ARM::ATOMIC_LOAD_UMAX_I8:
6812      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6813   case ARM::ATOMIC_LOAD_UMAX_I16:
6814      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6815   case ARM::ATOMIC_LOAD_UMAX_I32:
6816      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6817
6818   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6819   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6820   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6821
6822   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6823   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6824   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6825
6826
6827   case ARM::ATOMADD6432:
6828     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6829                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6830                               /*NeedsCarry*/ true);
6831   case ARM::ATOMSUB6432:
6832     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6833                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6834                               /*NeedsCarry*/ true);
6835   case ARM::ATOMOR6432:
6836     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6837                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6838   case ARM::ATOMXOR6432:
6839     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6840                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6841   case ARM::ATOMAND6432:
6842     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6843                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6844   case ARM::ATOMSWAP6432:
6845     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6846   case ARM::ATOMCMPXCHG6432:
6847     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6848                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6849                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6850
6851   case ARM::tMOVCCr_pseudo: {
6852     // To "insert" a SELECT_CC instruction, we actually have to insert the
6853     // diamond control-flow pattern.  The incoming instruction knows the
6854     // destination vreg to set, the condition code register to branch on, the
6855     // true/false values to select between, and a branch opcode to use.
6856     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6857     MachineFunction::iterator It = BB;
6858     ++It;
6859
6860     //  thisMBB:
6861     //  ...
6862     //   TrueVal = ...
6863     //   cmpTY ccX, r1, r2
6864     //   bCC copy1MBB
6865     //   fallthrough --> copy0MBB
6866     MachineBasicBlock *thisMBB  = BB;
6867     MachineFunction *F = BB->getParent();
6868     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6869     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6870     F->insert(It, copy0MBB);
6871     F->insert(It, sinkMBB);
6872
6873     // Transfer the remainder of BB and its successor edges to sinkMBB.
6874     sinkMBB->splice(sinkMBB->begin(), BB,
6875                     llvm::next(MachineBasicBlock::iterator(MI)),
6876                     BB->end());
6877     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6878
6879     BB->addSuccessor(copy0MBB);
6880     BB->addSuccessor(sinkMBB);
6881
6882     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6883       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6884
6885     //  copy0MBB:
6886     //   %FalseValue = ...
6887     //   # fallthrough to sinkMBB
6888     BB = copy0MBB;
6889
6890     // Update machine-CFG edges
6891     BB->addSuccessor(sinkMBB);
6892
6893     //  sinkMBB:
6894     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6895     //  ...
6896     BB = sinkMBB;
6897     BuildMI(*BB, BB->begin(), dl,
6898             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6899       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6900       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6901
6902     MI->eraseFromParent();   // The pseudo instruction is gone now.
6903     return BB;
6904   }
6905
6906   case ARM::BCCi64:
6907   case ARM::BCCZi64: {
6908     // If there is an unconditional branch to the other successor, remove it.
6909     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6910
6911     // Compare both parts that make up the double comparison separately for
6912     // equality.
6913     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6914
6915     unsigned LHS1 = MI->getOperand(1).getReg();
6916     unsigned LHS2 = MI->getOperand(2).getReg();
6917     if (RHSisZero) {
6918       AddDefaultPred(BuildMI(BB, dl,
6919                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6920                      .addReg(LHS1).addImm(0));
6921       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6922         .addReg(LHS2).addImm(0)
6923         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6924     } else {
6925       unsigned RHS1 = MI->getOperand(3).getReg();
6926       unsigned RHS2 = MI->getOperand(4).getReg();
6927       AddDefaultPred(BuildMI(BB, dl,
6928                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6929                      .addReg(LHS1).addReg(RHS1));
6930       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6931         .addReg(LHS2).addReg(RHS2)
6932         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6933     }
6934
6935     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6936     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6937     if (MI->getOperand(0).getImm() == ARMCC::NE)
6938       std::swap(destMBB, exitMBB);
6939
6940     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6941       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6942     if (isThumb2)
6943       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6944     else
6945       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6946
6947     MI->eraseFromParent();   // The pseudo instruction is gone now.
6948     return BB;
6949   }
6950
6951   case ARM::Int_eh_sjlj_setjmp:
6952   case ARM::Int_eh_sjlj_setjmp_nofp:
6953   case ARM::tInt_eh_sjlj_setjmp:
6954   case ARM::t2Int_eh_sjlj_setjmp:
6955   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6956     EmitSjLjDispatchBlock(MI, BB);
6957     return BB;
6958
6959   case ARM::ABS:
6960   case ARM::t2ABS: {
6961     // To insert an ABS instruction, we have to insert the
6962     // diamond control-flow pattern.  The incoming instruction knows the
6963     // source vreg to test against 0, the destination vreg to set,
6964     // the condition code register to branch on, the
6965     // true/false values to select between, and a branch opcode to use.
6966     // It transforms
6967     //     V1 = ABS V0
6968     // into
6969     //     V2 = MOVS V0
6970     //     BCC                      (branch to SinkBB if V0 >= 0)
6971     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6972     //     SinkBB: V1 = PHI(V2, V3)
6973     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6974     MachineFunction::iterator BBI = BB;
6975     ++BBI;
6976     MachineFunction *Fn = BB->getParent();
6977     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6978     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6979     Fn->insert(BBI, RSBBB);
6980     Fn->insert(BBI, SinkBB);
6981
6982     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6983     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6984     bool isThumb2 = Subtarget->isThumb2();
6985     MachineRegisterInfo &MRI = Fn->getRegInfo();
6986     // In Thumb mode S must not be specified if source register is the SP or
6987     // PC and if destination register is the SP, so restrict register class
6988     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6989       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6990       (const TargetRegisterClass*)&ARM::GPRRegClass);
6991
6992     // Transfer the remainder of BB and its successor edges to sinkMBB.
6993     SinkBB->splice(SinkBB->begin(), BB,
6994       llvm::next(MachineBasicBlock::iterator(MI)),
6995       BB->end());
6996     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6997
6998     BB->addSuccessor(RSBBB);
6999     BB->addSuccessor(SinkBB);
7000
7001     // fall through to SinkMBB
7002     RSBBB->addSuccessor(SinkBB);
7003
7004     // insert a cmp at the end of BB
7005     AddDefaultPred(BuildMI(BB, dl,
7006                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7007                    .addReg(ABSSrcReg).addImm(0));
7008
7009     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7010     BuildMI(BB, dl,
7011       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7012       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7013
7014     // insert rsbri in RSBBB
7015     // Note: BCC and rsbri will be converted into predicated rsbmi
7016     // by if-conversion pass
7017     BuildMI(*RSBBB, RSBBB->begin(), dl,
7018       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7019       .addReg(ABSSrcReg, RegState::Kill)
7020       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7021
7022     // insert PHI in SinkBB,
7023     // reuse ABSDstReg to not change uses of ABS instruction
7024     BuildMI(*SinkBB, SinkBB->begin(), dl,
7025       TII->get(ARM::PHI), ABSDstReg)
7026       .addReg(NewRsbDstReg).addMBB(RSBBB)
7027       .addReg(ABSSrcReg).addMBB(BB);
7028
7029     // remove ABS instruction
7030     MI->eraseFromParent();
7031
7032     // return last added BB
7033     return SinkBB;
7034   }
7035   case ARM::COPY_STRUCT_BYVAL_I32:
7036     ++NumLoopByVals;
7037     return EmitStructByval(MI, BB);
7038   }
7039 }
7040
7041 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7042                                                       SDNode *Node) const {
7043   if (!MI->hasPostISelHook()) {
7044     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7045            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7046     return;
7047   }
7048
7049   const MCInstrDesc *MCID = &MI->getDesc();
7050   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7051   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7052   // operand is still set to noreg. If needed, set the optional operand's
7053   // register to CPSR, and remove the redundant implicit def.
7054   //
7055   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7056
7057   // Rename pseudo opcodes.
7058   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7059   if (NewOpc) {
7060     const ARMBaseInstrInfo *TII =
7061       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7062     MCID = &TII->get(NewOpc);
7063
7064     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7065            "converted opcode should be the same except for cc_out");
7066
7067     MI->setDesc(*MCID);
7068
7069     // Add the optional cc_out operand
7070     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7071   }
7072   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7073
7074   // Any ARM instruction that sets the 's' bit should specify an optional
7075   // "cc_out" operand in the last operand position.
7076   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7077     assert(!NewOpc && "Optional cc_out operand required");
7078     return;
7079   }
7080   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7081   // since we already have an optional CPSR def.
7082   bool definesCPSR = false;
7083   bool deadCPSR = false;
7084   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7085        i != e; ++i) {
7086     const MachineOperand &MO = MI->getOperand(i);
7087     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7088       definesCPSR = true;
7089       if (MO.isDead())
7090         deadCPSR = true;
7091       MI->RemoveOperand(i);
7092       break;
7093     }
7094   }
7095   if (!definesCPSR) {
7096     assert(!NewOpc && "Optional cc_out operand required");
7097     return;
7098   }
7099   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7100   if (deadCPSR) {
7101     assert(!MI->getOperand(ccOutIdx).getReg() &&
7102            "expect uninitialized optional cc_out operand");
7103     return;
7104   }
7105
7106   // If this instruction was defined with an optional CPSR def and its dag node
7107   // had a live implicit CPSR def, then activate the optional CPSR def.
7108   MachineOperand &MO = MI->getOperand(ccOutIdx);
7109   MO.setReg(ARM::CPSR);
7110   MO.setIsDef(true);
7111 }
7112
7113 //===----------------------------------------------------------------------===//
7114 //                           ARM Optimization Hooks
7115 //===----------------------------------------------------------------------===//
7116
7117 // Helper function that checks if N is a null or all ones constant.
7118 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7119   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7120   if (!C)
7121     return false;
7122   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7123 }
7124
7125 // Return true if N is conditionally 0 or all ones.
7126 // Detects these expressions where cc is an i1 value:
7127 //
7128 //   (select cc 0, y)   [AllOnes=0]
7129 //   (select cc y, 0)   [AllOnes=0]
7130 //   (zext cc)          [AllOnes=0]
7131 //   (sext cc)          [AllOnes=0/1]
7132 //   (select cc -1, y)  [AllOnes=1]
7133 //   (select cc y, -1)  [AllOnes=1]
7134 //
7135 // Invert is set when N is the null/all ones constant when CC is false.
7136 // OtherOp is set to the alternative value of N.
7137 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7138                                        SDValue &CC, bool &Invert,
7139                                        SDValue &OtherOp,
7140                                        SelectionDAG &DAG) {
7141   switch (N->getOpcode()) {
7142   default: return false;
7143   case ISD::SELECT: {
7144     CC = N->getOperand(0);
7145     SDValue N1 = N->getOperand(1);
7146     SDValue N2 = N->getOperand(2);
7147     if (isZeroOrAllOnes(N1, AllOnes)) {
7148       Invert = false;
7149       OtherOp = N2;
7150       return true;
7151     }
7152     if (isZeroOrAllOnes(N2, AllOnes)) {
7153       Invert = true;
7154       OtherOp = N1;
7155       return true;
7156     }
7157     return false;
7158   }
7159   case ISD::ZERO_EXTEND:
7160     // (zext cc) can never be the all ones value.
7161     if (AllOnes)
7162       return false;
7163     // Fall through.
7164   case ISD::SIGN_EXTEND: {
7165     EVT VT = N->getValueType(0);
7166     CC = N->getOperand(0);
7167     if (CC.getValueType() != MVT::i1)
7168       return false;
7169     Invert = !AllOnes;
7170     if (AllOnes)
7171       // When looking for an AllOnes constant, N is an sext, and the 'other'
7172       // value is 0.
7173       OtherOp = DAG.getConstant(0, VT);
7174     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7175       // When looking for a 0 constant, N can be zext or sext.
7176       OtherOp = DAG.getConstant(1, VT);
7177     else
7178       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7179     return true;
7180   }
7181   }
7182 }
7183
7184 // Combine a constant select operand into its use:
7185 //
7186 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7187 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7188 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7189 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7190 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7191 //
7192 // The transform is rejected if the select doesn't have a constant operand that
7193 // is null, or all ones when AllOnes is set.
7194 //
7195 // Also recognize sext/zext from i1:
7196 //
7197 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7198 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7199 //
7200 // These transformations eventually create predicated instructions.
7201 //
7202 // @param N       The node to transform.
7203 // @param Slct    The N operand that is a select.
7204 // @param OtherOp The other N operand (x above).
7205 // @param DCI     Context.
7206 // @param AllOnes Require the select constant to be all ones instead of null.
7207 // @returns The new node, or SDValue() on failure.
7208 static
7209 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7210                             TargetLowering::DAGCombinerInfo &DCI,
7211                             bool AllOnes = false) {
7212   SelectionDAG &DAG = DCI.DAG;
7213   EVT VT = N->getValueType(0);
7214   SDValue NonConstantVal;
7215   SDValue CCOp;
7216   bool SwapSelectOps;
7217   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7218                                   NonConstantVal, DAG))
7219     return SDValue();
7220
7221   // Slct is now know to be the desired identity constant when CC is true.
7222   SDValue TrueVal = OtherOp;
7223   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7224                                  OtherOp, NonConstantVal);
7225   // Unless SwapSelectOps says CC should be false.
7226   if (SwapSelectOps)
7227     std::swap(TrueVal, FalseVal);
7228
7229   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7230                      CCOp, TrueVal, FalseVal);
7231 }
7232
7233 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7234 static
7235 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7236                                        TargetLowering::DAGCombinerInfo &DCI) {
7237   SDValue N0 = N->getOperand(0);
7238   SDValue N1 = N->getOperand(1);
7239   if (N0.getNode()->hasOneUse()) {
7240     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7241     if (Result.getNode())
7242       return Result;
7243   }
7244   if (N1.getNode()->hasOneUse()) {
7245     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7246     if (Result.getNode())
7247       return Result;
7248   }
7249   return SDValue();
7250 }
7251
7252 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7253 // (only after legalization).
7254 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7255                                  TargetLowering::DAGCombinerInfo &DCI,
7256                                  const ARMSubtarget *Subtarget) {
7257
7258   // Only perform optimization if after legalize, and if NEON is available. We
7259   // also expected both operands to be BUILD_VECTORs.
7260   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7261       || N0.getOpcode() != ISD::BUILD_VECTOR
7262       || N1.getOpcode() != ISD::BUILD_VECTOR)
7263     return SDValue();
7264
7265   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7266   EVT VT = N->getValueType(0);
7267   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7268     return SDValue();
7269
7270   // Check that the vector operands are of the right form.
7271   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7272   // operands, where N is the size of the formed vector.
7273   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7274   // index such that we have a pair wise add pattern.
7275
7276   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7277   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7278     return SDValue();
7279   SDValue Vec = N0->getOperand(0)->getOperand(0);
7280   SDNode *V = Vec.getNode();
7281   unsigned nextIndex = 0;
7282
7283   // For each operands to the ADD which are BUILD_VECTORs,
7284   // check to see if each of their operands are an EXTRACT_VECTOR with
7285   // the same vector and appropriate index.
7286   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7287     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7288         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7289
7290       SDValue ExtVec0 = N0->getOperand(i);
7291       SDValue ExtVec1 = N1->getOperand(i);
7292
7293       // First operand is the vector, verify its the same.
7294       if (V != ExtVec0->getOperand(0).getNode() ||
7295           V != ExtVec1->getOperand(0).getNode())
7296         return SDValue();
7297
7298       // Second is the constant, verify its correct.
7299       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7300       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7301
7302       // For the constant, we want to see all the even or all the odd.
7303       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7304           || C1->getZExtValue() != nextIndex+1)
7305         return SDValue();
7306
7307       // Increment index.
7308       nextIndex+=2;
7309     } else
7310       return SDValue();
7311   }
7312
7313   // Create VPADDL node.
7314   SelectionDAG &DAG = DCI.DAG;
7315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7316
7317   // Build operand list.
7318   SmallVector<SDValue, 8> Ops;
7319   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7320                                 TLI.getPointerTy()));
7321
7322   // Input is the vector.
7323   Ops.push_back(Vec);
7324
7325   // Get widened type and narrowed type.
7326   MVT widenType;
7327   unsigned numElem = VT.getVectorNumElements();
7328   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7329     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7330     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7331     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7332     default:
7333       llvm_unreachable("Invalid vector element type for padd optimization.");
7334   }
7335
7336   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7337                             widenType, &Ops[0], Ops.size());
7338   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7339 }
7340
7341 static SDValue findMUL_LOHI(SDValue V) {
7342   if (V->getOpcode() == ISD::UMUL_LOHI ||
7343       V->getOpcode() == ISD::SMUL_LOHI)
7344     return V;
7345   return SDValue();
7346 }
7347
7348 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7349                                      TargetLowering::DAGCombinerInfo &DCI,
7350                                      const ARMSubtarget *Subtarget) {
7351
7352   if (Subtarget->isThumb1Only()) return SDValue();
7353
7354   // Only perform the checks after legalize when the pattern is available.
7355   if (DCI.isBeforeLegalize()) return SDValue();
7356
7357   // Look for multiply add opportunities.
7358   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7359   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7360   // a glue link from the first add to the second add.
7361   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7362   // a S/UMLAL instruction.
7363   //          loAdd   UMUL_LOHI
7364   //            \    / :lo    \ :hi
7365   //             \  /          \          [no multiline comment]
7366   //              ADDC         |  hiAdd
7367   //                 \ :glue  /  /
7368   //                  \      /  /
7369   //                    ADDE
7370   //
7371   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7372   SDValue AddcOp0 = AddcNode->getOperand(0);
7373   SDValue AddcOp1 = AddcNode->getOperand(1);
7374
7375   // Check if the two operands are from the same mul_lohi node.
7376   if (AddcOp0.getNode() == AddcOp1.getNode())
7377     return SDValue();
7378
7379   assert(AddcNode->getNumValues() == 2 &&
7380          AddcNode->getValueType(0) == MVT::i32 &&
7381          AddcNode->getValueType(1) == MVT::Glue &&
7382          "Expect ADDC with two result values: i32, glue");
7383
7384   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7385   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7386       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7387       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7388       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7389     return SDValue();
7390
7391   // Look for the glued ADDE.
7392   SDNode* AddeNode = AddcNode->getGluedUser();
7393   if (AddeNode == NULL)
7394     return SDValue();
7395
7396   // Make sure it is really an ADDE.
7397   if (AddeNode->getOpcode() != ISD::ADDE)
7398     return SDValue();
7399
7400   assert(AddeNode->getNumOperands() == 3 &&
7401          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7402          "ADDE node has the wrong inputs");
7403
7404   // Check for the triangle shape.
7405   SDValue AddeOp0 = AddeNode->getOperand(0);
7406   SDValue AddeOp1 = AddeNode->getOperand(1);
7407
7408   // Make sure that the ADDE operands are not coming from the same node.
7409   if (AddeOp0.getNode() == AddeOp1.getNode())
7410     return SDValue();
7411
7412   // Find the MUL_LOHI node walking up ADDE's operands.
7413   bool IsLeftOperandMUL = false;
7414   SDValue MULOp = findMUL_LOHI(AddeOp0);
7415   if (MULOp == SDValue())
7416    MULOp = findMUL_LOHI(AddeOp1);
7417   else
7418     IsLeftOperandMUL = true;
7419   if (MULOp == SDValue())
7420      return SDValue();
7421
7422   // Figure out the right opcode.
7423   unsigned Opc = MULOp->getOpcode();
7424   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7425
7426   // Figure out the high and low input values to the MLAL node.
7427   SDValue* HiMul = &MULOp;
7428   SDValue* HiAdd = NULL;
7429   SDValue* LoMul = NULL;
7430   SDValue* LowAdd = NULL;
7431
7432   if (IsLeftOperandMUL)
7433     HiAdd = &AddeOp1;
7434   else
7435     HiAdd = &AddeOp0;
7436
7437
7438   if (AddcOp0->getOpcode() == Opc) {
7439     LoMul = &AddcOp0;
7440     LowAdd = &AddcOp1;
7441   }
7442   if (AddcOp1->getOpcode() == Opc) {
7443     LoMul = &AddcOp1;
7444     LowAdd = &AddcOp0;
7445   }
7446
7447   if (LoMul == NULL)
7448     return SDValue();
7449
7450   if (LoMul->getNode() != HiMul->getNode())
7451     return SDValue();
7452
7453   // Create the merged node.
7454   SelectionDAG &DAG = DCI.DAG;
7455
7456   // Build operand list.
7457   SmallVector<SDValue, 8> Ops;
7458   Ops.push_back(LoMul->getOperand(0));
7459   Ops.push_back(LoMul->getOperand(1));
7460   Ops.push_back(*LowAdd);
7461   Ops.push_back(*HiAdd);
7462
7463   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7464                                  DAG.getVTList(MVT::i32, MVT::i32),
7465                                  &Ops[0], Ops.size());
7466
7467   // Replace the ADDs' nodes uses by the MLA node's values.
7468   SDValue HiMLALResult(MLALNode.getNode(), 1);
7469   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7470
7471   SDValue LoMLALResult(MLALNode.getNode(), 0);
7472   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7473
7474   // Return original node to notify the driver to stop replacing.
7475   SDValue resNode(AddcNode, 0);
7476   return resNode;
7477 }
7478
7479 /// PerformADDCCombine - Target-specific dag combine transform from
7480 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7481 static SDValue PerformADDCCombine(SDNode *N,
7482                                  TargetLowering::DAGCombinerInfo &DCI,
7483                                  const ARMSubtarget *Subtarget) {
7484
7485   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7486
7487 }
7488
7489 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7490 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7491 /// called with the default operands, and if that fails, with commuted
7492 /// operands.
7493 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7494                                           TargetLowering::DAGCombinerInfo &DCI,
7495                                           const ARMSubtarget *Subtarget){
7496
7497   // Attempt to create vpaddl for this add.
7498   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7499   if (Result.getNode())
7500     return Result;
7501
7502   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7503   if (N0.getNode()->hasOneUse()) {
7504     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7505     if (Result.getNode()) return Result;
7506   }
7507   return SDValue();
7508 }
7509
7510 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7511 ///
7512 static SDValue PerformADDCombine(SDNode *N,
7513                                  TargetLowering::DAGCombinerInfo &DCI,
7514                                  const ARMSubtarget *Subtarget) {
7515   SDValue N0 = N->getOperand(0);
7516   SDValue N1 = N->getOperand(1);
7517
7518   // First try with the default operand order.
7519   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7520   if (Result.getNode())
7521     return Result;
7522
7523   // If that didn't work, try again with the operands commuted.
7524   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7525 }
7526
7527 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7528 ///
7529 static SDValue PerformSUBCombine(SDNode *N,
7530                                  TargetLowering::DAGCombinerInfo &DCI) {
7531   SDValue N0 = N->getOperand(0);
7532   SDValue N1 = N->getOperand(1);
7533
7534   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7535   if (N1.getNode()->hasOneUse()) {
7536     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7537     if (Result.getNode()) return Result;
7538   }
7539
7540   return SDValue();
7541 }
7542
7543 /// PerformVMULCombine
7544 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7545 /// special multiplier accumulator forwarding.
7546 ///   vmul d3, d0, d2
7547 ///   vmla d3, d1, d2
7548 /// is faster than
7549 ///   vadd d3, d0, d1
7550 ///   vmul d3, d3, d2
7551 static SDValue PerformVMULCombine(SDNode *N,
7552                                   TargetLowering::DAGCombinerInfo &DCI,
7553                                   const ARMSubtarget *Subtarget) {
7554   if (!Subtarget->hasVMLxForwarding())
7555     return SDValue();
7556
7557   SelectionDAG &DAG = DCI.DAG;
7558   SDValue N0 = N->getOperand(0);
7559   SDValue N1 = N->getOperand(1);
7560   unsigned Opcode = N0.getOpcode();
7561   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7562       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7563     Opcode = N1.getOpcode();
7564     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7565         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7566       return SDValue();
7567     std::swap(N0, N1);
7568   }
7569
7570   EVT VT = N->getValueType(0);
7571   DebugLoc DL = N->getDebugLoc();
7572   SDValue N00 = N0->getOperand(0);
7573   SDValue N01 = N0->getOperand(1);
7574   return DAG.getNode(Opcode, DL, VT,
7575                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7576                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7577 }
7578
7579 static SDValue PerformMULCombine(SDNode *N,
7580                                  TargetLowering::DAGCombinerInfo &DCI,
7581                                  const ARMSubtarget *Subtarget) {
7582   SelectionDAG &DAG = DCI.DAG;
7583
7584   if (Subtarget->isThumb1Only())
7585     return SDValue();
7586
7587   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7588     return SDValue();
7589
7590   EVT VT = N->getValueType(0);
7591   if (VT.is64BitVector() || VT.is128BitVector())
7592     return PerformVMULCombine(N, DCI, Subtarget);
7593   if (VT != MVT::i32)
7594     return SDValue();
7595
7596   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7597   if (!C)
7598     return SDValue();
7599
7600   int64_t MulAmt = C->getSExtValue();
7601   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7602
7603   ShiftAmt = ShiftAmt & (32 - 1);
7604   SDValue V = N->getOperand(0);
7605   DebugLoc DL = N->getDebugLoc();
7606
7607   SDValue Res;
7608   MulAmt >>= ShiftAmt;
7609
7610   if (MulAmt >= 0) {
7611     if (isPowerOf2_32(MulAmt - 1)) {
7612       // (mul x, 2^N + 1) => (add (shl x, N), x)
7613       Res = DAG.getNode(ISD::ADD, DL, VT,
7614                         V,
7615                         DAG.getNode(ISD::SHL, DL, VT,
7616                                     V,
7617                                     DAG.getConstant(Log2_32(MulAmt - 1),
7618                                                     MVT::i32)));
7619     } else if (isPowerOf2_32(MulAmt + 1)) {
7620       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7621       Res = DAG.getNode(ISD::SUB, DL, VT,
7622                         DAG.getNode(ISD::SHL, DL, VT,
7623                                     V,
7624                                     DAG.getConstant(Log2_32(MulAmt + 1),
7625                                                     MVT::i32)),
7626                         V);
7627     } else
7628       return SDValue();
7629   } else {
7630     uint64_t MulAmtAbs = -MulAmt;
7631     if (isPowerOf2_32(MulAmtAbs + 1)) {
7632       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7633       Res = DAG.getNode(ISD::SUB, DL, VT,
7634                         V,
7635                         DAG.getNode(ISD::SHL, DL, VT,
7636                                     V,
7637                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7638                                                     MVT::i32)));
7639     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7640       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7641       Res = DAG.getNode(ISD::ADD, DL, VT,
7642                         V,
7643                         DAG.getNode(ISD::SHL, DL, VT,
7644                                     V,
7645                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7646                                                     MVT::i32)));
7647       Res = DAG.getNode(ISD::SUB, DL, VT,
7648                         DAG.getConstant(0, MVT::i32),Res);
7649
7650     } else
7651       return SDValue();
7652   }
7653
7654   if (ShiftAmt != 0)
7655     Res = DAG.getNode(ISD::SHL, DL, VT,
7656                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7657
7658   // Do not add new nodes to DAG combiner worklist.
7659   DCI.CombineTo(N, Res, false);
7660   return SDValue();
7661 }
7662
7663 static SDValue PerformANDCombine(SDNode *N,
7664                                  TargetLowering::DAGCombinerInfo &DCI,
7665                                  const ARMSubtarget *Subtarget) {
7666
7667   // Attempt to use immediate-form VBIC
7668   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7669   DebugLoc dl = N->getDebugLoc();
7670   EVT VT = N->getValueType(0);
7671   SelectionDAG &DAG = DCI.DAG;
7672
7673   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7674     return SDValue();
7675
7676   APInt SplatBits, SplatUndef;
7677   unsigned SplatBitSize;
7678   bool HasAnyUndefs;
7679   if (BVN &&
7680       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7681     if (SplatBitSize <= 64) {
7682       EVT VbicVT;
7683       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7684                                       SplatUndef.getZExtValue(), SplatBitSize,
7685                                       DAG, VbicVT, VT.is128BitVector(),
7686                                       OtherModImm);
7687       if (Val.getNode()) {
7688         SDValue Input =
7689           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7690         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7691         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7692       }
7693     }
7694   }
7695
7696   if (!Subtarget->isThumb1Only()) {
7697     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7698     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7699     if (Result.getNode())
7700       return Result;
7701   }
7702
7703   return SDValue();
7704 }
7705
7706 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7707 static SDValue PerformORCombine(SDNode *N,
7708                                 TargetLowering::DAGCombinerInfo &DCI,
7709                                 const ARMSubtarget *Subtarget) {
7710   // Attempt to use immediate-form VORR
7711   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7712   DebugLoc dl = N->getDebugLoc();
7713   EVT VT = N->getValueType(0);
7714   SelectionDAG &DAG = DCI.DAG;
7715
7716   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7717     return SDValue();
7718
7719   APInt SplatBits, SplatUndef;
7720   unsigned SplatBitSize;
7721   bool HasAnyUndefs;
7722   if (BVN && Subtarget->hasNEON() &&
7723       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7724     if (SplatBitSize <= 64) {
7725       EVT VorrVT;
7726       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7727                                       SplatUndef.getZExtValue(), SplatBitSize,
7728                                       DAG, VorrVT, VT.is128BitVector(),
7729                                       OtherModImm);
7730       if (Val.getNode()) {
7731         SDValue Input =
7732           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7733         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7734         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7735       }
7736     }
7737   }
7738
7739   if (!Subtarget->isThumb1Only()) {
7740     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7741     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7742     if (Result.getNode())
7743       return Result;
7744   }
7745
7746   // The code below optimizes (or (and X, Y), Z).
7747   // The AND operand needs to have a single user to make these optimizations
7748   // profitable.
7749   SDValue N0 = N->getOperand(0);
7750   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7751     return SDValue();
7752   SDValue N1 = N->getOperand(1);
7753
7754   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7755   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7756       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7757     APInt SplatUndef;
7758     unsigned SplatBitSize;
7759     bool HasAnyUndefs;
7760
7761     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7762     APInt SplatBits0;
7763     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7764                                   HasAnyUndefs) && !HasAnyUndefs) {
7765       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7766       APInt SplatBits1;
7767       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7768                                     HasAnyUndefs) && !HasAnyUndefs &&
7769           SplatBits0 == ~SplatBits1) {
7770         // Canonicalize the vector type to make instruction selection simpler.
7771         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7772         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7773                                      N0->getOperand(1), N0->getOperand(0),
7774                                      N1->getOperand(0));
7775         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7776       }
7777     }
7778   }
7779
7780   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7781   // reasonable.
7782
7783   // BFI is only available on V6T2+
7784   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7785     return SDValue();
7786
7787   DebugLoc DL = N->getDebugLoc();
7788   // 1) or (and A, mask), val => ARMbfi A, val, mask
7789   //      iff (val & mask) == val
7790   //
7791   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7792   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7793   //          && mask == ~mask2
7794   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7795   //          && ~mask == mask2
7796   //  (i.e., copy a bitfield value into another bitfield of the same width)
7797
7798   if (VT != MVT::i32)
7799     return SDValue();
7800
7801   SDValue N00 = N0.getOperand(0);
7802
7803   // The value and the mask need to be constants so we can verify this is
7804   // actually a bitfield set. If the mask is 0xffff, we can do better
7805   // via a movt instruction, so don't use BFI in that case.
7806   SDValue MaskOp = N0.getOperand(1);
7807   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7808   if (!MaskC)
7809     return SDValue();
7810   unsigned Mask = MaskC->getZExtValue();
7811   if (Mask == 0xffff)
7812     return SDValue();
7813   SDValue Res;
7814   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7815   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7816   if (N1C) {
7817     unsigned Val = N1C->getZExtValue();
7818     if ((Val & ~Mask) != Val)
7819       return SDValue();
7820
7821     if (ARM::isBitFieldInvertedMask(Mask)) {
7822       Val >>= CountTrailingZeros_32(~Mask);
7823
7824       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7825                         DAG.getConstant(Val, MVT::i32),
7826                         DAG.getConstant(Mask, MVT::i32));
7827
7828       // Do not add new nodes to DAG combiner worklist.
7829       DCI.CombineTo(N, Res, false);
7830       return SDValue();
7831     }
7832   } else if (N1.getOpcode() == ISD::AND) {
7833     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7834     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7835     if (!N11C)
7836       return SDValue();
7837     unsigned Mask2 = N11C->getZExtValue();
7838
7839     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7840     // as is to match.
7841     if (ARM::isBitFieldInvertedMask(Mask) &&
7842         (Mask == ~Mask2)) {
7843       // The pack halfword instruction works better for masks that fit it,
7844       // so use that when it's available.
7845       if (Subtarget->hasT2ExtractPack() &&
7846           (Mask == 0xffff || Mask == 0xffff0000))
7847         return SDValue();
7848       // 2a
7849       unsigned amt = CountTrailingZeros_32(Mask2);
7850       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7851                         DAG.getConstant(amt, MVT::i32));
7852       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7853                         DAG.getConstant(Mask, MVT::i32));
7854       // Do not add new nodes to DAG combiner worklist.
7855       DCI.CombineTo(N, Res, false);
7856       return SDValue();
7857     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7858                (~Mask == Mask2)) {
7859       // The pack halfword instruction works better for masks that fit it,
7860       // so use that when it's available.
7861       if (Subtarget->hasT2ExtractPack() &&
7862           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7863         return SDValue();
7864       // 2b
7865       unsigned lsb = CountTrailingZeros_32(Mask);
7866       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7867                         DAG.getConstant(lsb, MVT::i32));
7868       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7869                         DAG.getConstant(Mask2, MVT::i32));
7870       // Do not add new nodes to DAG combiner worklist.
7871       DCI.CombineTo(N, Res, false);
7872       return SDValue();
7873     }
7874   }
7875
7876   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7877       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7878       ARM::isBitFieldInvertedMask(~Mask)) {
7879     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7880     // where lsb(mask) == #shamt and masked bits of B are known zero.
7881     SDValue ShAmt = N00.getOperand(1);
7882     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7883     unsigned LSB = CountTrailingZeros_32(Mask);
7884     if (ShAmtC != LSB)
7885       return SDValue();
7886
7887     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7888                       DAG.getConstant(~Mask, MVT::i32));
7889
7890     // Do not add new nodes to DAG combiner worklist.
7891     DCI.CombineTo(N, Res, false);
7892   }
7893
7894   return SDValue();
7895 }
7896
7897 static SDValue PerformXORCombine(SDNode *N,
7898                                  TargetLowering::DAGCombinerInfo &DCI,
7899                                  const ARMSubtarget *Subtarget) {
7900   EVT VT = N->getValueType(0);
7901   SelectionDAG &DAG = DCI.DAG;
7902
7903   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7904     return SDValue();
7905
7906   if (!Subtarget->isThumb1Only()) {
7907     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7908     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7909     if (Result.getNode())
7910       return Result;
7911   }
7912
7913   return SDValue();
7914 }
7915
7916 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7917 /// the bits being cleared by the AND are not demanded by the BFI.
7918 static SDValue PerformBFICombine(SDNode *N,
7919                                  TargetLowering::DAGCombinerInfo &DCI) {
7920   SDValue N1 = N->getOperand(1);
7921   if (N1.getOpcode() == ISD::AND) {
7922     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7923     if (!N11C)
7924       return SDValue();
7925     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7926     unsigned LSB = CountTrailingZeros_32(~InvMask);
7927     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7928     unsigned Mask = (1 << Width)-1;
7929     unsigned Mask2 = N11C->getZExtValue();
7930     if ((Mask & (~Mask2)) == 0)
7931       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7932                              N->getOperand(0), N1.getOperand(0),
7933                              N->getOperand(2));
7934   }
7935   return SDValue();
7936 }
7937
7938 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7939 /// ARMISD::VMOVRRD.
7940 static SDValue PerformVMOVRRDCombine(SDNode *N,
7941                                      TargetLowering::DAGCombinerInfo &DCI) {
7942   // vmovrrd(vmovdrr x, y) -> x,y
7943   SDValue InDouble = N->getOperand(0);
7944   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7945     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7946
7947   // vmovrrd(load f64) -> (load i32), (load i32)
7948   SDNode *InNode = InDouble.getNode();
7949   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7950       InNode->getValueType(0) == MVT::f64 &&
7951       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7952       !cast<LoadSDNode>(InNode)->isVolatile()) {
7953     // TODO: Should this be done for non-FrameIndex operands?
7954     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7955
7956     SelectionDAG &DAG = DCI.DAG;
7957     DebugLoc DL = LD->getDebugLoc();
7958     SDValue BasePtr = LD->getBasePtr();
7959     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7960                                  LD->getPointerInfo(), LD->isVolatile(),
7961                                  LD->isNonTemporal(), LD->isInvariant(),
7962                                  LD->getAlignment());
7963
7964     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7965                                     DAG.getConstant(4, MVT::i32));
7966     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7967                                  LD->getPointerInfo(), LD->isVolatile(),
7968                                  LD->isNonTemporal(), LD->isInvariant(),
7969                                  std::min(4U, LD->getAlignment() / 2));
7970
7971     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7972     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7973     DCI.RemoveFromWorklist(LD);
7974     DAG.DeleteNode(LD);
7975     return Result;
7976   }
7977
7978   return SDValue();
7979 }
7980
7981 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7982 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7983 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7984   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7985   SDValue Op0 = N->getOperand(0);
7986   SDValue Op1 = N->getOperand(1);
7987   if (Op0.getOpcode() == ISD::BITCAST)
7988     Op0 = Op0.getOperand(0);
7989   if (Op1.getOpcode() == ISD::BITCAST)
7990     Op1 = Op1.getOperand(0);
7991   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7992       Op0.getNode() == Op1.getNode() &&
7993       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7994     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7995                        N->getValueType(0), Op0.getOperand(0));
7996   return SDValue();
7997 }
7998
7999 /// PerformSTORECombine - Target-specific dag combine xforms for
8000 /// ISD::STORE.
8001 static SDValue PerformSTORECombine(SDNode *N,
8002                                    TargetLowering::DAGCombinerInfo &DCI) {
8003   StoreSDNode *St = cast<StoreSDNode>(N);
8004   if (St->isVolatile())
8005     return SDValue();
8006
8007   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8008   // pack all of the elements in one place.  Next, store to memory in fewer
8009   // chunks.
8010   SDValue StVal = St->getValue();
8011   EVT VT = StVal.getValueType();
8012   if (St->isTruncatingStore() && VT.isVector()) {
8013     SelectionDAG &DAG = DCI.DAG;
8014     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8015     EVT StVT = St->getMemoryVT();
8016     unsigned NumElems = VT.getVectorNumElements();
8017     assert(StVT != VT && "Cannot truncate to the same type");
8018     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8019     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8020
8021     // From, To sizes and ElemCount must be pow of two
8022     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8023
8024     // We are going to use the original vector elt for storing.
8025     // Accumulated smaller vector elements must be a multiple of the store size.
8026     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8027
8028     unsigned SizeRatio  = FromEltSz / ToEltSz;
8029     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8030
8031     // Create a type on which we perform the shuffle.
8032     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8033                                      NumElems*SizeRatio);
8034     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8035
8036     DebugLoc DL = St->getDebugLoc();
8037     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8038     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8039     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8040
8041     // Can't shuffle using an illegal type.
8042     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8043
8044     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8045                                 DAG.getUNDEF(WideVec.getValueType()),
8046                                 ShuffleVec.data());
8047     // At this point all of the data is stored at the bottom of the
8048     // register. We now need to save it to mem.
8049
8050     // Find the largest store unit
8051     MVT StoreType = MVT::i8;
8052     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8053          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8054       MVT Tp = (MVT::SimpleValueType)tp;
8055       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8056         StoreType = Tp;
8057     }
8058     // Didn't find a legal store type.
8059     if (!TLI.isTypeLegal(StoreType))
8060       return SDValue();
8061
8062     // Bitcast the original vector into a vector of store-size units
8063     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8064             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8065     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8066     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8067     SmallVector<SDValue, 8> Chains;
8068     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8069                                         TLI.getPointerTy());
8070     SDValue BasePtr = St->getBasePtr();
8071
8072     // Perform one or more big stores into memory.
8073     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8074     for (unsigned I = 0; I < E; I++) {
8075       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8076                                    StoreType, ShuffWide,
8077                                    DAG.getIntPtrConstant(I));
8078       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8079                                 St->getPointerInfo(), St->isVolatile(),
8080                                 St->isNonTemporal(), St->getAlignment());
8081       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8082                             Increment);
8083       Chains.push_back(Ch);
8084     }
8085     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8086                        Chains.size());
8087   }
8088
8089   if (!ISD::isNormalStore(St))
8090     return SDValue();
8091
8092   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8093   // ARM stores of arguments in the same cache line.
8094   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8095       StVal.getNode()->hasOneUse()) {
8096     SelectionDAG  &DAG = DCI.DAG;
8097     DebugLoc DL = St->getDebugLoc();
8098     SDValue BasePtr = St->getBasePtr();
8099     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8100                                   StVal.getNode()->getOperand(0), BasePtr,
8101                                   St->getPointerInfo(), St->isVolatile(),
8102                                   St->isNonTemporal(), St->getAlignment());
8103
8104     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8105                                     DAG.getConstant(4, MVT::i32));
8106     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8107                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8108                         St->isNonTemporal(),
8109                         std::min(4U, St->getAlignment() / 2));
8110   }
8111
8112   if (StVal.getValueType() != MVT::i64 ||
8113       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8114     return SDValue();
8115
8116   // Bitcast an i64 store extracted from a vector to f64.
8117   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8118   SelectionDAG &DAG = DCI.DAG;
8119   DebugLoc dl = StVal.getDebugLoc();
8120   SDValue IntVec = StVal.getOperand(0);
8121   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8122                                  IntVec.getValueType().getVectorNumElements());
8123   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8124   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8125                                Vec, StVal.getOperand(1));
8126   dl = N->getDebugLoc();
8127   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8128   // Make the DAGCombiner fold the bitcasts.
8129   DCI.AddToWorklist(Vec.getNode());
8130   DCI.AddToWorklist(ExtElt.getNode());
8131   DCI.AddToWorklist(V.getNode());
8132   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8133                       St->getPointerInfo(), St->isVolatile(),
8134                       St->isNonTemporal(), St->getAlignment(),
8135                       St->getTBAAInfo());
8136 }
8137
8138 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8139 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8140 /// i64 vector to have f64 elements, since the value can then be loaded
8141 /// directly into a VFP register.
8142 static bool hasNormalLoadOperand(SDNode *N) {
8143   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8144   for (unsigned i = 0; i < NumElts; ++i) {
8145     SDNode *Elt = N->getOperand(i).getNode();
8146     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8147       return true;
8148   }
8149   return false;
8150 }
8151
8152 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8153 /// ISD::BUILD_VECTOR.
8154 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8155                                           TargetLowering::DAGCombinerInfo &DCI){
8156   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8157   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8158   // into a pair of GPRs, which is fine when the value is used as a scalar,
8159   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8160   SelectionDAG &DAG = DCI.DAG;
8161   if (N->getNumOperands() == 2) {
8162     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8163     if (RV.getNode())
8164       return RV;
8165   }
8166
8167   // Load i64 elements as f64 values so that type legalization does not split
8168   // them up into i32 values.
8169   EVT VT = N->getValueType(0);
8170   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8171     return SDValue();
8172   DebugLoc dl = N->getDebugLoc();
8173   SmallVector<SDValue, 8> Ops;
8174   unsigned NumElts = VT.getVectorNumElements();
8175   for (unsigned i = 0; i < NumElts; ++i) {
8176     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8177     Ops.push_back(V);
8178     // Make the DAGCombiner fold the bitcast.
8179     DCI.AddToWorklist(V.getNode());
8180   }
8181   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8182   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8183   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8184 }
8185
8186 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8187 /// ISD::INSERT_VECTOR_ELT.
8188 static SDValue PerformInsertEltCombine(SDNode *N,
8189                                        TargetLowering::DAGCombinerInfo &DCI) {
8190   // Bitcast an i64 load inserted into a vector to f64.
8191   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8192   EVT VT = N->getValueType(0);
8193   SDNode *Elt = N->getOperand(1).getNode();
8194   if (VT.getVectorElementType() != MVT::i64 ||
8195       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8196     return SDValue();
8197
8198   SelectionDAG &DAG = DCI.DAG;
8199   DebugLoc dl = N->getDebugLoc();
8200   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8201                                  VT.getVectorNumElements());
8202   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8203   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8204   // Make the DAGCombiner fold the bitcasts.
8205   DCI.AddToWorklist(Vec.getNode());
8206   DCI.AddToWorklist(V.getNode());
8207   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8208                                Vec, V, N->getOperand(2));
8209   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8210 }
8211
8212 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8213 /// ISD::VECTOR_SHUFFLE.
8214 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8215   // The LLVM shufflevector instruction does not require the shuffle mask
8216   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8217   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8218   // operands do not match the mask length, they are extended by concatenating
8219   // them with undef vectors.  That is probably the right thing for other
8220   // targets, but for NEON it is better to concatenate two double-register
8221   // size vector operands into a single quad-register size vector.  Do that
8222   // transformation here:
8223   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8224   //   shuffle(concat(v1, v2), undef)
8225   SDValue Op0 = N->getOperand(0);
8226   SDValue Op1 = N->getOperand(1);
8227   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8228       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8229       Op0.getNumOperands() != 2 ||
8230       Op1.getNumOperands() != 2)
8231     return SDValue();
8232   SDValue Concat0Op1 = Op0.getOperand(1);
8233   SDValue Concat1Op1 = Op1.getOperand(1);
8234   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8235       Concat1Op1.getOpcode() != ISD::UNDEF)
8236     return SDValue();
8237   // Skip the transformation if any of the types are illegal.
8238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8239   EVT VT = N->getValueType(0);
8240   if (!TLI.isTypeLegal(VT) ||
8241       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8242       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8243     return SDValue();
8244
8245   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8246                                   Op0.getOperand(0), Op1.getOperand(0));
8247   // Translate the shuffle mask.
8248   SmallVector<int, 16> NewMask;
8249   unsigned NumElts = VT.getVectorNumElements();
8250   unsigned HalfElts = NumElts/2;
8251   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8252   for (unsigned n = 0; n < NumElts; ++n) {
8253     int MaskElt = SVN->getMaskElt(n);
8254     int NewElt = -1;
8255     if (MaskElt < (int)HalfElts)
8256       NewElt = MaskElt;
8257     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8258       NewElt = HalfElts + MaskElt - NumElts;
8259     NewMask.push_back(NewElt);
8260   }
8261   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8262                               DAG.getUNDEF(VT), NewMask.data());
8263 }
8264
8265 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8266 /// NEON load/store intrinsics to merge base address updates.
8267 static SDValue CombineBaseUpdate(SDNode *N,
8268                                  TargetLowering::DAGCombinerInfo &DCI) {
8269   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8270     return SDValue();
8271
8272   SelectionDAG &DAG = DCI.DAG;
8273   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8274                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8275   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8276   SDValue Addr = N->getOperand(AddrOpIdx);
8277
8278   // Search for a use of the address operand that is an increment.
8279   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8280          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8281     SDNode *User = *UI;
8282     if (User->getOpcode() != ISD::ADD ||
8283         UI.getUse().getResNo() != Addr.getResNo())
8284       continue;
8285
8286     // Check that the add is independent of the load/store.  Otherwise, folding
8287     // it would create a cycle.
8288     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8289       continue;
8290
8291     // Find the new opcode for the updating load/store.
8292     bool isLoad = true;
8293     bool isLaneOp = false;
8294     unsigned NewOpc = 0;
8295     unsigned NumVecs = 0;
8296     if (isIntrinsic) {
8297       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8298       switch (IntNo) {
8299       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8300       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8301         NumVecs = 1; break;
8302       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8303         NumVecs = 2; break;
8304       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8305         NumVecs = 3; break;
8306       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8307         NumVecs = 4; break;
8308       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8309         NumVecs = 2; isLaneOp = true; break;
8310       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8311         NumVecs = 3; isLaneOp = true; break;
8312       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8313         NumVecs = 4; isLaneOp = true; break;
8314       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8315         NumVecs = 1; isLoad = false; break;
8316       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8317         NumVecs = 2; isLoad = false; break;
8318       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8319         NumVecs = 3; isLoad = false; break;
8320       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8321         NumVecs = 4; isLoad = false; break;
8322       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8323         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8324       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8325         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8326       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8327         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8328       }
8329     } else {
8330       isLaneOp = true;
8331       switch (N->getOpcode()) {
8332       default: llvm_unreachable("unexpected opcode for Neon base update");
8333       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8334       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8335       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8336       }
8337     }
8338
8339     // Find the size of memory referenced by the load/store.
8340     EVT VecTy;
8341     if (isLoad)
8342       VecTy = N->getValueType(0);
8343     else
8344       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8345     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8346     if (isLaneOp)
8347       NumBytes /= VecTy.getVectorNumElements();
8348
8349     // If the increment is a constant, it must match the memory ref size.
8350     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8351     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8352       uint64_t IncVal = CInc->getZExtValue();
8353       if (IncVal != NumBytes)
8354         continue;
8355     } else if (NumBytes >= 3 * 16) {
8356       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8357       // separate instructions that make it harder to use a non-constant update.
8358       continue;
8359     }
8360
8361     // Create the new updating load/store node.
8362     EVT Tys[6];
8363     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8364     unsigned n;
8365     for (n = 0; n < NumResultVecs; ++n)
8366       Tys[n] = VecTy;
8367     Tys[n++] = MVT::i32;
8368     Tys[n] = MVT::Other;
8369     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8370     SmallVector<SDValue, 8> Ops;
8371     Ops.push_back(N->getOperand(0)); // incoming chain
8372     Ops.push_back(N->getOperand(AddrOpIdx));
8373     Ops.push_back(Inc);
8374     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8375       Ops.push_back(N->getOperand(i));
8376     }
8377     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8378     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8379                                            Ops.data(), Ops.size(),
8380                                            MemInt->getMemoryVT(),
8381                                            MemInt->getMemOperand());
8382
8383     // Update the uses.
8384     std::vector<SDValue> NewResults;
8385     for (unsigned i = 0; i < NumResultVecs; ++i) {
8386       NewResults.push_back(SDValue(UpdN.getNode(), i));
8387     }
8388     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8389     DCI.CombineTo(N, NewResults);
8390     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8391
8392     break;
8393   }
8394   return SDValue();
8395 }
8396
8397 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8398 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8399 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8400 /// return true.
8401 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8402   SelectionDAG &DAG = DCI.DAG;
8403   EVT VT = N->getValueType(0);
8404   // vldN-dup instructions only support 64-bit vectors for N > 1.
8405   if (!VT.is64BitVector())
8406     return false;
8407
8408   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8409   SDNode *VLD = N->getOperand(0).getNode();
8410   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8411     return false;
8412   unsigned NumVecs = 0;
8413   unsigned NewOpc = 0;
8414   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8415   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8416     NumVecs = 2;
8417     NewOpc = ARMISD::VLD2DUP;
8418   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8419     NumVecs = 3;
8420     NewOpc = ARMISD::VLD3DUP;
8421   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8422     NumVecs = 4;
8423     NewOpc = ARMISD::VLD4DUP;
8424   } else {
8425     return false;
8426   }
8427
8428   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8429   // numbers match the load.
8430   unsigned VLDLaneNo =
8431     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8432   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8433        UI != UE; ++UI) {
8434     // Ignore uses of the chain result.
8435     if (UI.getUse().getResNo() == NumVecs)
8436       continue;
8437     SDNode *User = *UI;
8438     if (User->getOpcode() != ARMISD::VDUPLANE ||
8439         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8440       return false;
8441   }
8442
8443   // Create the vldN-dup node.
8444   EVT Tys[5];
8445   unsigned n;
8446   for (n = 0; n < NumVecs; ++n)
8447     Tys[n] = VT;
8448   Tys[n] = MVT::Other;
8449   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8450   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8451   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8452   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8453                                            Ops, 2, VLDMemInt->getMemoryVT(),
8454                                            VLDMemInt->getMemOperand());
8455
8456   // Update the uses.
8457   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8458        UI != UE; ++UI) {
8459     unsigned ResNo = UI.getUse().getResNo();
8460     // Ignore uses of the chain result.
8461     if (ResNo == NumVecs)
8462       continue;
8463     SDNode *User = *UI;
8464     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8465   }
8466
8467   // Now the vldN-lane intrinsic is dead except for its chain result.
8468   // Update uses of the chain.
8469   std::vector<SDValue> VLDDupResults;
8470   for (unsigned n = 0; n < NumVecs; ++n)
8471     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8472   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8473   DCI.CombineTo(VLD, VLDDupResults);
8474
8475   return true;
8476 }
8477
8478 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8479 /// ARMISD::VDUPLANE.
8480 static SDValue PerformVDUPLANECombine(SDNode *N,
8481                                       TargetLowering::DAGCombinerInfo &DCI) {
8482   SDValue Op = N->getOperand(0);
8483
8484   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8485   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8486   if (CombineVLDDUP(N, DCI))
8487     return SDValue(N, 0);
8488
8489   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8490   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8491   while (Op.getOpcode() == ISD::BITCAST)
8492     Op = Op.getOperand(0);
8493   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8494     return SDValue();
8495
8496   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8497   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8498   // The canonical VMOV for a zero vector uses a 32-bit element size.
8499   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8500   unsigned EltBits;
8501   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8502     EltSize = 8;
8503   EVT VT = N->getValueType(0);
8504   if (EltSize > VT.getVectorElementType().getSizeInBits())
8505     return SDValue();
8506
8507   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8508 }
8509
8510 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8511 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8512 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8513 {
8514   integerPart cN;
8515   integerPart c0 = 0;
8516   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8517        I != E; I++) {
8518     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8519     if (!C)
8520       return false;
8521
8522     bool isExact;
8523     APFloat APF = C->getValueAPF();
8524     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8525         != APFloat::opOK || !isExact)
8526       return false;
8527
8528     c0 = (I == 0) ? cN : c0;
8529     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8530       return false;
8531   }
8532   C = c0;
8533   return true;
8534 }
8535
8536 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8537 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8538 /// when the VMUL has a constant operand that is a power of 2.
8539 ///
8540 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8541 ///  vmul.f32        d16, d17, d16
8542 ///  vcvt.s32.f32    d16, d16
8543 /// becomes:
8544 ///  vcvt.s32.f32    d16, d16, #3
8545 static SDValue PerformVCVTCombine(SDNode *N,
8546                                   TargetLowering::DAGCombinerInfo &DCI,
8547                                   const ARMSubtarget *Subtarget) {
8548   SelectionDAG &DAG = DCI.DAG;
8549   SDValue Op = N->getOperand(0);
8550
8551   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8552       Op.getOpcode() != ISD::FMUL)
8553     return SDValue();
8554
8555   uint64_t C;
8556   SDValue N0 = Op->getOperand(0);
8557   SDValue ConstVec = Op->getOperand(1);
8558   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8559
8560   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8561       !isConstVecPow2(ConstVec, isSigned, C))
8562     return SDValue();
8563
8564   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8565     Intrinsic::arm_neon_vcvtfp2fxu;
8566   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8567                      N->getValueType(0),
8568                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8569                      DAG.getConstant(Log2_64(C), MVT::i32));
8570 }
8571
8572 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8573 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8574 /// when the VDIV has a constant operand that is a power of 2.
8575 ///
8576 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8577 ///  vcvt.f32.s32    d16, d16
8578 ///  vdiv.f32        d16, d17, d16
8579 /// becomes:
8580 ///  vcvt.f32.s32    d16, d16, #3
8581 static SDValue PerformVDIVCombine(SDNode *N,
8582                                   TargetLowering::DAGCombinerInfo &DCI,
8583                                   const ARMSubtarget *Subtarget) {
8584   SelectionDAG &DAG = DCI.DAG;
8585   SDValue Op = N->getOperand(0);
8586   unsigned OpOpcode = Op.getNode()->getOpcode();
8587
8588   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8589       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8590     return SDValue();
8591
8592   uint64_t C;
8593   SDValue ConstVec = N->getOperand(1);
8594   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8595
8596   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8597       !isConstVecPow2(ConstVec, isSigned, C))
8598     return SDValue();
8599
8600   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8601     Intrinsic::arm_neon_vcvtfxu2fp;
8602   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8603                      Op.getValueType(),
8604                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8605                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8606 }
8607
8608 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8609 /// operand of a vector shift operation, where all the elements of the
8610 /// build_vector must have the same constant integer value.
8611 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8612   // Ignore bit_converts.
8613   while (Op.getOpcode() == ISD::BITCAST)
8614     Op = Op.getOperand(0);
8615   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8616   APInt SplatBits, SplatUndef;
8617   unsigned SplatBitSize;
8618   bool HasAnyUndefs;
8619   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8620                                       HasAnyUndefs, ElementBits) ||
8621       SplatBitSize > ElementBits)
8622     return false;
8623   Cnt = SplatBits.getSExtValue();
8624   return true;
8625 }
8626
8627 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8628 /// operand of a vector shift left operation.  That value must be in the range:
8629 ///   0 <= Value < ElementBits for a left shift; or
8630 ///   0 <= Value <= ElementBits for a long left shift.
8631 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8632   assert(VT.isVector() && "vector shift count is not a vector type");
8633   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8634   if (! getVShiftImm(Op, ElementBits, Cnt))
8635     return false;
8636   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8637 }
8638
8639 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8640 /// operand of a vector shift right operation.  For a shift opcode, the value
8641 /// is positive, but for an intrinsic the value count must be negative. The
8642 /// absolute value must be in the range:
8643 ///   1 <= |Value| <= ElementBits for a right shift; or
8644 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8645 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8646                          int64_t &Cnt) {
8647   assert(VT.isVector() && "vector shift count is not a vector type");
8648   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8649   if (! getVShiftImm(Op, ElementBits, Cnt))
8650     return false;
8651   if (isIntrinsic)
8652     Cnt = -Cnt;
8653   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8654 }
8655
8656 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8657 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8658   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8659   switch (IntNo) {
8660   default:
8661     // Don't do anything for most intrinsics.
8662     break;
8663
8664   // Vector shifts: check for immediate versions and lower them.
8665   // Note: This is done during DAG combining instead of DAG legalizing because
8666   // the build_vectors for 64-bit vector element shift counts are generally
8667   // not legal, and it is hard to see their values after they get legalized to
8668   // loads from a constant pool.
8669   case Intrinsic::arm_neon_vshifts:
8670   case Intrinsic::arm_neon_vshiftu:
8671   case Intrinsic::arm_neon_vshiftls:
8672   case Intrinsic::arm_neon_vshiftlu:
8673   case Intrinsic::arm_neon_vshiftn:
8674   case Intrinsic::arm_neon_vrshifts:
8675   case Intrinsic::arm_neon_vrshiftu:
8676   case Intrinsic::arm_neon_vrshiftn:
8677   case Intrinsic::arm_neon_vqshifts:
8678   case Intrinsic::arm_neon_vqshiftu:
8679   case Intrinsic::arm_neon_vqshiftsu:
8680   case Intrinsic::arm_neon_vqshiftns:
8681   case Intrinsic::arm_neon_vqshiftnu:
8682   case Intrinsic::arm_neon_vqshiftnsu:
8683   case Intrinsic::arm_neon_vqrshiftns:
8684   case Intrinsic::arm_neon_vqrshiftnu:
8685   case Intrinsic::arm_neon_vqrshiftnsu: {
8686     EVT VT = N->getOperand(1).getValueType();
8687     int64_t Cnt;
8688     unsigned VShiftOpc = 0;
8689
8690     switch (IntNo) {
8691     case Intrinsic::arm_neon_vshifts:
8692     case Intrinsic::arm_neon_vshiftu:
8693       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8694         VShiftOpc = ARMISD::VSHL;
8695         break;
8696       }
8697       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8698         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8699                      ARMISD::VSHRs : ARMISD::VSHRu);
8700         break;
8701       }
8702       return SDValue();
8703
8704     case Intrinsic::arm_neon_vshiftls:
8705     case Intrinsic::arm_neon_vshiftlu:
8706       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8707         break;
8708       llvm_unreachable("invalid shift count for vshll intrinsic");
8709
8710     case Intrinsic::arm_neon_vrshifts:
8711     case Intrinsic::arm_neon_vrshiftu:
8712       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8713         break;
8714       return SDValue();
8715
8716     case Intrinsic::arm_neon_vqshifts:
8717     case Intrinsic::arm_neon_vqshiftu:
8718       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8719         break;
8720       return SDValue();
8721
8722     case Intrinsic::arm_neon_vqshiftsu:
8723       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8724         break;
8725       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8726
8727     case Intrinsic::arm_neon_vshiftn:
8728     case Intrinsic::arm_neon_vrshiftn:
8729     case Intrinsic::arm_neon_vqshiftns:
8730     case Intrinsic::arm_neon_vqshiftnu:
8731     case Intrinsic::arm_neon_vqshiftnsu:
8732     case Intrinsic::arm_neon_vqrshiftns:
8733     case Intrinsic::arm_neon_vqrshiftnu:
8734     case Intrinsic::arm_neon_vqrshiftnsu:
8735       // Narrowing shifts require an immediate right shift.
8736       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8737         break;
8738       llvm_unreachable("invalid shift count for narrowing vector shift "
8739                        "intrinsic");
8740
8741     default:
8742       llvm_unreachable("unhandled vector shift");
8743     }
8744
8745     switch (IntNo) {
8746     case Intrinsic::arm_neon_vshifts:
8747     case Intrinsic::arm_neon_vshiftu:
8748       // Opcode already set above.
8749       break;
8750     case Intrinsic::arm_neon_vshiftls:
8751     case Intrinsic::arm_neon_vshiftlu:
8752       if (Cnt == VT.getVectorElementType().getSizeInBits())
8753         VShiftOpc = ARMISD::VSHLLi;
8754       else
8755         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8756                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8757       break;
8758     case Intrinsic::arm_neon_vshiftn:
8759       VShiftOpc = ARMISD::VSHRN; break;
8760     case Intrinsic::arm_neon_vrshifts:
8761       VShiftOpc = ARMISD::VRSHRs; break;
8762     case Intrinsic::arm_neon_vrshiftu:
8763       VShiftOpc = ARMISD::VRSHRu; break;
8764     case Intrinsic::arm_neon_vrshiftn:
8765       VShiftOpc = ARMISD::VRSHRN; break;
8766     case Intrinsic::arm_neon_vqshifts:
8767       VShiftOpc = ARMISD::VQSHLs; break;
8768     case Intrinsic::arm_neon_vqshiftu:
8769       VShiftOpc = ARMISD::VQSHLu; break;
8770     case Intrinsic::arm_neon_vqshiftsu:
8771       VShiftOpc = ARMISD::VQSHLsu; break;
8772     case Intrinsic::arm_neon_vqshiftns:
8773       VShiftOpc = ARMISD::VQSHRNs; break;
8774     case Intrinsic::arm_neon_vqshiftnu:
8775       VShiftOpc = ARMISD::VQSHRNu; break;
8776     case Intrinsic::arm_neon_vqshiftnsu:
8777       VShiftOpc = ARMISD::VQSHRNsu; break;
8778     case Intrinsic::arm_neon_vqrshiftns:
8779       VShiftOpc = ARMISD::VQRSHRNs; break;
8780     case Intrinsic::arm_neon_vqrshiftnu:
8781       VShiftOpc = ARMISD::VQRSHRNu; break;
8782     case Intrinsic::arm_neon_vqrshiftnsu:
8783       VShiftOpc = ARMISD::VQRSHRNsu; break;
8784     }
8785
8786     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8787                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8788   }
8789
8790   case Intrinsic::arm_neon_vshiftins: {
8791     EVT VT = N->getOperand(1).getValueType();
8792     int64_t Cnt;
8793     unsigned VShiftOpc = 0;
8794
8795     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8796       VShiftOpc = ARMISD::VSLI;
8797     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8798       VShiftOpc = ARMISD::VSRI;
8799     else {
8800       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8801     }
8802
8803     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8804                        N->getOperand(1), N->getOperand(2),
8805                        DAG.getConstant(Cnt, MVT::i32));
8806   }
8807
8808   case Intrinsic::arm_neon_vqrshifts:
8809   case Intrinsic::arm_neon_vqrshiftu:
8810     // No immediate versions of these to check for.
8811     break;
8812   }
8813
8814   return SDValue();
8815 }
8816
8817 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8818 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8819 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8820 /// vector element shift counts are generally not legal, and it is hard to see
8821 /// their values after they get legalized to loads from a constant pool.
8822 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8823                                    const ARMSubtarget *ST) {
8824   EVT VT = N->getValueType(0);
8825   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8826     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8827     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8828     SDValue N1 = N->getOperand(1);
8829     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8830       SDValue N0 = N->getOperand(0);
8831       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8832           DAG.MaskedValueIsZero(N0.getOperand(0),
8833                                 APInt::getHighBitsSet(32, 16)))
8834         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8835     }
8836   }
8837
8838   // Nothing to be done for scalar shifts.
8839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8840   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8841     return SDValue();
8842
8843   assert(ST->hasNEON() && "unexpected vector shift");
8844   int64_t Cnt;
8845
8846   switch (N->getOpcode()) {
8847   default: llvm_unreachable("unexpected shift opcode");
8848
8849   case ISD::SHL:
8850     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8851       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8852                          DAG.getConstant(Cnt, MVT::i32));
8853     break;
8854
8855   case ISD::SRA:
8856   case ISD::SRL:
8857     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8858       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8859                             ARMISD::VSHRs : ARMISD::VSHRu);
8860       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8861                          DAG.getConstant(Cnt, MVT::i32));
8862     }
8863   }
8864   return SDValue();
8865 }
8866
8867 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8868 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8869 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8870                                     const ARMSubtarget *ST) {
8871   SDValue N0 = N->getOperand(0);
8872
8873   // Check for sign- and zero-extensions of vector extract operations of 8-
8874   // and 16-bit vector elements.  NEON supports these directly.  They are
8875   // handled during DAG combining because type legalization will promote them
8876   // to 32-bit types and it is messy to recognize the operations after that.
8877   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8878     SDValue Vec = N0.getOperand(0);
8879     SDValue Lane = N0.getOperand(1);
8880     EVT VT = N->getValueType(0);
8881     EVT EltVT = N0.getValueType();
8882     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8883
8884     if (VT == MVT::i32 &&
8885         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8886         TLI.isTypeLegal(Vec.getValueType()) &&
8887         isa<ConstantSDNode>(Lane)) {
8888
8889       unsigned Opc = 0;
8890       switch (N->getOpcode()) {
8891       default: llvm_unreachable("unexpected opcode");
8892       case ISD::SIGN_EXTEND:
8893         Opc = ARMISD::VGETLANEs;
8894         break;
8895       case ISD::ZERO_EXTEND:
8896       case ISD::ANY_EXTEND:
8897         Opc = ARMISD::VGETLANEu;
8898         break;
8899       }
8900       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8901     }
8902   }
8903
8904   return SDValue();
8905 }
8906
8907 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8908 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8909 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8910                                        const ARMSubtarget *ST) {
8911   // If the target supports NEON, try to use vmax/vmin instructions for f32
8912   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8913   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8914   // a NaN; only do the transformation when it matches that behavior.
8915
8916   // For now only do this when using NEON for FP operations; if using VFP, it
8917   // is not obvious that the benefit outweighs the cost of switching to the
8918   // NEON pipeline.
8919   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8920       N->getValueType(0) != MVT::f32)
8921     return SDValue();
8922
8923   SDValue CondLHS = N->getOperand(0);
8924   SDValue CondRHS = N->getOperand(1);
8925   SDValue LHS = N->getOperand(2);
8926   SDValue RHS = N->getOperand(3);
8927   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8928
8929   unsigned Opcode = 0;
8930   bool IsReversed;
8931   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8932     IsReversed = false; // x CC y ? x : y
8933   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8934     IsReversed = true ; // x CC y ? y : x
8935   } else {
8936     return SDValue();
8937   }
8938
8939   bool IsUnordered;
8940   switch (CC) {
8941   default: break;
8942   case ISD::SETOLT:
8943   case ISD::SETOLE:
8944   case ISD::SETLT:
8945   case ISD::SETLE:
8946   case ISD::SETULT:
8947   case ISD::SETULE:
8948     // If LHS is NaN, an ordered comparison will be false and the result will
8949     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8950     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8951     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8952     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8953       break;
8954     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8955     // will return -0, so vmin can only be used for unsafe math or if one of
8956     // the operands is known to be nonzero.
8957     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8958         !DAG.getTarget().Options.UnsafeFPMath &&
8959         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8960       break;
8961     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8962     break;
8963
8964   case ISD::SETOGT:
8965   case ISD::SETOGE:
8966   case ISD::SETGT:
8967   case ISD::SETGE:
8968   case ISD::SETUGT:
8969   case ISD::SETUGE:
8970     // If LHS is NaN, an ordered comparison will be false and the result will
8971     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8972     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8973     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8974     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8975       break;
8976     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8977     // will return +0, so vmax can only be used for unsafe math or if one of
8978     // the operands is known to be nonzero.
8979     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8980         !DAG.getTarget().Options.UnsafeFPMath &&
8981         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8982       break;
8983     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8984     break;
8985   }
8986
8987   if (!Opcode)
8988     return SDValue();
8989   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8990 }
8991
8992 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8993 SDValue
8994 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8995   SDValue Cmp = N->getOperand(4);
8996   if (Cmp.getOpcode() != ARMISD::CMPZ)
8997     // Only looking at EQ and NE cases.
8998     return SDValue();
8999
9000   EVT VT = N->getValueType(0);
9001   DebugLoc dl = N->getDebugLoc();
9002   SDValue LHS = Cmp.getOperand(0);
9003   SDValue RHS = Cmp.getOperand(1);
9004   SDValue FalseVal = N->getOperand(0);
9005   SDValue TrueVal = N->getOperand(1);
9006   SDValue ARMcc = N->getOperand(2);
9007   ARMCC::CondCodes CC =
9008     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9009
9010   // Simplify
9011   //   mov     r1, r0
9012   //   cmp     r1, x
9013   //   mov     r0, y
9014   //   moveq   r0, x
9015   // to
9016   //   cmp     r0, x
9017   //   movne   r0, y
9018   //
9019   //   mov     r1, r0
9020   //   cmp     r1, x
9021   //   mov     r0, x
9022   //   movne   r0, y
9023   // to
9024   //   cmp     r0, x
9025   //   movne   r0, y
9026   /// FIXME: Turn this into a target neutral optimization?
9027   SDValue Res;
9028   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9029     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9030                       N->getOperand(3), Cmp);
9031   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9032     SDValue ARMcc;
9033     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9034     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9035                       N->getOperand(3), NewCmp);
9036   }
9037
9038   if (Res.getNode()) {
9039     APInt KnownZero, KnownOne;
9040     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9041     // Capture demanded bits information that would be otherwise lost.
9042     if (KnownZero == 0xfffffffe)
9043       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9044                         DAG.getValueType(MVT::i1));
9045     else if (KnownZero == 0xffffff00)
9046       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9047                         DAG.getValueType(MVT::i8));
9048     else if (KnownZero == 0xffff0000)
9049       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9050                         DAG.getValueType(MVT::i16));
9051   }
9052
9053   return Res;
9054 }
9055
9056 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9057                                              DAGCombinerInfo &DCI) const {
9058   switch (N->getOpcode()) {
9059   default: break;
9060   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9061   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9062   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9063   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9064   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9065   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9066   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9067   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9068   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9069   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9070   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9071   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9072   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9073   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9074   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9075   case ISD::FP_TO_SINT:
9076   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9077   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9078   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9079   case ISD::SHL:
9080   case ISD::SRA:
9081   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9082   case ISD::SIGN_EXTEND:
9083   case ISD::ZERO_EXTEND:
9084   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9085   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9086   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9087   case ARMISD::VLD2DUP:
9088   case ARMISD::VLD3DUP:
9089   case ARMISD::VLD4DUP:
9090     return CombineBaseUpdate(N, DCI);
9091   case ISD::INTRINSIC_VOID:
9092   case ISD::INTRINSIC_W_CHAIN:
9093     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9094     case Intrinsic::arm_neon_vld1:
9095     case Intrinsic::arm_neon_vld2:
9096     case Intrinsic::arm_neon_vld3:
9097     case Intrinsic::arm_neon_vld4:
9098     case Intrinsic::arm_neon_vld2lane:
9099     case Intrinsic::arm_neon_vld3lane:
9100     case Intrinsic::arm_neon_vld4lane:
9101     case Intrinsic::arm_neon_vst1:
9102     case Intrinsic::arm_neon_vst2:
9103     case Intrinsic::arm_neon_vst3:
9104     case Intrinsic::arm_neon_vst4:
9105     case Intrinsic::arm_neon_vst2lane:
9106     case Intrinsic::arm_neon_vst3lane:
9107     case Intrinsic::arm_neon_vst4lane:
9108       return CombineBaseUpdate(N, DCI);
9109     default: break;
9110     }
9111     break;
9112   }
9113   return SDValue();
9114 }
9115
9116 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9117                                                           EVT VT) const {
9118   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9119 }
9120
9121 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9122   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9123   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9124
9125   switch (VT.getSimpleVT().SimpleTy) {
9126   default:
9127     return false;
9128   case MVT::i8:
9129   case MVT::i16:
9130   case MVT::i32:
9131     // Unaligned access can use (for example) LRDB, LRDH, LDR
9132     return AllowsUnaligned;
9133   case MVT::f64:
9134   case MVT::v2f64:
9135     // For any little-endian targets with neon, we can support unaligned ld/st
9136     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9137     // A big-endian target may also explictly support unaligned accesses
9138     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9139   }
9140 }
9141
9142 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9143                        unsigned AlignCheck) {
9144   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9145           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9146 }
9147
9148 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9149                                            unsigned DstAlign, unsigned SrcAlign,
9150                                            bool IsZeroVal,
9151                                            bool MemcpyStrSrc,
9152                                            MachineFunction &MF) const {
9153   const Function *F = MF.getFunction();
9154
9155   // See if we can use NEON instructions for this...
9156   if (IsZeroVal &&
9157       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat) &&
9158       Subtarget->hasNEON()) {
9159     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9160       return MVT::v4i32;
9161     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9162       return MVT::v2i32;
9163     }
9164   }
9165
9166   // Lowering to i32/i16 if the size permits.
9167   if (Size >= 4) {
9168     return MVT::i32;
9169   } else if (Size >= 2) {
9170     return MVT::i16;
9171   }
9172
9173   // Let the target-independent logic figure it out.
9174   return MVT::Other;
9175 }
9176
9177 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9178   if (V < 0)
9179     return false;
9180
9181   unsigned Scale = 1;
9182   switch (VT.getSimpleVT().SimpleTy) {
9183   default: return false;
9184   case MVT::i1:
9185   case MVT::i8:
9186     // Scale == 1;
9187     break;
9188   case MVT::i16:
9189     // Scale == 2;
9190     Scale = 2;
9191     break;
9192   case MVT::i32:
9193     // Scale == 4;
9194     Scale = 4;
9195     break;
9196   }
9197
9198   if ((V & (Scale - 1)) != 0)
9199     return false;
9200   V /= Scale;
9201   return V == (V & ((1LL << 5) - 1));
9202 }
9203
9204 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9205                                       const ARMSubtarget *Subtarget) {
9206   bool isNeg = false;
9207   if (V < 0) {
9208     isNeg = true;
9209     V = - V;
9210   }
9211
9212   switch (VT.getSimpleVT().SimpleTy) {
9213   default: return false;
9214   case MVT::i1:
9215   case MVT::i8:
9216   case MVT::i16:
9217   case MVT::i32:
9218     // + imm12 or - imm8
9219     if (isNeg)
9220       return V == (V & ((1LL << 8) - 1));
9221     return V == (V & ((1LL << 12) - 1));
9222   case MVT::f32:
9223   case MVT::f64:
9224     // Same as ARM mode. FIXME: NEON?
9225     if (!Subtarget->hasVFP2())
9226       return false;
9227     if ((V & 3) != 0)
9228       return false;
9229     V >>= 2;
9230     return V == (V & ((1LL << 8) - 1));
9231   }
9232 }
9233
9234 /// isLegalAddressImmediate - Return true if the integer value can be used
9235 /// as the offset of the target addressing mode for load / store of the
9236 /// given type.
9237 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9238                                     const ARMSubtarget *Subtarget) {
9239   if (V == 0)
9240     return true;
9241
9242   if (!VT.isSimple())
9243     return false;
9244
9245   if (Subtarget->isThumb1Only())
9246     return isLegalT1AddressImmediate(V, VT);
9247   else if (Subtarget->isThumb2())
9248     return isLegalT2AddressImmediate(V, VT, Subtarget);
9249
9250   // ARM mode.
9251   if (V < 0)
9252     V = - V;
9253   switch (VT.getSimpleVT().SimpleTy) {
9254   default: return false;
9255   case MVT::i1:
9256   case MVT::i8:
9257   case MVT::i32:
9258     // +- imm12
9259     return V == (V & ((1LL << 12) - 1));
9260   case MVT::i16:
9261     // +- imm8
9262     return V == (V & ((1LL << 8) - 1));
9263   case MVT::f32:
9264   case MVT::f64:
9265     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9266       return false;
9267     if ((V & 3) != 0)
9268       return false;
9269     V >>= 2;
9270     return V == (V & ((1LL << 8) - 1));
9271   }
9272 }
9273
9274 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9275                                                       EVT VT) const {
9276   int Scale = AM.Scale;
9277   if (Scale < 0)
9278     return false;
9279
9280   switch (VT.getSimpleVT().SimpleTy) {
9281   default: return false;
9282   case MVT::i1:
9283   case MVT::i8:
9284   case MVT::i16:
9285   case MVT::i32:
9286     if (Scale == 1)
9287       return true;
9288     // r + r << imm
9289     Scale = Scale & ~1;
9290     return Scale == 2 || Scale == 4 || Scale == 8;
9291   case MVT::i64:
9292     // r + r
9293     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9294       return true;
9295     return false;
9296   case MVT::isVoid:
9297     // Note, we allow "void" uses (basically, uses that aren't loads or
9298     // stores), because arm allows folding a scale into many arithmetic
9299     // operations.  This should be made more precise and revisited later.
9300
9301     // Allow r << imm, but the imm has to be a multiple of two.
9302     if (Scale & 1) return false;
9303     return isPowerOf2_32(Scale);
9304   }
9305 }
9306
9307 /// isLegalAddressingMode - Return true if the addressing mode represented
9308 /// by AM is legal for this target, for a load/store of the specified type.
9309 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9310                                               Type *Ty) const {
9311   EVT VT = getValueType(Ty, true);
9312   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9313     return false;
9314
9315   // Can never fold addr of global into load/store.
9316   if (AM.BaseGV)
9317     return false;
9318
9319   switch (AM.Scale) {
9320   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9321     break;
9322   case 1:
9323     if (Subtarget->isThumb1Only())
9324       return false;
9325     // FALL THROUGH.
9326   default:
9327     // ARM doesn't support any R+R*scale+imm addr modes.
9328     if (AM.BaseOffs)
9329       return false;
9330
9331     if (!VT.isSimple())
9332       return false;
9333
9334     if (Subtarget->isThumb2())
9335       return isLegalT2ScaledAddressingMode(AM, VT);
9336
9337     int Scale = AM.Scale;
9338     switch (VT.getSimpleVT().SimpleTy) {
9339     default: return false;
9340     case MVT::i1:
9341     case MVT::i8:
9342     case MVT::i32:
9343       if (Scale < 0) Scale = -Scale;
9344       if (Scale == 1)
9345         return true;
9346       // r + r << imm
9347       return isPowerOf2_32(Scale & ~1);
9348     case MVT::i16:
9349     case MVT::i64:
9350       // r + r
9351       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9352         return true;
9353       return false;
9354
9355     case MVT::isVoid:
9356       // Note, we allow "void" uses (basically, uses that aren't loads or
9357       // stores), because arm allows folding a scale into many arithmetic
9358       // operations.  This should be made more precise and revisited later.
9359
9360       // Allow r << imm, but the imm has to be a multiple of two.
9361       if (Scale & 1) return false;
9362       return isPowerOf2_32(Scale);
9363     }
9364   }
9365   return true;
9366 }
9367
9368 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9369 /// icmp immediate, that is the target has icmp instructions which can compare
9370 /// a register against the immediate without having to materialize the
9371 /// immediate into a register.
9372 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9373   // Thumb2 and ARM modes can use cmn for negative immediates.
9374   if (!Subtarget->isThumb())
9375     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9376   if (Subtarget->isThumb2())
9377     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9378   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9379   return Imm >= 0 && Imm <= 255;
9380 }
9381
9382 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9383 /// *or sub* immediate, that is the target has add or sub instructions which can
9384 /// add a register with the immediate without having to materialize the
9385 /// immediate into a register.
9386 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9387   // Same encoding for add/sub, just flip the sign.
9388   int64_t AbsImm = llvm::abs64(Imm);
9389   if (!Subtarget->isThumb())
9390     return ARM_AM::getSOImmVal(AbsImm) != -1;
9391   if (Subtarget->isThumb2())
9392     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9393   // Thumb1 only has 8-bit unsigned immediate.
9394   return AbsImm >= 0 && AbsImm <= 255;
9395 }
9396
9397 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9398                                       bool isSEXTLoad, SDValue &Base,
9399                                       SDValue &Offset, bool &isInc,
9400                                       SelectionDAG &DAG) {
9401   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9402     return false;
9403
9404   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9405     // AddressingMode 3
9406     Base = Ptr->getOperand(0);
9407     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9408       int RHSC = (int)RHS->getZExtValue();
9409       if (RHSC < 0 && RHSC > -256) {
9410         assert(Ptr->getOpcode() == ISD::ADD);
9411         isInc = false;
9412         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9413         return true;
9414       }
9415     }
9416     isInc = (Ptr->getOpcode() == ISD::ADD);
9417     Offset = Ptr->getOperand(1);
9418     return true;
9419   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9420     // AddressingMode 2
9421     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9422       int RHSC = (int)RHS->getZExtValue();
9423       if (RHSC < 0 && RHSC > -0x1000) {
9424         assert(Ptr->getOpcode() == ISD::ADD);
9425         isInc = false;
9426         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9427         Base = Ptr->getOperand(0);
9428         return true;
9429       }
9430     }
9431
9432     if (Ptr->getOpcode() == ISD::ADD) {
9433       isInc = true;
9434       ARM_AM::ShiftOpc ShOpcVal=
9435         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9436       if (ShOpcVal != ARM_AM::no_shift) {
9437         Base = Ptr->getOperand(1);
9438         Offset = Ptr->getOperand(0);
9439       } else {
9440         Base = Ptr->getOperand(0);
9441         Offset = Ptr->getOperand(1);
9442       }
9443       return true;
9444     }
9445
9446     isInc = (Ptr->getOpcode() == ISD::ADD);
9447     Base = Ptr->getOperand(0);
9448     Offset = Ptr->getOperand(1);
9449     return true;
9450   }
9451
9452   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9453   return false;
9454 }
9455
9456 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9457                                      bool isSEXTLoad, SDValue &Base,
9458                                      SDValue &Offset, bool &isInc,
9459                                      SelectionDAG &DAG) {
9460   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9461     return false;
9462
9463   Base = Ptr->getOperand(0);
9464   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9465     int RHSC = (int)RHS->getZExtValue();
9466     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9467       assert(Ptr->getOpcode() == ISD::ADD);
9468       isInc = false;
9469       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9470       return true;
9471     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9472       isInc = Ptr->getOpcode() == ISD::ADD;
9473       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9474       return true;
9475     }
9476   }
9477
9478   return false;
9479 }
9480
9481 /// getPreIndexedAddressParts - returns true by value, base pointer and
9482 /// offset pointer and addressing mode by reference if the node's address
9483 /// can be legally represented as pre-indexed load / store address.
9484 bool
9485 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9486                                              SDValue &Offset,
9487                                              ISD::MemIndexedMode &AM,
9488                                              SelectionDAG &DAG) const {
9489   if (Subtarget->isThumb1Only())
9490     return false;
9491
9492   EVT VT;
9493   SDValue Ptr;
9494   bool isSEXTLoad = false;
9495   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9496     Ptr = LD->getBasePtr();
9497     VT  = LD->getMemoryVT();
9498     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9499   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9500     Ptr = ST->getBasePtr();
9501     VT  = ST->getMemoryVT();
9502   } else
9503     return false;
9504
9505   bool isInc;
9506   bool isLegal = false;
9507   if (Subtarget->isThumb2())
9508     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9509                                        Offset, isInc, DAG);
9510   else
9511     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9512                                         Offset, isInc, DAG);
9513   if (!isLegal)
9514     return false;
9515
9516   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9517   return true;
9518 }
9519
9520 /// getPostIndexedAddressParts - returns true by value, base pointer and
9521 /// offset pointer and addressing mode by reference if this node can be
9522 /// combined with a load / store to form a post-indexed load / store.
9523 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9524                                                    SDValue &Base,
9525                                                    SDValue &Offset,
9526                                                    ISD::MemIndexedMode &AM,
9527                                                    SelectionDAG &DAG) const {
9528   if (Subtarget->isThumb1Only())
9529     return false;
9530
9531   EVT VT;
9532   SDValue Ptr;
9533   bool isSEXTLoad = false;
9534   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9535     VT  = LD->getMemoryVT();
9536     Ptr = LD->getBasePtr();
9537     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9538   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9539     VT  = ST->getMemoryVT();
9540     Ptr = ST->getBasePtr();
9541   } else
9542     return false;
9543
9544   bool isInc;
9545   bool isLegal = false;
9546   if (Subtarget->isThumb2())
9547     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9548                                        isInc, DAG);
9549   else
9550     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9551                                         isInc, DAG);
9552   if (!isLegal)
9553     return false;
9554
9555   if (Ptr != Base) {
9556     // Swap base ptr and offset to catch more post-index load / store when
9557     // it's legal. In Thumb2 mode, offset must be an immediate.
9558     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9559         !Subtarget->isThumb2())
9560       std::swap(Base, Offset);
9561
9562     // Post-indexed load / store update the base pointer.
9563     if (Ptr != Base)
9564       return false;
9565   }
9566
9567   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9568   return true;
9569 }
9570
9571 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9572                                                        APInt &KnownZero,
9573                                                        APInt &KnownOne,
9574                                                        const SelectionDAG &DAG,
9575                                                        unsigned Depth) const {
9576   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9577   switch (Op.getOpcode()) {
9578   default: break;
9579   case ARMISD::CMOV: {
9580     // Bits are known zero/one if known on the LHS and RHS.
9581     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9582     if (KnownZero == 0 && KnownOne == 0) return;
9583
9584     APInt KnownZeroRHS, KnownOneRHS;
9585     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9586     KnownZero &= KnownZeroRHS;
9587     KnownOne  &= KnownOneRHS;
9588     return;
9589   }
9590   }
9591 }
9592
9593 //===----------------------------------------------------------------------===//
9594 //                           ARM Inline Assembly Support
9595 //===----------------------------------------------------------------------===//
9596
9597 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9598   // Looking for "rev" which is V6+.
9599   if (!Subtarget->hasV6Ops())
9600     return false;
9601
9602   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9603   std::string AsmStr = IA->getAsmString();
9604   SmallVector<StringRef, 4> AsmPieces;
9605   SplitString(AsmStr, AsmPieces, ";\n");
9606
9607   switch (AsmPieces.size()) {
9608   default: return false;
9609   case 1:
9610     AsmStr = AsmPieces[0];
9611     AsmPieces.clear();
9612     SplitString(AsmStr, AsmPieces, " \t,");
9613
9614     // rev $0, $1
9615     if (AsmPieces.size() == 3 &&
9616         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9617         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9618       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9619       if (Ty && Ty->getBitWidth() == 32)
9620         return IntrinsicLowering::LowerToByteSwap(CI);
9621     }
9622     break;
9623   }
9624
9625   return false;
9626 }
9627
9628 /// getConstraintType - Given a constraint letter, return the type of
9629 /// constraint it is for this target.
9630 ARMTargetLowering::ConstraintType
9631 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9632   if (Constraint.size() == 1) {
9633     switch (Constraint[0]) {
9634     default:  break;
9635     case 'l': return C_RegisterClass;
9636     case 'w': return C_RegisterClass;
9637     case 'h': return C_RegisterClass;
9638     case 'x': return C_RegisterClass;
9639     case 't': return C_RegisterClass;
9640     case 'j': return C_Other; // Constant for movw.
9641       // An address with a single base register. Due to the way we
9642       // currently handle addresses it is the same as an 'r' memory constraint.
9643     case 'Q': return C_Memory;
9644     }
9645   } else if (Constraint.size() == 2) {
9646     switch (Constraint[0]) {
9647     default: break;
9648     // All 'U+' constraints are addresses.
9649     case 'U': return C_Memory;
9650     }
9651   }
9652   return TargetLowering::getConstraintType(Constraint);
9653 }
9654
9655 /// Examine constraint type and operand type and determine a weight value.
9656 /// This object must already have been set up with the operand type
9657 /// and the current alternative constraint selected.
9658 TargetLowering::ConstraintWeight
9659 ARMTargetLowering::getSingleConstraintMatchWeight(
9660     AsmOperandInfo &info, const char *constraint) const {
9661   ConstraintWeight weight = CW_Invalid;
9662   Value *CallOperandVal = info.CallOperandVal;
9663     // If we don't have a value, we can't do a match,
9664     // but allow it at the lowest weight.
9665   if (CallOperandVal == NULL)
9666     return CW_Default;
9667   Type *type = CallOperandVal->getType();
9668   // Look at the constraint type.
9669   switch (*constraint) {
9670   default:
9671     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9672     break;
9673   case 'l':
9674     if (type->isIntegerTy()) {
9675       if (Subtarget->isThumb())
9676         weight = CW_SpecificReg;
9677       else
9678         weight = CW_Register;
9679     }
9680     break;
9681   case 'w':
9682     if (type->isFloatingPointTy())
9683       weight = CW_Register;
9684     break;
9685   }
9686   return weight;
9687 }
9688
9689 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9690 RCPair
9691 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9692                                                 EVT VT) const {
9693   if (Constraint.size() == 1) {
9694     // GCC ARM Constraint Letters
9695     switch (Constraint[0]) {
9696     case 'l': // Low regs or general regs.
9697       if (Subtarget->isThumb())
9698         return RCPair(0U, &ARM::tGPRRegClass);
9699       return RCPair(0U, &ARM::GPRRegClass);
9700     case 'h': // High regs or no regs.
9701       if (Subtarget->isThumb())
9702         return RCPair(0U, &ARM::hGPRRegClass);
9703       break;
9704     case 'r':
9705       return RCPair(0U, &ARM::GPRRegClass);
9706     case 'w':
9707       if (VT == MVT::f32)
9708         return RCPair(0U, &ARM::SPRRegClass);
9709       if (VT.getSizeInBits() == 64)
9710         return RCPair(0U, &ARM::DPRRegClass);
9711       if (VT.getSizeInBits() == 128)
9712         return RCPair(0U, &ARM::QPRRegClass);
9713       break;
9714     case 'x':
9715       if (VT == MVT::f32)
9716         return RCPair(0U, &ARM::SPR_8RegClass);
9717       if (VT.getSizeInBits() == 64)
9718         return RCPair(0U, &ARM::DPR_8RegClass);
9719       if (VT.getSizeInBits() == 128)
9720         return RCPair(0U, &ARM::QPR_8RegClass);
9721       break;
9722     case 't':
9723       if (VT == MVT::f32)
9724         return RCPair(0U, &ARM::SPRRegClass);
9725       break;
9726     }
9727   }
9728   if (StringRef("{cc}").equals_lower(Constraint))
9729     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9730
9731   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9732 }
9733
9734 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9735 /// vector.  If it is invalid, don't add anything to Ops.
9736 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9737                                                      std::string &Constraint,
9738                                                      std::vector<SDValue>&Ops,
9739                                                      SelectionDAG &DAG) const {
9740   SDValue Result(0, 0);
9741
9742   // Currently only support length 1 constraints.
9743   if (Constraint.length() != 1) return;
9744
9745   char ConstraintLetter = Constraint[0];
9746   switch (ConstraintLetter) {
9747   default: break;
9748   case 'j':
9749   case 'I': case 'J': case 'K': case 'L':
9750   case 'M': case 'N': case 'O':
9751     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9752     if (!C)
9753       return;
9754
9755     int64_t CVal64 = C->getSExtValue();
9756     int CVal = (int) CVal64;
9757     // None of these constraints allow values larger than 32 bits.  Check
9758     // that the value fits in an int.
9759     if (CVal != CVal64)
9760       return;
9761
9762     switch (ConstraintLetter) {
9763       case 'j':
9764         // Constant suitable for movw, must be between 0 and
9765         // 65535.
9766         if (Subtarget->hasV6T2Ops())
9767           if (CVal >= 0 && CVal <= 65535)
9768             break;
9769         return;
9770       case 'I':
9771         if (Subtarget->isThumb1Only()) {
9772           // This must be a constant between 0 and 255, for ADD
9773           // immediates.
9774           if (CVal >= 0 && CVal <= 255)
9775             break;
9776         } else if (Subtarget->isThumb2()) {
9777           // A constant that can be used as an immediate value in a
9778           // data-processing instruction.
9779           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9780             break;
9781         } else {
9782           // A constant that can be used as an immediate value in a
9783           // data-processing instruction.
9784           if (ARM_AM::getSOImmVal(CVal) != -1)
9785             break;
9786         }
9787         return;
9788
9789       case 'J':
9790         if (Subtarget->isThumb()) {  // FIXME thumb2
9791           // This must be a constant between -255 and -1, for negated ADD
9792           // immediates. This can be used in GCC with an "n" modifier that
9793           // prints the negated value, for use with SUB instructions. It is
9794           // not useful otherwise but is implemented for compatibility.
9795           if (CVal >= -255 && CVal <= -1)
9796             break;
9797         } else {
9798           // This must be a constant between -4095 and 4095. It is not clear
9799           // what this constraint is intended for. Implemented for
9800           // compatibility with GCC.
9801           if (CVal >= -4095 && CVal <= 4095)
9802             break;
9803         }
9804         return;
9805
9806       case 'K':
9807         if (Subtarget->isThumb1Only()) {
9808           // A 32-bit value where only one byte has a nonzero value. Exclude
9809           // zero to match GCC. This constraint is used by GCC internally for
9810           // constants that can be loaded with a move/shift combination.
9811           // It is not useful otherwise but is implemented for compatibility.
9812           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9813             break;
9814         } else if (Subtarget->isThumb2()) {
9815           // A constant whose bitwise inverse can be used as an immediate
9816           // value in a data-processing instruction. This can be used in GCC
9817           // with a "B" modifier that prints the inverted value, for use with
9818           // BIC and MVN instructions. It is not useful otherwise but is
9819           // implemented for compatibility.
9820           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9821             break;
9822         } else {
9823           // A constant whose bitwise inverse can be used as an immediate
9824           // value in a data-processing instruction. This can be used in GCC
9825           // with a "B" modifier that prints the inverted value, for use with
9826           // BIC and MVN instructions. It is not useful otherwise but is
9827           // implemented for compatibility.
9828           if (ARM_AM::getSOImmVal(~CVal) != -1)
9829             break;
9830         }
9831         return;
9832
9833       case 'L':
9834         if (Subtarget->isThumb1Only()) {
9835           // This must be a constant between -7 and 7,
9836           // for 3-operand ADD/SUB immediate instructions.
9837           if (CVal >= -7 && CVal < 7)
9838             break;
9839         } else if (Subtarget->isThumb2()) {
9840           // A constant whose negation can be used as an immediate value in a
9841           // data-processing instruction. This can be used in GCC with an "n"
9842           // modifier that prints the negated value, for use with SUB
9843           // instructions. It is not useful otherwise but is implemented for
9844           // compatibility.
9845           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9846             break;
9847         } else {
9848           // A constant whose negation can be used as an immediate value in a
9849           // data-processing instruction. This can be used in GCC with an "n"
9850           // modifier that prints the negated value, for use with SUB
9851           // instructions. It is not useful otherwise but is implemented for
9852           // compatibility.
9853           if (ARM_AM::getSOImmVal(-CVal) != -1)
9854             break;
9855         }
9856         return;
9857
9858       case 'M':
9859         if (Subtarget->isThumb()) { // FIXME thumb2
9860           // This must be a multiple of 4 between 0 and 1020, for
9861           // ADD sp + immediate.
9862           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9863             break;
9864         } else {
9865           // A power of two or a constant between 0 and 32.  This is used in
9866           // GCC for the shift amount on shifted register operands, but it is
9867           // useful in general for any shift amounts.
9868           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9869             break;
9870         }
9871         return;
9872
9873       case 'N':
9874         if (Subtarget->isThumb()) {  // FIXME thumb2
9875           // This must be a constant between 0 and 31, for shift amounts.
9876           if (CVal >= 0 && CVal <= 31)
9877             break;
9878         }
9879         return;
9880
9881       case 'O':
9882         if (Subtarget->isThumb()) {  // FIXME thumb2
9883           // This must be a multiple of 4 between -508 and 508, for
9884           // ADD/SUB sp = sp + immediate.
9885           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9886             break;
9887         }
9888         return;
9889     }
9890     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9891     break;
9892   }
9893
9894   if (Result.getNode()) {
9895     Ops.push_back(Result);
9896     return;
9897   }
9898   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9899 }
9900
9901 bool
9902 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9903   // The ARM target isn't yet aware of offsets.
9904   return false;
9905 }
9906
9907 bool ARM::isBitFieldInvertedMask(unsigned v) {
9908   if (v == 0xffffffff)
9909     return 0;
9910   // there can be 1's on either or both "outsides", all the "inside"
9911   // bits must be 0's
9912   unsigned int lsb = 0, msb = 31;
9913   while (v & (1 << msb)) --msb;
9914   while (v & (1 << lsb)) ++lsb;
9915   for (unsigned int i = lsb; i <= msb; ++i) {
9916     if (v & (1 << i))
9917       return 0;
9918   }
9919   return 1;
9920 }
9921
9922 /// isFPImmLegal - Returns true if the target can instruction select the
9923 /// specified FP immediate natively. If false, the legalizer will
9924 /// materialize the FP immediate as a load from a constant pool.
9925 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9926   if (!Subtarget->hasVFP3())
9927     return false;
9928   if (VT == MVT::f32)
9929     return ARM_AM::getFP32Imm(Imm) != -1;
9930   if (VT == MVT::f64)
9931     return ARM_AM::getFP64Imm(Imm) != -1;
9932   return false;
9933 }
9934
9935 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9936 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9937 /// specified in the intrinsic calls.
9938 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9939                                            const CallInst &I,
9940                                            unsigned Intrinsic) const {
9941   switch (Intrinsic) {
9942   case Intrinsic::arm_neon_vld1:
9943   case Intrinsic::arm_neon_vld2:
9944   case Intrinsic::arm_neon_vld3:
9945   case Intrinsic::arm_neon_vld4:
9946   case Intrinsic::arm_neon_vld2lane:
9947   case Intrinsic::arm_neon_vld3lane:
9948   case Intrinsic::arm_neon_vld4lane: {
9949     Info.opc = ISD::INTRINSIC_W_CHAIN;
9950     // Conservatively set memVT to the entire set of vectors loaded.
9951     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
9952     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9953     Info.ptrVal = I.getArgOperand(0);
9954     Info.offset = 0;
9955     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9956     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9957     Info.vol = false; // volatile loads with NEON intrinsics not supported
9958     Info.readMem = true;
9959     Info.writeMem = false;
9960     return true;
9961   }
9962   case Intrinsic::arm_neon_vst1:
9963   case Intrinsic::arm_neon_vst2:
9964   case Intrinsic::arm_neon_vst3:
9965   case Intrinsic::arm_neon_vst4:
9966   case Intrinsic::arm_neon_vst2lane:
9967   case Intrinsic::arm_neon_vst3lane:
9968   case Intrinsic::arm_neon_vst4lane: {
9969     Info.opc = ISD::INTRINSIC_VOID;
9970     // Conservatively set memVT to the entire set of vectors stored.
9971     unsigned NumElts = 0;
9972     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9973       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9974       if (!ArgTy->isVectorTy())
9975         break;
9976       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
9977     }
9978     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9979     Info.ptrVal = I.getArgOperand(0);
9980     Info.offset = 0;
9981     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9982     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9983     Info.vol = false; // volatile stores with NEON intrinsics not supported
9984     Info.readMem = false;
9985     Info.writeMem = true;
9986     return true;
9987   }
9988   case Intrinsic::arm_strexd: {
9989     Info.opc = ISD::INTRINSIC_W_CHAIN;
9990     Info.memVT = MVT::i64;
9991     Info.ptrVal = I.getArgOperand(2);
9992     Info.offset = 0;
9993     Info.align = 8;
9994     Info.vol = true;
9995     Info.readMem = false;
9996     Info.writeMem = true;
9997     return true;
9998   }
9999   case Intrinsic::arm_ldrexd: {
10000     Info.opc = ISD::INTRINSIC_W_CHAIN;
10001     Info.memVT = MVT::i64;
10002     Info.ptrVal = I.getArgOperand(0);
10003     Info.offset = 0;
10004     Info.align = 8;
10005     Info.vol = true;
10006     Info.readMem = true;
10007     Info.writeMem = false;
10008     return true;
10009   }
10010   default:
10011     break;
10012   }
10013
10014   return false;
10015 }