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