ARM getOperandLatency rewrite.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
94                                        EVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
97     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
98                        PromotedLdStVT.getSimpleVT());
99
100     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
101     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
102                        PromotedLdStVT.getSimpleVT());
103   }
104
105   EVT ElemTy = VT.getVectorElementType();
106   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
107     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
108   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
109   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
110   if (ElemTy == MVT::i32) {
111     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
112     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
113     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
114     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
115   } else {
116     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
117     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
118     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
119     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
120   }
121   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
122   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
123   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
124   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
125   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
126   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
128   if (VT.isInteger()) {
129     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
130     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
131     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
132   }
133
134   // Promote all bit-wise operations.
135   if (VT.isInteger() && VT != PromotedBitwiseVT) {
136     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
137     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
138                        PromotedBitwiseVT.getSimpleVT());
139     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
140     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
141                        PromotedBitwiseVT.getSimpleVT());
142     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
143     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
144                        PromotedBitwiseVT.getSimpleVT());
145   }
146
147   // Neon does not support vector divide/remainder operations.
148   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
149   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
150   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
153   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
154 }
155
156 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
157   addRegisterClass(VT, &ARM::DPRRegClass);
158   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
159 }
160
161 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
162   addRegisterClass(VT, &ARM::QPRRegClass);
163   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
164 }
165
166 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
167   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
168     return new TargetLoweringObjectFileMachO();
169
170   return new ARMElfTargetObjectFile();
171 }
172
173 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
174     : TargetLowering(TM, createTLOF(TM)) {
175   Subtarget = &TM.getSubtarget<ARMSubtarget>();
176   RegInfo = TM.getRegisterInfo();
177   Itins = TM.getInstrItineraryData();
178
179   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
180
181   if (Subtarget->isTargetDarwin()) {
182     // Uses VFP for Thumb libfuncs if available.
183     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
184       // Single-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
186       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
187       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
188       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
189
190       // Double-precision floating-point arithmetic.
191       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
192       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
193       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
194       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
195
196       // Single-precision comparisons.
197       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
198       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
199       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
200       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
201       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
202       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
203       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
204       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
205
206       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
213       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
214
215       // Double-precision comparisons.
216       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
217       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
218       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
219       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
220       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
221       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
222       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
223       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
224
225       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
231       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
232       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
233
234       // Floating-point to integer conversions.
235       // i64 conversions are done via library routines even when generating VFP
236       // instructions, so use the same ones.
237       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
238       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
239       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
240       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
241
242       // Conversions between floating types.
243       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
244       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
245
246       // Integer to floating-point conversions.
247       // i64 conversions are done via library routines even when generating VFP
248       // instructions, so use the same ones.
249       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
250       // e.g., __floatunsidf vs. __floatunssidfvfp.
251       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
252       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
253       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
254       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
255     }
256   }
257
258   // These libcalls are not available in 32-bit.
259   setLibcallName(RTLIB::SHL_I128, 0);
260   setLibcallName(RTLIB::SRL_I128, 0);
261   setLibcallName(RTLIB::SRA_I128, 0);
262
263   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
264     // Double-precision floating-point arithmetic helper functions
265     // RTABI chapter 4.1.2, Table 2
266     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
267     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
268     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
269     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
270     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
273     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
274
275     // Double-precision floating-point comparison helper functions
276     // RTABI chapter 4.1.2, Table 3
277     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
278     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
279     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
280     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
281     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
282     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
284     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
285     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
286     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
287     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
288     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
289     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
290     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
291     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
292     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
293     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
301
302     // Single-precision floating-point arithmetic helper functions
303     // RTABI chapter 4.1.2, Table 4
304     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
305     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
306     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
307     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
308     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
311     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
312
313     // Single-precision floating-point comparison helper functions
314     // RTABI chapter 4.1.2, Table 5
315     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
316     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
317     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
318     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
319     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
320     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
322     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
323     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
324     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
325     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
326     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
327     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
328     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
329     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
330     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
331     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
338     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
339
340     // Floating-point to integer conversions.
341     // RTABI chapter 4.1.2, Table 6
342     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
343     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
345     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
346     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
347     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
348     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
349     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
350     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
358
359     // Conversions between floating types.
360     // RTABI chapter 4.1.2, Table 7
361     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
362     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
363     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
364     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
365
366     // Integer to floating-point conversions.
367     // RTABI chapter 4.1.2, Table 8
368     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
369     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
370     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
371     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
372     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
373     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
374     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
375     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384
385     // Long long helper functions
386     // RTABI chapter 4.2, Table 9
387     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
388     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
389     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
390     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
391     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
397
398     // Integer division functions
399     // RTABI chapter 4.3.1
400     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
401     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
402     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
403     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
404     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
405     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
406     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
407     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
408     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
415     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
416
417     // Memory operations
418     // RTABI chapter 4.3.4
419     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
420     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
421     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
422     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
423     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
424     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
425   }
426
427   // Use divmod compiler-rt calls for iOS 5.0 and later.
428   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
429       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
430     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
431     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
432   }
433
434   if (Subtarget->isThumb1Only())
435     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
436   else
437     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
438   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
439       !Subtarget->isThumb1Only()) {
440     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
441     if (!Subtarget->isFPOnlySP())
442       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
443
444     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
445   }
446
447   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
449     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
450          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
451       setTruncStoreAction((MVT::SimpleValueType)VT,
452                           (MVT::SimpleValueType)InnerVT, Expand);
453     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
455     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
456   }
457
458   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
459
460   if (Subtarget->hasNEON()) {
461     addDRTypeForNEON(MVT::v2f32);
462     addDRTypeForNEON(MVT::v8i8);
463     addDRTypeForNEON(MVT::v4i16);
464     addDRTypeForNEON(MVT::v2i32);
465     addDRTypeForNEON(MVT::v1i64);
466
467     addQRTypeForNEON(MVT::v4f32);
468     addQRTypeForNEON(MVT::v2f64);
469     addQRTypeForNEON(MVT::v16i8);
470     addQRTypeForNEON(MVT::v8i16);
471     addQRTypeForNEON(MVT::v4i32);
472     addQRTypeForNEON(MVT::v2i64);
473
474     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
475     // neither Neon nor VFP support any arithmetic operations on it.
476     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
477     // supported for v4f32.
478     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
479     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
481     // FIXME: Code duplication: FDIV and FREM are expanded always, see
482     // ARMTargetLowering::addTypeForNEON method for details.
483     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
484     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
485     // FIXME: Create unittest.
486     // In another words, find a way when "copysign" appears in DAG with vector
487     // operands.
488     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
489     // FIXME: Code duplication: SETCC has custom operation action, see
490     // ARMTargetLowering::addTypeForNEON method for details.
491     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
492     // FIXME: Create unittest for FNEG and for FABS.
493     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
494     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
496     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
497     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
499     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
502     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
504     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
505     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
506     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
507     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
508     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
510     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
511
512     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522
523     // Neon does not support some operations on v1i64 and v2i64 types.
524     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
525     // Custom handling for some quad-vector types to detect VMULL.
526     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
527     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
528     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
529     // Custom handling for some vector types to avoid expensive expansions
530     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
531     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
532     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
533     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
534     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
535     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
536     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
537     // a destination type that is wider than the source, and nor does
538     // it have a FP_TO_[SU]INT instruction with a narrower destination than
539     // source.
540     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
543     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544
545     setTargetDAGCombine(ISD::INTRINSIC_VOID);
546     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
547     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
548     setTargetDAGCombine(ISD::SHL);
549     setTargetDAGCombine(ISD::SRL);
550     setTargetDAGCombine(ISD::SRA);
551     setTargetDAGCombine(ISD::SIGN_EXTEND);
552     setTargetDAGCombine(ISD::ZERO_EXTEND);
553     setTargetDAGCombine(ISD::ANY_EXTEND);
554     setTargetDAGCombine(ISD::SELECT_CC);
555     setTargetDAGCombine(ISD::BUILD_VECTOR);
556     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
557     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
558     setTargetDAGCombine(ISD::STORE);
559     setTargetDAGCombine(ISD::FP_TO_SINT);
560     setTargetDAGCombine(ISD::FP_TO_UINT);
561     setTargetDAGCombine(ISD::FDIV);
562
563     // It is legal to extload from v4i8 to v4i16 or v4i32.
564     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
565                   MVT::v4i16, MVT::v2i16,
566                   MVT::v2i32};
567     for (unsigned i = 0; i < 6; ++i) {
568       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
569       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
570       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
571     }
572   }
573
574   computeRegisterProperties();
575
576   // ARM does not have f32 extending load.
577   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
578
579   // ARM does not have i1 sign extending load.
580   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
581
582   // ARM supports all 4 flavors of integer indexed load / store.
583   if (!Subtarget->isThumb1Only()) {
584     for (unsigned im = (unsigned)ISD::PRE_INC;
585          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
586       setIndexedLoadAction(im,  MVT::i1,  Legal);
587       setIndexedLoadAction(im,  MVT::i8,  Legal);
588       setIndexedLoadAction(im,  MVT::i16, Legal);
589       setIndexedLoadAction(im,  MVT::i32, Legal);
590       setIndexedStoreAction(im, MVT::i1,  Legal);
591       setIndexedStoreAction(im, MVT::i8,  Legal);
592       setIndexedStoreAction(im, MVT::i16, Legal);
593       setIndexedStoreAction(im, MVT::i32, Legal);
594     }
595   }
596
597   // i64 operation support.
598   setOperationAction(ISD::MUL,     MVT::i64, Expand);
599   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
600   if (Subtarget->isThumb1Only()) {
601     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
602     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
603   }
604   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
605       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
606     setOperationAction(ISD::MULHS, MVT::i32, Expand);
607
608   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
609   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
610   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
611   setOperationAction(ISD::SRL,       MVT::i64, Custom);
612   setOperationAction(ISD::SRA,       MVT::i64, Custom);
613
614   if (!Subtarget->isThumb1Only()) {
615     // FIXME: We should do this for Thumb1 as well.
616     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
617     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
618     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
619     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
620   }
621
622   // ARM does not have ROTL.
623   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
624   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
625   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
626   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
627     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
628
629   // These just redirect to CTTZ and CTLZ on ARM.
630   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
631   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
632
633   // Only ARMv6 has BSWAP.
634   if (!Subtarget->hasV6Ops())
635     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
636
637   // These are expanded into libcalls.
638   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
639     // v7M has a hardware divider
640     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
641     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
642   }
643   setOperationAction(ISD::SREM,  MVT::i32, Expand);
644   setOperationAction(ISD::UREM,  MVT::i32, Expand);
645   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
646   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
647
648   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
649   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
650   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
651   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
652   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
653
654   setOperationAction(ISD::TRAP, MVT::Other, Legal);
655
656   // Use the default implementation.
657   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
658   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
659   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
660   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
661   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
662   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
663
664   if (!Subtarget->isTargetDarwin()) {
665     // Non-Darwin platforms may return values in these registers via the
666     // personality function.
667     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
668     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
669     setExceptionPointerRegister(ARM::R0);
670     setExceptionSelectorRegister(ARM::R1);
671   }
672
673   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
674   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
675   // the default expansion.
676   // FIXME: This should be checking for v6k, not just v6.
677   if (Subtarget->hasDataBarrier() ||
678       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
679     // membarrier needs custom lowering; the rest are legal and handled
680     // normally.
681     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
682     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
683     // Custom lowering for 64-bit ops
684     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
685     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
686     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
690     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
691     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
692     setInsertFencesForAtomic(true);
693   } else {
694     // Set them all for expansion, which will force libcalls.
695     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
696     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
697     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
698     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
709     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
710     // Unordered/Monotonic case.
711     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
712     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
713     // Since the libcalls include locking, fold in the fences
714     setShouldFoldAtomicFences(true);
715   }
716
717   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
718
719   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
720   if (!Subtarget->hasV6Ops()) {
721     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
722     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
723   }
724   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
725
726   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
727       !Subtarget->isThumb1Only()) {
728     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
729     // iff target supports vfp2.
730     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
731     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
732   }
733
734   // We want to custom lower some of our intrinsics.
735   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
736   if (Subtarget->isTargetDarwin()) {
737     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
738     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
739     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
740   }
741
742   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
743   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
744   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
745   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
746   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
747   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
748   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
749   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
750   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
751
752   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
753   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
754   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
755   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
756   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
757
758   // We don't support sin/cos/fmod/copysign/pow
759   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
760   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
761   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
762   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
763   setOperationAction(ISD::FREM,      MVT::f64, Expand);
764   setOperationAction(ISD::FREM,      MVT::f32, Expand);
765   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766       !Subtarget->isThumb1Only()) {
767     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
768     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
769   }
770   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
771   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
772
773   if (!Subtarget->hasVFP4()) {
774     setOperationAction(ISD::FMA, MVT::f64, Expand);
775     setOperationAction(ISD::FMA, MVT::f32, Expand);
776   }
777
778   // Various VFP goodness
779   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
780     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
781     if (Subtarget->hasVFP2()) {
782       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
783       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
784       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
785       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
786     }
787     // Special handling for half-precision FP.
788     if (!Subtarget->hasFP16()) {
789       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
790       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
791     }
792   }
793
794   // We have target-specific dag combine patterns for the following nodes:
795   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
796   setTargetDAGCombine(ISD::ADD);
797   setTargetDAGCombine(ISD::SUB);
798   setTargetDAGCombine(ISD::MUL);
799
800   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
801     setTargetDAGCombine(ISD::AND);
802     setTargetDAGCombine(ISD::OR);
803     setTargetDAGCombine(ISD::XOR);
804   }
805
806   if (Subtarget->hasV6Ops())
807     setTargetDAGCombine(ISD::SRL);
808
809   setStackPointerRegisterToSaveRestore(ARM::SP);
810
811   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
812       !Subtarget->hasVFP2())
813     setSchedulingPreference(Sched::RegPressure);
814   else
815     setSchedulingPreference(Sched::Hybrid);
816
817   //// temporary - rewrite interface to use type
818   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
819   maxStoresPerMemset = 16;
820   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
821
822   // On ARM arguments smaller than 4 bytes are extended, so all arguments
823   // are at least 4 bytes aligned.
824   setMinStackArgumentAlignment(4);
825
826   benefitFromCodePlacementOpt = true;
827
828   // Prefer likely predicted branches to selects on out-of-order cores.
829   predictableSelectIsExpensive = Subtarget->isCortexA9();
830
831   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
832 }
833
834 // FIXME: It might make sense to define the representative register class as the
835 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
836 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
837 // SPR's representative would be DPR_VFP2. This should work well if register
838 // pressure tracking were modified such that a register use would increment the
839 // pressure of the register class's representative and all of it's super
840 // classes' representatives transitively. We have not implemented this because
841 // of the difficulty prior to coalescing of modeling operand register classes
842 // due to the common occurrence of cross class copies and subregister insertions
843 // and extractions.
844 std::pair<const TargetRegisterClass*, uint8_t>
845 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
846   const TargetRegisterClass *RRC = 0;
847   uint8_t Cost = 1;
848   switch (VT.getSimpleVT().SimpleTy) {
849   default:
850     return TargetLowering::findRepresentativeClass(VT);
851   // Use DPR as representative register class for all floating point
852   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
853   // the cost is 1 for both f32 and f64.
854   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
855   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
856     RRC = &ARM::DPRRegClass;
857     // When NEON is used for SP, only half of the register file is available
858     // because operations that define both SP and DP results will be constrained
859     // to the VFP2 class (D0-D15). We currently model this constraint prior to
860     // coalescing by double-counting the SP regs. See the FIXME above.
861     if (Subtarget->useNEONForSinglePrecisionFP())
862       Cost = 2;
863     break;
864   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
865   case MVT::v4f32: case MVT::v2f64:
866     RRC = &ARM::DPRRegClass;
867     Cost = 2;
868     break;
869   case MVT::v4i64:
870     RRC = &ARM::DPRRegClass;
871     Cost = 4;
872     break;
873   case MVT::v8i64:
874     RRC = &ARM::DPRRegClass;
875     Cost = 8;
876     break;
877   }
878   return std::make_pair(RRC, Cost);
879 }
880
881 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
882   switch (Opcode) {
883   default: return 0;
884   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
885   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
886   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
887   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
888   case ARMISD::CALL:          return "ARMISD::CALL";
889   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
890   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
891   case ARMISD::tCALL:         return "ARMISD::tCALL";
892   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
893   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
894   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
895   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
896   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
897   case ARMISD::CMP:           return "ARMISD::CMP";
898   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
899   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
900   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
901   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
902   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
903
904   case ARMISD::CMOV:          return "ARMISD::CMOV";
905   case ARMISD::CAND:          return "ARMISD::CAND";
906   case ARMISD::COR:           return "ARMISD::COR";
907   case ARMISD::CXOR:          return "ARMISD::CXOR";
908
909   case ARMISD::RBIT:          return "ARMISD::RBIT";
910
911   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
912   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
913   case ARMISD::SITOF:         return "ARMISD::SITOF";
914   case ARMISD::UITOF:         return "ARMISD::UITOF";
915
916   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
917   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
918   case ARMISD::RRX:           return "ARMISD::RRX";
919
920   case ARMISD::ADDC:          return "ARMISD::ADDC";
921   case ARMISD::ADDE:          return "ARMISD::ADDE";
922   case ARMISD::SUBC:          return "ARMISD::SUBC";
923   case ARMISD::SUBE:          return "ARMISD::SUBE";
924
925   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
926   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
927
928   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
929   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
930
931   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
932
933   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
934
935   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
936
937   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
938   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
939
940   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
941
942   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
943   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
944   case ARMISD::VCGE:          return "ARMISD::VCGE";
945   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
946   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
947   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
948   case ARMISD::VCGT:          return "ARMISD::VCGT";
949   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
950   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
951   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
952   case ARMISD::VTST:          return "ARMISD::VTST";
953
954   case ARMISD::VSHL:          return "ARMISD::VSHL";
955   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
956   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
957   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
958   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
959   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
960   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
961   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
962   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
963   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
964   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
965   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
966   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
967   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
968   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
969   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
970   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
971   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
972   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
973   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
974   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
975   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
976   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
977   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
978   case ARMISD::VDUP:          return "ARMISD::VDUP";
979   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
980   case ARMISD::VEXT:          return "ARMISD::VEXT";
981   case ARMISD::VREV64:        return "ARMISD::VREV64";
982   case ARMISD::VREV32:        return "ARMISD::VREV32";
983   case ARMISD::VREV16:        return "ARMISD::VREV16";
984   case ARMISD::VZIP:          return "ARMISD::VZIP";
985   case ARMISD::VUZP:          return "ARMISD::VUZP";
986   case ARMISD::VTRN:          return "ARMISD::VTRN";
987   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
988   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
989   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
990   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
991   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
992   case ARMISD::FMAX:          return "ARMISD::FMAX";
993   case ARMISD::FMIN:          return "ARMISD::FMIN";
994   case ARMISD::BFI:           return "ARMISD::BFI";
995   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
996   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
997   case ARMISD::VBSL:          return "ARMISD::VBSL";
998   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
999   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1000   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1001   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1002   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1003   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1004   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1005   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1006   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1007   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1008   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1009   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1010   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1011   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1012   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1013   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1014   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1015   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1016   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1017   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1018   }
1019 }
1020
1021 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1022   if (!VT.isVector()) return getPointerTy();
1023   return VT.changeVectorElementTypeToInteger();
1024 }
1025
1026 /// getRegClassFor - Return the register class that should be used for the
1027 /// specified value type.
1028 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1029   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1030   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1031   // load / store 4 to 8 consecutive D registers.
1032   if (Subtarget->hasNEON()) {
1033     if (VT == MVT::v4i64)
1034       return &ARM::QQPRRegClass;
1035     if (VT == MVT::v8i64)
1036       return &ARM::QQQQPRRegClass;
1037   }
1038   return TargetLowering::getRegClassFor(VT);
1039 }
1040
1041 // Create a fast isel object.
1042 FastISel *
1043 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1044   return ARM::createFastISel(funcInfo);
1045 }
1046
1047 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1048 /// be used for loads / stores from the global.
1049 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1050   return (Subtarget->isThumb1Only() ? 127 : 4095);
1051 }
1052
1053 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1054   unsigned NumVals = N->getNumValues();
1055   if (!NumVals)
1056     return Sched::RegPressure;
1057
1058   for (unsigned i = 0; i != NumVals; ++i) {
1059     EVT VT = N->getValueType(i);
1060     if (VT == MVT::Glue || VT == MVT::Other)
1061       continue;
1062     if (VT.isFloatingPoint() || VT.isVector())
1063       return Sched::ILP;
1064   }
1065
1066   if (!N->isMachineOpcode())
1067     return Sched::RegPressure;
1068
1069   // Load are scheduled for latency even if there instruction itinerary
1070   // is not available.
1071   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1072   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1073
1074   if (MCID.getNumDefs() == 0)
1075     return Sched::RegPressure;
1076   if (!Itins->isEmpty() &&
1077       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1078     return Sched::ILP;
1079
1080   return Sched::RegPressure;
1081 }
1082
1083 //===----------------------------------------------------------------------===//
1084 // Lowering Code
1085 //===----------------------------------------------------------------------===//
1086
1087 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1088 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1089   switch (CC) {
1090   default: llvm_unreachable("Unknown condition code!");
1091   case ISD::SETNE:  return ARMCC::NE;
1092   case ISD::SETEQ:  return ARMCC::EQ;
1093   case ISD::SETGT:  return ARMCC::GT;
1094   case ISD::SETGE:  return ARMCC::GE;
1095   case ISD::SETLT:  return ARMCC::LT;
1096   case ISD::SETLE:  return ARMCC::LE;
1097   case ISD::SETUGT: return ARMCC::HI;
1098   case ISD::SETUGE: return ARMCC::HS;
1099   case ISD::SETULT: return ARMCC::LO;
1100   case ISD::SETULE: return ARMCC::LS;
1101   }
1102 }
1103
1104 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1105 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1106                         ARMCC::CondCodes &CondCode2) {
1107   CondCode2 = ARMCC::AL;
1108   switch (CC) {
1109   default: llvm_unreachable("Unknown FP condition!");
1110   case ISD::SETEQ:
1111   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1112   case ISD::SETGT:
1113   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1114   case ISD::SETGE:
1115   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1116   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1117   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1118   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1119   case ISD::SETO:   CondCode = ARMCC::VC; break;
1120   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1121   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1122   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1123   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1124   case ISD::SETLT:
1125   case ISD::SETULT: CondCode = ARMCC::LT; break;
1126   case ISD::SETLE:
1127   case ISD::SETULE: CondCode = ARMCC::LE; break;
1128   case ISD::SETNE:
1129   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1130   }
1131 }
1132
1133 //===----------------------------------------------------------------------===//
1134 //                      Calling Convention Implementation
1135 //===----------------------------------------------------------------------===//
1136
1137 #include "ARMGenCallingConv.inc"
1138
1139 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1140 /// given CallingConvention value.
1141 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1142                                                  bool Return,
1143                                                  bool isVarArg) const {
1144   switch (CC) {
1145   default:
1146     llvm_unreachable("Unsupported calling convention");
1147   case CallingConv::Fast:
1148     if (Subtarget->hasVFP2() && !isVarArg) {
1149       if (!Subtarget->isAAPCS_ABI())
1150         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1151       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1152       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1153     }
1154     // Fallthrough
1155   case CallingConv::C: {
1156     // Use target triple & subtarget features to do actual dispatch.
1157     if (!Subtarget->isAAPCS_ABI())
1158       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1159     else if (Subtarget->hasVFP2() &&
1160              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1161              !isVarArg)
1162       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1163     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1164   }
1165   case CallingConv::ARM_AAPCS_VFP:
1166     if (!isVarArg)
1167       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1168     // Fallthrough
1169   case CallingConv::ARM_AAPCS:
1170     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1171   case CallingConv::ARM_APCS:
1172     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1173   }
1174 }
1175
1176 /// LowerCallResult - Lower the result values of a call into the
1177 /// appropriate copies out of appropriate physical registers.
1178 SDValue
1179 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1180                                    CallingConv::ID CallConv, bool isVarArg,
1181                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1182                                    DebugLoc dl, SelectionDAG &DAG,
1183                                    SmallVectorImpl<SDValue> &InVals) const {
1184
1185   // Assign locations to each value returned by this call.
1186   SmallVector<CCValAssign, 16> RVLocs;
1187   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1188                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1189   CCInfo.AnalyzeCallResult(Ins,
1190                            CCAssignFnForNode(CallConv, /* Return*/ true,
1191                                              isVarArg));
1192
1193   // Copy all of the result registers out of their specified physreg.
1194   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1195     CCValAssign VA = RVLocs[i];
1196
1197     SDValue Val;
1198     if (VA.needsCustom()) {
1199       // Handle f64 or half of a v2f64.
1200       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1201                                       InFlag);
1202       Chain = Lo.getValue(1);
1203       InFlag = Lo.getValue(2);
1204       VA = RVLocs[++i]; // skip ahead to next loc
1205       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1206                                       InFlag);
1207       Chain = Hi.getValue(1);
1208       InFlag = Hi.getValue(2);
1209       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1210
1211       if (VA.getLocVT() == MVT::v2f64) {
1212         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1213         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1214                           DAG.getConstant(0, MVT::i32));
1215
1216         VA = RVLocs[++i]; // skip ahead to next loc
1217         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1218         Chain = Lo.getValue(1);
1219         InFlag = Lo.getValue(2);
1220         VA = RVLocs[++i]; // skip ahead to next loc
1221         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1222         Chain = Hi.getValue(1);
1223         InFlag = Hi.getValue(2);
1224         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1225         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1226                           DAG.getConstant(1, MVT::i32));
1227       }
1228     } else {
1229       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1230                                InFlag);
1231       Chain = Val.getValue(1);
1232       InFlag = Val.getValue(2);
1233     }
1234
1235     switch (VA.getLocInfo()) {
1236     default: llvm_unreachable("Unknown loc info!");
1237     case CCValAssign::Full: break;
1238     case CCValAssign::BCvt:
1239       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1240       break;
1241     }
1242
1243     InVals.push_back(Val);
1244   }
1245
1246   return Chain;
1247 }
1248
1249 /// LowerMemOpCallTo - Store the argument to the stack.
1250 SDValue
1251 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1252                                     SDValue StackPtr, SDValue Arg,
1253                                     DebugLoc dl, SelectionDAG &DAG,
1254                                     const CCValAssign &VA,
1255                                     ISD::ArgFlagsTy Flags) const {
1256   unsigned LocMemOffset = VA.getLocMemOffset();
1257   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1258   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1259   return DAG.getStore(Chain, dl, Arg, PtrOff,
1260                       MachinePointerInfo::getStack(LocMemOffset),
1261                       false, false, 0);
1262 }
1263
1264 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1265                                          SDValue Chain, SDValue &Arg,
1266                                          RegsToPassVector &RegsToPass,
1267                                          CCValAssign &VA, CCValAssign &NextVA,
1268                                          SDValue &StackPtr,
1269                                          SmallVector<SDValue, 8> &MemOpChains,
1270                                          ISD::ArgFlagsTy Flags) const {
1271
1272   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1273                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1274   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1275
1276   if (NextVA.isRegLoc())
1277     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1278   else {
1279     assert(NextVA.isMemLoc());
1280     if (StackPtr.getNode() == 0)
1281       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1282
1283     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1284                                            dl, DAG, NextVA,
1285                                            Flags));
1286   }
1287 }
1288
1289 /// LowerCall - Lowering a call into a callseq_start <-
1290 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1291 /// nodes.
1292 SDValue
1293 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1294                              SmallVectorImpl<SDValue> &InVals) const {
1295   SelectionDAG &DAG                     = CLI.DAG;
1296   DebugLoc &dl                          = CLI.DL;
1297   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1298   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1299   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1300   SDValue Chain                         = CLI.Chain;
1301   SDValue Callee                        = CLI.Callee;
1302   bool &isTailCall                      = CLI.IsTailCall;
1303   CallingConv::ID CallConv              = CLI.CallConv;
1304   bool doesNotRet                       = CLI.DoesNotReturn;
1305   bool isVarArg                         = CLI.IsVarArg;
1306
1307   MachineFunction &MF = DAG.getMachineFunction();
1308   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1309   bool IsSibCall = false;
1310   // Disable tail calls if they're not supported.
1311   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1312     isTailCall = false;
1313   if (isTailCall) {
1314     // Check if it's really possible to do a tail call.
1315     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1316                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1317                                                    Outs, OutVals, Ins, DAG);
1318     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1319     // detected sibcalls.
1320     if (isTailCall) {
1321       ++NumTailCalls;
1322       IsSibCall = true;
1323     }
1324   }
1325
1326   // Analyze operands of the call, assigning locations to each operand.
1327   SmallVector<CCValAssign, 16> ArgLocs;
1328   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1329                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1330   CCInfo.AnalyzeCallOperands(Outs,
1331                              CCAssignFnForNode(CallConv, /* Return*/ false,
1332                                                isVarArg));
1333
1334   // Get a count of how many bytes are to be pushed on the stack.
1335   unsigned NumBytes = CCInfo.getNextStackOffset();
1336
1337   // For tail calls, memory operands are available in our caller's stack.
1338   if (IsSibCall)
1339     NumBytes = 0;
1340
1341   // Adjust the stack pointer for the new arguments...
1342   // These operations are automatically eliminated by the prolog/epilog pass
1343   if (!IsSibCall)
1344     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1345
1346   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1347
1348   RegsToPassVector RegsToPass;
1349   SmallVector<SDValue, 8> MemOpChains;
1350
1351   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1352   // of tail call optimization, arguments are handled later.
1353   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1354        i != e;
1355        ++i, ++realArgIdx) {
1356     CCValAssign &VA = ArgLocs[i];
1357     SDValue Arg = OutVals[realArgIdx];
1358     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1359     bool isByVal = Flags.isByVal();
1360
1361     // Promote the value if needed.
1362     switch (VA.getLocInfo()) {
1363     default: llvm_unreachable("Unknown loc info!");
1364     case CCValAssign::Full: break;
1365     case CCValAssign::SExt:
1366       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1367       break;
1368     case CCValAssign::ZExt:
1369       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1370       break;
1371     case CCValAssign::AExt:
1372       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1373       break;
1374     case CCValAssign::BCvt:
1375       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1376       break;
1377     }
1378
1379     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1380     if (VA.needsCustom()) {
1381       if (VA.getLocVT() == MVT::v2f64) {
1382         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1383                                   DAG.getConstant(0, MVT::i32));
1384         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1385                                   DAG.getConstant(1, MVT::i32));
1386
1387         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1388                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1389
1390         VA = ArgLocs[++i]; // skip ahead to next loc
1391         if (VA.isRegLoc()) {
1392           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1393                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1394         } else {
1395           assert(VA.isMemLoc());
1396
1397           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1398                                                  dl, DAG, VA, Flags));
1399         }
1400       } else {
1401         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1402                          StackPtr, MemOpChains, Flags);
1403       }
1404     } else if (VA.isRegLoc()) {
1405       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1406     } else if (isByVal) {
1407       assert(VA.isMemLoc());
1408       unsigned offset = 0;
1409
1410       // True if this byval aggregate will be split between registers
1411       // and memory.
1412       if (CCInfo.isFirstByValRegValid()) {
1413         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1414         unsigned int i, j;
1415         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1416           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1417           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1418           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1419                                      MachinePointerInfo(),
1420                                      false, false, false, 0);
1421           MemOpChains.push_back(Load.getValue(1));
1422           RegsToPass.push_back(std::make_pair(j, Load));
1423         }
1424         offset = ARM::R4 - CCInfo.getFirstByValReg();
1425         CCInfo.clearFirstByValReg();
1426       }
1427
1428       if (Flags.getByValSize() - 4*offset > 0) {
1429         unsigned LocMemOffset = VA.getLocMemOffset();
1430         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1431         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1432                                   StkPtrOff);
1433         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1434         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1435         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1436                                            MVT::i32);
1437         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1438
1439         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1440         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1441         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1442                                           Ops, array_lengthof(Ops)));
1443       }
1444     } else if (!IsSibCall) {
1445       assert(VA.isMemLoc());
1446
1447       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1448                                              dl, DAG, VA, Flags));
1449     }
1450   }
1451
1452   if (!MemOpChains.empty())
1453     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1454                         &MemOpChains[0], MemOpChains.size());
1455
1456   // Build a sequence of copy-to-reg nodes chained together with token chain
1457   // and flag operands which copy the outgoing args into the appropriate regs.
1458   SDValue InFlag;
1459   // Tail call byval lowering might overwrite argument registers so in case of
1460   // tail call optimization the copies to registers are lowered later.
1461   if (!isTailCall)
1462     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1463       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1464                                RegsToPass[i].second, InFlag);
1465       InFlag = Chain.getValue(1);
1466     }
1467
1468   // For tail calls lower the arguments to the 'real' stack slot.
1469   if (isTailCall) {
1470     // Force all the incoming stack arguments to be loaded from the stack
1471     // before any new outgoing arguments are stored to the stack, because the
1472     // outgoing stack slots may alias the incoming argument stack slots, and
1473     // the alias isn't otherwise explicit. This is slightly more conservative
1474     // than necessary, because it means that each store effectively depends
1475     // on every argument instead of just those arguments it would clobber.
1476
1477     // Do not flag preceding copytoreg stuff together with the following stuff.
1478     InFlag = SDValue();
1479     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1480       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1481                                RegsToPass[i].second, InFlag);
1482       InFlag = Chain.getValue(1);
1483     }
1484     InFlag =SDValue();
1485   }
1486
1487   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1488   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1489   // node so that legalize doesn't hack it.
1490   bool isDirect = false;
1491   bool isARMFunc = false;
1492   bool isLocalARMFunc = false;
1493   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1494
1495   if (EnableARMLongCalls) {
1496     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1497             && "long-calls with non-static relocation model!");
1498     // Handle a global address or an external symbol. If it's not one of
1499     // those, the target's already in a register, so we don't need to do
1500     // anything extra.
1501     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1502       const GlobalValue *GV = G->getGlobal();
1503       // Create a constant pool entry for the callee address
1504       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1505       ARMConstantPoolValue *CPV =
1506         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1507
1508       // Get the address of the callee into a register
1509       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1510       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1511       Callee = DAG.getLoad(getPointerTy(), dl,
1512                            DAG.getEntryNode(), CPAddr,
1513                            MachinePointerInfo::getConstantPool(),
1514                            false, false, false, 0);
1515     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1516       const char *Sym = S->getSymbol();
1517
1518       // Create a constant pool entry for the callee address
1519       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1520       ARMConstantPoolValue *CPV =
1521         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1522                                       ARMPCLabelIndex, 0);
1523       // Get the address of the callee into a register
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     }
1531   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1532     const GlobalValue *GV = G->getGlobal();
1533     isDirect = true;
1534     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1535     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1536                    getTargetMachine().getRelocationModel() != Reloc::Static;
1537     isARMFunc = !Subtarget->isThumb() || isStub;
1538     // ARM call to a local ARM function is predicable.
1539     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1540     // tBX takes a register source operand.
1541     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1542       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1543       ARMConstantPoolValue *CPV =
1544         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1545       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1546       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1547       Callee = DAG.getLoad(getPointerTy(), dl,
1548                            DAG.getEntryNode(), CPAddr,
1549                            MachinePointerInfo::getConstantPool(),
1550                            false, false, false, 0);
1551       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1552       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1553                            getPointerTy(), Callee, PICLabel);
1554     } else {
1555       // On ELF targets for PIC code, direct calls should go through the PLT
1556       unsigned OpFlags = 0;
1557       if (Subtarget->isTargetELF() &&
1558                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1559         OpFlags = ARMII::MO_PLT;
1560       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1561     }
1562   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1563     isDirect = true;
1564     bool isStub = Subtarget->isTargetDarwin() &&
1565                   getTargetMachine().getRelocationModel() != Reloc::Static;
1566     isARMFunc = !Subtarget->isThumb() || isStub;
1567     // tBX takes a register source operand.
1568     const char *Sym = S->getSymbol();
1569     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1570       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1571       ARMConstantPoolValue *CPV =
1572         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1573                                       ARMPCLabelIndex, 4);
1574       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1575       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1576       Callee = DAG.getLoad(getPointerTy(), dl,
1577                            DAG.getEntryNode(), CPAddr,
1578                            MachinePointerInfo::getConstantPool(),
1579                            false, false, false, 0);
1580       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1581       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1582                            getPointerTy(), Callee, PICLabel);
1583     } else {
1584       unsigned OpFlags = 0;
1585       // On ELF targets for PIC code, direct calls should go through the PLT
1586       if (Subtarget->isTargetELF() &&
1587                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1588         OpFlags = ARMII::MO_PLT;
1589       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1590     }
1591   }
1592
1593   // FIXME: handle tail calls differently.
1594   unsigned CallOpc;
1595   if (Subtarget->isThumb()) {
1596     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1597       CallOpc = ARMISD::CALL_NOLINK;
1598     else if (doesNotRet && isDirect && !isARMFunc &&
1599              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1600       // "mov lr, pc; b _foo" to avoid confusing the RSP
1601       CallOpc = ARMISD::CALL_NOLINK;
1602     else
1603       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1604   } else {
1605     if (!isDirect && !Subtarget->hasV5TOps()) {
1606       CallOpc = ARMISD::CALL_NOLINK;
1607     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1608       // "mov lr, pc; b _foo" to avoid confusing the RSP
1609       CallOpc = ARMISD::CALL_NOLINK;
1610     else
1611       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1612   }
1613
1614   std::vector<SDValue> Ops;
1615   Ops.push_back(Chain);
1616   Ops.push_back(Callee);
1617
1618   // Add argument registers to the end of the list so that they are known live
1619   // into the call.
1620   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1621     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1622                                   RegsToPass[i].second.getValueType()));
1623
1624   // Add a register mask operand representing the call-preserved registers.
1625   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1626   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1627   assert(Mask && "Missing call preserved mask for calling convention");
1628   Ops.push_back(DAG.getRegisterMask(Mask));
1629
1630   if (InFlag.getNode())
1631     Ops.push_back(InFlag);
1632
1633   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1634   if (isTailCall)
1635     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1636
1637   // Returns a chain and a flag for retval copy to use.
1638   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1639   InFlag = Chain.getValue(1);
1640
1641   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1642                              DAG.getIntPtrConstant(0, true), InFlag);
1643   if (!Ins.empty())
1644     InFlag = Chain.getValue(1);
1645
1646   // Handle result values, copying them out of physregs into vregs that we
1647   // return.
1648   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1649                          dl, DAG, InVals);
1650 }
1651
1652 /// HandleByVal - Every parameter *after* a byval parameter is passed
1653 /// on the stack.  Remember the next parameter register to allocate,
1654 /// and then confiscate the rest of the parameter registers to insure
1655 /// this.
1656 void
1657 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1658   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1659   assert((State->getCallOrPrologue() == Prologue ||
1660           State->getCallOrPrologue() == Call) &&
1661          "unhandled ParmContext");
1662   if ((!State->isFirstByValRegValid()) &&
1663       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1664     State->setFirstByValReg(reg);
1665     // At a call site, a byval parameter that is split between
1666     // registers and memory needs its size truncated here.  In a
1667     // function prologue, such byval parameters are reassembled in
1668     // memory, and are not truncated.
1669     if (State->getCallOrPrologue() == Call) {
1670       unsigned excess = 4 * (ARM::R4 - reg);
1671       assert(size >= excess && "expected larger existing stack allocation");
1672       size -= excess;
1673     }
1674   }
1675   // Confiscate any remaining parameter registers to preclude their
1676   // assignment to subsequent parameters.
1677   while (State->AllocateReg(GPRArgRegs, 4))
1678     ;
1679 }
1680
1681 /// MatchingStackOffset - Return true if the given stack call argument is
1682 /// already available in the same position (relatively) of the caller's
1683 /// incoming argument stack.
1684 static
1685 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1686                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1687                          const TargetInstrInfo *TII) {
1688   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1689   int FI = INT_MAX;
1690   if (Arg.getOpcode() == ISD::CopyFromReg) {
1691     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1692     if (!TargetRegisterInfo::isVirtualRegister(VR))
1693       return false;
1694     MachineInstr *Def = MRI->getVRegDef(VR);
1695     if (!Def)
1696       return false;
1697     if (!Flags.isByVal()) {
1698       if (!TII->isLoadFromStackSlot(Def, FI))
1699         return false;
1700     } else {
1701       return false;
1702     }
1703   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1704     if (Flags.isByVal())
1705       // ByVal argument is passed in as a pointer but it's now being
1706       // dereferenced. e.g.
1707       // define @foo(%struct.X* %A) {
1708       //   tail call @bar(%struct.X* byval %A)
1709       // }
1710       return false;
1711     SDValue Ptr = Ld->getBasePtr();
1712     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1713     if (!FINode)
1714       return false;
1715     FI = FINode->getIndex();
1716   } else
1717     return false;
1718
1719   assert(FI != INT_MAX);
1720   if (!MFI->isFixedObjectIndex(FI))
1721     return false;
1722   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1723 }
1724
1725 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1726 /// for tail call optimization. Targets which want to do tail call
1727 /// optimization should implement this function.
1728 bool
1729 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1730                                                      CallingConv::ID CalleeCC,
1731                                                      bool isVarArg,
1732                                                      bool isCalleeStructRet,
1733                                                      bool isCallerStructRet,
1734                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1735                                     const SmallVectorImpl<SDValue> &OutVals,
1736                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1737                                                      SelectionDAG& DAG) const {
1738   const Function *CallerF = DAG.getMachineFunction().getFunction();
1739   CallingConv::ID CallerCC = CallerF->getCallingConv();
1740   bool CCMatch = CallerCC == CalleeCC;
1741
1742   // Look for obvious safe cases to perform tail call optimization that do not
1743   // require ABI changes. This is what gcc calls sibcall.
1744
1745   // Do not sibcall optimize vararg calls unless the call site is not passing
1746   // any arguments.
1747   if (isVarArg && !Outs.empty())
1748     return false;
1749
1750   // Also avoid sibcall optimization if either caller or callee uses struct
1751   // return semantics.
1752   if (isCalleeStructRet || isCallerStructRet)
1753     return false;
1754
1755   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1756   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1757   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1758   // support in the assembler and linker to be used. This would need to be
1759   // fixed to fully support tail calls in Thumb1.
1760   //
1761   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1762   // LR.  This means if we need to reload LR, it takes an extra instructions,
1763   // which outweighs the value of the tail call; but here we don't know yet
1764   // whether LR is going to be used.  Probably the right approach is to
1765   // generate the tail call here and turn it back into CALL/RET in
1766   // emitEpilogue if LR is used.
1767
1768   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1769   // but we need to make sure there are enough registers; the only valid
1770   // registers are the 4 used for parameters.  We don't currently do this
1771   // case.
1772   if (Subtarget->isThumb1Only())
1773     return false;
1774
1775   // If the calling conventions do not match, then we'd better make sure the
1776   // results are returned in the same way as what the caller expects.
1777   if (!CCMatch) {
1778     SmallVector<CCValAssign, 16> RVLocs1;
1779     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1780                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1781     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1782
1783     SmallVector<CCValAssign, 16> RVLocs2;
1784     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1785                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1786     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1787
1788     if (RVLocs1.size() != RVLocs2.size())
1789       return false;
1790     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1791       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1792         return false;
1793       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1794         return false;
1795       if (RVLocs1[i].isRegLoc()) {
1796         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1797           return false;
1798       } else {
1799         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1800           return false;
1801       }
1802     }
1803   }
1804
1805   // If the callee takes no arguments then go on to check the results of the
1806   // call.
1807   if (!Outs.empty()) {
1808     // Check if stack adjustment is needed. For now, do not do this if any
1809     // argument is passed on the stack.
1810     SmallVector<CCValAssign, 16> ArgLocs;
1811     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1812                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1813     CCInfo.AnalyzeCallOperands(Outs,
1814                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1815     if (CCInfo.getNextStackOffset()) {
1816       MachineFunction &MF = DAG.getMachineFunction();
1817
1818       // Check if the arguments are already laid out in the right way as
1819       // the caller's fixed stack objects.
1820       MachineFrameInfo *MFI = MF.getFrameInfo();
1821       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1822       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1823       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1824            i != e;
1825            ++i, ++realArgIdx) {
1826         CCValAssign &VA = ArgLocs[i];
1827         EVT RegVT = VA.getLocVT();
1828         SDValue Arg = OutVals[realArgIdx];
1829         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1830         if (VA.getLocInfo() == CCValAssign::Indirect)
1831           return false;
1832         if (VA.needsCustom()) {
1833           // f64 and vector types are split into multiple registers or
1834           // register/stack-slot combinations.  The types will not match
1835           // the registers; give up on memory f64 refs until we figure
1836           // out what to do about this.
1837           if (!VA.isRegLoc())
1838             return false;
1839           if (!ArgLocs[++i].isRegLoc())
1840             return false;
1841           if (RegVT == MVT::v2f64) {
1842             if (!ArgLocs[++i].isRegLoc())
1843               return false;
1844             if (!ArgLocs[++i].isRegLoc())
1845               return false;
1846           }
1847         } else if (!VA.isRegLoc()) {
1848           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1849                                    MFI, MRI, TII))
1850             return false;
1851         }
1852       }
1853     }
1854   }
1855
1856   return true;
1857 }
1858
1859 SDValue
1860 ARMTargetLowering::LowerReturn(SDValue Chain,
1861                                CallingConv::ID CallConv, bool isVarArg,
1862                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1863                                const SmallVectorImpl<SDValue> &OutVals,
1864                                DebugLoc dl, SelectionDAG &DAG) const {
1865
1866   // CCValAssign - represent the assignment of the return value to a location.
1867   SmallVector<CCValAssign, 16> RVLocs;
1868
1869   // CCState - Info about the registers and stack slots.
1870   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1871                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1872
1873   // Analyze outgoing return values.
1874   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1875                                                isVarArg));
1876
1877   // If this is the first return lowered for this function, add
1878   // the regs to the liveout set for the function.
1879   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1880     for (unsigned i = 0; i != RVLocs.size(); ++i)
1881       if (RVLocs[i].isRegLoc())
1882         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1883   }
1884
1885   SDValue Flag;
1886
1887   // Copy the result values into the output registers.
1888   for (unsigned i = 0, realRVLocIdx = 0;
1889        i != RVLocs.size();
1890        ++i, ++realRVLocIdx) {
1891     CCValAssign &VA = RVLocs[i];
1892     assert(VA.isRegLoc() && "Can only return in registers!");
1893
1894     SDValue Arg = OutVals[realRVLocIdx];
1895
1896     switch (VA.getLocInfo()) {
1897     default: llvm_unreachable("Unknown loc info!");
1898     case CCValAssign::Full: break;
1899     case CCValAssign::BCvt:
1900       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1901       break;
1902     }
1903
1904     if (VA.needsCustom()) {
1905       if (VA.getLocVT() == MVT::v2f64) {
1906         // Extract the first half and return it in two registers.
1907         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1908                                    DAG.getConstant(0, MVT::i32));
1909         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1910                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1911
1912         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1913         Flag = Chain.getValue(1);
1914         VA = RVLocs[++i]; // skip ahead to next loc
1915         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1916                                  HalfGPRs.getValue(1), Flag);
1917         Flag = Chain.getValue(1);
1918         VA = RVLocs[++i]; // skip ahead to next loc
1919
1920         // Extract the 2nd half and fall through to handle it as an f64 value.
1921         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1922                           DAG.getConstant(1, MVT::i32));
1923       }
1924       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1925       // available.
1926       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1927                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1928       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1929       Flag = Chain.getValue(1);
1930       VA = RVLocs[++i]; // skip ahead to next loc
1931       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1932                                Flag);
1933     } else
1934       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1935
1936     // Guarantee that all emitted copies are
1937     // stuck together, avoiding something bad.
1938     Flag = Chain.getValue(1);
1939   }
1940
1941   SDValue result;
1942   if (Flag.getNode())
1943     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1944   else // Return Void
1945     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1946
1947   return result;
1948 }
1949
1950 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1951   if (N->getNumValues() != 1)
1952     return false;
1953   if (!N->hasNUsesOfValue(1, 0))
1954     return false;
1955
1956   SDValue TCChain = Chain;
1957   SDNode *Copy = *N->use_begin();
1958   if (Copy->getOpcode() == ISD::CopyToReg) {
1959     // If the copy has a glue operand, we conservatively assume it isn't safe to
1960     // perform a tail call.
1961     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1962       return false;
1963     TCChain = Copy->getOperand(0);
1964   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1965     SDNode *VMov = Copy;
1966     // f64 returned in a pair of GPRs.
1967     SmallPtrSet<SDNode*, 2> Copies;
1968     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1969          UI != UE; ++UI) {
1970       if (UI->getOpcode() != ISD::CopyToReg)
1971         return false;
1972       Copies.insert(*UI);
1973     }
1974     if (Copies.size() > 2)
1975       return false;
1976
1977     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1978          UI != UE; ++UI) {
1979       SDValue UseChain = UI->getOperand(0);
1980       if (Copies.count(UseChain.getNode()))
1981         // Second CopyToReg
1982         Copy = *UI;
1983       else
1984         // First CopyToReg
1985         TCChain = UseChain;
1986     }
1987   } else if (Copy->getOpcode() == ISD::BITCAST) {
1988     // f32 returned in a single GPR.
1989     if (!Copy->hasOneUse())
1990       return false;
1991     Copy = *Copy->use_begin();
1992     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1993       return false;
1994     Chain = Copy->getOperand(0);
1995   } else {
1996     return false;
1997   }
1998
1999   bool HasRet = false;
2000   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2001        UI != UE; ++UI) {
2002     if (UI->getOpcode() != ARMISD::RET_FLAG)
2003       return false;
2004     HasRet = true;
2005   }
2006
2007   if (!HasRet)
2008     return false;
2009
2010   Chain = TCChain;
2011   return true;
2012 }
2013
2014 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2015   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2016     return false;
2017
2018   if (!CI->isTailCall())
2019     return false;
2020
2021   return !Subtarget->isThumb1Only();
2022 }
2023
2024 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2025 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2026 // one of the above mentioned nodes. It has to be wrapped because otherwise
2027 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2028 // be used to form addressing mode. These wrapped nodes will be selected
2029 // into MOVi.
2030 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2031   EVT PtrVT = Op.getValueType();
2032   // FIXME there is no actual debug info here
2033   DebugLoc dl = Op.getDebugLoc();
2034   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2035   SDValue Res;
2036   if (CP->isMachineConstantPoolEntry())
2037     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2038                                     CP->getAlignment());
2039   else
2040     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2041                                     CP->getAlignment());
2042   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2043 }
2044
2045 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2046   return MachineJumpTableInfo::EK_Inline;
2047 }
2048
2049 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2050                                              SelectionDAG &DAG) const {
2051   MachineFunction &MF = DAG.getMachineFunction();
2052   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2053   unsigned ARMPCLabelIndex = 0;
2054   DebugLoc DL = Op.getDebugLoc();
2055   EVT PtrVT = getPointerTy();
2056   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2057   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2058   SDValue CPAddr;
2059   if (RelocM == Reloc::Static) {
2060     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2061   } else {
2062     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2063     ARMPCLabelIndex = AFI->createPICLabelUId();
2064     ARMConstantPoolValue *CPV =
2065       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2066                                       ARMCP::CPBlockAddress, PCAdj);
2067     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2068   }
2069   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2070   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2071                                MachinePointerInfo::getConstantPool(),
2072                                false, false, false, 0);
2073   if (RelocM == Reloc::Static)
2074     return Result;
2075   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2076   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2077 }
2078
2079 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2080 SDValue
2081 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2082                                                  SelectionDAG &DAG) const {
2083   DebugLoc dl = GA->getDebugLoc();
2084   EVT PtrVT = getPointerTy();
2085   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2086   MachineFunction &MF = DAG.getMachineFunction();
2087   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2088   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2089   ARMConstantPoolValue *CPV =
2090     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2091                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2092   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2093   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2094   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2095                          MachinePointerInfo::getConstantPool(),
2096                          false, false, false, 0);
2097   SDValue Chain = Argument.getValue(1);
2098
2099   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2100   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2101
2102   // call __tls_get_addr.
2103   ArgListTy Args;
2104   ArgListEntry Entry;
2105   Entry.Node = Argument;
2106   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2107   Args.push_back(Entry);
2108   // FIXME: is there useful debug info available here?
2109   TargetLowering::CallLoweringInfo CLI(Chain,
2110                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2111                 false, false, false, false,
2112                 0, CallingConv::C, /*isTailCall=*/false,
2113                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2114                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2115   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2116   return CallResult.first;
2117 }
2118
2119 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2120 // "local exec" model.
2121 SDValue
2122 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2123                                         SelectionDAG &DAG,
2124                                         TLSModel::Model model) const {
2125   const GlobalValue *GV = GA->getGlobal();
2126   DebugLoc dl = GA->getDebugLoc();
2127   SDValue Offset;
2128   SDValue Chain = DAG.getEntryNode();
2129   EVT PtrVT = getPointerTy();
2130   // Get the Thread Pointer
2131   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2132
2133   if (model == TLSModel::InitialExec) {
2134     MachineFunction &MF = DAG.getMachineFunction();
2135     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2136     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2137     // Initial exec model.
2138     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2139     ARMConstantPoolValue *CPV =
2140       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2141                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2142                                       true);
2143     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2144     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2145     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2146                          MachinePointerInfo::getConstantPool(),
2147                          false, false, false, 0);
2148     Chain = Offset.getValue(1);
2149
2150     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2151     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2152
2153     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2154                          MachinePointerInfo::getConstantPool(),
2155                          false, false, false, 0);
2156   } else {
2157     // local exec model
2158     assert(model == TLSModel::LocalExec);
2159     ARMConstantPoolValue *CPV =
2160       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2161     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2162     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2163     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2164                          MachinePointerInfo::getConstantPool(),
2165                          false, false, false, 0);
2166   }
2167
2168   // The address of the thread local variable is the add of the thread
2169   // pointer with the offset of the variable.
2170   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2171 }
2172
2173 SDValue
2174 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2175   // TODO: implement the "local dynamic" model
2176   assert(Subtarget->isTargetELF() &&
2177          "TLS not implemented for non-ELF targets");
2178   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2179
2180   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2181
2182   switch (model) {
2183     case TLSModel::GeneralDynamic:
2184     case TLSModel::LocalDynamic:
2185       return LowerToTLSGeneralDynamicModel(GA, DAG);
2186     case TLSModel::InitialExec:
2187     case TLSModel::LocalExec:
2188       return LowerToTLSExecModels(GA, DAG, model);
2189   }
2190   llvm_unreachable("bogus TLS model");
2191 }
2192
2193 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2194                                                  SelectionDAG &DAG) const {
2195   EVT PtrVT = getPointerTy();
2196   DebugLoc dl = Op.getDebugLoc();
2197   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2198   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2199   if (RelocM == Reloc::PIC_) {
2200     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2201     ARMConstantPoolValue *CPV =
2202       ARMConstantPoolConstant::Create(GV,
2203                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2204     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2205     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2206     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2207                                  CPAddr,
2208                                  MachinePointerInfo::getConstantPool(),
2209                                  false, false, false, 0);
2210     SDValue Chain = Result.getValue(1);
2211     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2212     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2213     if (!UseGOTOFF)
2214       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2215                            MachinePointerInfo::getGOT(),
2216                            false, false, false, 0);
2217     return Result;
2218   }
2219
2220   // If we have T2 ops, we can materialize the address directly via movt/movw
2221   // pair. This is always cheaper.
2222   if (Subtarget->useMovt()) {
2223     ++NumMovwMovt;
2224     // FIXME: Once remat is capable of dealing with instructions with register
2225     // operands, expand this into two nodes.
2226     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2227                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2228   } else {
2229     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2230     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2231     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2232                        MachinePointerInfo::getConstantPool(),
2233                        false, false, false, 0);
2234   }
2235 }
2236
2237 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2238                                                     SelectionDAG &DAG) const {
2239   EVT PtrVT = getPointerTy();
2240   DebugLoc dl = Op.getDebugLoc();
2241   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2242   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2243   MachineFunction &MF = DAG.getMachineFunction();
2244   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2245
2246   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2247   // update ARMFastISel::ARMMaterializeGV.
2248   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2249     ++NumMovwMovt;
2250     // FIXME: Once remat is capable of dealing with instructions with register
2251     // operands, expand this into two nodes.
2252     if (RelocM == Reloc::Static)
2253       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2254                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2255
2256     unsigned Wrapper = (RelocM == Reloc::PIC_)
2257       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2258     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2259                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2260     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2261       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2262                            MachinePointerInfo::getGOT(),
2263                            false, false, false, 0);
2264     return Result;
2265   }
2266
2267   unsigned ARMPCLabelIndex = 0;
2268   SDValue CPAddr;
2269   if (RelocM == Reloc::Static) {
2270     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2271   } else {
2272     ARMPCLabelIndex = AFI->createPICLabelUId();
2273     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2274     ARMConstantPoolValue *CPV =
2275       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2276                                       PCAdj);
2277     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2278   }
2279   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2280
2281   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2282                                MachinePointerInfo::getConstantPool(),
2283                                false, false, false, 0);
2284   SDValue Chain = Result.getValue(1);
2285
2286   if (RelocM == Reloc::PIC_) {
2287     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2288     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2289   }
2290
2291   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2292     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2293                          false, false, false, 0);
2294
2295   return Result;
2296 }
2297
2298 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2299                                                     SelectionDAG &DAG) const {
2300   assert(Subtarget->isTargetELF() &&
2301          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2302   MachineFunction &MF = DAG.getMachineFunction();
2303   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2304   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2305   EVT PtrVT = getPointerTy();
2306   DebugLoc dl = Op.getDebugLoc();
2307   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2308   ARMConstantPoolValue *CPV =
2309     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2310                                   ARMPCLabelIndex, PCAdj);
2311   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2312   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2313   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2314                                MachinePointerInfo::getConstantPool(),
2315                                false, false, false, 0);
2316   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2317   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2318 }
2319
2320 SDValue
2321 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2322   DebugLoc dl = Op.getDebugLoc();
2323   SDValue Val = DAG.getConstant(0, MVT::i32);
2324   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2325                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2326                      Op.getOperand(1), Val);
2327 }
2328
2329 SDValue
2330 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2331   DebugLoc dl = Op.getDebugLoc();
2332   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2333                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2334 }
2335
2336 SDValue
2337 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2338                                           const ARMSubtarget *Subtarget) const {
2339   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2340   DebugLoc dl = Op.getDebugLoc();
2341   switch (IntNo) {
2342   default: return SDValue();    // Don't custom lower most intrinsics.
2343   case Intrinsic::arm_thread_pointer: {
2344     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2345     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2346   }
2347   case Intrinsic::eh_sjlj_lsda: {
2348     MachineFunction &MF = DAG.getMachineFunction();
2349     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2350     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2351     EVT PtrVT = getPointerTy();
2352     DebugLoc dl = Op.getDebugLoc();
2353     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2354     SDValue CPAddr;
2355     unsigned PCAdj = (RelocM != Reloc::PIC_)
2356       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2357     ARMConstantPoolValue *CPV =
2358       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2359                                       ARMCP::CPLSDA, PCAdj);
2360     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2361     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2362     SDValue Result =
2363       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2364                   MachinePointerInfo::getConstantPool(),
2365                   false, false, false, 0);
2366
2367     if (RelocM == Reloc::PIC_) {
2368       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2369       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2370     }
2371     return Result;
2372   }
2373   case Intrinsic::arm_neon_vmulls:
2374   case Intrinsic::arm_neon_vmullu: {
2375     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2376       ? ARMISD::VMULLs : ARMISD::VMULLu;
2377     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2378                        Op.getOperand(1), Op.getOperand(2));
2379   }
2380   }
2381 }
2382
2383 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2384                                const ARMSubtarget *Subtarget) {
2385   DebugLoc dl = Op.getDebugLoc();
2386   if (!Subtarget->hasDataBarrier()) {
2387     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2388     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2389     // here.
2390     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2391            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2392     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2393                        DAG.getConstant(0, MVT::i32));
2394   }
2395
2396   SDValue Op5 = Op.getOperand(5);
2397   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2398   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2399   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2400   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2401
2402   ARM_MB::MemBOpt DMBOpt;
2403   if (isDeviceBarrier)
2404     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2405   else
2406     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2407   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2408                      DAG.getConstant(DMBOpt, MVT::i32));
2409 }
2410
2411
2412 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2413                                  const ARMSubtarget *Subtarget) {
2414   // FIXME: handle "fence singlethread" more efficiently.
2415   DebugLoc dl = Op.getDebugLoc();
2416   if (!Subtarget->hasDataBarrier()) {
2417     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2418     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2419     // here.
2420     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2421            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2422     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2423                        DAG.getConstant(0, MVT::i32));
2424   }
2425
2426   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2427                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2428 }
2429
2430 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2431                              const ARMSubtarget *Subtarget) {
2432   // ARM pre v5TE and Thumb1 does not have preload instructions.
2433   if (!(Subtarget->isThumb2() ||
2434         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2435     // Just preserve the chain.
2436     return Op.getOperand(0);
2437
2438   DebugLoc dl = Op.getDebugLoc();
2439   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2440   if (!isRead &&
2441       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2442     // ARMv7 with MP extension has PLDW.
2443     return Op.getOperand(0);
2444
2445   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2446   if (Subtarget->isThumb()) {
2447     // Invert the bits.
2448     isRead = ~isRead & 1;
2449     isData = ~isData & 1;
2450   }
2451
2452   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2453                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2454                      DAG.getConstant(isData, MVT::i32));
2455 }
2456
2457 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2458   MachineFunction &MF = DAG.getMachineFunction();
2459   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2460
2461   // vastart just stores the address of the VarArgsFrameIndex slot into the
2462   // memory location argument.
2463   DebugLoc dl = Op.getDebugLoc();
2464   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2465   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2466   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2467   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2468                       MachinePointerInfo(SV), false, false, 0);
2469 }
2470
2471 SDValue
2472 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2473                                         SDValue &Root, SelectionDAG &DAG,
2474                                         DebugLoc dl) const {
2475   MachineFunction &MF = DAG.getMachineFunction();
2476   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2477
2478   const TargetRegisterClass *RC;
2479   if (AFI->isThumb1OnlyFunction())
2480     RC = &ARM::tGPRRegClass;
2481   else
2482     RC = &ARM::GPRRegClass;
2483
2484   // Transform the arguments stored in physical registers into virtual ones.
2485   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2486   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2487
2488   SDValue ArgValue2;
2489   if (NextVA.isMemLoc()) {
2490     MachineFrameInfo *MFI = MF.getFrameInfo();
2491     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2492
2493     // Create load node to retrieve arguments from the stack.
2494     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2495     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2496                             MachinePointerInfo::getFixedStack(FI),
2497                             false, false, false, 0);
2498   } else {
2499     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2500     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2501   }
2502
2503   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2504 }
2505
2506 void
2507 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2508                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2509   const {
2510   unsigned NumGPRs;
2511   if (CCInfo.isFirstByValRegValid())
2512     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2513   else {
2514     unsigned int firstUnalloced;
2515     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2516                                                 sizeof(GPRArgRegs) /
2517                                                 sizeof(GPRArgRegs[0]));
2518     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2519   }
2520
2521   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2522   VARegSize = NumGPRs * 4;
2523   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2524 }
2525
2526 // The remaining GPRs hold either the beginning of variable-argument
2527 // data, or the beginning of an aggregate passed by value (usuall
2528 // byval).  Either way, we allocate stack slots adjacent to the data
2529 // provided by our caller, and store the unallocated registers there.
2530 // If this is a variadic function, the va_list pointer will begin with
2531 // these values; otherwise, this reassembles a (byval) structure that
2532 // was split between registers and memory.
2533 void
2534 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2535                                         DebugLoc dl, SDValue &Chain,
2536                                         unsigned ArgOffset) const {
2537   MachineFunction &MF = DAG.getMachineFunction();
2538   MachineFrameInfo *MFI = MF.getFrameInfo();
2539   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2540   unsigned firstRegToSaveIndex;
2541   if (CCInfo.isFirstByValRegValid())
2542     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2543   else {
2544     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2545       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2546   }
2547
2548   unsigned VARegSize, VARegSaveSize;
2549   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2550   if (VARegSaveSize) {
2551     // If this function is vararg, store any remaining integer argument regs
2552     // to their spots on the stack so that they may be loaded by deferencing
2553     // the result of va_next.
2554     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2555     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2556                                                      ArgOffset + VARegSaveSize
2557                                                      - VARegSize,
2558                                                      false));
2559     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2560                                     getPointerTy());
2561
2562     SmallVector<SDValue, 4> MemOps;
2563     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2564       const TargetRegisterClass *RC;
2565       if (AFI->isThumb1OnlyFunction())
2566         RC = &ARM::tGPRRegClass;
2567       else
2568         RC = &ARM::GPRRegClass;
2569
2570       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2571       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2572       SDValue Store =
2573         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2574                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2575                      false, false, 0);
2576       MemOps.push_back(Store);
2577       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2578                         DAG.getConstant(4, getPointerTy()));
2579     }
2580     if (!MemOps.empty())
2581       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2582                           &MemOps[0], MemOps.size());
2583   } else
2584     // This will point to the next argument passed via stack.
2585     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2586 }
2587
2588 SDValue
2589 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2590                                         CallingConv::ID CallConv, bool isVarArg,
2591                                         const SmallVectorImpl<ISD::InputArg>
2592                                           &Ins,
2593                                         DebugLoc dl, SelectionDAG &DAG,
2594                                         SmallVectorImpl<SDValue> &InVals)
2595                                           const {
2596   MachineFunction &MF = DAG.getMachineFunction();
2597   MachineFrameInfo *MFI = MF.getFrameInfo();
2598
2599   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2600
2601   // Assign locations to all of the incoming arguments.
2602   SmallVector<CCValAssign, 16> ArgLocs;
2603   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2604                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2605   CCInfo.AnalyzeFormalArguments(Ins,
2606                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2607                                                   isVarArg));
2608
2609   SmallVector<SDValue, 16> ArgValues;
2610   int lastInsIndex = -1;
2611
2612   SDValue ArgValue;
2613   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2614     CCValAssign &VA = ArgLocs[i];
2615
2616     // Arguments stored in registers.
2617     if (VA.isRegLoc()) {
2618       EVT RegVT = VA.getLocVT();
2619
2620       if (VA.needsCustom()) {
2621         // f64 and vector types are split up into multiple registers or
2622         // combinations of registers and stack slots.
2623         if (VA.getLocVT() == MVT::v2f64) {
2624           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2625                                                    Chain, DAG, dl);
2626           VA = ArgLocs[++i]; // skip ahead to next loc
2627           SDValue ArgValue2;
2628           if (VA.isMemLoc()) {
2629             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2630             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2631             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2632                                     MachinePointerInfo::getFixedStack(FI),
2633                                     false, false, false, 0);
2634           } else {
2635             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2636                                              Chain, DAG, dl);
2637           }
2638           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2639           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2640                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2641           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2642                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2643         } else
2644           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2645
2646       } else {
2647         const TargetRegisterClass *RC;
2648
2649         if (RegVT == MVT::f32)
2650           RC = &ARM::SPRRegClass;
2651         else if (RegVT == MVT::f64)
2652           RC = &ARM::DPRRegClass;
2653         else if (RegVT == MVT::v2f64)
2654           RC = &ARM::QPRRegClass;
2655         else if (RegVT == MVT::i32)
2656           RC = AFI->isThumb1OnlyFunction() ?
2657             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2658             (const TargetRegisterClass*)&ARM::GPRRegClass;
2659         else
2660           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2661
2662         // Transform the arguments in physical registers into virtual ones.
2663         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2664         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2665       }
2666
2667       // If this is an 8 or 16-bit value, it is really passed promoted
2668       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2669       // truncate to the right size.
2670       switch (VA.getLocInfo()) {
2671       default: llvm_unreachable("Unknown loc info!");
2672       case CCValAssign::Full: break;
2673       case CCValAssign::BCvt:
2674         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2675         break;
2676       case CCValAssign::SExt:
2677         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2678                                DAG.getValueType(VA.getValVT()));
2679         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2680         break;
2681       case CCValAssign::ZExt:
2682         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2683                                DAG.getValueType(VA.getValVT()));
2684         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2685         break;
2686       }
2687
2688       InVals.push_back(ArgValue);
2689
2690     } else { // VA.isRegLoc()
2691
2692       // sanity check
2693       assert(VA.isMemLoc());
2694       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2695
2696       int index = ArgLocs[i].getValNo();
2697
2698       // Some Ins[] entries become multiple ArgLoc[] entries.
2699       // Process them only once.
2700       if (index != lastInsIndex)
2701         {
2702           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2703           // FIXME: For now, all byval parameter objects are marked mutable.
2704           // This can be changed with more analysis.
2705           // In case of tail call optimization mark all arguments mutable.
2706           // Since they could be overwritten by lowering of arguments in case of
2707           // a tail call.
2708           if (Flags.isByVal()) {
2709             unsigned VARegSize, VARegSaveSize;
2710             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2711             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2712             unsigned Bytes = Flags.getByValSize() - VARegSize;
2713             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2714             int FI = MFI->CreateFixedObject(Bytes,
2715                                             VA.getLocMemOffset(), false);
2716             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2717           } else {
2718             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2719                                             VA.getLocMemOffset(), true);
2720
2721             // Create load nodes to retrieve arguments from the stack.
2722             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2723             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2724                                          MachinePointerInfo::getFixedStack(FI),
2725                                          false, false, false, 0));
2726           }
2727           lastInsIndex = index;
2728         }
2729     }
2730   }
2731
2732   // varargs
2733   if (isVarArg)
2734     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2735
2736   return Chain;
2737 }
2738
2739 /// isFloatingPointZero - Return true if this is +0.0.
2740 static bool isFloatingPointZero(SDValue Op) {
2741   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2742     return CFP->getValueAPF().isPosZero();
2743   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2744     // Maybe this has already been legalized into the constant pool?
2745     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2746       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2747       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2748         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2749           return CFP->getValueAPF().isPosZero();
2750     }
2751   }
2752   return false;
2753 }
2754
2755 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2756 /// the given operands.
2757 SDValue
2758 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2759                              SDValue &ARMcc, SelectionDAG &DAG,
2760                              DebugLoc dl) const {
2761   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2762     unsigned C = RHSC->getZExtValue();
2763     if (!isLegalICmpImmediate(C)) {
2764       // Constant does not fit, try adjusting it by one?
2765       switch (CC) {
2766       default: break;
2767       case ISD::SETLT:
2768       case ISD::SETGE:
2769         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2770           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2771           RHS = DAG.getConstant(C-1, MVT::i32);
2772         }
2773         break;
2774       case ISD::SETULT:
2775       case ISD::SETUGE:
2776         if (C != 0 && isLegalICmpImmediate(C-1)) {
2777           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2778           RHS = DAG.getConstant(C-1, MVT::i32);
2779         }
2780         break;
2781       case ISD::SETLE:
2782       case ISD::SETGT:
2783         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2784           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2785           RHS = DAG.getConstant(C+1, MVT::i32);
2786         }
2787         break;
2788       case ISD::SETULE:
2789       case ISD::SETUGT:
2790         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2791           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2792           RHS = DAG.getConstant(C+1, MVT::i32);
2793         }
2794         break;
2795       }
2796     }
2797   }
2798
2799   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2800   ARMISD::NodeType CompareType;
2801   switch (CondCode) {
2802   default:
2803     CompareType = ARMISD::CMP;
2804     break;
2805   case ARMCC::EQ:
2806   case ARMCC::NE:
2807     // Uses only Z Flag
2808     CompareType = ARMISD::CMPZ;
2809     break;
2810   }
2811   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2812   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2813 }
2814
2815 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2816 SDValue
2817 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2818                              DebugLoc dl) const {
2819   SDValue Cmp;
2820   if (!isFloatingPointZero(RHS))
2821     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2822   else
2823     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2824   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2825 }
2826
2827 /// duplicateCmp - Glue values can have only one use, so this function
2828 /// duplicates a comparison node.
2829 SDValue
2830 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2831   unsigned Opc = Cmp.getOpcode();
2832   DebugLoc DL = Cmp.getDebugLoc();
2833   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2834     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2835
2836   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2837   Cmp = Cmp.getOperand(0);
2838   Opc = Cmp.getOpcode();
2839   if (Opc == ARMISD::CMPFP)
2840     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2841   else {
2842     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2843     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2844   }
2845   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2846 }
2847
2848 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2849   SDValue Cond = Op.getOperand(0);
2850   SDValue SelectTrue = Op.getOperand(1);
2851   SDValue SelectFalse = Op.getOperand(2);
2852   DebugLoc dl = Op.getDebugLoc();
2853
2854   // Convert:
2855   //
2856   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2857   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2858   //
2859   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2860     const ConstantSDNode *CMOVTrue =
2861       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2862     const ConstantSDNode *CMOVFalse =
2863       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2864
2865     if (CMOVTrue && CMOVFalse) {
2866       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2867       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2868
2869       SDValue True;
2870       SDValue False;
2871       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2872         True = SelectTrue;
2873         False = SelectFalse;
2874       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2875         True = SelectFalse;
2876         False = SelectTrue;
2877       }
2878
2879       if (True.getNode() && False.getNode()) {
2880         EVT VT = Op.getValueType();
2881         SDValue ARMcc = Cond.getOperand(2);
2882         SDValue CCR = Cond.getOperand(3);
2883         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2884         assert(True.getValueType() == VT);
2885         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2886       }
2887     }
2888   }
2889
2890   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2891   // undefined bits before doing a full-word comparison with zero.
2892   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2893                      DAG.getConstant(1, Cond.getValueType()));
2894
2895   return DAG.getSelectCC(dl, Cond,
2896                          DAG.getConstant(0, Cond.getValueType()),
2897                          SelectTrue, SelectFalse, ISD::SETNE);
2898 }
2899
2900 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2901   EVT VT = Op.getValueType();
2902   SDValue LHS = Op.getOperand(0);
2903   SDValue RHS = Op.getOperand(1);
2904   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2905   SDValue TrueVal = Op.getOperand(2);
2906   SDValue FalseVal = Op.getOperand(3);
2907   DebugLoc dl = Op.getDebugLoc();
2908
2909   if (LHS.getValueType() == MVT::i32) {
2910     SDValue ARMcc;
2911     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2912     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2913     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2914   }
2915
2916   ARMCC::CondCodes CondCode, CondCode2;
2917   FPCCToARMCC(CC, CondCode, CondCode2);
2918
2919   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2920   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2921   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2922   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2923                                ARMcc, CCR, Cmp);
2924   if (CondCode2 != ARMCC::AL) {
2925     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2926     // FIXME: Needs another CMP because flag can have but one use.
2927     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2928     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2929                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2930   }
2931   return Result;
2932 }
2933
2934 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2935 /// to morph to an integer compare sequence.
2936 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2937                            const ARMSubtarget *Subtarget) {
2938   SDNode *N = Op.getNode();
2939   if (!N->hasOneUse())
2940     // Otherwise it requires moving the value from fp to integer registers.
2941     return false;
2942   if (!N->getNumValues())
2943     return false;
2944   EVT VT = Op.getValueType();
2945   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2946     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2947     // vmrs are very slow, e.g. cortex-a8.
2948     return false;
2949
2950   if (isFloatingPointZero(Op)) {
2951     SeenZero = true;
2952     return true;
2953   }
2954   return ISD::isNormalLoad(N);
2955 }
2956
2957 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2958   if (isFloatingPointZero(Op))
2959     return DAG.getConstant(0, MVT::i32);
2960
2961   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2962     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2963                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2964                        Ld->isVolatile(), Ld->isNonTemporal(),
2965                        Ld->isInvariant(), Ld->getAlignment());
2966
2967   llvm_unreachable("Unknown VFP cmp argument!");
2968 }
2969
2970 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2971                            SDValue &RetVal1, SDValue &RetVal2) {
2972   if (isFloatingPointZero(Op)) {
2973     RetVal1 = DAG.getConstant(0, MVT::i32);
2974     RetVal2 = DAG.getConstant(0, MVT::i32);
2975     return;
2976   }
2977
2978   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2979     SDValue Ptr = Ld->getBasePtr();
2980     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2981                           Ld->getChain(), Ptr,
2982                           Ld->getPointerInfo(),
2983                           Ld->isVolatile(), Ld->isNonTemporal(),
2984                           Ld->isInvariant(), Ld->getAlignment());
2985
2986     EVT PtrType = Ptr.getValueType();
2987     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2988     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2989                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2990     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2991                           Ld->getChain(), NewPtr,
2992                           Ld->getPointerInfo().getWithOffset(4),
2993                           Ld->isVolatile(), Ld->isNonTemporal(),
2994                           Ld->isInvariant(), NewAlign);
2995     return;
2996   }
2997
2998   llvm_unreachable("Unknown VFP cmp argument!");
2999 }
3000
3001 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3002 /// f32 and even f64 comparisons to integer ones.
3003 SDValue
3004 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3005   SDValue Chain = Op.getOperand(0);
3006   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3007   SDValue LHS = Op.getOperand(2);
3008   SDValue RHS = Op.getOperand(3);
3009   SDValue Dest = Op.getOperand(4);
3010   DebugLoc dl = Op.getDebugLoc();
3011
3012   bool LHSSeenZero = false;
3013   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3014   bool RHSSeenZero = false;
3015   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3016   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3017     // If unsafe fp math optimization is enabled and there are no other uses of
3018     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3019     // to an integer comparison.
3020     if (CC == ISD::SETOEQ)
3021       CC = ISD::SETEQ;
3022     else if (CC == ISD::SETUNE)
3023       CC = ISD::SETNE;
3024
3025     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3026     SDValue ARMcc;
3027     if (LHS.getValueType() == MVT::f32) {
3028       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3029                         bitcastf32Toi32(LHS, DAG), Mask);
3030       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3031                         bitcastf32Toi32(RHS, DAG), Mask);
3032       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3033       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3034       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3035                          Chain, Dest, ARMcc, CCR, Cmp);
3036     }
3037
3038     SDValue LHS1, LHS2;
3039     SDValue RHS1, RHS2;
3040     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3041     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3042     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3043     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3044     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3045     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3046     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3047     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3048     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3049   }
3050
3051   return SDValue();
3052 }
3053
3054 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3055   SDValue Chain = Op.getOperand(0);
3056   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3057   SDValue LHS = Op.getOperand(2);
3058   SDValue RHS = Op.getOperand(3);
3059   SDValue Dest = Op.getOperand(4);
3060   DebugLoc dl = Op.getDebugLoc();
3061
3062   if (LHS.getValueType() == MVT::i32) {
3063     SDValue ARMcc;
3064     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3065     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3066     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3067                        Chain, Dest, ARMcc, CCR, Cmp);
3068   }
3069
3070   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3071
3072   if (getTargetMachine().Options.UnsafeFPMath &&
3073       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3074        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3075     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3076     if (Result.getNode())
3077       return Result;
3078   }
3079
3080   ARMCC::CondCodes CondCode, CondCode2;
3081   FPCCToARMCC(CC, CondCode, CondCode2);
3082
3083   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3084   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3085   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3086   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3087   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3088   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3089   if (CondCode2 != ARMCC::AL) {
3090     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3091     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3092     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3093   }
3094   return Res;
3095 }
3096
3097 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3098   SDValue Chain = Op.getOperand(0);
3099   SDValue Table = Op.getOperand(1);
3100   SDValue Index = Op.getOperand(2);
3101   DebugLoc dl = Op.getDebugLoc();
3102
3103   EVT PTy = getPointerTy();
3104   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3105   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3106   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3107   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3108   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3109   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3110   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3111   if (Subtarget->isThumb2()) {
3112     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3113     // which does another jump to the destination. This also makes it easier
3114     // to translate it to TBB / TBH later.
3115     // FIXME: This might not work if the function is extremely large.
3116     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3117                        Addr, Op.getOperand(2), JTI, UId);
3118   }
3119   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3120     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3121                        MachinePointerInfo::getJumpTable(),
3122                        false, false, false, 0);
3123     Chain = Addr.getValue(1);
3124     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3125     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3126   } else {
3127     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3128                        MachinePointerInfo::getJumpTable(),
3129                        false, false, false, 0);
3130     Chain = Addr.getValue(1);
3131     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3132   }
3133 }
3134
3135 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3136   EVT VT = Op.getValueType();
3137   DebugLoc dl = Op.getDebugLoc();
3138
3139   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3140     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3141       return Op;
3142     return DAG.UnrollVectorOp(Op.getNode());
3143   }
3144
3145   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3146          "Invalid type for custom lowering!");
3147   if (VT != MVT::v4i16)
3148     return DAG.UnrollVectorOp(Op.getNode());
3149
3150   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3151   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3152 }
3153
3154 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3155   EVT VT = Op.getValueType();
3156   if (VT.isVector())
3157     return LowerVectorFP_TO_INT(Op, DAG);
3158
3159   DebugLoc dl = Op.getDebugLoc();
3160   unsigned Opc;
3161
3162   switch (Op.getOpcode()) {
3163   default: llvm_unreachable("Invalid opcode!");
3164   case ISD::FP_TO_SINT:
3165     Opc = ARMISD::FTOSI;
3166     break;
3167   case ISD::FP_TO_UINT:
3168     Opc = ARMISD::FTOUI;
3169     break;
3170   }
3171   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3172   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3173 }
3174
3175 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3176   EVT VT = Op.getValueType();
3177   DebugLoc dl = Op.getDebugLoc();
3178
3179   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3180     if (VT.getVectorElementType() == MVT::f32)
3181       return Op;
3182     return DAG.UnrollVectorOp(Op.getNode());
3183   }
3184
3185   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3186          "Invalid type for custom lowering!");
3187   if (VT != MVT::v4f32)
3188     return DAG.UnrollVectorOp(Op.getNode());
3189
3190   unsigned CastOpc;
3191   unsigned Opc;
3192   switch (Op.getOpcode()) {
3193   default: llvm_unreachable("Invalid opcode!");
3194   case ISD::SINT_TO_FP:
3195     CastOpc = ISD::SIGN_EXTEND;
3196     Opc = ISD::SINT_TO_FP;
3197     break;
3198   case ISD::UINT_TO_FP:
3199     CastOpc = ISD::ZERO_EXTEND;
3200     Opc = ISD::UINT_TO_FP;
3201     break;
3202   }
3203
3204   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3205   return DAG.getNode(Opc, dl, VT, Op);
3206 }
3207
3208 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3209   EVT VT = Op.getValueType();
3210   if (VT.isVector())
3211     return LowerVectorINT_TO_FP(Op, DAG);
3212
3213   DebugLoc dl = Op.getDebugLoc();
3214   unsigned Opc;
3215
3216   switch (Op.getOpcode()) {
3217   default: llvm_unreachable("Invalid opcode!");
3218   case ISD::SINT_TO_FP:
3219     Opc = ARMISD::SITOF;
3220     break;
3221   case ISD::UINT_TO_FP:
3222     Opc = ARMISD::UITOF;
3223     break;
3224   }
3225
3226   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3227   return DAG.getNode(Opc, dl, VT, Op);
3228 }
3229
3230 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3231   // Implement fcopysign with a fabs and a conditional fneg.
3232   SDValue Tmp0 = Op.getOperand(0);
3233   SDValue Tmp1 = Op.getOperand(1);
3234   DebugLoc dl = Op.getDebugLoc();
3235   EVT VT = Op.getValueType();
3236   EVT SrcVT = Tmp1.getValueType();
3237   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3238     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3239   bool UseNEON = !InGPR && Subtarget->hasNEON();
3240
3241   if (UseNEON) {
3242     // Use VBSL to copy the sign bit.
3243     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3244     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3245                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3246     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3247     if (VT == MVT::f64)
3248       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3249                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3250                          DAG.getConstant(32, MVT::i32));
3251     else /*if (VT == MVT::f32)*/
3252       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3253     if (SrcVT == MVT::f32) {
3254       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3255       if (VT == MVT::f64)
3256         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3257                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3258                            DAG.getConstant(32, MVT::i32));
3259     } else if (VT == MVT::f32)
3260       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3261                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3262                          DAG.getConstant(32, MVT::i32));
3263     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3264     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3265
3266     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3267                                             MVT::i32);
3268     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3269     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3270                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3271
3272     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3273                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3274                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3275     if (VT == MVT::f32) {
3276       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3277       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3278                         DAG.getConstant(0, MVT::i32));
3279     } else {
3280       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3281     }
3282
3283     return Res;
3284   }
3285
3286   // Bitcast operand 1 to i32.
3287   if (SrcVT == MVT::f64)
3288     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3289                        &Tmp1, 1).getValue(1);
3290   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3291
3292   // Or in the signbit with integer operations.
3293   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3294   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3295   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3296   if (VT == MVT::f32) {
3297     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3298                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3299     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3300                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3301   }
3302
3303   // f64: Or the high part with signbit and then combine two parts.
3304   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3305                      &Tmp0, 1);
3306   SDValue Lo = Tmp0.getValue(0);
3307   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3308   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3309   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3310 }
3311
3312 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3313   MachineFunction &MF = DAG.getMachineFunction();
3314   MachineFrameInfo *MFI = MF.getFrameInfo();
3315   MFI->setReturnAddressIsTaken(true);
3316
3317   EVT VT = Op.getValueType();
3318   DebugLoc dl = Op.getDebugLoc();
3319   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3320   if (Depth) {
3321     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3322     SDValue Offset = DAG.getConstant(4, MVT::i32);
3323     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3324                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3325                        MachinePointerInfo(), false, false, false, 0);
3326   }
3327
3328   // Return LR, which contains the return address. Mark it an implicit live-in.
3329   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3330   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3331 }
3332
3333 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3334   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3335   MFI->setFrameAddressIsTaken(true);
3336
3337   EVT VT = Op.getValueType();
3338   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3339   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3340   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3341     ? ARM::R7 : ARM::R11;
3342   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3343   while (Depth--)
3344     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3345                             MachinePointerInfo(),
3346                             false, false, false, 0);
3347   return FrameAddr;
3348 }
3349
3350 /// ExpandBITCAST - If the target supports VFP, this function is called to
3351 /// expand a bit convert where either the source or destination type is i64 to
3352 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3353 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3354 /// vectors), since the legalizer won't know what to do with that.
3355 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3357   DebugLoc dl = N->getDebugLoc();
3358   SDValue Op = N->getOperand(0);
3359
3360   // This function is only supposed to be called for i64 types, either as the
3361   // source or destination of the bit convert.
3362   EVT SrcVT = Op.getValueType();
3363   EVT DstVT = N->getValueType(0);
3364   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3365          "ExpandBITCAST called for non-i64 type");
3366
3367   // Turn i64->f64 into VMOVDRR.
3368   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3369     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3370                              DAG.getConstant(0, MVT::i32));
3371     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3372                              DAG.getConstant(1, MVT::i32));
3373     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3374                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3375   }
3376
3377   // Turn f64->i64 into VMOVRRD.
3378   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3379     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3380                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3381     // Merge the pieces into a single i64 value.
3382     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3383   }
3384
3385   return SDValue();
3386 }
3387
3388 /// getZeroVector - Returns a vector of specified type with all zero elements.
3389 /// Zero vectors are used to represent vector negation and in those cases
3390 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3391 /// not support i64 elements, so sometimes the zero vectors will need to be
3392 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3393 /// zero vector.
3394 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3395   assert(VT.isVector() && "Expected a vector type");
3396   // The canonical modified immediate encoding of a zero vector is....0!
3397   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3398   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3399   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3400   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3401 }
3402
3403 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3404 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3405 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3406                                                 SelectionDAG &DAG) const {
3407   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3408   EVT VT = Op.getValueType();
3409   unsigned VTBits = VT.getSizeInBits();
3410   DebugLoc dl = Op.getDebugLoc();
3411   SDValue ShOpLo = Op.getOperand(0);
3412   SDValue ShOpHi = Op.getOperand(1);
3413   SDValue ShAmt  = Op.getOperand(2);
3414   SDValue ARMcc;
3415   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3416
3417   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3418
3419   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3420                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3421   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3422   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3423                                    DAG.getConstant(VTBits, MVT::i32));
3424   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3425   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3426   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3427
3428   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3429   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3430                           ARMcc, DAG, dl);
3431   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3432   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3433                            CCR, Cmp);
3434
3435   SDValue Ops[2] = { Lo, Hi };
3436   return DAG.getMergeValues(Ops, 2, dl);
3437 }
3438
3439 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3440 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3441 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3442                                                SelectionDAG &DAG) const {
3443   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3444   EVT VT = Op.getValueType();
3445   unsigned VTBits = VT.getSizeInBits();
3446   DebugLoc dl = Op.getDebugLoc();
3447   SDValue ShOpLo = Op.getOperand(0);
3448   SDValue ShOpHi = Op.getOperand(1);
3449   SDValue ShAmt  = Op.getOperand(2);
3450   SDValue ARMcc;
3451
3452   assert(Op.getOpcode() == ISD::SHL_PARTS);
3453   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3454                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3455   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3456   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3457                                    DAG.getConstant(VTBits, MVT::i32));
3458   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3459   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3460
3461   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3462   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3463   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3464                           ARMcc, DAG, dl);
3465   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3466   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3467                            CCR, Cmp);
3468
3469   SDValue Ops[2] = { Lo, Hi };
3470   return DAG.getMergeValues(Ops, 2, dl);
3471 }
3472
3473 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3474                                             SelectionDAG &DAG) const {
3475   // The rounding mode is in bits 23:22 of the FPSCR.
3476   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3477   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3478   // so that the shift + and get folded into a bitfield extract.
3479   DebugLoc dl = Op.getDebugLoc();
3480   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3481                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3482                                               MVT::i32));
3483   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3484                                   DAG.getConstant(1U << 22, MVT::i32));
3485   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3486                               DAG.getConstant(22, MVT::i32));
3487   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3488                      DAG.getConstant(3, MVT::i32));
3489 }
3490
3491 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3492                          const ARMSubtarget *ST) {
3493   EVT VT = N->getValueType(0);
3494   DebugLoc dl = N->getDebugLoc();
3495
3496   if (!ST->hasV6T2Ops())
3497     return SDValue();
3498
3499   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3500   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3501 }
3502
3503 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3504                           const ARMSubtarget *ST) {
3505   EVT VT = N->getValueType(0);
3506   DebugLoc dl = N->getDebugLoc();
3507
3508   if (!VT.isVector())
3509     return SDValue();
3510
3511   // Lower vector shifts on NEON to use VSHL.
3512   assert(ST->hasNEON() && "unexpected vector shift");
3513
3514   // Left shifts translate directly to the vshiftu intrinsic.
3515   if (N->getOpcode() == ISD::SHL)
3516     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3517                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3518                        N->getOperand(0), N->getOperand(1));
3519
3520   assert((N->getOpcode() == ISD::SRA ||
3521           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3522
3523   // NEON uses the same intrinsics for both left and right shifts.  For
3524   // right shifts, the shift amounts are negative, so negate the vector of
3525   // shift amounts.
3526   EVT ShiftVT = N->getOperand(1).getValueType();
3527   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3528                                      getZeroVector(ShiftVT, DAG, dl),
3529                                      N->getOperand(1));
3530   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3531                              Intrinsic::arm_neon_vshifts :
3532                              Intrinsic::arm_neon_vshiftu);
3533   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3534                      DAG.getConstant(vshiftInt, MVT::i32),
3535                      N->getOperand(0), NegatedCount);
3536 }
3537
3538 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3539                                 const ARMSubtarget *ST) {
3540   EVT VT = N->getValueType(0);
3541   DebugLoc dl = N->getDebugLoc();
3542
3543   // We can get here for a node like i32 = ISD::SHL i32, i64
3544   if (VT != MVT::i64)
3545     return SDValue();
3546
3547   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3548          "Unknown shift to lower!");
3549
3550   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3551   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3552       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3553     return SDValue();
3554
3555   // If we are in thumb mode, we don't have RRX.
3556   if (ST->isThumb1Only()) return SDValue();
3557
3558   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3559   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3560                            DAG.getConstant(0, MVT::i32));
3561   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3562                            DAG.getConstant(1, MVT::i32));
3563
3564   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3565   // captures the result into a carry flag.
3566   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3567   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3568
3569   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3570   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3571
3572   // Merge the pieces into a single i64 value.
3573  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3574 }
3575
3576 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3577   SDValue TmpOp0, TmpOp1;
3578   bool Invert = false;
3579   bool Swap = false;
3580   unsigned Opc = 0;
3581
3582   SDValue Op0 = Op.getOperand(0);
3583   SDValue Op1 = Op.getOperand(1);
3584   SDValue CC = Op.getOperand(2);
3585   EVT VT = Op.getValueType();
3586   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3587   DebugLoc dl = Op.getDebugLoc();
3588
3589   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3590     switch (SetCCOpcode) {
3591     default: llvm_unreachable("Illegal FP comparison");
3592     case ISD::SETUNE:
3593     case ISD::SETNE:  Invert = true; // Fallthrough
3594     case ISD::SETOEQ:
3595     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3596     case ISD::SETOLT:
3597     case ISD::SETLT: Swap = true; // Fallthrough
3598     case ISD::SETOGT:
3599     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3600     case ISD::SETOLE:
3601     case ISD::SETLE:  Swap = true; // Fallthrough
3602     case ISD::SETOGE:
3603     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3604     case ISD::SETUGE: Swap = true; // Fallthrough
3605     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3606     case ISD::SETUGT: Swap = true; // Fallthrough
3607     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3608     case ISD::SETUEQ: Invert = true; // Fallthrough
3609     case ISD::SETONE:
3610       // Expand this to (OLT | OGT).
3611       TmpOp0 = Op0;
3612       TmpOp1 = Op1;
3613       Opc = ISD::OR;
3614       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3615       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3616       break;
3617     case ISD::SETUO: Invert = true; // Fallthrough
3618     case ISD::SETO:
3619       // Expand this to (OLT | OGE).
3620       TmpOp0 = Op0;
3621       TmpOp1 = Op1;
3622       Opc = ISD::OR;
3623       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3624       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3625       break;
3626     }
3627   } else {
3628     // Integer comparisons.
3629     switch (SetCCOpcode) {
3630     default: llvm_unreachable("Illegal integer comparison");
3631     case ISD::SETNE:  Invert = true;
3632     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3633     case ISD::SETLT:  Swap = true;
3634     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3635     case ISD::SETLE:  Swap = true;
3636     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3637     case ISD::SETULT: Swap = true;
3638     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3639     case ISD::SETULE: Swap = true;
3640     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3641     }
3642
3643     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3644     if (Opc == ARMISD::VCEQ) {
3645
3646       SDValue AndOp;
3647       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3648         AndOp = Op0;
3649       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3650         AndOp = Op1;
3651
3652       // Ignore bitconvert.
3653       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3654         AndOp = AndOp.getOperand(0);
3655
3656       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3657         Opc = ARMISD::VTST;
3658         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3659         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3660         Invert = !Invert;
3661       }
3662     }
3663   }
3664
3665   if (Swap)
3666     std::swap(Op0, Op1);
3667
3668   // If one of the operands is a constant vector zero, attempt to fold the
3669   // comparison to a specialized compare-against-zero form.
3670   SDValue SingleOp;
3671   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3672     SingleOp = Op0;
3673   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3674     if (Opc == ARMISD::VCGE)
3675       Opc = ARMISD::VCLEZ;
3676     else if (Opc == ARMISD::VCGT)
3677       Opc = ARMISD::VCLTZ;
3678     SingleOp = Op1;
3679   }
3680
3681   SDValue Result;
3682   if (SingleOp.getNode()) {
3683     switch (Opc) {
3684     case ARMISD::VCEQ:
3685       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3686     case ARMISD::VCGE:
3687       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3688     case ARMISD::VCLEZ:
3689       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3690     case ARMISD::VCGT:
3691       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3692     case ARMISD::VCLTZ:
3693       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3694     default:
3695       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3696     }
3697   } else {
3698      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3699   }
3700
3701   if (Invert)
3702     Result = DAG.getNOT(dl, Result, VT);
3703
3704   return Result;
3705 }
3706
3707 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3708 /// valid vector constant for a NEON instruction with a "modified immediate"
3709 /// operand (e.g., VMOV).  If so, return the encoded value.
3710 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3711                                  unsigned SplatBitSize, SelectionDAG &DAG,
3712                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3713   unsigned OpCmode, Imm;
3714
3715   // SplatBitSize is set to the smallest size that splats the vector, so a
3716   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3717   // immediate instructions others than VMOV do not support the 8-bit encoding
3718   // of a zero vector, and the default encoding of zero is supposed to be the
3719   // 32-bit version.
3720   if (SplatBits == 0)
3721     SplatBitSize = 32;
3722
3723   switch (SplatBitSize) {
3724   case 8:
3725     if (type != VMOVModImm)
3726       return SDValue();
3727     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3728     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3729     OpCmode = 0xe;
3730     Imm = SplatBits;
3731     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3732     break;
3733
3734   case 16:
3735     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3736     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3737     if ((SplatBits & ~0xff) == 0) {
3738       // Value = 0x00nn: Op=x, Cmode=100x.
3739       OpCmode = 0x8;
3740       Imm = SplatBits;
3741       break;
3742     }
3743     if ((SplatBits & ~0xff00) == 0) {
3744       // Value = 0xnn00: Op=x, Cmode=101x.
3745       OpCmode = 0xa;
3746       Imm = SplatBits >> 8;
3747       break;
3748     }
3749     return SDValue();
3750
3751   case 32:
3752     // NEON's 32-bit VMOV supports splat values where:
3753     // * only one byte is nonzero, or
3754     // * the least significant byte is 0xff and the second byte is nonzero, or
3755     // * the least significant 2 bytes are 0xff and the third is nonzero.
3756     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3757     if ((SplatBits & ~0xff) == 0) {
3758       // Value = 0x000000nn: Op=x, Cmode=000x.
3759       OpCmode = 0;
3760       Imm = SplatBits;
3761       break;
3762     }
3763     if ((SplatBits & ~0xff00) == 0) {
3764       // Value = 0x0000nn00: Op=x, Cmode=001x.
3765       OpCmode = 0x2;
3766       Imm = SplatBits >> 8;
3767       break;
3768     }
3769     if ((SplatBits & ~0xff0000) == 0) {
3770       // Value = 0x00nn0000: Op=x, Cmode=010x.
3771       OpCmode = 0x4;
3772       Imm = SplatBits >> 16;
3773       break;
3774     }
3775     if ((SplatBits & ~0xff000000) == 0) {
3776       // Value = 0xnn000000: Op=x, Cmode=011x.
3777       OpCmode = 0x6;
3778       Imm = SplatBits >> 24;
3779       break;
3780     }
3781
3782     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3783     if (type == OtherModImm) return SDValue();
3784
3785     if ((SplatBits & ~0xffff) == 0 &&
3786         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3787       // Value = 0x0000nnff: Op=x, Cmode=1100.
3788       OpCmode = 0xc;
3789       Imm = SplatBits >> 8;
3790       SplatBits |= 0xff;
3791       break;
3792     }
3793
3794     if ((SplatBits & ~0xffffff) == 0 &&
3795         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3796       // Value = 0x00nnffff: Op=x, Cmode=1101.
3797       OpCmode = 0xd;
3798       Imm = SplatBits >> 16;
3799       SplatBits |= 0xffff;
3800       break;
3801     }
3802
3803     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3804     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3805     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3806     // and fall through here to test for a valid 64-bit splat.  But, then the
3807     // caller would also need to check and handle the change in size.
3808     return SDValue();
3809
3810   case 64: {
3811     if (type != VMOVModImm)
3812       return SDValue();
3813     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3814     uint64_t BitMask = 0xff;
3815     uint64_t Val = 0;
3816     unsigned ImmMask = 1;
3817     Imm = 0;
3818     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3819       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3820         Val |= BitMask;
3821         Imm |= ImmMask;
3822       } else if ((SplatBits & BitMask) != 0) {
3823         return SDValue();
3824       }
3825       BitMask <<= 8;
3826       ImmMask <<= 1;
3827     }
3828     // Op=1, Cmode=1110.
3829     OpCmode = 0x1e;
3830     SplatBits = Val;
3831     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3832     break;
3833   }
3834
3835   default:
3836     llvm_unreachable("unexpected size for isNEONModifiedImm");
3837   }
3838
3839   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3840   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3841 }
3842
3843 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3844                                            const ARMSubtarget *ST) const {
3845   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3846     return SDValue();
3847
3848   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3849   assert(Op.getValueType() == MVT::f32 &&
3850          "ConstantFP custom lowering should only occur for f32.");
3851
3852   // Try splatting with a VMOV.f32...
3853   APFloat FPVal = CFP->getValueAPF();
3854   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3855   if (ImmVal != -1) {
3856     DebugLoc DL = Op.getDebugLoc();
3857     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3858     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3859                                       NewVal);
3860     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3861                        DAG.getConstant(0, MVT::i32));
3862   }
3863
3864   // If that fails, try a VMOV.i32
3865   EVT VMovVT;
3866   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3867   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3868                                      VMOVModImm);
3869   if (NewVal != SDValue()) {
3870     DebugLoc DL = Op.getDebugLoc();
3871     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3872                                       NewVal);
3873     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3874                                        VecConstant);
3875     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3876                        DAG.getConstant(0, MVT::i32));
3877   }
3878
3879   // Finally, try a VMVN.i32
3880   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3881                              VMVNModImm);
3882   if (NewVal != SDValue()) {
3883     DebugLoc DL = Op.getDebugLoc();
3884     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3885     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3886                                        VecConstant);
3887     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3888                        DAG.getConstant(0, MVT::i32));
3889   }
3890
3891   return SDValue();
3892 }
3893
3894
3895 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3896                        bool &ReverseVEXT, unsigned &Imm) {
3897   unsigned NumElts = VT.getVectorNumElements();
3898   ReverseVEXT = false;
3899
3900   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3901   if (M[0] < 0)
3902     return false;
3903
3904   Imm = M[0];
3905
3906   // If this is a VEXT shuffle, the immediate value is the index of the first
3907   // element.  The other shuffle indices must be the successive elements after
3908   // the first one.
3909   unsigned ExpectedElt = Imm;
3910   for (unsigned i = 1; i < NumElts; ++i) {
3911     // Increment the expected index.  If it wraps around, it may still be
3912     // a VEXT but the source vectors must be swapped.
3913     ExpectedElt += 1;
3914     if (ExpectedElt == NumElts * 2) {
3915       ExpectedElt = 0;
3916       ReverseVEXT = true;
3917     }
3918
3919     if (M[i] < 0) continue; // ignore UNDEF indices
3920     if (ExpectedElt != static_cast<unsigned>(M[i]))
3921       return false;
3922   }
3923
3924   // Adjust the index value if the source operands will be swapped.
3925   if (ReverseVEXT)
3926     Imm -= NumElts;
3927
3928   return true;
3929 }
3930
3931 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3932 /// instruction with the specified blocksize.  (The order of the elements
3933 /// within each block of the vector is reversed.)
3934 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3935   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3936          "Only possible block sizes for VREV are: 16, 32, 64");
3937
3938   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3939   if (EltSz == 64)
3940     return false;
3941
3942   unsigned NumElts = VT.getVectorNumElements();
3943   unsigned BlockElts = M[0] + 1;
3944   // If the first shuffle index is UNDEF, be optimistic.
3945   if (M[0] < 0)
3946     BlockElts = BlockSize / EltSz;
3947
3948   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3949     return false;
3950
3951   for (unsigned i = 0; i < NumElts; ++i) {
3952     if (M[i] < 0) continue; // ignore UNDEF indices
3953     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3954       return false;
3955   }
3956
3957   return true;
3958 }
3959
3960 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3961   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3962   // range, then 0 is placed into the resulting vector. So pretty much any mask
3963   // of 8 elements can work here.
3964   return VT == MVT::v8i8 && M.size() == 8;
3965 }
3966
3967 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3968   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3969   if (EltSz == 64)
3970     return false;
3971
3972   unsigned NumElts = VT.getVectorNumElements();
3973   WhichResult = (M[0] == 0 ? 0 : 1);
3974   for (unsigned i = 0; i < NumElts; i += 2) {
3975     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3976         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3977       return false;
3978   }
3979   return true;
3980 }
3981
3982 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3983 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3984 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3985 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3986   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3987   if (EltSz == 64)
3988     return false;
3989
3990   unsigned NumElts = VT.getVectorNumElements();
3991   WhichResult = (M[0] == 0 ? 0 : 1);
3992   for (unsigned i = 0; i < NumElts; i += 2) {
3993     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3994         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3995       return false;
3996   }
3997   return true;
3998 }
3999
4000 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4001   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4002   if (EltSz == 64)
4003     return false;
4004
4005   unsigned NumElts = VT.getVectorNumElements();
4006   WhichResult = (M[0] == 0 ? 0 : 1);
4007   for (unsigned i = 0; i != NumElts; ++i) {
4008     if (M[i] < 0) continue; // ignore UNDEF indices
4009     if ((unsigned) M[i] != 2 * i + WhichResult)
4010       return false;
4011   }
4012
4013   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4014   if (VT.is64BitVector() && EltSz == 32)
4015     return false;
4016
4017   return true;
4018 }
4019
4020 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4021 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4022 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4023 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4024   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4025   if (EltSz == 64)
4026     return false;
4027
4028   unsigned Half = VT.getVectorNumElements() / 2;
4029   WhichResult = (M[0] == 0 ? 0 : 1);
4030   for (unsigned j = 0; j != 2; ++j) {
4031     unsigned Idx = WhichResult;
4032     for (unsigned i = 0; i != Half; ++i) {
4033       int MIdx = M[i + j * Half];
4034       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4035         return false;
4036       Idx += 2;
4037     }
4038   }
4039
4040   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4041   if (VT.is64BitVector() && EltSz == 32)
4042     return false;
4043
4044   return true;
4045 }
4046
4047 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4048   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4049   if (EltSz == 64)
4050     return false;
4051
4052   unsigned NumElts = VT.getVectorNumElements();
4053   WhichResult = (M[0] == 0 ? 0 : 1);
4054   unsigned Idx = WhichResult * NumElts / 2;
4055   for (unsigned i = 0; i != NumElts; i += 2) {
4056     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4057         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4058       return false;
4059     Idx += 1;
4060   }
4061
4062   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4063   if (VT.is64BitVector() && EltSz == 32)
4064     return false;
4065
4066   return true;
4067 }
4068
4069 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4070 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4071 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4072 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4073   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4074   if (EltSz == 64)
4075     return false;
4076
4077   unsigned NumElts = VT.getVectorNumElements();
4078   WhichResult = (M[0] == 0 ? 0 : 1);
4079   unsigned Idx = WhichResult * NumElts / 2;
4080   for (unsigned i = 0; i != NumElts; i += 2) {
4081     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4082         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4083       return false;
4084     Idx += 1;
4085   }
4086
4087   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4088   if (VT.is64BitVector() && EltSz == 32)
4089     return false;
4090
4091   return true;
4092 }
4093
4094 // If N is an integer constant that can be moved into a register in one
4095 // instruction, return an SDValue of such a constant (will become a MOV
4096 // instruction).  Otherwise return null.
4097 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4098                                      const ARMSubtarget *ST, DebugLoc dl) {
4099   uint64_t Val;
4100   if (!isa<ConstantSDNode>(N))
4101     return SDValue();
4102   Val = cast<ConstantSDNode>(N)->getZExtValue();
4103
4104   if (ST->isThumb1Only()) {
4105     if (Val <= 255 || ~Val <= 255)
4106       return DAG.getConstant(Val, MVT::i32);
4107   } else {
4108     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4109       return DAG.getConstant(Val, MVT::i32);
4110   }
4111   return SDValue();
4112 }
4113
4114 // If this is a case we can't handle, return null and let the default
4115 // expansion code take care of it.
4116 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4117                                              const ARMSubtarget *ST) const {
4118   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4119   DebugLoc dl = Op.getDebugLoc();
4120   EVT VT = Op.getValueType();
4121
4122   APInt SplatBits, SplatUndef;
4123   unsigned SplatBitSize;
4124   bool HasAnyUndefs;
4125   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4126     if (SplatBitSize <= 64) {
4127       // Check if an immediate VMOV works.
4128       EVT VmovVT;
4129       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4130                                       SplatUndef.getZExtValue(), SplatBitSize,
4131                                       DAG, VmovVT, VT.is128BitVector(),
4132                                       VMOVModImm);
4133       if (Val.getNode()) {
4134         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4135         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4136       }
4137
4138       // Try an immediate VMVN.
4139       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4140       Val = isNEONModifiedImm(NegatedImm,
4141                                       SplatUndef.getZExtValue(), SplatBitSize,
4142                                       DAG, VmovVT, VT.is128BitVector(),
4143                                       VMVNModImm);
4144       if (Val.getNode()) {
4145         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4146         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4147       }
4148
4149       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4150       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4151         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4152         if (ImmVal != -1) {
4153           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4154           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4155         }
4156       }
4157     }
4158   }
4159
4160   // Scan through the operands to see if only one value is used.
4161   unsigned NumElts = VT.getVectorNumElements();
4162   bool isOnlyLowElement = true;
4163   bool usesOnlyOneValue = true;
4164   bool isConstant = true;
4165   SDValue Value;
4166   for (unsigned i = 0; i < NumElts; ++i) {
4167     SDValue V = Op.getOperand(i);
4168     if (V.getOpcode() == ISD::UNDEF)
4169       continue;
4170     if (i > 0)
4171       isOnlyLowElement = false;
4172     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4173       isConstant = false;
4174
4175     if (!Value.getNode())
4176       Value = V;
4177     else if (V != Value)
4178       usesOnlyOneValue = false;
4179   }
4180
4181   if (!Value.getNode())
4182     return DAG.getUNDEF(VT);
4183
4184   if (isOnlyLowElement)
4185     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4186
4187   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4188
4189   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4190   // i32 and try again.
4191   if (usesOnlyOneValue && EltSize <= 32) {
4192     if (!isConstant)
4193       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4194     if (VT.getVectorElementType().isFloatingPoint()) {
4195       SmallVector<SDValue, 8> Ops;
4196       for (unsigned i = 0; i < NumElts; ++i)
4197         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4198                                   Op.getOperand(i)));
4199       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4200       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4201       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4202       if (Val.getNode())
4203         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4204     }
4205     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4206     if (Val.getNode())
4207       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4208   }
4209
4210   // If all elements are constants and the case above didn't get hit, fall back
4211   // to the default expansion, which will generate a load from the constant
4212   // pool.
4213   if (isConstant)
4214     return SDValue();
4215
4216   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4217   if (NumElts >= 4) {
4218     SDValue shuffle = ReconstructShuffle(Op, DAG);
4219     if (shuffle != SDValue())
4220       return shuffle;
4221   }
4222
4223   // Vectors with 32- or 64-bit elements can be built by directly assigning
4224   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4225   // will be legalized.
4226   if (EltSize >= 32) {
4227     // Do the expansion with floating-point types, since that is what the VFP
4228     // registers are defined to use, and since i64 is not legal.
4229     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4230     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4231     SmallVector<SDValue, 8> Ops;
4232     for (unsigned i = 0; i < NumElts; ++i)
4233       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4234     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4235     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4236   }
4237
4238   return SDValue();
4239 }
4240
4241 // Gather data to see if the operation can be modelled as a
4242 // shuffle in combination with VEXTs.
4243 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4244                                               SelectionDAG &DAG) const {
4245   DebugLoc dl = Op.getDebugLoc();
4246   EVT VT = Op.getValueType();
4247   unsigned NumElts = VT.getVectorNumElements();
4248
4249   SmallVector<SDValue, 2> SourceVecs;
4250   SmallVector<unsigned, 2> MinElts;
4251   SmallVector<unsigned, 2> MaxElts;
4252
4253   for (unsigned i = 0; i < NumElts; ++i) {
4254     SDValue V = Op.getOperand(i);
4255     if (V.getOpcode() == ISD::UNDEF)
4256       continue;
4257     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4258       // A shuffle can only come from building a vector from various
4259       // elements of other vectors.
4260       return SDValue();
4261     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4262                VT.getVectorElementType()) {
4263       // This code doesn't know how to handle shuffles where the vector
4264       // element types do not match (this happens because type legalization
4265       // promotes the return type of EXTRACT_VECTOR_ELT).
4266       // FIXME: It might be appropriate to extend this code to handle
4267       // mismatched types.
4268       return SDValue();
4269     }
4270
4271     // Record this extraction against the appropriate vector if possible...
4272     SDValue SourceVec = V.getOperand(0);
4273     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4274     bool FoundSource = false;
4275     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4276       if (SourceVecs[j] == SourceVec) {
4277         if (MinElts[j] > EltNo)
4278           MinElts[j] = EltNo;
4279         if (MaxElts[j] < EltNo)
4280           MaxElts[j] = EltNo;
4281         FoundSource = true;
4282         break;
4283       }
4284     }
4285
4286     // Or record a new source if not...
4287     if (!FoundSource) {
4288       SourceVecs.push_back(SourceVec);
4289       MinElts.push_back(EltNo);
4290       MaxElts.push_back(EltNo);
4291     }
4292   }
4293
4294   // Currently only do something sane when at most two source vectors
4295   // involved.
4296   if (SourceVecs.size() > 2)
4297     return SDValue();
4298
4299   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4300   int VEXTOffsets[2] = {0, 0};
4301
4302   // This loop extracts the usage patterns of the source vectors
4303   // and prepares appropriate SDValues for a shuffle if possible.
4304   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4305     if (SourceVecs[i].getValueType() == VT) {
4306       // No VEXT necessary
4307       ShuffleSrcs[i] = SourceVecs[i];
4308       VEXTOffsets[i] = 0;
4309       continue;
4310     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4311       // It probably isn't worth padding out a smaller vector just to
4312       // break it down again in a shuffle.
4313       return SDValue();
4314     }
4315
4316     // Since only 64-bit and 128-bit vectors are legal on ARM and
4317     // we've eliminated the other cases...
4318     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4319            "unexpected vector sizes in ReconstructShuffle");
4320
4321     if (MaxElts[i] - MinElts[i] >= NumElts) {
4322       // Span too large for a VEXT to cope
4323       return SDValue();
4324     }
4325
4326     if (MinElts[i] >= NumElts) {
4327       // The extraction can just take the second half
4328       VEXTOffsets[i] = NumElts;
4329       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4330                                    SourceVecs[i],
4331                                    DAG.getIntPtrConstant(NumElts));
4332     } else if (MaxElts[i] < NumElts) {
4333       // The extraction can just take the first half
4334       VEXTOffsets[i] = 0;
4335       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4336                                    SourceVecs[i],
4337                                    DAG.getIntPtrConstant(0));
4338     } else {
4339       // An actual VEXT is needed
4340       VEXTOffsets[i] = MinElts[i];
4341       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4342                                      SourceVecs[i],
4343                                      DAG.getIntPtrConstant(0));
4344       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4345                                      SourceVecs[i],
4346                                      DAG.getIntPtrConstant(NumElts));
4347       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4348                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4349     }
4350   }
4351
4352   SmallVector<int, 8> Mask;
4353
4354   for (unsigned i = 0; i < NumElts; ++i) {
4355     SDValue Entry = Op.getOperand(i);
4356     if (Entry.getOpcode() == ISD::UNDEF) {
4357       Mask.push_back(-1);
4358       continue;
4359     }
4360
4361     SDValue ExtractVec = Entry.getOperand(0);
4362     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4363                                           .getOperand(1))->getSExtValue();
4364     if (ExtractVec == SourceVecs[0]) {
4365       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4366     } else {
4367       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4368     }
4369   }
4370
4371   // Final check before we try to produce nonsense...
4372   if (isShuffleMaskLegal(Mask, VT))
4373     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4374                                 &Mask[0]);
4375
4376   return SDValue();
4377 }
4378
4379 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4380 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4381 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4382 /// are assumed to be legal.
4383 bool
4384 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4385                                       EVT VT) const {
4386   if (VT.getVectorNumElements() == 4 &&
4387       (VT.is128BitVector() || VT.is64BitVector())) {
4388     unsigned PFIndexes[4];
4389     for (unsigned i = 0; i != 4; ++i) {
4390       if (M[i] < 0)
4391         PFIndexes[i] = 8;
4392       else
4393         PFIndexes[i] = M[i];
4394     }
4395
4396     // Compute the index in the perfect shuffle table.
4397     unsigned PFTableIndex =
4398       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4399     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4400     unsigned Cost = (PFEntry >> 30);
4401
4402     if (Cost <= 4)
4403       return true;
4404   }
4405
4406   bool ReverseVEXT;
4407   unsigned Imm, WhichResult;
4408
4409   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4410   return (EltSize >= 32 ||
4411           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4412           isVREVMask(M, VT, 64) ||
4413           isVREVMask(M, VT, 32) ||
4414           isVREVMask(M, VT, 16) ||
4415           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4416           isVTBLMask(M, VT) ||
4417           isVTRNMask(M, VT, WhichResult) ||
4418           isVUZPMask(M, VT, WhichResult) ||
4419           isVZIPMask(M, VT, WhichResult) ||
4420           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4421           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4422           isVZIP_v_undef_Mask(M, VT, WhichResult));
4423 }
4424
4425 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4426 /// the specified operations to build the shuffle.
4427 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4428                                       SDValue RHS, SelectionDAG &DAG,
4429                                       DebugLoc dl) {
4430   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4431   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4432   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4433
4434   enum {
4435     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4436     OP_VREV,
4437     OP_VDUP0,
4438     OP_VDUP1,
4439     OP_VDUP2,
4440     OP_VDUP3,
4441     OP_VEXT1,
4442     OP_VEXT2,
4443     OP_VEXT3,
4444     OP_VUZPL, // VUZP, left result
4445     OP_VUZPR, // VUZP, right result
4446     OP_VZIPL, // VZIP, left result
4447     OP_VZIPR, // VZIP, right result
4448     OP_VTRNL, // VTRN, left result
4449     OP_VTRNR  // VTRN, right result
4450   };
4451
4452   if (OpNum == OP_COPY) {
4453     if (LHSID == (1*9+2)*9+3) return LHS;
4454     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4455     return RHS;
4456   }
4457
4458   SDValue OpLHS, OpRHS;
4459   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4460   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4461   EVT VT = OpLHS.getValueType();
4462
4463   switch (OpNum) {
4464   default: llvm_unreachable("Unknown shuffle opcode!");
4465   case OP_VREV:
4466     // VREV divides the vector in half and swaps within the half.
4467     if (VT.getVectorElementType() == MVT::i32 ||
4468         VT.getVectorElementType() == MVT::f32)
4469       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4470     // vrev <4 x i16> -> VREV32
4471     if (VT.getVectorElementType() == MVT::i16)
4472       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4473     // vrev <4 x i8> -> VREV16
4474     assert(VT.getVectorElementType() == MVT::i8);
4475     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4476   case OP_VDUP0:
4477   case OP_VDUP1:
4478   case OP_VDUP2:
4479   case OP_VDUP3:
4480     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4481                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4482   case OP_VEXT1:
4483   case OP_VEXT2:
4484   case OP_VEXT3:
4485     return DAG.getNode(ARMISD::VEXT, dl, VT,
4486                        OpLHS, OpRHS,
4487                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4488   case OP_VUZPL:
4489   case OP_VUZPR:
4490     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4491                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4492   case OP_VZIPL:
4493   case OP_VZIPR:
4494     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4495                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4496   case OP_VTRNL:
4497   case OP_VTRNR:
4498     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4499                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4500   }
4501 }
4502
4503 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4504                                        ArrayRef<int> ShuffleMask,
4505                                        SelectionDAG &DAG) {
4506   // Check to see if we can use the VTBL instruction.
4507   SDValue V1 = Op.getOperand(0);
4508   SDValue V2 = Op.getOperand(1);
4509   DebugLoc DL = Op.getDebugLoc();
4510
4511   SmallVector<SDValue, 8> VTBLMask;
4512   for (ArrayRef<int>::iterator
4513          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4514     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4515
4516   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4517     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4518                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4519                                    &VTBLMask[0], 8));
4520
4521   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4522                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4523                                  &VTBLMask[0], 8));
4524 }
4525
4526 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4527   SDValue V1 = Op.getOperand(0);
4528   SDValue V2 = Op.getOperand(1);
4529   DebugLoc dl = Op.getDebugLoc();
4530   EVT VT = Op.getValueType();
4531   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4532
4533   // Convert shuffles that are directly supported on NEON to target-specific
4534   // DAG nodes, instead of keeping them as shuffles and matching them again
4535   // during code selection.  This is more efficient and avoids the possibility
4536   // of inconsistencies between legalization and selection.
4537   // FIXME: floating-point vectors should be canonicalized to integer vectors
4538   // of the same time so that they get CSEd properly.
4539   ArrayRef<int> ShuffleMask = SVN->getMask();
4540
4541   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4542   if (EltSize <= 32) {
4543     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4544       int Lane = SVN->getSplatIndex();
4545       // If this is undef splat, generate it via "just" vdup, if possible.
4546       if (Lane == -1) Lane = 0;
4547
4548       // Test if V1 is a SCALAR_TO_VECTOR.
4549       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4550         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4551       }
4552       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4553       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4554       // reaches it).
4555       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4556           !isa<ConstantSDNode>(V1.getOperand(0))) {
4557         bool IsScalarToVector = true;
4558         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4559           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4560             IsScalarToVector = false;
4561             break;
4562           }
4563         if (IsScalarToVector)
4564           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4565       }
4566       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4567                          DAG.getConstant(Lane, MVT::i32));
4568     }
4569
4570     bool ReverseVEXT;
4571     unsigned Imm;
4572     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4573       if (ReverseVEXT)
4574         std::swap(V1, V2);
4575       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4576                          DAG.getConstant(Imm, MVT::i32));
4577     }
4578
4579     if (isVREVMask(ShuffleMask, VT, 64))
4580       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4581     if (isVREVMask(ShuffleMask, VT, 32))
4582       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4583     if (isVREVMask(ShuffleMask, VT, 16))
4584       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4585
4586     // Check for Neon shuffles that modify both input vectors in place.
4587     // If both results are used, i.e., if there are two shuffles with the same
4588     // source operands and with masks corresponding to both results of one of
4589     // these operations, DAG memoization will ensure that a single node is
4590     // used for both shuffles.
4591     unsigned WhichResult;
4592     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4593       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4594                          V1, V2).getValue(WhichResult);
4595     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4596       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4597                          V1, V2).getValue(WhichResult);
4598     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4599       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4600                          V1, V2).getValue(WhichResult);
4601
4602     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4603       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4604                          V1, V1).getValue(WhichResult);
4605     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4606       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4607                          V1, V1).getValue(WhichResult);
4608     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4609       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4610                          V1, V1).getValue(WhichResult);
4611   }
4612
4613   // If the shuffle is not directly supported and it has 4 elements, use
4614   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4615   unsigned NumElts = VT.getVectorNumElements();
4616   if (NumElts == 4) {
4617     unsigned PFIndexes[4];
4618     for (unsigned i = 0; i != 4; ++i) {
4619       if (ShuffleMask[i] < 0)
4620         PFIndexes[i] = 8;
4621       else
4622         PFIndexes[i] = ShuffleMask[i];
4623     }
4624
4625     // Compute the index in the perfect shuffle table.
4626     unsigned PFTableIndex =
4627       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4628     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4629     unsigned Cost = (PFEntry >> 30);
4630
4631     if (Cost <= 4)
4632       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4633   }
4634
4635   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4636   if (EltSize >= 32) {
4637     // Do the expansion with floating-point types, since that is what the VFP
4638     // registers are defined to use, and since i64 is not legal.
4639     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4640     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4641     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4642     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4643     SmallVector<SDValue, 8> Ops;
4644     for (unsigned i = 0; i < NumElts; ++i) {
4645       if (ShuffleMask[i] < 0)
4646         Ops.push_back(DAG.getUNDEF(EltVT));
4647       else
4648         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4649                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4650                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4651                                                   MVT::i32)));
4652     }
4653     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4654     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4655   }
4656
4657   if (VT == MVT::v8i8) {
4658     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4659     if (NewOp.getNode())
4660       return NewOp;
4661   }
4662
4663   return SDValue();
4664 }
4665
4666 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4667   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4668   SDValue Lane = Op.getOperand(2);
4669   if (!isa<ConstantSDNode>(Lane))
4670     return SDValue();
4671
4672   return Op;
4673 }
4674
4675 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4676   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4677   SDValue Lane = Op.getOperand(1);
4678   if (!isa<ConstantSDNode>(Lane))
4679     return SDValue();
4680
4681   SDValue Vec = Op.getOperand(0);
4682   if (Op.getValueType() == MVT::i32 &&
4683       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4684     DebugLoc dl = Op.getDebugLoc();
4685     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4686   }
4687
4688   return Op;
4689 }
4690
4691 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4692   // The only time a CONCAT_VECTORS operation can have legal types is when
4693   // two 64-bit vectors are concatenated to a 128-bit vector.
4694   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4695          "unexpected CONCAT_VECTORS");
4696   DebugLoc dl = Op.getDebugLoc();
4697   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4698   SDValue Op0 = Op.getOperand(0);
4699   SDValue Op1 = Op.getOperand(1);
4700   if (Op0.getOpcode() != ISD::UNDEF)
4701     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4702                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4703                       DAG.getIntPtrConstant(0));
4704   if (Op1.getOpcode() != ISD::UNDEF)
4705     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4706                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4707                       DAG.getIntPtrConstant(1));
4708   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4709 }
4710
4711 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4712 /// element has been zero/sign-extended, depending on the isSigned parameter,
4713 /// from an integer type half its size.
4714 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4715                                    bool isSigned) {
4716   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4717   EVT VT = N->getValueType(0);
4718   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4719     SDNode *BVN = N->getOperand(0).getNode();
4720     if (BVN->getValueType(0) != MVT::v4i32 ||
4721         BVN->getOpcode() != ISD::BUILD_VECTOR)
4722       return false;
4723     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4724     unsigned HiElt = 1 - LoElt;
4725     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4726     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4727     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4728     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4729     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4730       return false;
4731     if (isSigned) {
4732       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4733           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4734         return true;
4735     } else {
4736       if (Hi0->isNullValue() && Hi1->isNullValue())
4737         return true;
4738     }
4739     return false;
4740   }
4741
4742   if (N->getOpcode() != ISD::BUILD_VECTOR)
4743     return false;
4744
4745   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4746     SDNode *Elt = N->getOperand(i).getNode();
4747     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4748       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4749       unsigned HalfSize = EltSize / 2;
4750       if (isSigned) {
4751         if (!isIntN(HalfSize, C->getSExtValue()))
4752           return false;
4753       } else {
4754         if (!isUIntN(HalfSize, C->getZExtValue()))
4755           return false;
4756       }
4757       continue;
4758     }
4759     return false;
4760   }
4761
4762   return true;
4763 }
4764
4765 /// isSignExtended - Check if a node is a vector value that is sign-extended
4766 /// or a constant BUILD_VECTOR with sign-extended elements.
4767 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4768   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4769     return true;
4770   if (isExtendedBUILD_VECTOR(N, DAG, true))
4771     return true;
4772   return false;
4773 }
4774
4775 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4776 /// or a constant BUILD_VECTOR with zero-extended elements.
4777 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4778   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4779     return true;
4780   if (isExtendedBUILD_VECTOR(N, DAG, false))
4781     return true;
4782   return false;
4783 }
4784
4785 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4786 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4787 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4788   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4789     return N->getOperand(0);
4790   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4791     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4792                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4793                        LD->isNonTemporal(), LD->isInvariant(),
4794                        LD->getAlignment());
4795   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4796   // have been legalized as a BITCAST from v4i32.
4797   if (N->getOpcode() == ISD::BITCAST) {
4798     SDNode *BVN = N->getOperand(0).getNode();
4799     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4800            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4801     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4802     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4803                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4804   }
4805   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4806   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4807   EVT VT = N->getValueType(0);
4808   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4809   unsigned NumElts = VT.getVectorNumElements();
4810   MVT TruncVT = MVT::getIntegerVT(EltSize);
4811   SmallVector<SDValue, 8> Ops;
4812   for (unsigned i = 0; i != NumElts; ++i) {
4813     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4814     const APInt &CInt = C->getAPIntValue();
4815     // Element types smaller than 32 bits are not legal, so use i32 elements.
4816     // The values are implicitly truncated so sext vs. zext doesn't matter.
4817     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4818   }
4819   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4820                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4821 }
4822
4823 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4824   unsigned Opcode = N->getOpcode();
4825   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4826     SDNode *N0 = N->getOperand(0).getNode();
4827     SDNode *N1 = N->getOperand(1).getNode();
4828     return N0->hasOneUse() && N1->hasOneUse() &&
4829       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4830   }
4831   return false;
4832 }
4833
4834 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4835   unsigned Opcode = N->getOpcode();
4836   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4837     SDNode *N0 = N->getOperand(0).getNode();
4838     SDNode *N1 = N->getOperand(1).getNode();
4839     return N0->hasOneUse() && N1->hasOneUse() &&
4840       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4841   }
4842   return false;
4843 }
4844
4845 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4846   // Multiplications are only custom-lowered for 128-bit vectors so that
4847   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4848   EVT VT = Op.getValueType();
4849   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4850   SDNode *N0 = Op.getOperand(0).getNode();
4851   SDNode *N1 = Op.getOperand(1).getNode();
4852   unsigned NewOpc = 0;
4853   bool isMLA = false;
4854   bool isN0SExt = isSignExtended(N0, DAG);
4855   bool isN1SExt = isSignExtended(N1, DAG);
4856   if (isN0SExt && isN1SExt)
4857     NewOpc = ARMISD::VMULLs;
4858   else {
4859     bool isN0ZExt = isZeroExtended(N0, DAG);
4860     bool isN1ZExt = isZeroExtended(N1, DAG);
4861     if (isN0ZExt && isN1ZExt)
4862       NewOpc = ARMISD::VMULLu;
4863     else if (isN1SExt || isN1ZExt) {
4864       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4865       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4866       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4867         NewOpc = ARMISD::VMULLs;
4868         isMLA = true;
4869       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4870         NewOpc = ARMISD::VMULLu;
4871         isMLA = true;
4872       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4873         std::swap(N0, N1);
4874         NewOpc = ARMISD::VMULLu;
4875         isMLA = true;
4876       }
4877     }
4878
4879     if (!NewOpc) {
4880       if (VT == MVT::v2i64)
4881         // Fall through to expand this.  It is not legal.
4882         return SDValue();
4883       else
4884         // Other vector multiplications are legal.
4885         return Op;
4886     }
4887   }
4888
4889   // Legalize to a VMULL instruction.
4890   DebugLoc DL = Op.getDebugLoc();
4891   SDValue Op0;
4892   SDValue Op1 = SkipExtension(N1, DAG);
4893   if (!isMLA) {
4894     Op0 = SkipExtension(N0, DAG);
4895     assert(Op0.getValueType().is64BitVector() &&
4896            Op1.getValueType().is64BitVector() &&
4897            "unexpected types for extended operands to VMULL");
4898     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4899   }
4900
4901   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4902   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4903   //   vmull q0, d4, d6
4904   //   vmlal q0, d5, d6
4905   // is faster than
4906   //   vaddl q0, d4, d5
4907   //   vmovl q1, d6
4908   //   vmul  q0, q0, q1
4909   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4910   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4911   EVT Op1VT = Op1.getValueType();
4912   return DAG.getNode(N0->getOpcode(), DL, VT,
4913                      DAG.getNode(NewOpc, DL, VT,
4914                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4915                      DAG.getNode(NewOpc, DL, VT,
4916                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4917 }
4918
4919 static SDValue
4920 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4921   // Convert to float
4922   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4923   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4924   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4925   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4926   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4927   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4928   // Get reciprocal estimate.
4929   // float4 recip = vrecpeq_f32(yf);
4930   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4931                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4932   // Because char has a smaller range than uchar, we can actually get away
4933   // without any newton steps.  This requires that we use a weird bias
4934   // of 0xb000, however (again, this has been exhaustively tested).
4935   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4936   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4937   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4938   Y = DAG.getConstant(0xb000, MVT::i32);
4939   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4940   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4941   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4942   // Convert back to short.
4943   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4944   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4945   return X;
4946 }
4947
4948 static SDValue
4949 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4950   SDValue N2;
4951   // Convert to float.
4952   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4953   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4954   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4955   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4956   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4957   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4958
4959   // Use reciprocal estimate and one refinement step.
4960   // float4 recip = vrecpeq_f32(yf);
4961   // recip *= vrecpsq_f32(yf, recip);
4962   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4963                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4964   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4965                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4966                    N1, N2);
4967   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4968   // Because short has a smaller range than ushort, we can actually get away
4969   // with only a single newton step.  This requires that we use a weird bias
4970   // of 89, however (again, this has been exhaustively tested).
4971   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4972   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4973   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4974   N1 = DAG.getConstant(0x89, MVT::i32);
4975   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4976   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4977   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4978   // Convert back to integer and return.
4979   // return vmovn_s32(vcvt_s32_f32(result));
4980   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4981   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4982   return N0;
4983 }
4984
4985 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4986   EVT VT = Op.getValueType();
4987   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4988          "unexpected type for custom-lowering ISD::SDIV");
4989
4990   DebugLoc dl = Op.getDebugLoc();
4991   SDValue N0 = Op.getOperand(0);
4992   SDValue N1 = Op.getOperand(1);
4993   SDValue N2, N3;
4994
4995   if (VT == MVT::v8i8) {
4996     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4997     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4998
4999     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5000                      DAG.getIntPtrConstant(4));
5001     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5002                      DAG.getIntPtrConstant(4));
5003     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5004                      DAG.getIntPtrConstant(0));
5005     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5006                      DAG.getIntPtrConstant(0));
5007
5008     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5009     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5010
5011     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5012     N0 = LowerCONCAT_VECTORS(N0, DAG);
5013
5014     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5015     return N0;
5016   }
5017   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5018 }
5019
5020 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5021   EVT VT = Op.getValueType();
5022   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5023          "unexpected type for custom-lowering ISD::UDIV");
5024
5025   DebugLoc dl = Op.getDebugLoc();
5026   SDValue N0 = Op.getOperand(0);
5027   SDValue N1 = Op.getOperand(1);
5028   SDValue N2, N3;
5029
5030   if (VT == MVT::v8i8) {
5031     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5032     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5033
5034     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5035                      DAG.getIntPtrConstant(4));
5036     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5037                      DAG.getIntPtrConstant(4));
5038     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5039                      DAG.getIntPtrConstant(0));
5040     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5041                      DAG.getIntPtrConstant(0));
5042
5043     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5044     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5045
5046     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5047     N0 = LowerCONCAT_VECTORS(N0, DAG);
5048
5049     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5050                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5051                      N0);
5052     return N0;
5053   }
5054
5055   // v4i16 sdiv ... Convert to float.
5056   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5057   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5058   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5059   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5060   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5061   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5062
5063   // Use reciprocal estimate and two refinement steps.
5064   // float4 recip = vrecpeq_f32(yf);
5065   // recip *= vrecpsq_f32(yf, recip);
5066   // recip *= vrecpsq_f32(yf, recip);
5067   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5068                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5069   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5070                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5071                    BN1, N2);
5072   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5073   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5074                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5075                    BN1, N2);
5076   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5077   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5078   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5079   // and that it will never cause us to return an answer too large).
5080   // float4 result = as_float4(as_int4(xf*recip) + 2);
5081   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5082   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5083   N1 = DAG.getConstant(2, MVT::i32);
5084   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5085   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5086   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5087   // Convert back to integer and return.
5088   // return vmovn_u32(vcvt_s32_f32(result));
5089   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5090   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5091   return N0;
5092 }
5093
5094 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5095   EVT VT = Op.getNode()->getValueType(0);
5096   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5097
5098   unsigned Opc;
5099   bool ExtraOp = false;
5100   switch (Op.getOpcode()) {
5101   default: llvm_unreachable("Invalid code");
5102   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5103   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5104   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5105   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5106   }
5107
5108   if (!ExtraOp)
5109     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5110                        Op.getOperand(1));
5111   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5112                      Op.getOperand(1), Op.getOperand(2));
5113 }
5114
5115 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5116   // Monotonic load/store is legal for all targets
5117   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5118     return Op;
5119
5120   // Aquire/Release load/store is not legal for targets without a
5121   // dmb or equivalent available.
5122   return SDValue();
5123 }
5124
5125
5126 static void
5127 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5128                     SelectionDAG &DAG, unsigned NewOp) {
5129   DebugLoc dl = Node->getDebugLoc();
5130   assert (Node->getValueType(0) == MVT::i64 &&
5131           "Only know how to expand i64 atomics");
5132
5133   SmallVector<SDValue, 6> Ops;
5134   Ops.push_back(Node->getOperand(0)); // Chain
5135   Ops.push_back(Node->getOperand(1)); // Ptr
5136   // Low part of Val1
5137   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5138                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5139   // High part of Val1
5140   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5141                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5142   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5143     // High part of Val1
5144     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5145                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5146     // High part of Val2
5147     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5148                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5149   }
5150   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5151   SDValue Result =
5152     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5153                             cast<MemSDNode>(Node)->getMemOperand());
5154   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5155   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5156   Results.push_back(Result.getValue(2));
5157 }
5158
5159 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5160   switch (Op.getOpcode()) {
5161   default: llvm_unreachable("Don't know how to custom lower this!");
5162   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5163   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5164   case ISD::GlobalAddress:
5165     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5166       LowerGlobalAddressELF(Op, DAG);
5167   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5168   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5169   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5170   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5171   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5172   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5173   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5174   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5175   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5176   case ISD::SINT_TO_FP:
5177   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5178   case ISD::FP_TO_SINT:
5179   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5180   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5181   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5182   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5183   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5184   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5185   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5186   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5187                                                                Subtarget);
5188   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5189   case ISD::SHL:
5190   case ISD::SRL:
5191   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5192   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5193   case ISD::SRL_PARTS:
5194   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5195   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5196   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5197   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5198   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5199   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5200   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5201   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5202   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5203   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5204   case ISD::MUL:           return LowerMUL(Op, DAG);
5205   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5206   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5207   case ISD::ADDC:
5208   case ISD::ADDE:
5209   case ISD::SUBC:
5210   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5211   case ISD::ATOMIC_LOAD:
5212   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5213   }
5214 }
5215
5216 /// ReplaceNodeResults - Replace the results of node with an illegal result
5217 /// type with new values built out of custom code.
5218 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5219                                            SmallVectorImpl<SDValue>&Results,
5220                                            SelectionDAG &DAG) const {
5221   SDValue Res;
5222   switch (N->getOpcode()) {
5223   default:
5224     llvm_unreachable("Don't know how to custom expand this!");
5225   case ISD::BITCAST:
5226     Res = ExpandBITCAST(N, DAG);
5227     break;
5228   case ISD::SRL:
5229   case ISD::SRA:
5230     Res = Expand64BitShift(N, DAG, Subtarget);
5231     break;
5232   case ISD::ATOMIC_LOAD_ADD:
5233     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5234     return;
5235   case ISD::ATOMIC_LOAD_AND:
5236     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5237     return;
5238   case ISD::ATOMIC_LOAD_NAND:
5239     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5240     return;
5241   case ISD::ATOMIC_LOAD_OR:
5242     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5243     return;
5244   case ISD::ATOMIC_LOAD_SUB:
5245     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5246     return;
5247   case ISD::ATOMIC_LOAD_XOR:
5248     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5249     return;
5250   case ISD::ATOMIC_SWAP:
5251     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5252     return;
5253   case ISD::ATOMIC_CMP_SWAP:
5254     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5255     return;
5256   }
5257   if (Res.getNode())
5258     Results.push_back(Res);
5259 }
5260
5261 //===----------------------------------------------------------------------===//
5262 //                           ARM Scheduler Hooks
5263 //===----------------------------------------------------------------------===//
5264
5265 MachineBasicBlock *
5266 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5267                                      MachineBasicBlock *BB,
5268                                      unsigned Size) const {
5269   unsigned dest    = MI->getOperand(0).getReg();
5270   unsigned ptr     = MI->getOperand(1).getReg();
5271   unsigned oldval  = MI->getOperand(2).getReg();
5272   unsigned newval  = MI->getOperand(3).getReg();
5273   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5274   DebugLoc dl = MI->getDebugLoc();
5275   bool isThumb2 = Subtarget->isThumb2();
5276
5277   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5278   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5279     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5280     (const TargetRegisterClass*)&ARM::GPRRegClass);
5281
5282   if (isThumb2) {
5283     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5284     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5285     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5286   }
5287
5288   unsigned ldrOpc, strOpc;
5289   switch (Size) {
5290   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5291   case 1:
5292     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5293     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5294     break;
5295   case 2:
5296     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5297     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5298     break;
5299   case 4:
5300     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5301     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5302     break;
5303   }
5304
5305   MachineFunction *MF = BB->getParent();
5306   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5307   MachineFunction::iterator It = BB;
5308   ++It; // insert the new blocks after the current block
5309
5310   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5311   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5312   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5313   MF->insert(It, loop1MBB);
5314   MF->insert(It, loop2MBB);
5315   MF->insert(It, exitMBB);
5316
5317   // Transfer the remainder of BB and its successor edges to exitMBB.
5318   exitMBB->splice(exitMBB->begin(), BB,
5319                   llvm::next(MachineBasicBlock::iterator(MI)),
5320                   BB->end());
5321   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5322
5323   //  thisMBB:
5324   //   ...
5325   //   fallthrough --> loop1MBB
5326   BB->addSuccessor(loop1MBB);
5327
5328   // loop1MBB:
5329   //   ldrex dest, [ptr]
5330   //   cmp dest, oldval
5331   //   bne exitMBB
5332   BB = loop1MBB;
5333   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5334   if (ldrOpc == ARM::t2LDREX)
5335     MIB.addImm(0);
5336   AddDefaultPred(MIB);
5337   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5338                  .addReg(dest).addReg(oldval));
5339   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5340     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5341   BB->addSuccessor(loop2MBB);
5342   BB->addSuccessor(exitMBB);
5343
5344   // loop2MBB:
5345   //   strex scratch, newval, [ptr]
5346   //   cmp scratch, #0
5347   //   bne loop1MBB
5348   BB = loop2MBB;
5349   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5350   if (strOpc == ARM::t2STREX)
5351     MIB.addImm(0);
5352   AddDefaultPred(MIB);
5353   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5354                  .addReg(scratch).addImm(0));
5355   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5356     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5357   BB->addSuccessor(loop1MBB);
5358   BB->addSuccessor(exitMBB);
5359
5360   //  exitMBB:
5361   //   ...
5362   BB = exitMBB;
5363
5364   MI->eraseFromParent();   // The instruction is gone now.
5365
5366   return BB;
5367 }
5368
5369 MachineBasicBlock *
5370 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5371                                     unsigned Size, unsigned BinOpcode) const {
5372   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5373   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5374
5375   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5376   MachineFunction *MF = BB->getParent();
5377   MachineFunction::iterator It = BB;
5378   ++It;
5379
5380   unsigned dest = MI->getOperand(0).getReg();
5381   unsigned ptr = MI->getOperand(1).getReg();
5382   unsigned incr = MI->getOperand(2).getReg();
5383   DebugLoc dl = MI->getDebugLoc();
5384   bool isThumb2 = Subtarget->isThumb2();
5385
5386   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5387   if (isThumb2) {
5388     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5389     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5390   }
5391
5392   unsigned ldrOpc, strOpc;
5393   switch (Size) {
5394   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5395   case 1:
5396     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5397     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5398     break;
5399   case 2:
5400     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5401     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5402     break;
5403   case 4:
5404     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5405     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5406     break;
5407   }
5408
5409   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5410   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5411   MF->insert(It, loopMBB);
5412   MF->insert(It, exitMBB);
5413
5414   // Transfer the remainder of BB and its successor edges to exitMBB.
5415   exitMBB->splice(exitMBB->begin(), BB,
5416                   llvm::next(MachineBasicBlock::iterator(MI)),
5417                   BB->end());
5418   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5419
5420   const TargetRegisterClass *TRC = isThumb2 ?
5421     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5422     (const TargetRegisterClass*)&ARM::GPRRegClass;
5423   unsigned scratch = MRI.createVirtualRegister(TRC);
5424   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5425
5426   //  thisMBB:
5427   //   ...
5428   //   fallthrough --> loopMBB
5429   BB->addSuccessor(loopMBB);
5430
5431   //  loopMBB:
5432   //   ldrex dest, ptr
5433   //   <binop> scratch2, dest, incr
5434   //   strex scratch, scratch2, ptr
5435   //   cmp scratch, #0
5436   //   bne- loopMBB
5437   //   fallthrough --> exitMBB
5438   BB = loopMBB;
5439   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5440   if (ldrOpc == ARM::t2LDREX)
5441     MIB.addImm(0);
5442   AddDefaultPred(MIB);
5443   if (BinOpcode) {
5444     // operand order needs to go the other way for NAND
5445     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5446       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5447                      addReg(incr).addReg(dest)).addReg(0);
5448     else
5449       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5450                      addReg(dest).addReg(incr)).addReg(0);
5451   }
5452
5453   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5454   if (strOpc == ARM::t2STREX)
5455     MIB.addImm(0);
5456   AddDefaultPred(MIB);
5457   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5458                  .addReg(scratch).addImm(0));
5459   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5460     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5461
5462   BB->addSuccessor(loopMBB);
5463   BB->addSuccessor(exitMBB);
5464
5465   //  exitMBB:
5466   //   ...
5467   BB = exitMBB;
5468
5469   MI->eraseFromParent();   // The instruction is gone now.
5470
5471   return BB;
5472 }
5473
5474 MachineBasicBlock *
5475 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5476                                           MachineBasicBlock *BB,
5477                                           unsigned Size,
5478                                           bool signExtend,
5479                                           ARMCC::CondCodes Cond) const {
5480   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5481
5482   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5483   MachineFunction *MF = BB->getParent();
5484   MachineFunction::iterator It = BB;
5485   ++It;
5486
5487   unsigned dest = MI->getOperand(0).getReg();
5488   unsigned ptr = MI->getOperand(1).getReg();
5489   unsigned incr = MI->getOperand(2).getReg();
5490   unsigned oldval = dest;
5491   DebugLoc dl = MI->getDebugLoc();
5492   bool isThumb2 = Subtarget->isThumb2();
5493
5494   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5495   if (isThumb2) {
5496     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5497     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5498   }
5499
5500   unsigned ldrOpc, strOpc, extendOpc;
5501   switch (Size) {
5502   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5503   case 1:
5504     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5505     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5506     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5507     break;
5508   case 2:
5509     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5510     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5511     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5512     break;
5513   case 4:
5514     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5515     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5516     extendOpc = 0;
5517     break;
5518   }
5519
5520   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5521   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5522   MF->insert(It, loopMBB);
5523   MF->insert(It, exitMBB);
5524
5525   // Transfer the remainder of BB and its successor edges to exitMBB.
5526   exitMBB->splice(exitMBB->begin(), BB,
5527                   llvm::next(MachineBasicBlock::iterator(MI)),
5528                   BB->end());
5529   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5530
5531   const TargetRegisterClass *TRC = isThumb2 ?
5532     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5533     (const TargetRegisterClass*)&ARM::GPRRegClass;
5534   unsigned scratch = MRI.createVirtualRegister(TRC);
5535   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5536
5537   //  thisMBB:
5538   //   ...
5539   //   fallthrough --> loopMBB
5540   BB->addSuccessor(loopMBB);
5541
5542   //  loopMBB:
5543   //   ldrex dest, ptr
5544   //   (sign extend dest, if required)
5545   //   cmp dest, incr
5546   //   cmov.cond scratch2, dest, incr
5547   //   strex scratch, scratch2, ptr
5548   //   cmp scratch, #0
5549   //   bne- loopMBB
5550   //   fallthrough --> exitMBB
5551   BB = loopMBB;
5552   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5553   if (ldrOpc == ARM::t2LDREX)
5554     MIB.addImm(0);
5555   AddDefaultPred(MIB);
5556
5557   // Sign extend the value, if necessary.
5558   if (signExtend && extendOpc) {
5559     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5560     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5561                      .addReg(dest)
5562                      .addImm(0));
5563   }
5564
5565   // Build compare and cmov instructions.
5566   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5567                  .addReg(oldval).addReg(incr));
5568   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5569          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5570
5571   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5572   if (strOpc == ARM::t2STREX)
5573     MIB.addImm(0);
5574   AddDefaultPred(MIB);
5575   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5576                  .addReg(scratch).addImm(0));
5577   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5578     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5579
5580   BB->addSuccessor(loopMBB);
5581   BB->addSuccessor(exitMBB);
5582
5583   //  exitMBB:
5584   //   ...
5585   BB = exitMBB;
5586
5587   MI->eraseFromParent();   // The instruction is gone now.
5588
5589   return BB;
5590 }
5591
5592 MachineBasicBlock *
5593 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5594                                       unsigned Op1, unsigned Op2,
5595                                       bool NeedsCarry, bool IsCmpxchg) const {
5596   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5597   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5598
5599   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5600   MachineFunction *MF = BB->getParent();
5601   MachineFunction::iterator It = BB;
5602   ++It;
5603
5604   unsigned destlo = MI->getOperand(0).getReg();
5605   unsigned desthi = MI->getOperand(1).getReg();
5606   unsigned ptr = MI->getOperand(2).getReg();
5607   unsigned vallo = MI->getOperand(3).getReg();
5608   unsigned valhi = MI->getOperand(4).getReg();
5609   DebugLoc dl = MI->getDebugLoc();
5610   bool isThumb2 = Subtarget->isThumb2();
5611
5612   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5613   if (isThumb2) {
5614     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5615     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5616     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5617   }
5618
5619   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5620   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5621
5622   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5623   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5624   if (IsCmpxchg) {
5625     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5626     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5627   }
5628   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5629   MF->insert(It, loopMBB);
5630   if (IsCmpxchg) {
5631     MF->insert(It, contBB);
5632     MF->insert(It, cont2BB);
5633   }
5634   MF->insert(It, exitMBB);
5635
5636   // Transfer the remainder of BB and its successor edges to exitMBB.
5637   exitMBB->splice(exitMBB->begin(), BB,
5638                   llvm::next(MachineBasicBlock::iterator(MI)),
5639                   BB->end());
5640   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5641
5642   const TargetRegisterClass *TRC = isThumb2 ?
5643     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5644     (const TargetRegisterClass*)&ARM::GPRRegClass;
5645   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5646
5647   //  thisMBB:
5648   //   ...
5649   //   fallthrough --> loopMBB
5650   BB->addSuccessor(loopMBB);
5651
5652   //  loopMBB:
5653   //   ldrexd r2, r3, ptr
5654   //   <binopa> r0, r2, incr
5655   //   <binopb> r1, r3, incr
5656   //   strexd storesuccess, r0, r1, ptr
5657   //   cmp storesuccess, #0
5658   //   bne- loopMBB
5659   //   fallthrough --> exitMBB
5660   //
5661   // Note that the registers are explicitly specified because there is not any
5662   // way to force the register allocator to allocate a register pair.
5663   //
5664   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5665   // need to properly enforce the restriction that the two output registers
5666   // for ldrexd must be different.
5667   BB = loopMBB;
5668   // Load
5669   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5670                  .addReg(ARM::R2, RegState::Define)
5671                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5672   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5673   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5674   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5675
5676   if (IsCmpxchg) {
5677     // Add early exit
5678     for (unsigned i = 0; i < 2; i++) {
5679       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5680                                                          ARM::CMPrr))
5681                      .addReg(i == 0 ? destlo : desthi)
5682                      .addReg(i == 0 ? vallo : valhi));
5683       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5684         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5685       BB->addSuccessor(exitMBB);
5686       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5687       BB = (i == 0 ? contBB : cont2BB);
5688     }
5689
5690     // Copy to physregs for strexd
5691     unsigned setlo = MI->getOperand(5).getReg();
5692     unsigned sethi = MI->getOperand(6).getReg();
5693     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5694     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5695   } else if (Op1) {
5696     // Perform binary operation
5697     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5698                    .addReg(destlo).addReg(vallo))
5699         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5700     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5701                    .addReg(desthi).addReg(valhi)).addReg(0);
5702   } else {
5703     // Copy to physregs for strexd
5704     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5705     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5706   }
5707
5708   // Store
5709   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5710                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5711   // Cmp+jump
5712   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5713                  .addReg(storesuccess).addImm(0));
5714   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5715     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5716
5717   BB->addSuccessor(loopMBB);
5718   BB->addSuccessor(exitMBB);
5719
5720   //  exitMBB:
5721   //   ...
5722   BB = exitMBB;
5723
5724   MI->eraseFromParent();   // The instruction is gone now.
5725
5726   return BB;
5727 }
5728
5729 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5730 /// registers the function context.
5731 void ARMTargetLowering::
5732 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5733                        MachineBasicBlock *DispatchBB, int FI) const {
5734   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5735   DebugLoc dl = MI->getDebugLoc();
5736   MachineFunction *MF = MBB->getParent();
5737   MachineRegisterInfo *MRI = &MF->getRegInfo();
5738   MachineConstantPool *MCP = MF->getConstantPool();
5739   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5740   const Function *F = MF->getFunction();
5741
5742   bool isThumb = Subtarget->isThumb();
5743   bool isThumb2 = Subtarget->isThumb2();
5744
5745   unsigned PCLabelId = AFI->createPICLabelUId();
5746   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5747   ARMConstantPoolValue *CPV =
5748     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5749   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5750
5751   const TargetRegisterClass *TRC = isThumb ?
5752     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5753     (const TargetRegisterClass*)&ARM::GPRRegClass;
5754
5755   // Grab constant pool and fixed stack memory operands.
5756   MachineMemOperand *CPMMO =
5757     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5758                              MachineMemOperand::MOLoad, 4, 4);
5759
5760   MachineMemOperand *FIMMOSt =
5761     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5762                              MachineMemOperand::MOStore, 4, 4);
5763
5764   // Load the address of the dispatch MBB into the jump buffer.
5765   if (isThumb2) {
5766     // Incoming value: jbuf
5767     //   ldr.n  r5, LCPI1_1
5768     //   orr    r5, r5, #1
5769     //   add    r5, pc
5770     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5771     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5772     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5773                    .addConstantPoolIndex(CPI)
5774                    .addMemOperand(CPMMO));
5775     // Set the low bit because of thumb mode.
5776     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5777     AddDefaultCC(
5778       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5779                      .addReg(NewVReg1, RegState::Kill)
5780                      .addImm(0x01)));
5781     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5782     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5783       .addReg(NewVReg2, RegState::Kill)
5784       .addImm(PCLabelId);
5785     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5786                    .addReg(NewVReg3, RegState::Kill)
5787                    .addFrameIndex(FI)
5788                    .addImm(36)  // &jbuf[1] :: pc
5789                    .addMemOperand(FIMMOSt));
5790   } else if (isThumb) {
5791     // Incoming value: jbuf
5792     //   ldr.n  r1, LCPI1_4
5793     //   add    r1, pc
5794     //   mov    r2, #1
5795     //   orrs   r1, r2
5796     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5797     //   str    r1, [r2]
5798     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5799     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5800                    .addConstantPoolIndex(CPI)
5801                    .addMemOperand(CPMMO));
5802     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5803     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5804       .addReg(NewVReg1, RegState::Kill)
5805       .addImm(PCLabelId);
5806     // Set the low bit because of thumb mode.
5807     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5808     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5809                    .addReg(ARM::CPSR, RegState::Define)
5810                    .addImm(1));
5811     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5812     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5813                    .addReg(ARM::CPSR, RegState::Define)
5814                    .addReg(NewVReg2, RegState::Kill)
5815                    .addReg(NewVReg3, RegState::Kill));
5816     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5817     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5818                    .addFrameIndex(FI)
5819                    .addImm(36)); // &jbuf[1] :: pc
5820     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5821                    .addReg(NewVReg4, RegState::Kill)
5822                    .addReg(NewVReg5, RegState::Kill)
5823                    .addImm(0)
5824                    .addMemOperand(FIMMOSt));
5825   } else {
5826     // Incoming value: jbuf
5827     //   ldr  r1, LCPI1_1
5828     //   add  r1, pc, r1
5829     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5830     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5831     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5832                    .addConstantPoolIndex(CPI)
5833                    .addImm(0)
5834                    .addMemOperand(CPMMO));
5835     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5836     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5837                    .addReg(NewVReg1, RegState::Kill)
5838                    .addImm(PCLabelId));
5839     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5840                    .addReg(NewVReg2, RegState::Kill)
5841                    .addFrameIndex(FI)
5842                    .addImm(36)  // &jbuf[1] :: pc
5843                    .addMemOperand(FIMMOSt));
5844   }
5845 }
5846
5847 MachineBasicBlock *ARMTargetLowering::
5848 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5849   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5850   DebugLoc dl = MI->getDebugLoc();
5851   MachineFunction *MF = MBB->getParent();
5852   MachineRegisterInfo *MRI = &MF->getRegInfo();
5853   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5854   MachineFrameInfo *MFI = MF->getFrameInfo();
5855   int FI = MFI->getFunctionContextIndex();
5856
5857   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5858     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5859     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5860
5861   // Get a mapping of the call site numbers to all of the landing pads they're
5862   // associated with.
5863   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5864   unsigned MaxCSNum = 0;
5865   MachineModuleInfo &MMI = MF->getMMI();
5866   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5867        ++BB) {
5868     if (!BB->isLandingPad()) continue;
5869
5870     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5871     // pad.
5872     for (MachineBasicBlock::iterator
5873            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5874       if (!II->isEHLabel()) continue;
5875
5876       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5877       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5878
5879       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5880       for (SmallVectorImpl<unsigned>::iterator
5881              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5882            CSI != CSE; ++CSI) {
5883         CallSiteNumToLPad[*CSI].push_back(BB);
5884         MaxCSNum = std::max(MaxCSNum, *CSI);
5885       }
5886       break;
5887     }
5888   }
5889
5890   // Get an ordered list of the machine basic blocks for the jump table.
5891   std::vector<MachineBasicBlock*> LPadList;
5892   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5893   LPadList.reserve(CallSiteNumToLPad.size());
5894   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5895     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5896     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5897            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5898       LPadList.push_back(*II);
5899       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5900     }
5901   }
5902
5903   assert(!LPadList.empty() &&
5904          "No landing pad destinations for the dispatch jump table!");
5905
5906   // Create the jump table and associated information.
5907   MachineJumpTableInfo *JTI =
5908     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5909   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5910   unsigned UId = AFI->createJumpTableUId();
5911
5912   // Create the MBBs for the dispatch code.
5913
5914   // Shove the dispatch's address into the return slot in the function context.
5915   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5916   DispatchBB->setIsLandingPad();
5917
5918   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5919   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5920   DispatchBB->addSuccessor(TrapBB);
5921
5922   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5923   DispatchBB->addSuccessor(DispContBB);
5924
5925   // Insert and MBBs.
5926   MF->insert(MF->end(), DispatchBB);
5927   MF->insert(MF->end(), DispContBB);
5928   MF->insert(MF->end(), TrapBB);
5929
5930   // Insert code into the entry block that creates and registers the function
5931   // context.
5932   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5933
5934   MachineMemOperand *FIMMOLd =
5935     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5936                              MachineMemOperand::MOLoad |
5937                              MachineMemOperand::MOVolatile, 4, 4);
5938
5939   if (AFI->isThumb1OnlyFunction())
5940     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5941   else if (!Subtarget->hasVFP2())
5942     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5943   else
5944     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5945
5946   unsigned NumLPads = LPadList.size();
5947   if (Subtarget->isThumb2()) {
5948     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5949     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5950                    .addFrameIndex(FI)
5951                    .addImm(4)
5952                    .addMemOperand(FIMMOLd));
5953
5954     if (NumLPads < 256) {
5955       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5956                      .addReg(NewVReg1)
5957                      .addImm(LPadList.size()));
5958     } else {
5959       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5960       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5961                      .addImm(NumLPads & 0xFFFF));
5962
5963       unsigned VReg2 = VReg1;
5964       if ((NumLPads & 0xFFFF0000) != 0) {
5965         VReg2 = MRI->createVirtualRegister(TRC);
5966         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5967                        .addReg(VReg1)
5968                        .addImm(NumLPads >> 16));
5969       }
5970
5971       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5972                      .addReg(NewVReg1)
5973                      .addReg(VReg2));
5974     }
5975
5976     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5977       .addMBB(TrapBB)
5978       .addImm(ARMCC::HI)
5979       .addReg(ARM::CPSR);
5980
5981     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5982     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5983                    .addJumpTableIndex(MJTI)
5984                    .addImm(UId));
5985
5986     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5987     AddDefaultCC(
5988       AddDefaultPred(
5989         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5990         .addReg(NewVReg3, RegState::Kill)
5991         .addReg(NewVReg1)
5992         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5993
5994     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5995       .addReg(NewVReg4, RegState::Kill)
5996       .addReg(NewVReg1)
5997       .addJumpTableIndex(MJTI)
5998       .addImm(UId);
5999   } else if (Subtarget->isThumb()) {
6000     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6001     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6002                    .addFrameIndex(FI)
6003                    .addImm(1)
6004                    .addMemOperand(FIMMOLd));
6005
6006     if (NumLPads < 256) {
6007       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6008                      .addReg(NewVReg1)
6009                      .addImm(NumLPads));
6010     } else {
6011       MachineConstantPool *ConstantPool = MF->getConstantPool();
6012       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6013       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6014
6015       // MachineConstantPool wants an explicit alignment.
6016       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6017       if (Align == 0)
6018         Align = getTargetData()->getTypeAllocSize(C->getType());
6019       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6020
6021       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6022       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6023                      .addReg(VReg1, RegState::Define)
6024                      .addConstantPoolIndex(Idx));
6025       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6026                      .addReg(NewVReg1)
6027                      .addReg(VReg1));
6028     }
6029
6030     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6031       .addMBB(TrapBB)
6032       .addImm(ARMCC::HI)
6033       .addReg(ARM::CPSR);
6034
6035     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6036     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6037                    .addReg(ARM::CPSR, RegState::Define)
6038                    .addReg(NewVReg1)
6039                    .addImm(2));
6040
6041     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6042     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6043                    .addJumpTableIndex(MJTI)
6044                    .addImm(UId));
6045
6046     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6047     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6048                    .addReg(ARM::CPSR, RegState::Define)
6049                    .addReg(NewVReg2, RegState::Kill)
6050                    .addReg(NewVReg3));
6051
6052     MachineMemOperand *JTMMOLd =
6053       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6054                                MachineMemOperand::MOLoad, 4, 4);
6055
6056     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6057     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6058                    .addReg(NewVReg4, RegState::Kill)
6059                    .addImm(0)
6060                    .addMemOperand(JTMMOLd));
6061
6062     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6063     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6064                    .addReg(ARM::CPSR, RegState::Define)
6065                    .addReg(NewVReg5, RegState::Kill)
6066                    .addReg(NewVReg3));
6067
6068     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6069       .addReg(NewVReg6, RegState::Kill)
6070       .addJumpTableIndex(MJTI)
6071       .addImm(UId);
6072   } else {
6073     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6074     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6075                    .addFrameIndex(FI)
6076                    .addImm(4)
6077                    .addMemOperand(FIMMOLd));
6078
6079     if (NumLPads < 256) {
6080       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6081                      .addReg(NewVReg1)
6082                      .addImm(NumLPads));
6083     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6084       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6085       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6086                      .addImm(NumLPads & 0xFFFF));
6087
6088       unsigned VReg2 = VReg1;
6089       if ((NumLPads & 0xFFFF0000) != 0) {
6090         VReg2 = MRI->createVirtualRegister(TRC);
6091         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6092                        .addReg(VReg1)
6093                        .addImm(NumLPads >> 16));
6094       }
6095
6096       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6097                      .addReg(NewVReg1)
6098                      .addReg(VReg2));
6099     } else {
6100       MachineConstantPool *ConstantPool = MF->getConstantPool();
6101       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6102       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6103
6104       // MachineConstantPool wants an explicit alignment.
6105       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6106       if (Align == 0)
6107         Align = getTargetData()->getTypeAllocSize(C->getType());
6108       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6109
6110       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6111       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6112                      .addReg(VReg1, RegState::Define)
6113                      .addConstantPoolIndex(Idx)
6114                      .addImm(0));
6115       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6116                      .addReg(NewVReg1)
6117                      .addReg(VReg1, RegState::Kill));
6118     }
6119
6120     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6121       .addMBB(TrapBB)
6122       .addImm(ARMCC::HI)
6123       .addReg(ARM::CPSR);
6124
6125     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6126     AddDefaultCC(
6127       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6128                      .addReg(NewVReg1)
6129                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6130     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6131     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6132                    .addJumpTableIndex(MJTI)
6133                    .addImm(UId));
6134
6135     MachineMemOperand *JTMMOLd =
6136       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6137                                MachineMemOperand::MOLoad, 4, 4);
6138     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6139     AddDefaultPred(
6140       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6141       .addReg(NewVReg3, RegState::Kill)
6142       .addReg(NewVReg4)
6143       .addImm(0)
6144       .addMemOperand(JTMMOLd));
6145
6146     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6147       .addReg(NewVReg5, RegState::Kill)
6148       .addReg(NewVReg4)
6149       .addJumpTableIndex(MJTI)
6150       .addImm(UId);
6151   }
6152
6153   // Add the jump table entries as successors to the MBB.
6154   MachineBasicBlock *PrevMBB = 0;
6155   for (std::vector<MachineBasicBlock*>::iterator
6156          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6157     MachineBasicBlock *CurMBB = *I;
6158     if (PrevMBB != CurMBB)
6159       DispContBB->addSuccessor(CurMBB);
6160     PrevMBB = CurMBB;
6161   }
6162
6163   // N.B. the order the invoke BBs are processed in doesn't matter here.
6164   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6165   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6166   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6167   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6168   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6169          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6170     MachineBasicBlock *BB = *I;
6171
6172     // Remove the landing pad successor from the invoke block and replace it
6173     // with the new dispatch block.
6174     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6175                                                   BB->succ_end());
6176     while (!Successors.empty()) {
6177       MachineBasicBlock *SMBB = Successors.pop_back_val();
6178       if (SMBB->isLandingPad()) {
6179         BB->removeSuccessor(SMBB);
6180         MBBLPads.push_back(SMBB);
6181       }
6182     }
6183
6184     BB->addSuccessor(DispatchBB);
6185
6186     // Find the invoke call and mark all of the callee-saved registers as
6187     // 'implicit defined' so that they're spilled. This prevents code from
6188     // moving instructions to before the EH block, where they will never be
6189     // executed.
6190     for (MachineBasicBlock::reverse_iterator
6191            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6192       if (!II->isCall()) continue;
6193
6194       DenseMap<unsigned, bool> DefRegs;
6195       for (MachineInstr::mop_iterator
6196              OI = II->operands_begin(), OE = II->operands_end();
6197            OI != OE; ++OI) {
6198         if (!OI->isReg()) continue;
6199         DefRegs[OI->getReg()] = true;
6200       }
6201
6202       MachineInstrBuilder MIB(&*II);
6203
6204       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6205         unsigned Reg = SavedRegs[i];
6206         if (Subtarget->isThumb2() &&
6207             !ARM::tGPRRegClass.contains(Reg) &&
6208             !ARM::hGPRRegClass.contains(Reg))
6209           continue;
6210         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6211           continue;
6212         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6213           continue;
6214         if (!DefRegs[Reg])
6215           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6216       }
6217
6218       break;
6219     }
6220   }
6221
6222   // Mark all former landing pads as non-landing pads. The dispatch is the only
6223   // landing pad now.
6224   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6225          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6226     (*I)->setIsLandingPad(false);
6227
6228   // The instruction is gone now.
6229   MI->eraseFromParent();
6230
6231   return MBB;
6232 }
6233
6234 static
6235 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6236   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6237        E = MBB->succ_end(); I != E; ++I)
6238     if (*I != Succ)
6239       return *I;
6240   llvm_unreachable("Expecting a BB with two successors!");
6241 }
6242
6243 MachineBasicBlock *ARMTargetLowering::
6244 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6245   // This pseudo instruction has 3 operands: dst, src, size
6246   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6247   // Otherwise, we will generate unrolled scalar copies.
6248   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6249   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6250   MachineFunction::iterator It = BB;
6251   ++It;
6252
6253   unsigned dest = MI->getOperand(0).getReg();
6254   unsigned src = MI->getOperand(1).getReg();
6255   unsigned SizeVal = MI->getOperand(2).getImm();
6256   unsigned Align = MI->getOperand(3).getImm();
6257   DebugLoc dl = MI->getDebugLoc();
6258
6259   bool isThumb2 = Subtarget->isThumb2();
6260   MachineFunction *MF = BB->getParent();
6261   MachineRegisterInfo &MRI = MF->getRegInfo();
6262   unsigned ldrOpc, strOpc, UnitSize;
6263
6264   const TargetRegisterClass *TRC = isThumb2 ?
6265     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6266     (const TargetRegisterClass*)&ARM::GPRRegClass;
6267
6268   if (Align & 1) {
6269     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6270     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6271     UnitSize = 1;
6272   } else if (Align & 2) {
6273     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6274     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6275     UnitSize = 2;
6276   } else {
6277     ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6278     strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6279     UnitSize = 4;
6280   }
6281   unsigned BytesLeft = SizeVal % UnitSize;
6282   unsigned LoopSize = SizeVal - BytesLeft;
6283
6284   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6285     // Use LDR and STR to copy.
6286     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6287     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6288     unsigned srcIn = src;
6289     unsigned destIn = dest;
6290     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6291       unsigned scratch = MRI.createVirtualRegister(TRC);
6292       unsigned srcOut = MRI.createVirtualRegister(TRC);
6293       unsigned destOut = MRI.createVirtualRegister(TRC);
6294       if (isThumb2) {
6295         AddDefaultPred(BuildMI(*BB, MI, dl,
6296           TII->get(ldrOpc), scratch)
6297           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6298
6299         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6300           .addReg(scratch).addReg(destIn)
6301           .addImm(UnitSize));
6302       } else {
6303         AddDefaultPred(BuildMI(*BB, MI, dl,
6304           TII->get(ldrOpc), scratch)
6305           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6306           .addImm(UnitSize));
6307
6308         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6309           .addReg(scratch).addReg(destIn)
6310           .addReg(0).addImm(UnitSize));
6311       }
6312       srcIn = srcOut;
6313       destIn = destOut;
6314     }
6315
6316     // Handle the leftover bytes with LDRB and STRB.
6317     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6318     // [destOut] = STRB_POST(scratch, destIn, 1)
6319     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6320     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6321     for (unsigned i = 0; i < BytesLeft; i++) {
6322       unsigned scratch = MRI.createVirtualRegister(TRC);
6323       unsigned srcOut = MRI.createVirtualRegister(TRC);
6324       unsigned destOut = MRI.createVirtualRegister(TRC);
6325       if (isThumb2) {
6326         AddDefaultPred(BuildMI(*BB, MI, dl,
6327           TII->get(ldrOpc),scratch)
6328           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6329
6330         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6331           .addReg(scratch).addReg(destIn)
6332           .addReg(0).addImm(1));
6333       } else {
6334         AddDefaultPred(BuildMI(*BB, MI, dl,
6335           TII->get(ldrOpc),scratch)
6336           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6337
6338         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6339           .addReg(scratch).addReg(destIn)
6340           .addReg(0).addImm(1));
6341       }
6342       srcIn = srcOut;
6343       destIn = destOut;
6344     }
6345     MI->eraseFromParent();   // The instruction is gone now.
6346     return BB;
6347   }
6348
6349   // Expand the pseudo op to a loop.
6350   // thisMBB:
6351   //   ...
6352   //   movw varEnd, # --> with thumb2
6353   //   movt varEnd, #
6354   //   ldrcp varEnd, idx --> without thumb2
6355   //   fallthrough --> loopMBB
6356   // loopMBB:
6357   //   PHI varPhi, varEnd, varLoop
6358   //   PHI srcPhi, src, srcLoop
6359   //   PHI destPhi, dst, destLoop
6360   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6361   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6362   //   subs varLoop, varPhi, #UnitSize
6363   //   bne loopMBB
6364   //   fallthrough --> exitMBB
6365   // exitMBB:
6366   //   epilogue to handle left-over bytes
6367   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6368   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6369   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6370   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6371   MF->insert(It, loopMBB);
6372   MF->insert(It, exitMBB);
6373
6374   // Transfer the remainder of BB and its successor edges to exitMBB.
6375   exitMBB->splice(exitMBB->begin(), BB,
6376                   llvm::next(MachineBasicBlock::iterator(MI)),
6377                   BB->end());
6378   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6379
6380   // Load an immediate to varEnd.
6381   unsigned varEnd = MRI.createVirtualRegister(TRC);
6382   if (isThumb2) {
6383     unsigned VReg1 = varEnd;
6384     if ((LoopSize & 0xFFFF0000) != 0)
6385       VReg1 = MRI.createVirtualRegister(TRC);
6386     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6387                    .addImm(LoopSize & 0xFFFF));
6388
6389     if ((LoopSize & 0xFFFF0000) != 0)
6390       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6391                      .addReg(VReg1)
6392                      .addImm(LoopSize >> 16));
6393   } else {
6394     MachineConstantPool *ConstantPool = MF->getConstantPool();
6395     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6396     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6397
6398     // MachineConstantPool wants an explicit alignment.
6399     unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6400     if (Align == 0)
6401       Align = getTargetData()->getTypeAllocSize(C->getType());
6402     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6403
6404     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6405                    .addReg(varEnd, RegState::Define)
6406                    .addConstantPoolIndex(Idx)
6407                    .addImm(0));
6408   }
6409   BB->addSuccessor(loopMBB);
6410
6411   // Generate the loop body:
6412   //   varPhi = PHI(varLoop, varEnd)
6413   //   srcPhi = PHI(srcLoop, src)
6414   //   destPhi = PHI(destLoop, dst)
6415   MachineBasicBlock *entryBB = BB;
6416   BB = loopMBB;
6417   unsigned varLoop = MRI.createVirtualRegister(TRC);
6418   unsigned varPhi = MRI.createVirtualRegister(TRC);
6419   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6420   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6421   unsigned destLoop = MRI.createVirtualRegister(TRC);
6422   unsigned destPhi = MRI.createVirtualRegister(TRC);
6423
6424   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6425     .addReg(varLoop).addMBB(loopMBB)
6426     .addReg(varEnd).addMBB(entryBB);
6427   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6428     .addReg(srcLoop).addMBB(loopMBB)
6429     .addReg(src).addMBB(entryBB);
6430   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6431     .addReg(destLoop).addMBB(loopMBB)
6432     .addReg(dest).addMBB(entryBB);
6433
6434   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6435   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6436   unsigned scratch = MRI.createVirtualRegister(TRC);
6437   if (isThumb2) {
6438     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6439       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6440
6441     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6442       .addReg(scratch).addReg(destPhi)
6443       .addImm(UnitSize));
6444   } else {
6445     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6446       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6447       .addImm(UnitSize));
6448
6449     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6450       .addReg(scratch).addReg(destPhi)
6451       .addReg(0).addImm(UnitSize));
6452   }
6453
6454   // Decrement loop variable by UnitSize.
6455   MachineInstrBuilder MIB = BuildMI(BB, dl,
6456     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6457   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6458   MIB->getOperand(5).setReg(ARM::CPSR);
6459   MIB->getOperand(5).setIsDef(true);
6460
6461   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6462     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6463
6464   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6465   BB->addSuccessor(loopMBB);
6466   BB->addSuccessor(exitMBB);
6467
6468   // Add epilogue to handle BytesLeft.
6469   BB = exitMBB;
6470   MachineInstr *StartOfExit = exitMBB->begin();
6471   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6472   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6473
6474   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6475   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6476   unsigned srcIn = srcLoop;
6477   unsigned destIn = destLoop;
6478   for (unsigned i = 0; i < BytesLeft; i++) {
6479     unsigned scratch = MRI.createVirtualRegister(TRC);
6480     unsigned srcOut = MRI.createVirtualRegister(TRC);
6481     unsigned destOut = MRI.createVirtualRegister(TRC);
6482     if (isThumb2) {
6483       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6484         TII->get(ldrOpc),scratch)
6485         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6486
6487       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6488         .addReg(scratch).addReg(destIn)
6489         .addImm(1));
6490     } else {
6491       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6492         TII->get(ldrOpc),scratch)
6493         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6494
6495       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6496         .addReg(scratch).addReg(destIn)
6497         .addReg(0).addImm(1));
6498     }
6499     srcIn = srcOut;
6500     destIn = destOut;
6501   }
6502
6503   MI->eraseFromParent();   // The instruction is gone now.
6504   return BB;
6505 }
6506
6507 MachineBasicBlock *
6508 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6509                                                MachineBasicBlock *BB) const {
6510   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6511   DebugLoc dl = MI->getDebugLoc();
6512   bool isThumb2 = Subtarget->isThumb2();
6513   switch (MI->getOpcode()) {
6514   default: {
6515     MI->dump();
6516     llvm_unreachable("Unexpected instr type to insert");
6517   }
6518   // The Thumb2 pre-indexed stores have the same MI operands, they just
6519   // define them differently in the .td files from the isel patterns, so
6520   // they need pseudos.
6521   case ARM::t2STR_preidx:
6522     MI->setDesc(TII->get(ARM::t2STR_PRE));
6523     return BB;
6524   case ARM::t2STRB_preidx:
6525     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6526     return BB;
6527   case ARM::t2STRH_preidx:
6528     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6529     return BB;
6530
6531   case ARM::STRi_preidx:
6532   case ARM::STRBi_preidx: {
6533     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6534       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6535     // Decode the offset.
6536     unsigned Offset = MI->getOperand(4).getImm();
6537     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6538     Offset = ARM_AM::getAM2Offset(Offset);
6539     if (isSub)
6540       Offset = -Offset;
6541
6542     MachineMemOperand *MMO = *MI->memoperands_begin();
6543     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6544       .addOperand(MI->getOperand(0))  // Rn_wb
6545       .addOperand(MI->getOperand(1))  // Rt
6546       .addOperand(MI->getOperand(2))  // Rn
6547       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6548       .addOperand(MI->getOperand(5))  // pred
6549       .addOperand(MI->getOperand(6))
6550       .addMemOperand(MMO);
6551     MI->eraseFromParent();
6552     return BB;
6553   }
6554   case ARM::STRr_preidx:
6555   case ARM::STRBr_preidx:
6556   case ARM::STRH_preidx: {
6557     unsigned NewOpc;
6558     switch (MI->getOpcode()) {
6559     default: llvm_unreachable("unexpected opcode!");
6560     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6561     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6562     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6563     }
6564     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6565     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6566       MIB.addOperand(MI->getOperand(i));
6567     MI->eraseFromParent();
6568     return BB;
6569   }
6570   case ARM::ATOMIC_LOAD_ADD_I8:
6571      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6572   case ARM::ATOMIC_LOAD_ADD_I16:
6573      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6574   case ARM::ATOMIC_LOAD_ADD_I32:
6575      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6576
6577   case ARM::ATOMIC_LOAD_AND_I8:
6578      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6579   case ARM::ATOMIC_LOAD_AND_I16:
6580      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6581   case ARM::ATOMIC_LOAD_AND_I32:
6582      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6583
6584   case ARM::ATOMIC_LOAD_OR_I8:
6585      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6586   case ARM::ATOMIC_LOAD_OR_I16:
6587      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6588   case ARM::ATOMIC_LOAD_OR_I32:
6589      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6590
6591   case ARM::ATOMIC_LOAD_XOR_I8:
6592      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6593   case ARM::ATOMIC_LOAD_XOR_I16:
6594      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6595   case ARM::ATOMIC_LOAD_XOR_I32:
6596      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6597
6598   case ARM::ATOMIC_LOAD_NAND_I8:
6599      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6600   case ARM::ATOMIC_LOAD_NAND_I16:
6601      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6602   case ARM::ATOMIC_LOAD_NAND_I32:
6603      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6604
6605   case ARM::ATOMIC_LOAD_SUB_I8:
6606      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6607   case ARM::ATOMIC_LOAD_SUB_I16:
6608      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6609   case ARM::ATOMIC_LOAD_SUB_I32:
6610      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6611
6612   case ARM::ATOMIC_LOAD_MIN_I8:
6613      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6614   case ARM::ATOMIC_LOAD_MIN_I16:
6615      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6616   case ARM::ATOMIC_LOAD_MIN_I32:
6617      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6618
6619   case ARM::ATOMIC_LOAD_MAX_I8:
6620      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6621   case ARM::ATOMIC_LOAD_MAX_I16:
6622      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6623   case ARM::ATOMIC_LOAD_MAX_I32:
6624      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6625
6626   case ARM::ATOMIC_LOAD_UMIN_I8:
6627      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6628   case ARM::ATOMIC_LOAD_UMIN_I16:
6629      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6630   case ARM::ATOMIC_LOAD_UMIN_I32:
6631      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6632
6633   case ARM::ATOMIC_LOAD_UMAX_I8:
6634      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6635   case ARM::ATOMIC_LOAD_UMAX_I16:
6636      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6637   case ARM::ATOMIC_LOAD_UMAX_I32:
6638      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6639
6640   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6641   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6642   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6643
6644   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6645   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6646   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6647
6648
6649   case ARM::ATOMADD6432:
6650     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6651                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6652                               /*NeedsCarry*/ true);
6653   case ARM::ATOMSUB6432:
6654     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6655                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6656                               /*NeedsCarry*/ true);
6657   case ARM::ATOMOR6432:
6658     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6659                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6660   case ARM::ATOMXOR6432:
6661     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6662                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6663   case ARM::ATOMAND6432:
6664     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6665                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6666   case ARM::ATOMSWAP6432:
6667     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6668   case ARM::ATOMCMPXCHG6432:
6669     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6670                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6671                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6672
6673   case ARM::tMOVCCr_pseudo: {
6674     // To "insert" a SELECT_CC instruction, we actually have to insert the
6675     // diamond control-flow pattern.  The incoming instruction knows the
6676     // destination vreg to set, the condition code register to branch on, the
6677     // true/false values to select between, and a branch opcode to use.
6678     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6679     MachineFunction::iterator It = BB;
6680     ++It;
6681
6682     //  thisMBB:
6683     //  ...
6684     //   TrueVal = ...
6685     //   cmpTY ccX, r1, r2
6686     //   bCC copy1MBB
6687     //   fallthrough --> copy0MBB
6688     MachineBasicBlock *thisMBB  = BB;
6689     MachineFunction *F = BB->getParent();
6690     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6691     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6692     F->insert(It, copy0MBB);
6693     F->insert(It, sinkMBB);
6694
6695     // Transfer the remainder of BB and its successor edges to sinkMBB.
6696     sinkMBB->splice(sinkMBB->begin(), BB,
6697                     llvm::next(MachineBasicBlock::iterator(MI)),
6698                     BB->end());
6699     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6700
6701     BB->addSuccessor(copy0MBB);
6702     BB->addSuccessor(sinkMBB);
6703
6704     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6705       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6706
6707     //  copy0MBB:
6708     //   %FalseValue = ...
6709     //   # fallthrough to sinkMBB
6710     BB = copy0MBB;
6711
6712     // Update machine-CFG edges
6713     BB->addSuccessor(sinkMBB);
6714
6715     //  sinkMBB:
6716     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6717     //  ...
6718     BB = sinkMBB;
6719     BuildMI(*BB, BB->begin(), dl,
6720             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6721       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6722       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6723
6724     MI->eraseFromParent();   // The pseudo instruction is gone now.
6725     return BB;
6726   }
6727
6728   case ARM::BCCi64:
6729   case ARM::BCCZi64: {
6730     // If there is an unconditional branch to the other successor, remove it.
6731     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6732
6733     // Compare both parts that make up the double comparison separately for
6734     // equality.
6735     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6736
6737     unsigned LHS1 = MI->getOperand(1).getReg();
6738     unsigned LHS2 = MI->getOperand(2).getReg();
6739     if (RHSisZero) {
6740       AddDefaultPred(BuildMI(BB, dl,
6741                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6742                      .addReg(LHS1).addImm(0));
6743       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6744         .addReg(LHS2).addImm(0)
6745         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6746     } else {
6747       unsigned RHS1 = MI->getOperand(3).getReg();
6748       unsigned RHS2 = MI->getOperand(4).getReg();
6749       AddDefaultPred(BuildMI(BB, dl,
6750                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6751                      .addReg(LHS1).addReg(RHS1));
6752       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6753         .addReg(LHS2).addReg(RHS2)
6754         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6755     }
6756
6757     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6758     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6759     if (MI->getOperand(0).getImm() == ARMCC::NE)
6760       std::swap(destMBB, exitMBB);
6761
6762     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6763       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6764     if (isThumb2)
6765       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6766     else
6767       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6768
6769     MI->eraseFromParent();   // The pseudo instruction is gone now.
6770     return BB;
6771   }
6772
6773   case ARM::Int_eh_sjlj_setjmp:
6774   case ARM::Int_eh_sjlj_setjmp_nofp:
6775   case ARM::tInt_eh_sjlj_setjmp:
6776   case ARM::t2Int_eh_sjlj_setjmp:
6777   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6778     EmitSjLjDispatchBlock(MI, BB);
6779     return BB;
6780
6781   case ARM::ABS:
6782   case ARM::t2ABS: {
6783     // To insert an ABS instruction, we have to insert the
6784     // diamond control-flow pattern.  The incoming instruction knows the
6785     // source vreg to test against 0, the destination vreg to set,
6786     // the condition code register to branch on, the
6787     // true/false values to select between, and a branch opcode to use.
6788     // It transforms
6789     //     V1 = ABS V0
6790     // into
6791     //     V2 = MOVS V0
6792     //     BCC                      (branch to SinkBB if V0 >= 0)
6793     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6794     //     SinkBB: V1 = PHI(V2, V3)
6795     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6796     MachineFunction::iterator BBI = BB;
6797     ++BBI;
6798     MachineFunction *Fn = BB->getParent();
6799     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6800     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6801     Fn->insert(BBI, RSBBB);
6802     Fn->insert(BBI, SinkBB);
6803
6804     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6805     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6806     bool isThumb2 = Subtarget->isThumb2();
6807     MachineRegisterInfo &MRI = Fn->getRegInfo();
6808     // In Thumb mode S must not be specified if source register is the SP or
6809     // PC and if destination register is the SP, so restrict register class
6810     unsigned NewMovDstReg = MRI.createVirtualRegister(isThumb2 ?
6811       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6812       (const TargetRegisterClass*)&ARM::GPRRegClass);
6813     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6814       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6815       (const TargetRegisterClass*)&ARM::GPRRegClass);
6816
6817     // Transfer the remainder of BB and its successor edges to sinkMBB.
6818     SinkBB->splice(SinkBB->begin(), BB,
6819       llvm::next(MachineBasicBlock::iterator(MI)),
6820       BB->end());
6821     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6822
6823     BB->addSuccessor(RSBBB);
6824     BB->addSuccessor(SinkBB);
6825
6826     // fall through to SinkMBB
6827     RSBBB->addSuccessor(SinkBB);
6828
6829     // insert a movs at the end of BB
6830     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6831       NewMovDstReg)
6832       .addReg(ABSSrcReg, RegState::Kill)
6833       .addImm((unsigned)ARMCC::AL).addReg(0)
6834       .addReg(ARM::CPSR, RegState::Define);
6835
6836     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6837     BuildMI(BB, dl,
6838       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6839       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6840
6841     // insert rsbri in RSBBB
6842     // Note: BCC and rsbri will be converted into predicated rsbmi
6843     // by if-conversion pass
6844     BuildMI(*RSBBB, RSBBB->begin(), dl,
6845       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6846       .addReg(NewMovDstReg, RegState::Kill)
6847       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6848
6849     // insert PHI in SinkBB,
6850     // reuse ABSDstReg to not change uses of ABS instruction
6851     BuildMI(*SinkBB, SinkBB->begin(), dl,
6852       TII->get(ARM::PHI), ABSDstReg)
6853       .addReg(NewRsbDstReg).addMBB(RSBBB)
6854       .addReg(NewMovDstReg).addMBB(BB);
6855
6856     // remove ABS instruction
6857     MI->eraseFromParent();
6858
6859     // return last added BB
6860     return SinkBB;
6861   }
6862   case ARM::COPY_STRUCT_BYVAL_I32:
6863     ++NumLoopByVals;
6864     return EmitStructByval(MI, BB);
6865   }
6866 }
6867
6868 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6869                                                       SDNode *Node) const {
6870   if (!MI->hasPostISelHook()) {
6871     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6872            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6873     return;
6874   }
6875
6876   const MCInstrDesc *MCID = &MI->getDesc();
6877   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6878   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6879   // operand is still set to noreg. If needed, set the optional operand's
6880   // register to CPSR, and remove the redundant implicit def.
6881   //
6882   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6883
6884   // Rename pseudo opcodes.
6885   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6886   if (NewOpc) {
6887     const ARMBaseInstrInfo *TII =
6888       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6889     MCID = &TII->get(NewOpc);
6890
6891     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6892            "converted opcode should be the same except for cc_out");
6893
6894     MI->setDesc(*MCID);
6895
6896     // Add the optional cc_out operand
6897     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6898   }
6899   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6900
6901   // Any ARM instruction that sets the 's' bit should specify an optional
6902   // "cc_out" operand in the last operand position.
6903   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6904     assert(!NewOpc && "Optional cc_out operand required");
6905     return;
6906   }
6907   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6908   // since we already have an optional CPSR def.
6909   bool definesCPSR = false;
6910   bool deadCPSR = false;
6911   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6912        i != e; ++i) {
6913     const MachineOperand &MO = MI->getOperand(i);
6914     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6915       definesCPSR = true;
6916       if (MO.isDead())
6917         deadCPSR = true;
6918       MI->RemoveOperand(i);
6919       break;
6920     }
6921   }
6922   if (!definesCPSR) {
6923     assert(!NewOpc && "Optional cc_out operand required");
6924     return;
6925   }
6926   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6927   if (deadCPSR) {
6928     assert(!MI->getOperand(ccOutIdx).getReg() &&
6929            "expect uninitialized optional cc_out operand");
6930     return;
6931   }
6932
6933   // If this instruction was defined with an optional CPSR def and its dag node
6934   // had a live implicit CPSR def, then activate the optional CPSR def.
6935   MachineOperand &MO = MI->getOperand(ccOutIdx);
6936   MO.setReg(ARM::CPSR);
6937   MO.setIsDef(true);
6938 }
6939
6940 //===----------------------------------------------------------------------===//
6941 //                           ARM Optimization Hooks
6942 //===----------------------------------------------------------------------===//
6943
6944 static
6945 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6946                             TargetLowering::DAGCombinerInfo &DCI) {
6947   SelectionDAG &DAG = DCI.DAG;
6948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6949   EVT VT = N->getValueType(0);
6950   unsigned Opc = N->getOpcode();
6951   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6952   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6953   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6954   ISD::CondCode CC = ISD::SETCC_INVALID;
6955
6956   if (isSlctCC) {
6957     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6958   } else {
6959     SDValue CCOp = Slct.getOperand(0);
6960     if (CCOp.getOpcode() == ISD::SETCC)
6961       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6962   }
6963
6964   bool DoXform = false;
6965   bool InvCC = false;
6966   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6967           "Bad input!");
6968
6969   if (LHS.getOpcode() == ISD::Constant &&
6970       cast<ConstantSDNode>(LHS)->isNullValue()) {
6971     DoXform = true;
6972   } else if (CC != ISD::SETCC_INVALID &&
6973              RHS.getOpcode() == ISD::Constant &&
6974              cast<ConstantSDNode>(RHS)->isNullValue()) {
6975     std::swap(LHS, RHS);
6976     SDValue Op0 = Slct.getOperand(0);
6977     EVT OpVT = isSlctCC ? Op0.getValueType() :
6978                           Op0.getOperand(0).getValueType();
6979     bool isInt = OpVT.isInteger();
6980     CC = ISD::getSetCCInverse(CC, isInt);
6981
6982     if (!TLI.isCondCodeLegal(CC, OpVT))
6983       return SDValue();         // Inverse operator isn't legal.
6984
6985     DoXform = true;
6986     InvCC = true;
6987   }
6988
6989   if (DoXform) {
6990     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6991     if (isSlctCC)
6992       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6993                              Slct.getOperand(0), Slct.getOperand(1), CC);
6994     SDValue CCOp = Slct.getOperand(0);
6995     if (InvCC)
6996       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6997                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
6998     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6999                        CCOp, OtherOp, Result);
7000   }
7001   return SDValue();
7002 }
7003
7004 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7005 // (only after legalization).
7006 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7007                                  TargetLowering::DAGCombinerInfo &DCI,
7008                                  const ARMSubtarget *Subtarget) {
7009
7010   // Only perform optimization if after legalize, and if NEON is available. We
7011   // also expected both operands to be BUILD_VECTORs.
7012   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7013       || N0.getOpcode() != ISD::BUILD_VECTOR
7014       || N1.getOpcode() != ISD::BUILD_VECTOR)
7015     return SDValue();
7016
7017   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7018   EVT VT = N->getValueType(0);
7019   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7020     return SDValue();
7021
7022   // Check that the vector operands are of the right form.
7023   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7024   // operands, where N is the size of the formed vector.
7025   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7026   // index such that we have a pair wise add pattern.
7027
7028   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7029   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7030     return SDValue();
7031   SDValue Vec = N0->getOperand(0)->getOperand(0);
7032   SDNode *V = Vec.getNode();
7033   unsigned nextIndex = 0;
7034
7035   // For each operands to the ADD which are BUILD_VECTORs,
7036   // check to see if each of their operands are an EXTRACT_VECTOR with
7037   // the same vector and appropriate index.
7038   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7039     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7040         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7041
7042       SDValue ExtVec0 = N0->getOperand(i);
7043       SDValue ExtVec1 = N1->getOperand(i);
7044
7045       // First operand is the vector, verify its the same.
7046       if (V != ExtVec0->getOperand(0).getNode() ||
7047           V != ExtVec1->getOperand(0).getNode())
7048         return SDValue();
7049
7050       // Second is the constant, verify its correct.
7051       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7052       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7053
7054       // For the constant, we want to see all the even or all the odd.
7055       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7056           || C1->getZExtValue() != nextIndex+1)
7057         return SDValue();
7058
7059       // Increment index.
7060       nextIndex+=2;
7061     } else
7062       return SDValue();
7063   }
7064
7065   // Create VPADDL node.
7066   SelectionDAG &DAG = DCI.DAG;
7067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7068
7069   // Build operand list.
7070   SmallVector<SDValue, 8> Ops;
7071   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7072                                 TLI.getPointerTy()));
7073
7074   // Input is the vector.
7075   Ops.push_back(Vec);
7076
7077   // Get widened type and narrowed type.
7078   MVT widenType;
7079   unsigned numElem = VT.getVectorNumElements();
7080   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7081     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7082     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7083     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7084     default:
7085       llvm_unreachable("Invalid vector element type for padd optimization.");
7086   }
7087
7088   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7089                             widenType, &Ops[0], Ops.size());
7090   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7091 }
7092
7093 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7094 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7095 /// called with the default operands, and if that fails, with commuted
7096 /// operands.
7097 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7098                                           TargetLowering::DAGCombinerInfo &DCI,
7099                                           const ARMSubtarget *Subtarget){
7100
7101   // Attempt to create vpaddl for this add.
7102   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7103   if (Result.getNode())
7104     return Result;
7105
7106   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7107   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
7108     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7109     if (Result.getNode()) return Result;
7110   }
7111   return SDValue();
7112 }
7113
7114 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7115 ///
7116 static SDValue PerformADDCombine(SDNode *N,
7117                                  TargetLowering::DAGCombinerInfo &DCI,
7118                                  const ARMSubtarget *Subtarget) {
7119   SDValue N0 = N->getOperand(0);
7120   SDValue N1 = N->getOperand(1);
7121
7122   // First try with the default operand order.
7123   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7124   if (Result.getNode())
7125     return Result;
7126
7127   // If that didn't work, try again with the operands commuted.
7128   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7129 }
7130
7131 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7132 ///
7133 static SDValue PerformSUBCombine(SDNode *N,
7134                                  TargetLowering::DAGCombinerInfo &DCI) {
7135   SDValue N0 = N->getOperand(0);
7136   SDValue N1 = N->getOperand(1);
7137
7138   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7139   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
7140     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7141     if (Result.getNode()) return Result;
7142   }
7143
7144   return SDValue();
7145 }
7146
7147 /// PerformVMULCombine
7148 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7149 /// special multiplier accumulator forwarding.
7150 ///   vmul d3, d0, d2
7151 ///   vmla d3, d1, d2
7152 /// is faster than
7153 ///   vadd d3, d0, d1
7154 ///   vmul d3, d3, d2
7155 static SDValue PerformVMULCombine(SDNode *N,
7156                                   TargetLowering::DAGCombinerInfo &DCI,
7157                                   const ARMSubtarget *Subtarget) {
7158   if (!Subtarget->hasVMLxForwarding())
7159     return SDValue();
7160
7161   SelectionDAG &DAG = DCI.DAG;
7162   SDValue N0 = N->getOperand(0);
7163   SDValue N1 = N->getOperand(1);
7164   unsigned Opcode = N0.getOpcode();
7165   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7166       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7167     Opcode = N1.getOpcode();
7168     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7169         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7170       return SDValue();
7171     std::swap(N0, N1);
7172   }
7173
7174   EVT VT = N->getValueType(0);
7175   DebugLoc DL = N->getDebugLoc();
7176   SDValue N00 = N0->getOperand(0);
7177   SDValue N01 = N0->getOperand(1);
7178   return DAG.getNode(Opcode, DL, VT,
7179                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7180                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7181 }
7182
7183 static SDValue PerformMULCombine(SDNode *N,
7184                                  TargetLowering::DAGCombinerInfo &DCI,
7185                                  const ARMSubtarget *Subtarget) {
7186   SelectionDAG &DAG = DCI.DAG;
7187
7188   if (Subtarget->isThumb1Only())
7189     return SDValue();
7190
7191   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7192     return SDValue();
7193
7194   EVT VT = N->getValueType(0);
7195   if (VT.is64BitVector() || VT.is128BitVector())
7196     return PerformVMULCombine(N, DCI, Subtarget);
7197   if (VT != MVT::i32)
7198     return SDValue();
7199
7200   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7201   if (!C)
7202     return SDValue();
7203
7204   int64_t MulAmt = C->getSExtValue();
7205   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7206
7207   ShiftAmt = ShiftAmt & (32 - 1);
7208   SDValue V = N->getOperand(0);
7209   DebugLoc DL = N->getDebugLoc();
7210
7211   SDValue Res;
7212   MulAmt >>= ShiftAmt;
7213
7214   if (MulAmt >= 0) {
7215     if (isPowerOf2_32(MulAmt - 1)) {
7216       // (mul x, 2^N + 1) => (add (shl x, N), x)
7217       Res = DAG.getNode(ISD::ADD, DL, VT,
7218                         V,
7219                         DAG.getNode(ISD::SHL, DL, VT,
7220                                     V,
7221                                     DAG.getConstant(Log2_32(MulAmt - 1),
7222                                                     MVT::i32)));
7223     } else if (isPowerOf2_32(MulAmt + 1)) {
7224       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7225       Res = DAG.getNode(ISD::SUB, DL, VT,
7226                         DAG.getNode(ISD::SHL, DL, VT,
7227                                     V,
7228                                     DAG.getConstant(Log2_32(MulAmt + 1),
7229                                                     MVT::i32)),
7230                         V);
7231     } else
7232       return SDValue();
7233   } else {
7234     uint64_t MulAmtAbs = -MulAmt;
7235     if (isPowerOf2_32(MulAmtAbs + 1)) {
7236       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7237       Res = DAG.getNode(ISD::SUB, DL, VT,
7238                         V,
7239                         DAG.getNode(ISD::SHL, DL, VT,
7240                                     V,
7241                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7242                                                     MVT::i32)));
7243     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7244       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7245       Res = DAG.getNode(ISD::ADD, DL, VT,
7246                         V,
7247                         DAG.getNode(ISD::SHL, DL, VT,
7248                                     V,
7249                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7250                                                     MVT::i32)));
7251       Res = DAG.getNode(ISD::SUB, DL, VT,
7252                         DAG.getConstant(0, MVT::i32),Res);
7253
7254     } else
7255       return SDValue();
7256   }
7257
7258   if (ShiftAmt != 0)
7259     Res = DAG.getNode(ISD::SHL, DL, VT,
7260                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7261
7262   // Do not add new nodes to DAG combiner worklist.
7263   DCI.CombineTo(N, Res, false);
7264   return SDValue();
7265 }
7266
7267 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
7268   if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
7269     return false;
7270
7271   SDValue FalseVal = N.getOperand(0);
7272   ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
7273   if (!C)
7274     return false;
7275   if (AllOnes)
7276     return C->isAllOnesValue();
7277   return C->isNullValue();
7278 }
7279
7280 /// formConditionalOp - Combine an operation with a conditional move operand
7281 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7282 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7283 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7284                                  bool Commutable) {
7285   SDValue N0 = N->getOperand(0);
7286   SDValue N1 = N->getOperand(1);
7287
7288   bool isAND = N->getOpcode() == ISD::AND;
7289   bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7290   if (!isCand && Commutable) {
7291     isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7292     if (isCand)
7293       std::swap(N0, N1);
7294   }
7295   if (!isCand)
7296     return SDValue();
7297
7298   unsigned Opc = 0;
7299   switch (N->getOpcode()) {
7300   default: llvm_unreachable("Unexpected node");
7301   case ISD::AND: Opc = ARMISD::CAND; break;
7302   case ISD::OR:  Opc = ARMISD::COR; break;
7303   case ISD::XOR: Opc = ARMISD::CXOR; break;
7304   }
7305   return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7306                      N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7307                      N1.getOperand(4));
7308 }
7309
7310 static SDValue PerformANDCombine(SDNode *N,
7311                                  TargetLowering::DAGCombinerInfo &DCI,
7312                                  const ARMSubtarget *Subtarget) {
7313
7314   // Attempt to use immediate-form VBIC
7315   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7316   DebugLoc dl = N->getDebugLoc();
7317   EVT VT = N->getValueType(0);
7318   SelectionDAG &DAG = DCI.DAG;
7319
7320   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7321     return SDValue();
7322
7323   APInt SplatBits, SplatUndef;
7324   unsigned SplatBitSize;
7325   bool HasAnyUndefs;
7326   if (BVN &&
7327       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7328     if (SplatBitSize <= 64) {
7329       EVT VbicVT;
7330       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7331                                       SplatUndef.getZExtValue(), SplatBitSize,
7332                                       DAG, VbicVT, VT.is128BitVector(),
7333                                       OtherModImm);
7334       if (Val.getNode()) {
7335         SDValue Input =
7336           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7337         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7338         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7339       }
7340     }
7341   }
7342
7343   if (!Subtarget->isThumb1Only()) {
7344     // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7345     SDValue CAND = formConditionalOp(N, DAG, true);
7346     if (CAND.getNode())
7347       return CAND;
7348   }
7349
7350   return SDValue();
7351 }
7352
7353 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7354 static SDValue PerformORCombine(SDNode *N,
7355                                 TargetLowering::DAGCombinerInfo &DCI,
7356                                 const ARMSubtarget *Subtarget) {
7357   // Attempt to use immediate-form VORR
7358   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7359   DebugLoc dl = N->getDebugLoc();
7360   EVT VT = N->getValueType(0);
7361   SelectionDAG &DAG = DCI.DAG;
7362
7363   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7364     return SDValue();
7365
7366   APInt SplatBits, SplatUndef;
7367   unsigned SplatBitSize;
7368   bool HasAnyUndefs;
7369   if (BVN && Subtarget->hasNEON() &&
7370       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7371     if (SplatBitSize <= 64) {
7372       EVT VorrVT;
7373       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7374                                       SplatUndef.getZExtValue(), SplatBitSize,
7375                                       DAG, VorrVT, VT.is128BitVector(),
7376                                       OtherModImm);
7377       if (Val.getNode()) {
7378         SDValue Input =
7379           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7380         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7381         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7382       }
7383     }
7384   }
7385
7386   if (!Subtarget->isThumb1Only()) {
7387     // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7388     SDValue COR = formConditionalOp(N, DAG, true);
7389     if (COR.getNode())
7390       return COR;
7391   }
7392
7393   SDValue N0 = N->getOperand(0);
7394   if (N0.getOpcode() != ISD::AND)
7395     return SDValue();
7396   SDValue N1 = N->getOperand(1);
7397
7398   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7399   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7400       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7401     APInt SplatUndef;
7402     unsigned SplatBitSize;
7403     bool HasAnyUndefs;
7404
7405     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7406     APInt SplatBits0;
7407     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7408                                   HasAnyUndefs) && !HasAnyUndefs) {
7409       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7410       APInt SplatBits1;
7411       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7412                                     HasAnyUndefs) && !HasAnyUndefs &&
7413           SplatBits0 == ~SplatBits1) {
7414         // Canonicalize the vector type to make instruction selection simpler.
7415         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7416         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7417                                      N0->getOperand(1), N0->getOperand(0),
7418                                      N1->getOperand(0));
7419         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7420       }
7421     }
7422   }
7423
7424   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7425   // reasonable.
7426
7427   // BFI is only available on V6T2+
7428   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7429     return SDValue();
7430
7431   DebugLoc DL = N->getDebugLoc();
7432   // 1) or (and A, mask), val => ARMbfi A, val, mask
7433   //      iff (val & mask) == val
7434   //
7435   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7436   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7437   //          && mask == ~mask2
7438   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7439   //          && ~mask == mask2
7440   //  (i.e., copy a bitfield value into another bitfield of the same width)
7441
7442   if (VT != MVT::i32)
7443     return SDValue();
7444
7445   SDValue N00 = N0.getOperand(0);
7446
7447   // The value and the mask need to be constants so we can verify this is
7448   // actually a bitfield set. If the mask is 0xffff, we can do better
7449   // via a movt instruction, so don't use BFI in that case.
7450   SDValue MaskOp = N0.getOperand(1);
7451   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7452   if (!MaskC)
7453     return SDValue();
7454   unsigned Mask = MaskC->getZExtValue();
7455   if (Mask == 0xffff)
7456     return SDValue();
7457   SDValue Res;
7458   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7460   if (N1C) {
7461     unsigned Val = N1C->getZExtValue();
7462     if ((Val & ~Mask) != Val)
7463       return SDValue();
7464
7465     if (ARM::isBitFieldInvertedMask(Mask)) {
7466       Val >>= CountTrailingZeros_32(~Mask);
7467
7468       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7469                         DAG.getConstant(Val, MVT::i32),
7470                         DAG.getConstant(Mask, MVT::i32));
7471
7472       // Do not add new nodes to DAG combiner worklist.
7473       DCI.CombineTo(N, Res, false);
7474       return SDValue();
7475     }
7476   } else if (N1.getOpcode() == ISD::AND) {
7477     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7478     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7479     if (!N11C)
7480       return SDValue();
7481     unsigned Mask2 = N11C->getZExtValue();
7482
7483     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7484     // as is to match.
7485     if (ARM::isBitFieldInvertedMask(Mask) &&
7486         (Mask == ~Mask2)) {
7487       // The pack halfword instruction works better for masks that fit it,
7488       // so use that when it's available.
7489       if (Subtarget->hasT2ExtractPack() &&
7490           (Mask == 0xffff || Mask == 0xffff0000))
7491         return SDValue();
7492       // 2a
7493       unsigned amt = CountTrailingZeros_32(Mask2);
7494       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7495                         DAG.getConstant(amt, MVT::i32));
7496       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7497                         DAG.getConstant(Mask, MVT::i32));
7498       // Do not add new nodes to DAG combiner worklist.
7499       DCI.CombineTo(N, Res, false);
7500       return SDValue();
7501     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7502                (~Mask == Mask2)) {
7503       // The pack halfword instruction works better for masks that fit it,
7504       // so use that when it's available.
7505       if (Subtarget->hasT2ExtractPack() &&
7506           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7507         return SDValue();
7508       // 2b
7509       unsigned lsb = CountTrailingZeros_32(Mask);
7510       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7511                         DAG.getConstant(lsb, MVT::i32));
7512       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7513                         DAG.getConstant(Mask2, MVT::i32));
7514       // Do not add new nodes to DAG combiner worklist.
7515       DCI.CombineTo(N, Res, false);
7516       return SDValue();
7517     }
7518   }
7519
7520   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7521       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7522       ARM::isBitFieldInvertedMask(~Mask)) {
7523     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7524     // where lsb(mask) == #shamt and masked bits of B are known zero.
7525     SDValue ShAmt = N00.getOperand(1);
7526     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7527     unsigned LSB = CountTrailingZeros_32(Mask);
7528     if (ShAmtC != LSB)
7529       return SDValue();
7530
7531     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7532                       DAG.getConstant(~Mask, MVT::i32));
7533
7534     // Do not add new nodes to DAG combiner worklist.
7535     DCI.CombineTo(N, Res, false);
7536   }
7537
7538   return SDValue();
7539 }
7540
7541 static SDValue PerformXORCombine(SDNode *N,
7542                                  TargetLowering::DAGCombinerInfo &DCI,
7543                                  const ARMSubtarget *Subtarget) {
7544   EVT VT = N->getValueType(0);
7545   SelectionDAG &DAG = DCI.DAG;
7546
7547   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7548     return SDValue();
7549
7550   if (!Subtarget->isThumb1Only()) {
7551     // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7552     SDValue CXOR = formConditionalOp(N, DAG, true);
7553     if (CXOR.getNode())
7554       return CXOR;
7555   }
7556
7557   return SDValue();
7558 }
7559
7560 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7561 /// the bits being cleared by the AND are not demanded by the BFI.
7562 static SDValue PerformBFICombine(SDNode *N,
7563                                  TargetLowering::DAGCombinerInfo &DCI) {
7564   SDValue N1 = N->getOperand(1);
7565   if (N1.getOpcode() == ISD::AND) {
7566     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7567     if (!N11C)
7568       return SDValue();
7569     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7570     unsigned LSB = CountTrailingZeros_32(~InvMask);
7571     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7572     unsigned Mask = (1 << Width)-1;
7573     unsigned Mask2 = N11C->getZExtValue();
7574     if ((Mask & (~Mask2)) == 0)
7575       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7576                              N->getOperand(0), N1.getOperand(0),
7577                              N->getOperand(2));
7578   }
7579   return SDValue();
7580 }
7581
7582 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7583 /// ARMISD::VMOVRRD.
7584 static SDValue PerformVMOVRRDCombine(SDNode *N,
7585                                      TargetLowering::DAGCombinerInfo &DCI) {
7586   // vmovrrd(vmovdrr x, y) -> x,y
7587   SDValue InDouble = N->getOperand(0);
7588   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7589     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7590
7591   // vmovrrd(load f64) -> (load i32), (load i32)
7592   SDNode *InNode = InDouble.getNode();
7593   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7594       InNode->getValueType(0) == MVT::f64 &&
7595       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7596       !cast<LoadSDNode>(InNode)->isVolatile()) {
7597     // TODO: Should this be done for non-FrameIndex operands?
7598     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7599
7600     SelectionDAG &DAG = DCI.DAG;
7601     DebugLoc DL = LD->getDebugLoc();
7602     SDValue BasePtr = LD->getBasePtr();
7603     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7604                                  LD->getPointerInfo(), LD->isVolatile(),
7605                                  LD->isNonTemporal(), LD->isInvariant(),
7606                                  LD->getAlignment());
7607
7608     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7609                                     DAG.getConstant(4, MVT::i32));
7610     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7611                                  LD->getPointerInfo(), LD->isVolatile(),
7612                                  LD->isNonTemporal(), LD->isInvariant(),
7613                                  std::min(4U, LD->getAlignment() / 2));
7614
7615     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7616     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7617     DCI.RemoveFromWorklist(LD);
7618     DAG.DeleteNode(LD);
7619     return Result;
7620   }
7621
7622   return SDValue();
7623 }
7624
7625 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7626 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7627 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7628   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7629   SDValue Op0 = N->getOperand(0);
7630   SDValue Op1 = N->getOperand(1);
7631   if (Op0.getOpcode() == ISD::BITCAST)
7632     Op0 = Op0.getOperand(0);
7633   if (Op1.getOpcode() == ISD::BITCAST)
7634     Op1 = Op1.getOperand(0);
7635   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7636       Op0.getNode() == Op1.getNode() &&
7637       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7638     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7639                        N->getValueType(0), Op0.getOperand(0));
7640   return SDValue();
7641 }
7642
7643 /// PerformSTORECombine - Target-specific dag combine xforms for
7644 /// ISD::STORE.
7645 static SDValue PerformSTORECombine(SDNode *N,
7646                                    TargetLowering::DAGCombinerInfo &DCI) {
7647   StoreSDNode *St = cast<StoreSDNode>(N);
7648   if (St->isVolatile())
7649     return SDValue();
7650
7651   // Optimize trunc store (of multiple scalars) to shuffle and store.  First, 
7652   // pack all of the elements in one place.  Next, store to memory in fewer
7653   // chunks.
7654   SDValue StVal = St->getValue();
7655   EVT VT = StVal.getValueType();
7656   if (St->isTruncatingStore() && VT.isVector()) {
7657     SelectionDAG &DAG = DCI.DAG;
7658     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7659     EVT StVT = St->getMemoryVT();
7660     unsigned NumElems = VT.getVectorNumElements();
7661     assert(StVT != VT && "Cannot truncate to the same type");
7662     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7663     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7664
7665     // From, To sizes and ElemCount must be pow of two
7666     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7667
7668     // We are going to use the original vector elt for storing.
7669     // Accumulated smaller vector elements must be a multiple of the store size.
7670     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7671
7672     unsigned SizeRatio  = FromEltSz / ToEltSz;
7673     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7674
7675     // Create a type on which we perform the shuffle.
7676     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7677                                      NumElems*SizeRatio);
7678     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7679
7680     DebugLoc DL = St->getDebugLoc();
7681     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7682     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7683     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7684
7685     // Can't shuffle using an illegal type.
7686     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7687
7688     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7689                                 DAG.getUNDEF(WideVec.getValueType()),
7690                                 ShuffleVec.data());
7691     // At this point all of the data is stored at the bottom of the
7692     // register. We now need to save it to mem.
7693
7694     // Find the largest store unit
7695     MVT StoreType = MVT::i8;
7696     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7697          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7698       MVT Tp = (MVT::SimpleValueType)tp;
7699       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7700         StoreType = Tp;
7701     }
7702     // Didn't find a legal store type.
7703     if (!TLI.isTypeLegal(StoreType))
7704       return SDValue();
7705
7706     // Bitcast the original vector into a vector of store-size units
7707     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7708             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7709     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7710     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7711     SmallVector<SDValue, 8> Chains;
7712     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7713                                         TLI.getPointerTy());
7714     SDValue BasePtr = St->getBasePtr();
7715
7716     // Perform one or more big stores into memory.
7717     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7718     for (unsigned I = 0; I < E; I++) {
7719       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7720                                    StoreType, ShuffWide,
7721                                    DAG.getIntPtrConstant(I));
7722       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7723                                 St->getPointerInfo(), St->isVolatile(),
7724                                 St->isNonTemporal(), St->getAlignment());
7725       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7726                             Increment);
7727       Chains.push_back(Ch);
7728     }
7729     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7730                        Chains.size());
7731   }
7732
7733   if (!ISD::isNormalStore(St))
7734     return SDValue();
7735
7736   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7737   // ARM stores of arguments in the same cache line.
7738   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7739       StVal.getNode()->hasOneUse()) {
7740     SelectionDAG  &DAG = DCI.DAG;
7741     DebugLoc DL = St->getDebugLoc();
7742     SDValue BasePtr = St->getBasePtr();
7743     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7744                                   StVal.getNode()->getOperand(0), BasePtr,
7745                                   St->getPointerInfo(), St->isVolatile(),
7746                                   St->isNonTemporal(), St->getAlignment());
7747
7748     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7749                                     DAG.getConstant(4, MVT::i32));
7750     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7751                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7752                         St->isNonTemporal(),
7753                         std::min(4U, St->getAlignment() / 2));
7754   }
7755
7756   if (StVal.getValueType() != MVT::i64 ||
7757       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7758     return SDValue();
7759
7760   // Bitcast an i64 store extracted from a vector to f64.
7761   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7762   SelectionDAG &DAG = DCI.DAG;
7763   DebugLoc dl = StVal.getDebugLoc();
7764   SDValue IntVec = StVal.getOperand(0);
7765   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7766                                  IntVec.getValueType().getVectorNumElements());
7767   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7768   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7769                                Vec, StVal.getOperand(1));
7770   dl = N->getDebugLoc();
7771   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7772   // Make the DAGCombiner fold the bitcasts.
7773   DCI.AddToWorklist(Vec.getNode());
7774   DCI.AddToWorklist(ExtElt.getNode());
7775   DCI.AddToWorklist(V.getNode());
7776   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7777                       St->getPointerInfo(), St->isVolatile(),
7778                       St->isNonTemporal(), St->getAlignment(),
7779                       St->getTBAAInfo());
7780 }
7781
7782 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7783 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7784 /// i64 vector to have f64 elements, since the value can then be loaded
7785 /// directly into a VFP register.
7786 static bool hasNormalLoadOperand(SDNode *N) {
7787   unsigned NumElts = N->getValueType(0).getVectorNumElements();
7788   for (unsigned i = 0; i < NumElts; ++i) {
7789     SDNode *Elt = N->getOperand(i).getNode();
7790     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7791       return true;
7792   }
7793   return false;
7794 }
7795
7796 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7797 /// ISD::BUILD_VECTOR.
7798 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7799                                           TargetLowering::DAGCombinerInfo &DCI){
7800   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7801   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7802   // into a pair of GPRs, which is fine when the value is used as a scalar,
7803   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7804   SelectionDAG &DAG = DCI.DAG;
7805   if (N->getNumOperands() == 2) {
7806     SDValue RV = PerformVMOVDRRCombine(N, DAG);
7807     if (RV.getNode())
7808       return RV;
7809   }
7810
7811   // Load i64 elements as f64 values so that type legalization does not split
7812   // them up into i32 values.
7813   EVT VT = N->getValueType(0);
7814   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7815     return SDValue();
7816   DebugLoc dl = N->getDebugLoc();
7817   SmallVector<SDValue, 8> Ops;
7818   unsigned NumElts = VT.getVectorNumElements();
7819   for (unsigned i = 0; i < NumElts; ++i) {
7820     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7821     Ops.push_back(V);
7822     // Make the DAGCombiner fold the bitcast.
7823     DCI.AddToWorklist(V.getNode());
7824   }
7825   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7826   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7827   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7828 }
7829
7830 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7831 /// ISD::INSERT_VECTOR_ELT.
7832 static SDValue PerformInsertEltCombine(SDNode *N,
7833                                        TargetLowering::DAGCombinerInfo &DCI) {
7834   // Bitcast an i64 load inserted into a vector to f64.
7835   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7836   EVT VT = N->getValueType(0);
7837   SDNode *Elt = N->getOperand(1).getNode();
7838   if (VT.getVectorElementType() != MVT::i64 ||
7839       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7840     return SDValue();
7841
7842   SelectionDAG &DAG = DCI.DAG;
7843   DebugLoc dl = N->getDebugLoc();
7844   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7845                                  VT.getVectorNumElements());
7846   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7847   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7848   // Make the DAGCombiner fold the bitcasts.
7849   DCI.AddToWorklist(Vec.getNode());
7850   DCI.AddToWorklist(V.getNode());
7851   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7852                                Vec, V, N->getOperand(2));
7853   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7854 }
7855
7856 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7857 /// ISD::VECTOR_SHUFFLE.
7858 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7859   // The LLVM shufflevector instruction does not require the shuffle mask
7860   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7861   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7862   // operands do not match the mask length, they are extended by concatenating
7863   // them with undef vectors.  That is probably the right thing for other
7864   // targets, but for NEON it is better to concatenate two double-register
7865   // size vector operands into a single quad-register size vector.  Do that
7866   // transformation here:
7867   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7868   //   shuffle(concat(v1, v2), undef)
7869   SDValue Op0 = N->getOperand(0);
7870   SDValue Op1 = N->getOperand(1);
7871   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7872       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7873       Op0.getNumOperands() != 2 ||
7874       Op1.getNumOperands() != 2)
7875     return SDValue();
7876   SDValue Concat0Op1 = Op0.getOperand(1);
7877   SDValue Concat1Op1 = Op1.getOperand(1);
7878   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7879       Concat1Op1.getOpcode() != ISD::UNDEF)
7880     return SDValue();
7881   // Skip the transformation if any of the types are illegal.
7882   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7883   EVT VT = N->getValueType(0);
7884   if (!TLI.isTypeLegal(VT) ||
7885       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7886       !TLI.isTypeLegal(Concat1Op1.getValueType()))
7887     return SDValue();
7888
7889   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7890                                   Op0.getOperand(0), Op1.getOperand(0));
7891   // Translate the shuffle mask.
7892   SmallVector<int, 16> NewMask;
7893   unsigned NumElts = VT.getVectorNumElements();
7894   unsigned HalfElts = NumElts/2;
7895   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7896   for (unsigned n = 0; n < NumElts; ++n) {
7897     int MaskElt = SVN->getMaskElt(n);
7898     int NewElt = -1;
7899     if (MaskElt < (int)HalfElts)
7900       NewElt = MaskElt;
7901     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7902       NewElt = HalfElts + MaskElt - NumElts;
7903     NewMask.push_back(NewElt);
7904   }
7905   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7906                               DAG.getUNDEF(VT), NewMask.data());
7907 }
7908
7909 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7910 /// NEON load/store intrinsics to merge base address updates.
7911 static SDValue CombineBaseUpdate(SDNode *N,
7912                                  TargetLowering::DAGCombinerInfo &DCI) {
7913   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7914     return SDValue();
7915
7916   SelectionDAG &DAG = DCI.DAG;
7917   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7918                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7919   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7920   SDValue Addr = N->getOperand(AddrOpIdx);
7921
7922   // Search for a use of the address operand that is an increment.
7923   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7924          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7925     SDNode *User = *UI;
7926     if (User->getOpcode() != ISD::ADD ||
7927         UI.getUse().getResNo() != Addr.getResNo())
7928       continue;
7929
7930     // Check that the add is independent of the load/store.  Otherwise, folding
7931     // it would create a cycle.
7932     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7933       continue;
7934
7935     // Find the new opcode for the updating load/store.
7936     bool isLoad = true;
7937     bool isLaneOp = false;
7938     unsigned NewOpc = 0;
7939     unsigned NumVecs = 0;
7940     if (isIntrinsic) {
7941       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7942       switch (IntNo) {
7943       default: llvm_unreachable("unexpected intrinsic for Neon base update");
7944       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
7945         NumVecs = 1; break;
7946       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
7947         NumVecs = 2; break;
7948       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
7949         NumVecs = 3; break;
7950       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
7951         NumVecs = 4; break;
7952       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7953         NumVecs = 2; isLaneOp = true; break;
7954       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7955         NumVecs = 3; isLaneOp = true; break;
7956       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7957         NumVecs = 4; isLaneOp = true; break;
7958       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
7959         NumVecs = 1; isLoad = false; break;
7960       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
7961         NumVecs = 2; isLoad = false; break;
7962       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
7963         NumVecs = 3; isLoad = false; break;
7964       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
7965         NumVecs = 4; isLoad = false; break;
7966       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7967         NumVecs = 2; isLoad = false; isLaneOp = true; break;
7968       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7969         NumVecs = 3; isLoad = false; isLaneOp = true; break;
7970       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7971         NumVecs = 4; isLoad = false; isLaneOp = true; break;
7972       }
7973     } else {
7974       isLaneOp = true;
7975       switch (N->getOpcode()) {
7976       default: llvm_unreachable("unexpected opcode for Neon base update");
7977       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7978       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7979       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7980       }
7981     }
7982
7983     // Find the size of memory referenced by the load/store.
7984     EVT VecTy;
7985     if (isLoad)
7986       VecTy = N->getValueType(0);
7987     else
7988       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7989     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7990     if (isLaneOp)
7991       NumBytes /= VecTy.getVectorNumElements();
7992
7993     // If the increment is a constant, it must match the memory ref size.
7994     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7995     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7996       uint64_t IncVal = CInc->getZExtValue();
7997       if (IncVal != NumBytes)
7998         continue;
7999     } else if (NumBytes >= 3 * 16) {
8000       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8001       // separate instructions that make it harder to use a non-constant update.
8002       continue;
8003     }
8004
8005     // Create the new updating load/store node.
8006     EVT Tys[6];
8007     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8008     unsigned n;
8009     for (n = 0; n < NumResultVecs; ++n)
8010       Tys[n] = VecTy;
8011     Tys[n++] = MVT::i32;
8012     Tys[n] = MVT::Other;
8013     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8014     SmallVector<SDValue, 8> Ops;
8015     Ops.push_back(N->getOperand(0)); // incoming chain
8016     Ops.push_back(N->getOperand(AddrOpIdx));
8017     Ops.push_back(Inc);
8018     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8019       Ops.push_back(N->getOperand(i));
8020     }
8021     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8022     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8023                                            Ops.data(), Ops.size(),
8024                                            MemInt->getMemoryVT(),
8025                                            MemInt->getMemOperand());
8026
8027     // Update the uses.
8028     std::vector<SDValue> NewResults;
8029     for (unsigned i = 0; i < NumResultVecs; ++i) {
8030       NewResults.push_back(SDValue(UpdN.getNode(), i));
8031     }
8032     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8033     DCI.CombineTo(N, NewResults);
8034     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8035
8036     break;
8037   }
8038   return SDValue();
8039 }
8040
8041 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8042 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8043 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8044 /// return true.
8045 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8046   SelectionDAG &DAG = DCI.DAG;
8047   EVT VT = N->getValueType(0);
8048   // vldN-dup instructions only support 64-bit vectors for N > 1.
8049   if (!VT.is64BitVector())
8050     return false;
8051
8052   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8053   SDNode *VLD = N->getOperand(0).getNode();
8054   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8055     return false;
8056   unsigned NumVecs = 0;
8057   unsigned NewOpc = 0;
8058   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8059   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8060     NumVecs = 2;
8061     NewOpc = ARMISD::VLD2DUP;
8062   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8063     NumVecs = 3;
8064     NewOpc = ARMISD::VLD3DUP;
8065   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8066     NumVecs = 4;
8067     NewOpc = ARMISD::VLD4DUP;
8068   } else {
8069     return false;
8070   }
8071
8072   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8073   // numbers match the load.
8074   unsigned VLDLaneNo =
8075     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8076   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8077        UI != UE; ++UI) {
8078     // Ignore uses of the chain result.
8079     if (UI.getUse().getResNo() == NumVecs)
8080       continue;
8081     SDNode *User = *UI;
8082     if (User->getOpcode() != ARMISD::VDUPLANE ||
8083         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8084       return false;
8085   }
8086
8087   // Create the vldN-dup node.
8088   EVT Tys[5];
8089   unsigned n;
8090   for (n = 0; n < NumVecs; ++n)
8091     Tys[n] = VT;
8092   Tys[n] = MVT::Other;
8093   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8094   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8095   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8096   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8097                                            Ops, 2, VLDMemInt->getMemoryVT(),
8098                                            VLDMemInt->getMemOperand());
8099
8100   // Update the uses.
8101   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8102        UI != UE; ++UI) {
8103     unsigned ResNo = UI.getUse().getResNo();
8104     // Ignore uses of the chain result.
8105     if (ResNo == NumVecs)
8106       continue;
8107     SDNode *User = *UI;
8108     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8109   }
8110
8111   // Now the vldN-lane intrinsic is dead except for its chain result.
8112   // Update uses of the chain.
8113   std::vector<SDValue> VLDDupResults;
8114   for (unsigned n = 0; n < NumVecs; ++n)
8115     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8116   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8117   DCI.CombineTo(VLD, VLDDupResults);
8118
8119   return true;
8120 }
8121
8122 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8123 /// ARMISD::VDUPLANE.
8124 static SDValue PerformVDUPLANECombine(SDNode *N,
8125                                       TargetLowering::DAGCombinerInfo &DCI) {
8126   SDValue Op = N->getOperand(0);
8127
8128   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8129   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8130   if (CombineVLDDUP(N, DCI))
8131     return SDValue(N, 0);
8132
8133   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8134   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8135   while (Op.getOpcode() == ISD::BITCAST)
8136     Op = Op.getOperand(0);
8137   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8138     return SDValue();
8139
8140   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8141   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8142   // The canonical VMOV for a zero vector uses a 32-bit element size.
8143   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8144   unsigned EltBits;
8145   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8146     EltSize = 8;
8147   EVT VT = N->getValueType(0);
8148   if (EltSize > VT.getVectorElementType().getSizeInBits())
8149     return SDValue();
8150
8151   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8152 }
8153
8154 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8155 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8156 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8157 {
8158   integerPart cN;
8159   integerPart c0 = 0;
8160   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8161        I != E; I++) {
8162     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8163     if (!C)
8164       return false;
8165
8166     bool isExact;
8167     APFloat APF = C->getValueAPF();
8168     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8169         != APFloat::opOK || !isExact)
8170       return false;
8171
8172     c0 = (I == 0) ? cN : c0;
8173     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8174       return false;
8175   }
8176   C = c0;
8177   return true;
8178 }
8179
8180 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8181 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8182 /// when the VMUL has a constant operand that is a power of 2.
8183 ///
8184 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8185 ///  vmul.f32        d16, d17, d16
8186 ///  vcvt.s32.f32    d16, d16
8187 /// becomes:
8188 ///  vcvt.s32.f32    d16, d16, #3
8189 static SDValue PerformVCVTCombine(SDNode *N,
8190                                   TargetLowering::DAGCombinerInfo &DCI,
8191                                   const ARMSubtarget *Subtarget) {
8192   SelectionDAG &DAG = DCI.DAG;
8193   SDValue Op = N->getOperand(0);
8194
8195   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8196       Op.getOpcode() != ISD::FMUL)
8197     return SDValue();
8198
8199   uint64_t C;
8200   SDValue N0 = Op->getOperand(0);
8201   SDValue ConstVec = Op->getOperand(1);
8202   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8203
8204   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8205       !isConstVecPow2(ConstVec, isSigned, C))
8206     return SDValue();
8207
8208   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8209     Intrinsic::arm_neon_vcvtfp2fxu;
8210   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8211                      N->getValueType(0),
8212                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8213                      DAG.getConstant(Log2_64(C), MVT::i32));
8214 }
8215
8216 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8217 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8218 /// when the VDIV has a constant operand that is a power of 2.
8219 ///
8220 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8221 ///  vcvt.f32.s32    d16, d16
8222 ///  vdiv.f32        d16, d17, d16
8223 /// becomes:
8224 ///  vcvt.f32.s32    d16, d16, #3
8225 static SDValue PerformVDIVCombine(SDNode *N,
8226                                   TargetLowering::DAGCombinerInfo &DCI,
8227                                   const ARMSubtarget *Subtarget) {
8228   SelectionDAG &DAG = DCI.DAG;
8229   SDValue Op = N->getOperand(0);
8230   unsigned OpOpcode = Op.getNode()->getOpcode();
8231
8232   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8233       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8234     return SDValue();
8235
8236   uint64_t C;
8237   SDValue ConstVec = N->getOperand(1);
8238   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8239
8240   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8241       !isConstVecPow2(ConstVec, isSigned, C))
8242     return SDValue();
8243
8244   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8245     Intrinsic::arm_neon_vcvtfxu2fp;
8246   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8247                      Op.getValueType(),
8248                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8249                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8250 }
8251
8252 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8253 /// operand of a vector shift operation, where all the elements of the
8254 /// build_vector must have the same constant integer value.
8255 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8256   // Ignore bit_converts.
8257   while (Op.getOpcode() == ISD::BITCAST)
8258     Op = Op.getOperand(0);
8259   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8260   APInt SplatBits, SplatUndef;
8261   unsigned SplatBitSize;
8262   bool HasAnyUndefs;
8263   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8264                                       HasAnyUndefs, ElementBits) ||
8265       SplatBitSize > ElementBits)
8266     return false;
8267   Cnt = SplatBits.getSExtValue();
8268   return true;
8269 }
8270
8271 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8272 /// operand of a vector shift left operation.  That value must be in the range:
8273 ///   0 <= Value < ElementBits for a left shift; or
8274 ///   0 <= Value <= ElementBits for a long left shift.
8275 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8276   assert(VT.isVector() && "vector shift count is not a vector type");
8277   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8278   if (! getVShiftImm(Op, ElementBits, Cnt))
8279     return false;
8280   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8281 }
8282
8283 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8284 /// operand of a vector shift right operation.  For a shift opcode, the value
8285 /// is positive, but for an intrinsic the value count must be negative. The
8286 /// absolute value must be in the range:
8287 ///   1 <= |Value| <= ElementBits for a right shift; or
8288 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8289 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8290                          int64_t &Cnt) {
8291   assert(VT.isVector() && "vector shift count is not a vector type");
8292   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8293   if (! getVShiftImm(Op, ElementBits, Cnt))
8294     return false;
8295   if (isIntrinsic)
8296     Cnt = -Cnt;
8297   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8298 }
8299
8300 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8301 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8302   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8303   switch (IntNo) {
8304   default:
8305     // Don't do anything for most intrinsics.
8306     break;
8307
8308   // Vector shifts: check for immediate versions and lower them.
8309   // Note: This is done during DAG combining instead of DAG legalizing because
8310   // the build_vectors for 64-bit vector element shift counts are generally
8311   // not legal, and it is hard to see their values after they get legalized to
8312   // loads from a constant pool.
8313   case Intrinsic::arm_neon_vshifts:
8314   case Intrinsic::arm_neon_vshiftu:
8315   case Intrinsic::arm_neon_vshiftls:
8316   case Intrinsic::arm_neon_vshiftlu:
8317   case Intrinsic::arm_neon_vshiftn:
8318   case Intrinsic::arm_neon_vrshifts:
8319   case Intrinsic::arm_neon_vrshiftu:
8320   case Intrinsic::arm_neon_vrshiftn:
8321   case Intrinsic::arm_neon_vqshifts:
8322   case Intrinsic::arm_neon_vqshiftu:
8323   case Intrinsic::arm_neon_vqshiftsu:
8324   case Intrinsic::arm_neon_vqshiftns:
8325   case Intrinsic::arm_neon_vqshiftnu:
8326   case Intrinsic::arm_neon_vqshiftnsu:
8327   case Intrinsic::arm_neon_vqrshiftns:
8328   case Intrinsic::arm_neon_vqrshiftnu:
8329   case Intrinsic::arm_neon_vqrshiftnsu: {
8330     EVT VT = N->getOperand(1).getValueType();
8331     int64_t Cnt;
8332     unsigned VShiftOpc = 0;
8333
8334     switch (IntNo) {
8335     case Intrinsic::arm_neon_vshifts:
8336     case Intrinsic::arm_neon_vshiftu:
8337       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8338         VShiftOpc = ARMISD::VSHL;
8339         break;
8340       }
8341       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8342         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8343                      ARMISD::VSHRs : ARMISD::VSHRu);
8344         break;
8345       }
8346       return SDValue();
8347
8348     case Intrinsic::arm_neon_vshiftls:
8349     case Intrinsic::arm_neon_vshiftlu:
8350       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8351         break;
8352       llvm_unreachable("invalid shift count for vshll intrinsic");
8353
8354     case Intrinsic::arm_neon_vrshifts:
8355     case Intrinsic::arm_neon_vrshiftu:
8356       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8357         break;
8358       return SDValue();
8359
8360     case Intrinsic::arm_neon_vqshifts:
8361     case Intrinsic::arm_neon_vqshiftu:
8362       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8363         break;
8364       return SDValue();
8365
8366     case Intrinsic::arm_neon_vqshiftsu:
8367       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8368         break;
8369       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8370
8371     case Intrinsic::arm_neon_vshiftn:
8372     case Intrinsic::arm_neon_vrshiftn:
8373     case Intrinsic::arm_neon_vqshiftns:
8374     case Intrinsic::arm_neon_vqshiftnu:
8375     case Intrinsic::arm_neon_vqshiftnsu:
8376     case Intrinsic::arm_neon_vqrshiftns:
8377     case Intrinsic::arm_neon_vqrshiftnu:
8378     case Intrinsic::arm_neon_vqrshiftnsu:
8379       // Narrowing shifts require an immediate right shift.
8380       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8381         break;
8382       llvm_unreachable("invalid shift count for narrowing vector shift "
8383                        "intrinsic");
8384
8385     default:
8386       llvm_unreachable("unhandled vector shift");
8387     }
8388
8389     switch (IntNo) {
8390     case Intrinsic::arm_neon_vshifts:
8391     case Intrinsic::arm_neon_vshiftu:
8392       // Opcode already set above.
8393       break;
8394     case Intrinsic::arm_neon_vshiftls:
8395     case Intrinsic::arm_neon_vshiftlu:
8396       if (Cnt == VT.getVectorElementType().getSizeInBits())
8397         VShiftOpc = ARMISD::VSHLLi;
8398       else
8399         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8400                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8401       break;
8402     case Intrinsic::arm_neon_vshiftn:
8403       VShiftOpc = ARMISD::VSHRN; break;
8404     case Intrinsic::arm_neon_vrshifts:
8405       VShiftOpc = ARMISD::VRSHRs; break;
8406     case Intrinsic::arm_neon_vrshiftu:
8407       VShiftOpc = ARMISD::VRSHRu; break;
8408     case Intrinsic::arm_neon_vrshiftn:
8409       VShiftOpc = ARMISD::VRSHRN; break;
8410     case Intrinsic::arm_neon_vqshifts:
8411       VShiftOpc = ARMISD::VQSHLs; break;
8412     case Intrinsic::arm_neon_vqshiftu:
8413       VShiftOpc = ARMISD::VQSHLu; break;
8414     case Intrinsic::arm_neon_vqshiftsu:
8415       VShiftOpc = ARMISD::VQSHLsu; break;
8416     case Intrinsic::arm_neon_vqshiftns:
8417       VShiftOpc = ARMISD::VQSHRNs; break;
8418     case Intrinsic::arm_neon_vqshiftnu:
8419       VShiftOpc = ARMISD::VQSHRNu; break;
8420     case Intrinsic::arm_neon_vqshiftnsu:
8421       VShiftOpc = ARMISD::VQSHRNsu; break;
8422     case Intrinsic::arm_neon_vqrshiftns:
8423       VShiftOpc = ARMISD::VQRSHRNs; break;
8424     case Intrinsic::arm_neon_vqrshiftnu:
8425       VShiftOpc = ARMISD::VQRSHRNu; break;
8426     case Intrinsic::arm_neon_vqrshiftnsu:
8427       VShiftOpc = ARMISD::VQRSHRNsu; break;
8428     }
8429
8430     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8431                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8432   }
8433
8434   case Intrinsic::arm_neon_vshiftins: {
8435     EVT VT = N->getOperand(1).getValueType();
8436     int64_t Cnt;
8437     unsigned VShiftOpc = 0;
8438
8439     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8440       VShiftOpc = ARMISD::VSLI;
8441     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8442       VShiftOpc = ARMISD::VSRI;
8443     else {
8444       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8445     }
8446
8447     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8448                        N->getOperand(1), N->getOperand(2),
8449                        DAG.getConstant(Cnt, MVT::i32));
8450   }
8451
8452   case Intrinsic::arm_neon_vqrshifts:
8453   case Intrinsic::arm_neon_vqrshiftu:
8454     // No immediate versions of these to check for.
8455     break;
8456   }
8457
8458   return SDValue();
8459 }
8460
8461 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8462 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8463 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8464 /// vector element shift counts are generally not legal, and it is hard to see
8465 /// their values after they get legalized to loads from a constant pool.
8466 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8467                                    const ARMSubtarget *ST) {
8468   EVT VT = N->getValueType(0);
8469   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8470     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8471     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8472     SDValue N1 = N->getOperand(1);
8473     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8474       SDValue N0 = N->getOperand(0);
8475       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8476           DAG.MaskedValueIsZero(N0.getOperand(0),
8477                                 APInt::getHighBitsSet(32, 16)))
8478         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8479     }
8480   }
8481
8482   // Nothing to be done for scalar shifts.
8483   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8484   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8485     return SDValue();
8486
8487   assert(ST->hasNEON() && "unexpected vector shift");
8488   int64_t Cnt;
8489
8490   switch (N->getOpcode()) {
8491   default: llvm_unreachable("unexpected shift opcode");
8492
8493   case ISD::SHL:
8494     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8495       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8496                          DAG.getConstant(Cnt, MVT::i32));
8497     break;
8498
8499   case ISD::SRA:
8500   case ISD::SRL:
8501     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8502       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8503                             ARMISD::VSHRs : ARMISD::VSHRu);
8504       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8505                          DAG.getConstant(Cnt, MVT::i32));
8506     }
8507   }
8508   return SDValue();
8509 }
8510
8511 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8512 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8513 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8514                                     const ARMSubtarget *ST) {
8515   SDValue N0 = N->getOperand(0);
8516
8517   // Check for sign- and zero-extensions of vector extract operations of 8-
8518   // and 16-bit vector elements.  NEON supports these directly.  They are
8519   // handled during DAG combining because type legalization will promote them
8520   // to 32-bit types and it is messy to recognize the operations after that.
8521   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8522     SDValue Vec = N0.getOperand(0);
8523     SDValue Lane = N0.getOperand(1);
8524     EVT VT = N->getValueType(0);
8525     EVT EltVT = N0.getValueType();
8526     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8527
8528     if (VT == MVT::i32 &&
8529         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8530         TLI.isTypeLegal(Vec.getValueType()) &&
8531         isa<ConstantSDNode>(Lane)) {
8532
8533       unsigned Opc = 0;
8534       switch (N->getOpcode()) {
8535       default: llvm_unreachable("unexpected opcode");
8536       case ISD::SIGN_EXTEND:
8537         Opc = ARMISD::VGETLANEs;
8538         break;
8539       case ISD::ZERO_EXTEND:
8540       case ISD::ANY_EXTEND:
8541         Opc = ARMISD::VGETLANEu;
8542         break;
8543       }
8544       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8545     }
8546   }
8547
8548   return SDValue();
8549 }
8550
8551 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8552 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8553 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8554                                        const ARMSubtarget *ST) {
8555   // If the target supports NEON, try to use vmax/vmin instructions for f32
8556   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8557   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8558   // a NaN; only do the transformation when it matches that behavior.
8559
8560   // For now only do this when using NEON for FP operations; if using VFP, it
8561   // is not obvious that the benefit outweighs the cost of switching to the
8562   // NEON pipeline.
8563   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8564       N->getValueType(0) != MVT::f32)
8565     return SDValue();
8566
8567   SDValue CondLHS = N->getOperand(0);
8568   SDValue CondRHS = N->getOperand(1);
8569   SDValue LHS = N->getOperand(2);
8570   SDValue RHS = N->getOperand(3);
8571   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8572
8573   unsigned Opcode = 0;
8574   bool IsReversed;
8575   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8576     IsReversed = false; // x CC y ? x : y
8577   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8578     IsReversed = true ; // x CC y ? y : x
8579   } else {
8580     return SDValue();
8581   }
8582
8583   bool IsUnordered;
8584   switch (CC) {
8585   default: break;
8586   case ISD::SETOLT:
8587   case ISD::SETOLE:
8588   case ISD::SETLT:
8589   case ISD::SETLE:
8590   case ISD::SETULT:
8591   case ISD::SETULE:
8592     // If LHS is NaN, an ordered comparison will be false and the result will
8593     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8594     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8595     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8596     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8597       break;
8598     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8599     // will return -0, so vmin can only be used for unsafe math or if one of
8600     // the operands is known to be nonzero.
8601     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8602         !DAG.getTarget().Options.UnsafeFPMath &&
8603         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8604       break;
8605     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8606     break;
8607
8608   case ISD::SETOGT:
8609   case ISD::SETOGE:
8610   case ISD::SETGT:
8611   case ISD::SETGE:
8612   case ISD::SETUGT:
8613   case ISD::SETUGE:
8614     // If LHS is NaN, an ordered comparison will be false and the result will
8615     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8616     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8617     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8618     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8619       break;
8620     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8621     // will return +0, so vmax can only be used for unsafe math or if one of
8622     // the operands is known to be nonzero.
8623     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8624         !DAG.getTarget().Options.UnsafeFPMath &&
8625         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8626       break;
8627     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8628     break;
8629   }
8630
8631   if (!Opcode)
8632     return SDValue();
8633   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8634 }
8635
8636 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8637 SDValue
8638 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8639   SDValue Cmp = N->getOperand(4);
8640   if (Cmp.getOpcode() != ARMISD::CMPZ)
8641     // Only looking at EQ and NE cases.
8642     return SDValue();
8643
8644   EVT VT = N->getValueType(0);
8645   DebugLoc dl = N->getDebugLoc();
8646   SDValue LHS = Cmp.getOperand(0);
8647   SDValue RHS = Cmp.getOperand(1);
8648   SDValue FalseVal = N->getOperand(0);
8649   SDValue TrueVal = N->getOperand(1);
8650   SDValue ARMcc = N->getOperand(2);
8651   ARMCC::CondCodes CC =
8652     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8653
8654   // Simplify
8655   //   mov     r1, r0
8656   //   cmp     r1, x
8657   //   mov     r0, y
8658   //   moveq   r0, x
8659   // to
8660   //   cmp     r0, x
8661   //   movne   r0, y
8662   //
8663   //   mov     r1, r0
8664   //   cmp     r1, x
8665   //   mov     r0, x
8666   //   movne   r0, y
8667   // to
8668   //   cmp     r0, x
8669   //   movne   r0, y
8670   /// FIXME: Turn this into a target neutral optimization?
8671   SDValue Res;
8672   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8673     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8674                       N->getOperand(3), Cmp);
8675   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8676     SDValue ARMcc;
8677     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8678     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8679                       N->getOperand(3), NewCmp);
8680   }
8681
8682   if (Res.getNode()) {
8683     APInt KnownZero, KnownOne;
8684     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8685     // Capture demanded bits information that would be otherwise lost.
8686     if (KnownZero == 0xfffffffe)
8687       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8688                         DAG.getValueType(MVT::i1));
8689     else if (KnownZero == 0xffffff00)
8690       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8691                         DAG.getValueType(MVT::i8));
8692     else if (KnownZero == 0xffff0000)
8693       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8694                         DAG.getValueType(MVT::i16));
8695   }
8696
8697   return Res;
8698 }
8699
8700 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8701                                              DAGCombinerInfo &DCI) const {
8702   switch (N->getOpcode()) {
8703   default: break;
8704   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8705   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8706   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8707   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8708   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8709   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8710   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8711   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8712   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8713   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8714   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8715   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8716   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8717   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8718   case ISD::FP_TO_SINT:
8719   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8720   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8721   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8722   case ISD::SHL:
8723   case ISD::SRA:
8724   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8725   case ISD::SIGN_EXTEND:
8726   case ISD::ZERO_EXTEND:
8727   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8728   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8729   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8730   case ARMISD::VLD2DUP:
8731   case ARMISD::VLD3DUP:
8732   case ARMISD::VLD4DUP:
8733     return CombineBaseUpdate(N, DCI);
8734   case ISD::INTRINSIC_VOID:
8735   case ISD::INTRINSIC_W_CHAIN:
8736     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8737     case Intrinsic::arm_neon_vld1:
8738     case Intrinsic::arm_neon_vld2:
8739     case Intrinsic::arm_neon_vld3:
8740     case Intrinsic::arm_neon_vld4:
8741     case Intrinsic::arm_neon_vld2lane:
8742     case Intrinsic::arm_neon_vld3lane:
8743     case Intrinsic::arm_neon_vld4lane:
8744     case Intrinsic::arm_neon_vst1:
8745     case Intrinsic::arm_neon_vst2:
8746     case Intrinsic::arm_neon_vst3:
8747     case Intrinsic::arm_neon_vst4:
8748     case Intrinsic::arm_neon_vst2lane:
8749     case Intrinsic::arm_neon_vst3lane:
8750     case Intrinsic::arm_neon_vst4lane:
8751       return CombineBaseUpdate(N, DCI);
8752     default: break;
8753     }
8754     break;
8755   }
8756   return SDValue();
8757 }
8758
8759 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8760                                                           EVT VT) const {
8761   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8762 }
8763
8764 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8765   if (!Subtarget->allowsUnalignedMem())
8766     return false;
8767
8768   switch (VT.getSimpleVT().SimpleTy) {
8769   default:
8770     return false;
8771   case MVT::i8:
8772   case MVT::i16:
8773   case MVT::i32:
8774     return true;
8775   // FIXME: VLD1 etc with standard alignment is legal.
8776   }
8777 }
8778
8779 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8780                        unsigned AlignCheck) {
8781   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8782           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8783 }
8784
8785 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8786                                            unsigned DstAlign, unsigned SrcAlign,
8787                                            bool IsZeroVal,
8788                                            bool MemcpyStrSrc,
8789                                            MachineFunction &MF) const {
8790   const Function *F = MF.getFunction();
8791
8792   // See if we can use NEON instructions for this...
8793   if (IsZeroVal &&
8794       !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8795       Subtarget->hasNEON()) {
8796     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8797       return MVT::v4i32;
8798     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8799       return MVT::v2i32;
8800     }
8801   }
8802
8803   // Lowering to i32/i16 if the size permits.
8804   if (Size >= 4) {
8805     return MVT::i32;
8806   } else if (Size >= 2) {
8807     return MVT::i16;
8808   }
8809
8810   // Let the target-independent logic figure it out.
8811   return MVT::Other;
8812 }
8813
8814 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8815   if (V < 0)
8816     return false;
8817
8818   unsigned Scale = 1;
8819   switch (VT.getSimpleVT().SimpleTy) {
8820   default: return false;
8821   case MVT::i1:
8822   case MVT::i8:
8823     // Scale == 1;
8824     break;
8825   case MVT::i16:
8826     // Scale == 2;
8827     Scale = 2;
8828     break;
8829   case MVT::i32:
8830     // Scale == 4;
8831     Scale = 4;
8832     break;
8833   }
8834
8835   if ((V & (Scale - 1)) != 0)
8836     return false;
8837   V /= Scale;
8838   return V == (V & ((1LL << 5) - 1));
8839 }
8840
8841 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8842                                       const ARMSubtarget *Subtarget) {
8843   bool isNeg = false;
8844   if (V < 0) {
8845     isNeg = true;
8846     V = - V;
8847   }
8848
8849   switch (VT.getSimpleVT().SimpleTy) {
8850   default: return false;
8851   case MVT::i1:
8852   case MVT::i8:
8853   case MVT::i16:
8854   case MVT::i32:
8855     // + imm12 or - imm8
8856     if (isNeg)
8857       return V == (V & ((1LL << 8) - 1));
8858     return V == (V & ((1LL << 12) - 1));
8859   case MVT::f32:
8860   case MVT::f64:
8861     // Same as ARM mode. FIXME: NEON?
8862     if (!Subtarget->hasVFP2())
8863       return false;
8864     if ((V & 3) != 0)
8865       return false;
8866     V >>= 2;
8867     return V == (V & ((1LL << 8) - 1));
8868   }
8869 }
8870
8871 /// isLegalAddressImmediate - Return true if the integer value can be used
8872 /// as the offset of the target addressing mode for load / store of the
8873 /// given type.
8874 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8875                                     const ARMSubtarget *Subtarget) {
8876   if (V == 0)
8877     return true;
8878
8879   if (!VT.isSimple())
8880     return false;
8881
8882   if (Subtarget->isThumb1Only())
8883     return isLegalT1AddressImmediate(V, VT);
8884   else if (Subtarget->isThumb2())
8885     return isLegalT2AddressImmediate(V, VT, Subtarget);
8886
8887   // ARM mode.
8888   if (V < 0)
8889     V = - V;
8890   switch (VT.getSimpleVT().SimpleTy) {
8891   default: return false;
8892   case MVT::i1:
8893   case MVT::i8:
8894   case MVT::i32:
8895     // +- imm12
8896     return V == (V & ((1LL << 12) - 1));
8897   case MVT::i16:
8898     // +- imm8
8899     return V == (V & ((1LL << 8) - 1));
8900   case MVT::f32:
8901   case MVT::f64:
8902     if (!Subtarget->hasVFP2()) // FIXME: NEON?
8903       return false;
8904     if ((V & 3) != 0)
8905       return false;
8906     V >>= 2;
8907     return V == (V & ((1LL << 8) - 1));
8908   }
8909 }
8910
8911 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8912                                                       EVT VT) const {
8913   int Scale = AM.Scale;
8914   if (Scale < 0)
8915     return false;
8916
8917   switch (VT.getSimpleVT().SimpleTy) {
8918   default: return false;
8919   case MVT::i1:
8920   case MVT::i8:
8921   case MVT::i16:
8922   case MVT::i32:
8923     if (Scale == 1)
8924       return true;
8925     // r + r << imm
8926     Scale = Scale & ~1;
8927     return Scale == 2 || Scale == 4 || Scale == 8;
8928   case MVT::i64:
8929     // r + r
8930     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8931       return true;
8932     return false;
8933   case MVT::isVoid:
8934     // Note, we allow "void" uses (basically, uses that aren't loads or
8935     // stores), because arm allows folding a scale into many arithmetic
8936     // operations.  This should be made more precise and revisited later.
8937
8938     // Allow r << imm, but the imm has to be a multiple of two.
8939     if (Scale & 1) return false;
8940     return isPowerOf2_32(Scale);
8941   }
8942 }
8943
8944 /// isLegalAddressingMode - Return true if the addressing mode represented
8945 /// by AM is legal for this target, for a load/store of the specified type.
8946 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8947                                               Type *Ty) const {
8948   EVT VT = getValueType(Ty, true);
8949   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8950     return false;
8951
8952   // Can never fold addr of global into load/store.
8953   if (AM.BaseGV)
8954     return false;
8955
8956   switch (AM.Scale) {
8957   case 0:  // no scale reg, must be "r+i" or "r", or "i".
8958     break;
8959   case 1:
8960     if (Subtarget->isThumb1Only())
8961       return false;
8962     // FALL THROUGH.
8963   default:
8964     // ARM doesn't support any R+R*scale+imm addr modes.
8965     if (AM.BaseOffs)
8966       return false;
8967
8968     if (!VT.isSimple())
8969       return false;
8970
8971     if (Subtarget->isThumb2())
8972       return isLegalT2ScaledAddressingMode(AM, VT);
8973
8974     int Scale = AM.Scale;
8975     switch (VT.getSimpleVT().SimpleTy) {
8976     default: return false;
8977     case MVT::i1:
8978     case MVT::i8:
8979     case MVT::i32:
8980       if (Scale < 0) Scale = -Scale;
8981       if (Scale == 1)
8982         return true;
8983       // r + r << imm
8984       return isPowerOf2_32(Scale & ~1);
8985     case MVT::i16:
8986     case MVT::i64:
8987       // r + r
8988       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8989         return true;
8990       return false;
8991
8992     case MVT::isVoid:
8993       // Note, we allow "void" uses (basically, uses that aren't loads or
8994       // stores), because arm allows folding a scale into many arithmetic
8995       // operations.  This should be made more precise and revisited later.
8996
8997       // Allow r << imm, but the imm has to be a multiple of two.
8998       if (Scale & 1) return false;
8999       return isPowerOf2_32(Scale);
9000     }
9001   }
9002   return true;
9003 }
9004
9005 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9006 /// icmp immediate, that is the target has icmp instructions which can compare
9007 /// a register against the immediate without having to materialize the
9008 /// immediate into a register.
9009 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9010   // Thumb2 and ARM modes can use cmn for negative immediates.
9011   if (!Subtarget->isThumb())
9012     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9013   if (Subtarget->isThumb2())
9014     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9015   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9016   return Imm >= 0 && Imm <= 255;
9017 }
9018
9019 /// isLegalAddImmediate - Return true if the specified immediate is legal
9020 /// add immediate, that is the target has add instructions which can add
9021 /// a register with the immediate without having to materialize the
9022 /// immediate into a register.
9023 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9024   return ARM_AM::getSOImmVal(Imm) != -1;
9025 }
9026
9027 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9028                                       bool isSEXTLoad, SDValue &Base,
9029                                       SDValue &Offset, bool &isInc,
9030                                       SelectionDAG &DAG) {
9031   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9032     return false;
9033
9034   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9035     // AddressingMode 3
9036     Base = Ptr->getOperand(0);
9037     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9038       int RHSC = (int)RHS->getZExtValue();
9039       if (RHSC < 0 && RHSC > -256) {
9040         assert(Ptr->getOpcode() == ISD::ADD);
9041         isInc = false;
9042         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9043         return true;
9044       }
9045     }
9046     isInc = (Ptr->getOpcode() == ISD::ADD);
9047     Offset = Ptr->getOperand(1);
9048     return true;
9049   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9050     // AddressingMode 2
9051     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9052       int RHSC = (int)RHS->getZExtValue();
9053       if (RHSC < 0 && RHSC > -0x1000) {
9054         assert(Ptr->getOpcode() == ISD::ADD);
9055         isInc = false;
9056         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9057         Base = Ptr->getOperand(0);
9058         return true;
9059       }
9060     }
9061
9062     if (Ptr->getOpcode() == ISD::ADD) {
9063       isInc = true;
9064       ARM_AM::ShiftOpc ShOpcVal=
9065         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9066       if (ShOpcVal != ARM_AM::no_shift) {
9067         Base = Ptr->getOperand(1);
9068         Offset = Ptr->getOperand(0);
9069       } else {
9070         Base = Ptr->getOperand(0);
9071         Offset = Ptr->getOperand(1);
9072       }
9073       return true;
9074     }
9075
9076     isInc = (Ptr->getOpcode() == ISD::ADD);
9077     Base = Ptr->getOperand(0);
9078     Offset = Ptr->getOperand(1);
9079     return true;
9080   }
9081
9082   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9083   return false;
9084 }
9085
9086 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9087                                      bool isSEXTLoad, SDValue &Base,
9088                                      SDValue &Offset, bool &isInc,
9089                                      SelectionDAG &DAG) {
9090   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9091     return false;
9092
9093   Base = Ptr->getOperand(0);
9094   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9095     int RHSC = (int)RHS->getZExtValue();
9096     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9097       assert(Ptr->getOpcode() == ISD::ADD);
9098       isInc = false;
9099       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9100       return true;
9101     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9102       isInc = Ptr->getOpcode() == ISD::ADD;
9103       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9104       return true;
9105     }
9106   }
9107
9108   return false;
9109 }
9110
9111 /// getPreIndexedAddressParts - returns true by value, base pointer and
9112 /// offset pointer and addressing mode by reference if the node's address
9113 /// can be legally represented as pre-indexed load / store address.
9114 bool
9115 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9116                                              SDValue &Offset,
9117                                              ISD::MemIndexedMode &AM,
9118                                              SelectionDAG &DAG) const {
9119   if (Subtarget->isThumb1Only())
9120     return false;
9121
9122   EVT VT;
9123   SDValue Ptr;
9124   bool isSEXTLoad = false;
9125   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9126     Ptr = LD->getBasePtr();
9127     VT  = LD->getMemoryVT();
9128     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9129   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9130     Ptr = ST->getBasePtr();
9131     VT  = ST->getMemoryVT();
9132   } else
9133     return false;
9134
9135   bool isInc;
9136   bool isLegal = false;
9137   if (Subtarget->isThumb2())
9138     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9139                                        Offset, isInc, DAG);
9140   else
9141     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9142                                         Offset, isInc, DAG);
9143   if (!isLegal)
9144     return false;
9145
9146   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9147   return true;
9148 }
9149
9150 /// getPostIndexedAddressParts - returns true by value, base pointer and
9151 /// offset pointer and addressing mode by reference if this node can be
9152 /// combined with a load / store to form a post-indexed load / store.
9153 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9154                                                    SDValue &Base,
9155                                                    SDValue &Offset,
9156                                                    ISD::MemIndexedMode &AM,
9157                                                    SelectionDAG &DAG) const {
9158   if (Subtarget->isThumb1Only())
9159     return false;
9160
9161   EVT VT;
9162   SDValue Ptr;
9163   bool isSEXTLoad = false;
9164   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9165     VT  = LD->getMemoryVT();
9166     Ptr = LD->getBasePtr();
9167     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9168   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9169     VT  = ST->getMemoryVT();
9170     Ptr = ST->getBasePtr();
9171   } else
9172     return false;
9173
9174   bool isInc;
9175   bool isLegal = false;
9176   if (Subtarget->isThumb2())
9177     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9178                                        isInc, DAG);
9179   else
9180     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9181                                         isInc, DAG);
9182   if (!isLegal)
9183     return false;
9184
9185   if (Ptr != Base) {
9186     // Swap base ptr and offset to catch more post-index load / store when
9187     // it's legal. In Thumb2 mode, offset must be an immediate.
9188     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9189         !Subtarget->isThumb2())
9190       std::swap(Base, Offset);
9191
9192     // Post-indexed load / store update the base pointer.
9193     if (Ptr != Base)
9194       return false;
9195   }
9196
9197   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9198   return true;
9199 }
9200
9201 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9202                                                        APInt &KnownZero,
9203                                                        APInt &KnownOne,
9204                                                        const SelectionDAG &DAG,
9205                                                        unsigned Depth) const {
9206   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9207   switch (Op.getOpcode()) {
9208   default: break;
9209   case ARMISD::CMOV: {
9210     // Bits are known zero/one if known on the LHS and RHS.
9211     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9212     if (KnownZero == 0 && KnownOne == 0) return;
9213
9214     APInt KnownZeroRHS, KnownOneRHS;
9215     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9216     KnownZero &= KnownZeroRHS;
9217     KnownOne  &= KnownOneRHS;
9218     return;
9219   }
9220   }
9221 }
9222
9223 //===----------------------------------------------------------------------===//
9224 //                           ARM Inline Assembly Support
9225 //===----------------------------------------------------------------------===//
9226
9227 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9228   // Looking for "rev" which is V6+.
9229   if (!Subtarget->hasV6Ops())
9230     return false;
9231
9232   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9233   std::string AsmStr = IA->getAsmString();
9234   SmallVector<StringRef, 4> AsmPieces;
9235   SplitString(AsmStr, AsmPieces, ";\n");
9236
9237   switch (AsmPieces.size()) {
9238   default: return false;
9239   case 1:
9240     AsmStr = AsmPieces[0];
9241     AsmPieces.clear();
9242     SplitString(AsmStr, AsmPieces, " \t,");
9243
9244     // rev $0, $1
9245     if (AsmPieces.size() == 3 &&
9246         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9247         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9248       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9249       if (Ty && Ty->getBitWidth() == 32)
9250         return IntrinsicLowering::LowerToByteSwap(CI);
9251     }
9252     break;
9253   }
9254
9255   return false;
9256 }
9257
9258 /// getConstraintType - Given a constraint letter, return the type of
9259 /// constraint it is for this target.
9260 ARMTargetLowering::ConstraintType
9261 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9262   if (Constraint.size() == 1) {
9263     switch (Constraint[0]) {
9264     default:  break;
9265     case 'l': return C_RegisterClass;
9266     case 'w': return C_RegisterClass;
9267     case 'h': return C_RegisterClass;
9268     case 'x': return C_RegisterClass;
9269     case 't': return C_RegisterClass;
9270     case 'j': return C_Other; // Constant for movw.
9271       // An address with a single base register. Due to the way we
9272       // currently handle addresses it is the same as an 'r' memory constraint.
9273     case 'Q': return C_Memory;
9274     }
9275   } else if (Constraint.size() == 2) {
9276     switch (Constraint[0]) {
9277     default: break;
9278     // All 'U+' constraints are addresses.
9279     case 'U': return C_Memory;
9280     }
9281   }
9282   return TargetLowering::getConstraintType(Constraint);
9283 }
9284
9285 /// Examine constraint type and operand type and determine a weight value.
9286 /// This object must already have been set up with the operand type
9287 /// and the current alternative constraint selected.
9288 TargetLowering::ConstraintWeight
9289 ARMTargetLowering::getSingleConstraintMatchWeight(
9290     AsmOperandInfo &info, const char *constraint) const {
9291   ConstraintWeight weight = CW_Invalid;
9292   Value *CallOperandVal = info.CallOperandVal;
9293     // If we don't have a value, we can't do a match,
9294     // but allow it at the lowest weight.
9295   if (CallOperandVal == NULL)
9296     return CW_Default;
9297   Type *type = CallOperandVal->getType();
9298   // Look at the constraint type.
9299   switch (*constraint) {
9300   default:
9301     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9302     break;
9303   case 'l':
9304     if (type->isIntegerTy()) {
9305       if (Subtarget->isThumb())
9306         weight = CW_SpecificReg;
9307       else
9308         weight = CW_Register;
9309     }
9310     break;
9311   case 'w':
9312     if (type->isFloatingPointTy())
9313       weight = CW_Register;
9314     break;
9315   }
9316   return weight;
9317 }
9318
9319 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9320 RCPair
9321 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9322                                                 EVT VT) const {
9323   if (Constraint.size() == 1) {
9324     // GCC ARM Constraint Letters
9325     switch (Constraint[0]) {
9326     case 'l': // Low regs or general regs.
9327       if (Subtarget->isThumb())
9328         return RCPair(0U, &ARM::tGPRRegClass);
9329       return RCPair(0U, &ARM::GPRRegClass);
9330     case 'h': // High regs or no regs.
9331       if (Subtarget->isThumb())
9332         return RCPair(0U, &ARM::hGPRRegClass);
9333       break;
9334     case 'r':
9335       return RCPair(0U, &ARM::GPRRegClass);
9336     case 'w':
9337       if (VT == MVT::f32)
9338         return RCPair(0U, &ARM::SPRRegClass);
9339       if (VT.getSizeInBits() == 64)
9340         return RCPair(0U, &ARM::DPRRegClass);
9341       if (VT.getSizeInBits() == 128)
9342         return RCPair(0U, &ARM::QPRRegClass);
9343       break;
9344     case 'x':
9345       if (VT == MVT::f32)
9346         return RCPair(0U, &ARM::SPR_8RegClass);
9347       if (VT.getSizeInBits() == 64)
9348         return RCPair(0U, &ARM::DPR_8RegClass);
9349       if (VT.getSizeInBits() == 128)
9350         return RCPair(0U, &ARM::QPR_8RegClass);
9351       break;
9352     case 't':
9353       if (VT == MVT::f32)
9354         return RCPair(0U, &ARM::SPRRegClass);
9355       break;
9356     }
9357   }
9358   if (StringRef("{cc}").equals_lower(Constraint))
9359     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9360
9361   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9362 }
9363
9364 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9365 /// vector.  If it is invalid, don't add anything to Ops.
9366 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9367                                                      std::string &Constraint,
9368                                                      std::vector<SDValue>&Ops,
9369                                                      SelectionDAG &DAG) const {
9370   SDValue Result(0, 0);
9371
9372   // Currently only support length 1 constraints.
9373   if (Constraint.length() != 1) return;
9374
9375   char ConstraintLetter = Constraint[0];
9376   switch (ConstraintLetter) {
9377   default: break;
9378   case 'j':
9379   case 'I': case 'J': case 'K': case 'L':
9380   case 'M': case 'N': case 'O':
9381     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9382     if (!C)
9383       return;
9384
9385     int64_t CVal64 = C->getSExtValue();
9386     int CVal = (int) CVal64;
9387     // None of these constraints allow values larger than 32 bits.  Check
9388     // that the value fits in an int.
9389     if (CVal != CVal64)
9390       return;
9391
9392     switch (ConstraintLetter) {
9393       case 'j':
9394         // Constant suitable for movw, must be between 0 and
9395         // 65535.
9396         if (Subtarget->hasV6T2Ops())
9397           if (CVal >= 0 && CVal <= 65535)
9398             break;
9399         return;
9400       case 'I':
9401         if (Subtarget->isThumb1Only()) {
9402           // This must be a constant between 0 and 255, for ADD
9403           // immediates.
9404           if (CVal >= 0 && CVal <= 255)
9405             break;
9406         } else if (Subtarget->isThumb2()) {
9407           // A constant that can be used as an immediate value in a
9408           // data-processing instruction.
9409           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9410             break;
9411         } else {
9412           // A constant that can be used as an immediate value in a
9413           // data-processing instruction.
9414           if (ARM_AM::getSOImmVal(CVal) != -1)
9415             break;
9416         }
9417         return;
9418
9419       case 'J':
9420         if (Subtarget->isThumb()) {  // FIXME thumb2
9421           // This must be a constant between -255 and -1, for negated ADD
9422           // immediates. This can be used in GCC with an "n" modifier that
9423           // prints the negated value, for use with SUB instructions. It is
9424           // not useful otherwise but is implemented for compatibility.
9425           if (CVal >= -255 && CVal <= -1)
9426             break;
9427         } else {
9428           // This must be a constant between -4095 and 4095. It is not clear
9429           // what this constraint is intended for. Implemented for
9430           // compatibility with GCC.
9431           if (CVal >= -4095 && CVal <= 4095)
9432             break;
9433         }
9434         return;
9435
9436       case 'K':
9437         if (Subtarget->isThumb1Only()) {
9438           // A 32-bit value where only one byte has a nonzero value. Exclude
9439           // zero to match GCC. This constraint is used by GCC internally for
9440           // constants that can be loaded with a move/shift combination.
9441           // It is not useful otherwise but is implemented for compatibility.
9442           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9443             break;
9444         } else if (Subtarget->isThumb2()) {
9445           // A constant whose bitwise inverse can be used as an immediate
9446           // value in a data-processing instruction. This can be used in GCC
9447           // with a "B" modifier that prints the inverted value, for use with
9448           // BIC and MVN instructions. It is not useful otherwise but is
9449           // implemented for compatibility.
9450           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9451             break;
9452         } else {
9453           // A constant whose bitwise inverse can be used as an immediate
9454           // value in a data-processing instruction. This can be used in GCC
9455           // with a "B" modifier that prints the inverted value, for use with
9456           // BIC and MVN instructions. It is not useful otherwise but is
9457           // implemented for compatibility.
9458           if (ARM_AM::getSOImmVal(~CVal) != -1)
9459             break;
9460         }
9461         return;
9462
9463       case 'L':
9464         if (Subtarget->isThumb1Only()) {
9465           // This must be a constant between -7 and 7,
9466           // for 3-operand ADD/SUB immediate instructions.
9467           if (CVal >= -7 && CVal < 7)
9468             break;
9469         } else if (Subtarget->isThumb2()) {
9470           // A constant whose negation can be used as an immediate value in a
9471           // data-processing instruction. This can be used in GCC with an "n"
9472           // modifier that prints the negated value, for use with SUB
9473           // instructions. It is not useful otherwise but is implemented for
9474           // compatibility.
9475           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9476             break;
9477         } else {
9478           // A constant whose negation can be used as an immediate value in a
9479           // data-processing instruction. This can be used in GCC with an "n"
9480           // modifier that prints the negated value, for use with SUB
9481           // instructions. It is not useful otherwise but is implemented for
9482           // compatibility.
9483           if (ARM_AM::getSOImmVal(-CVal) != -1)
9484             break;
9485         }
9486         return;
9487
9488       case 'M':
9489         if (Subtarget->isThumb()) { // FIXME thumb2
9490           // This must be a multiple of 4 between 0 and 1020, for
9491           // ADD sp + immediate.
9492           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9493             break;
9494         } else {
9495           // A power of two or a constant between 0 and 32.  This is used in
9496           // GCC for the shift amount on shifted register operands, but it is
9497           // useful in general for any shift amounts.
9498           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9499             break;
9500         }
9501         return;
9502
9503       case 'N':
9504         if (Subtarget->isThumb()) {  // FIXME thumb2
9505           // This must be a constant between 0 and 31, for shift amounts.
9506           if (CVal >= 0 && CVal <= 31)
9507             break;
9508         }
9509         return;
9510
9511       case 'O':
9512         if (Subtarget->isThumb()) {  // FIXME thumb2
9513           // This must be a multiple of 4 between -508 and 508, for
9514           // ADD/SUB sp = sp + immediate.
9515           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9516             break;
9517         }
9518         return;
9519     }
9520     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9521     break;
9522   }
9523
9524   if (Result.getNode()) {
9525     Ops.push_back(Result);
9526     return;
9527   }
9528   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9529 }
9530
9531 bool
9532 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9533   // The ARM target isn't yet aware of offsets.
9534   return false;
9535 }
9536
9537 bool ARM::isBitFieldInvertedMask(unsigned v) {
9538   if (v == 0xffffffff)
9539     return 0;
9540   // there can be 1's on either or both "outsides", all the "inside"
9541   // bits must be 0's
9542   unsigned int lsb = 0, msb = 31;
9543   while (v & (1 << msb)) --msb;
9544   while (v & (1 << lsb)) ++lsb;
9545   for (unsigned int i = lsb; i <= msb; ++i) {
9546     if (v & (1 << i))
9547       return 0;
9548   }
9549   return 1;
9550 }
9551
9552 /// isFPImmLegal - Returns true if the target can instruction select the
9553 /// specified FP immediate natively. If false, the legalizer will
9554 /// materialize the FP immediate as a load from a constant pool.
9555 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9556   if (!Subtarget->hasVFP3())
9557     return false;
9558   if (VT == MVT::f32)
9559     return ARM_AM::getFP32Imm(Imm) != -1;
9560   if (VT == MVT::f64)
9561     return ARM_AM::getFP64Imm(Imm) != -1;
9562   return false;
9563 }
9564
9565 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9566 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9567 /// specified in the intrinsic calls.
9568 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9569                                            const CallInst &I,
9570                                            unsigned Intrinsic) const {
9571   switch (Intrinsic) {
9572   case Intrinsic::arm_neon_vld1:
9573   case Intrinsic::arm_neon_vld2:
9574   case Intrinsic::arm_neon_vld3:
9575   case Intrinsic::arm_neon_vld4:
9576   case Intrinsic::arm_neon_vld2lane:
9577   case Intrinsic::arm_neon_vld3lane:
9578   case Intrinsic::arm_neon_vld4lane: {
9579     Info.opc = ISD::INTRINSIC_W_CHAIN;
9580     // Conservatively set memVT to the entire set of vectors loaded.
9581     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9582     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9583     Info.ptrVal = I.getArgOperand(0);
9584     Info.offset = 0;
9585     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9586     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9587     Info.vol = false; // volatile loads with NEON intrinsics not supported
9588     Info.readMem = true;
9589     Info.writeMem = false;
9590     return true;
9591   }
9592   case Intrinsic::arm_neon_vst1:
9593   case Intrinsic::arm_neon_vst2:
9594   case Intrinsic::arm_neon_vst3:
9595   case Intrinsic::arm_neon_vst4:
9596   case Intrinsic::arm_neon_vst2lane:
9597   case Intrinsic::arm_neon_vst3lane:
9598   case Intrinsic::arm_neon_vst4lane: {
9599     Info.opc = ISD::INTRINSIC_VOID;
9600     // Conservatively set memVT to the entire set of vectors stored.
9601     unsigned NumElts = 0;
9602     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9603       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9604       if (!ArgTy->isVectorTy())
9605         break;
9606       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9607     }
9608     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9609     Info.ptrVal = I.getArgOperand(0);
9610     Info.offset = 0;
9611     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9612     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9613     Info.vol = false; // volatile stores with NEON intrinsics not supported
9614     Info.readMem = false;
9615     Info.writeMem = true;
9616     return true;
9617   }
9618   case Intrinsic::arm_strexd: {
9619     Info.opc = ISD::INTRINSIC_W_CHAIN;
9620     Info.memVT = MVT::i64;
9621     Info.ptrVal = I.getArgOperand(2);
9622     Info.offset = 0;
9623     Info.align = 8;
9624     Info.vol = true;
9625     Info.readMem = false;
9626     Info.writeMem = true;
9627     return true;
9628   }
9629   case Intrinsic::arm_ldrexd: {
9630     Info.opc = ISD::INTRINSIC_W_CHAIN;
9631     Info.memVT = MVT::i64;
9632     Info.ptrVal = I.getArgOperand(0);
9633     Info.offset = 0;
9634     Info.align = 8;
9635     Info.vol = true;
9636     Info.readMem = true;
9637     Info.writeMem = false;
9638     return true;
9639   }
9640   default:
9641     break;
9642   }
9643
9644   return false;
9645 }