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