Revert "AMDGPU: Add core backend files for R600/SI codegen v6"
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
94                                        EVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
97     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
98                        PromotedLdStVT.getSimpleVT());
99
100     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
101     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
102                        PromotedLdStVT.getSimpleVT());
103   }
104
105   EVT ElemTy = VT.getVectorElementType();
106   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
107     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
108   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
109   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
110   if (ElemTy == MVT::i32) {
111     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
112     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
113     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
114     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
115   } else {
116     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
117     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
118     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
119     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
120   }
121   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
122   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
123   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
124   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
125   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
126   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
128   if (VT.isInteger()) {
129     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
130     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
131     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
132   }
133
134   // Promote all bit-wise operations.
135   if (VT.isInteger() && VT != PromotedBitwiseVT) {
136     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
137     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
138                        PromotedBitwiseVT.getSimpleVT());
139     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
140     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
141                        PromotedBitwiseVT.getSimpleVT());
142     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
143     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
144                        PromotedBitwiseVT.getSimpleVT());
145   }
146
147   // Neon does not support vector divide/remainder operations.
148   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
149   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
150   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
153   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
154 }
155
156 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
157   addRegisterClass(VT, &ARM::DPRRegClass);
158   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
159 }
160
161 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
162   addRegisterClass(VT, &ARM::QPRRegClass);
163   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
164 }
165
166 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
167   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
168     return new TargetLoweringObjectFileMachO();
169
170   return new ARMElfTargetObjectFile();
171 }
172
173 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
174     : TargetLowering(TM, createTLOF(TM)) {
175   Subtarget = &TM.getSubtarget<ARMSubtarget>();
176   RegInfo = TM.getRegisterInfo();
177   Itins = TM.getInstrItineraryData();
178
179   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
180
181   if (Subtarget->isTargetDarwin()) {
182     // Uses VFP for Thumb libfuncs if available.
183     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
184       // Single-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
186       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
187       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
188       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
189
190       // Double-precision floating-point arithmetic.
191       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
192       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
193       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
194       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
195
196       // Single-precision comparisons.
197       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
198       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
199       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
200       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
201       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
202       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
203       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
204       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
205
206       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
213       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
214
215       // Double-precision comparisons.
216       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
217       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
218       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
219       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
220       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
221       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
222       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
223       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
224
225       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
231       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
232       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
233
234       // Floating-point to integer conversions.
235       // i64 conversions are done via library routines even when generating VFP
236       // instructions, so use the same ones.
237       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
238       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
239       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
240       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
241
242       // Conversions between floating types.
243       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
244       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
245
246       // Integer to floating-point conversions.
247       // i64 conversions are done via library routines even when generating VFP
248       // instructions, so use the same ones.
249       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
250       // e.g., __floatunsidf vs. __floatunssidfvfp.
251       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
252       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
253       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
254       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
255     }
256   }
257
258   // These libcalls are not available in 32-bit.
259   setLibcallName(RTLIB::SHL_I128, 0);
260   setLibcallName(RTLIB::SRL_I128, 0);
261   setLibcallName(RTLIB::SRA_I128, 0);
262
263   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
264     // Double-precision floating-point arithmetic helper functions
265     // RTABI chapter 4.1.2, Table 2
266     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
267     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
268     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
269     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
270     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
273     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
274
275     // Double-precision floating-point comparison helper functions
276     // RTABI chapter 4.1.2, Table 3
277     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
278     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
279     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
280     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
281     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
282     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
284     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
285     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
286     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
287     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
288     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
289     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
290     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
291     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
292     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
293     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
301
302     // Single-precision floating-point arithmetic helper functions
303     // RTABI chapter 4.1.2, Table 4
304     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
305     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
306     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
307     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
308     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
311     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
312
313     // Single-precision floating-point comparison helper functions
314     // RTABI chapter 4.1.2, Table 5
315     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
316     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
317     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
318     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
319     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
320     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
322     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
323     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
324     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
325     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
326     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
327     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
328     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
329     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
330     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
331     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
338     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
339
340     // Floating-point to integer conversions.
341     // RTABI chapter 4.1.2, Table 6
342     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
343     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
345     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
346     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
347     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
348     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
349     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
350     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
358
359     // Conversions between floating types.
360     // RTABI chapter 4.1.2, Table 7
361     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
362     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
363     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
364     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
365
366     // Integer to floating-point conversions.
367     // RTABI chapter 4.1.2, Table 8
368     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
369     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
370     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
371     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
372     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
373     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
374     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
375     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384
385     // Long long helper functions
386     // RTABI chapter 4.2, Table 9
387     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
388     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
389     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
390     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
391     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
397
398     // Integer division functions
399     // RTABI chapter 4.3.1
400     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
401     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
402     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
403     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
404     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
405     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
406     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
407     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
408     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
415     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
416
417     // Memory operations
418     // RTABI chapter 4.3.4
419     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
420     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
421     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
422     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
423     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
424     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
425   }
426
427   // Use divmod compiler-rt calls for iOS 5.0 and later.
428   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
429       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
430     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
431     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
432   }
433
434   if (Subtarget->isThumb1Only())
435     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
436   else
437     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
438   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
439       !Subtarget->isThumb1Only()) {
440     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
441     if (!Subtarget->isFPOnlySP())
442       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
443
444     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
445   }
446
447   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
449     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
450          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
451       setTruncStoreAction((MVT::SimpleValueType)VT,
452                           (MVT::SimpleValueType)InnerVT, Expand);
453     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
455     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
456   }
457
458   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
459
460   if (Subtarget->hasNEON()) {
461     addDRTypeForNEON(MVT::v2f32);
462     addDRTypeForNEON(MVT::v8i8);
463     addDRTypeForNEON(MVT::v4i16);
464     addDRTypeForNEON(MVT::v2i32);
465     addDRTypeForNEON(MVT::v1i64);
466
467     addQRTypeForNEON(MVT::v4f32);
468     addQRTypeForNEON(MVT::v2f64);
469     addQRTypeForNEON(MVT::v16i8);
470     addQRTypeForNEON(MVT::v8i16);
471     addQRTypeForNEON(MVT::v4i32);
472     addQRTypeForNEON(MVT::v2i64);
473
474     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
475     // neither Neon nor VFP support any arithmetic operations on it.
476     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
477     // supported for v4f32.
478     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
479     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
481     // FIXME: Code duplication: FDIV and FREM are expanded always, see
482     // ARMTargetLowering::addTypeForNEON method for details.
483     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
484     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
485     // FIXME: Create unittest.
486     // In another words, find a way when "copysign" appears in DAG with vector
487     // operands.
488     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
489     // FIXME: Code duplication: SETCC has custom operation action, see
490     // ARMTargetLowering::addTypeForNEON method for details.
491     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
492     // FIXME: Create unittest for FNEG and for FABS.
493     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
494     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
496     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
497     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
499     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
502     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
504     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
505     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
506     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
507     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
508     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
510     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
511
512     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522
523     // Neon does not support some operations on v1i64 and v2i64 types.
524     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
525     // Custom handling for some quad-vector types to detect VMULL.
526     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
527     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
528     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
529     // Custom handling for some vector types to avoid expensive expansions
530     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
531     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
532     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
533     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
534     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
535     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
536     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
537     // a destination type that is wider than the source, and nor does
538     // it have a FP_TO_[SU]INT instruction with a narrower destination than
539     // source.
540     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
543     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544
545     setTargetDAGCombine(ISD::INTRINSIC_VOID);
546     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
547     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
548     setTargetDAGCombine(ISD::SHL);
549     setTargetDAGCombine(ISD::SRL);
550     setTargetDAGCombine(ISD::SRA);
551     setTargetDAGCombine(ISD::SIGN_EXTEND);
552     setTargetDAGCombine(ISD::ZERO_EXTEND);
553     setTargetDAGCombine(ISD::ANY_EXTEND);
554     setTargetDAGCombine(ISD::SELECT_CC);
555     setTargetDAGCombine(ISD::BUILD_VECTOR);
556     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
557     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
558     setTargetDAGCombine(ISD::STORE);
559     setTargetDAGCombine(ISD::FP_TO_SINT);
560     setTargetDAGCombine(ISD::FP_TO_UINT);
561     setTargetDAGCombine(ISD::FDIV);
562
563     // It is legal to extload from v4i8 to v4i16 or v4i32.
564     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
565                   MVT::v4i16, MVT::v2i16,
566                   MVT::v2i32};
567     for (unsigned i = 0; i < 6; ++i) {
568       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
569       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
570       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
571     }
572   }
573
574   computeRegisterProperties();
575
576   // ARM does not have f32 extending load.
577   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
578
579   // ARM does not have i1 sign extending load.
580   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
581
582   // ARM supports all 4 flavors of integer indexed load / store.
583   if (!Subtarget->isThumb1Only()) {
584     for (unsigned im = (unsigned)ISD::PRE_INC;
585          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
586       setIndexedLoadAction(im,  MVT::i1,  Legal);
587       setIndexedLoadAction(im,  MVT::i8,  Legal);
588       setIndexedLoadAction(im,  MVT::i16, Legal);
589       setIndexedLoadAction(im,  MVT::i32, Legal);
590       setIndexedStoreAction(im, MVT::i1,  Legal);
591       setIndexedStoreAction(im, MVT::i8,  Legal);
592       setIndexedStoreAction(im, MVT::i16, Legal);
593       setIndexedStoreAction(im, MVT::i32, Legal);
594     }
595   }
596
597   // i64 operation support.
598   setOperationAction(ISD::MUL,     MVT::i64, Expand);
599   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
600   if (Subtarget->isThumb1Only()) {
601     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
602     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
603   }
604   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
605       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
606     setOperationAction(ISD::MULHS, MVT::i32, Expand);
607
608   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
609   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
610   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
611   setOperationAction(ISD::SRL,       MVT::i64, Custom);
612   setOperationAction(ISD::SRA,       MVT::i64, Custom);
613
614   if (!Subtarget->isThumb1Only()) {
615     // FIXME: We should do this for Thumb1 as well.
616     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
617     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
618     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
619     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
620   }
621
622   // ARM does not have ROTL.
623   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
624   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
625   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
626   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
627     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
628
629   // These just redirect to CTTZ and CTLZ on ARM.
630   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
631   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
632
633   // Only ARMv6 has BSWAP.
634   if (!Subtarget->hasV6Ops())
635     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
636
637   // These are expanded into libcalls.
638   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
639     // v7M has a hardware divider
640     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
641     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
642   }
643   setOperationAction(ISD::SREM,  MVT::i32, Expand);
644   setOperationAction(ISD::UREM,  MVT::i32, Expand);
645   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
646   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
647
648   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
649   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
650   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
651   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
652   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
653
654   setOperationAction(ISD::TRAP, MVT::Other, Legal);
655
656   // Use the default implementation.
657   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
658   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
659   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
660   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
661   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
662   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
663
664   if (!Subtarget->isTargetDarwin()) {
665     // Non-Darwin platforms may return values in these registers via the
666     // personality function.
667     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
668     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
669     setExceptionPointerRegister(ARM::R0);
670     setExceptionSelectorRegister(ARM::R1);
671   }
672
673   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
674   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
675   // the default expansion.
676   // FIXME: This should be checking for v6k, not just v6.
677   if (Subtarget->hasDataBarrier() ||
678       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
679     // membarrier needs custom lowering; the rest are legal and handled
680     // normally.
681     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
682     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
683     // Custom lowering for 64-bit ops
684     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
685     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
686     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
690     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
691     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
692     setInsertFencesForAtomic(true);
693   } else {
694     // Set them all for expansion, which will force libcalls.
695     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
696     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
697     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
698     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
709     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
710     // Unordered/Monotonic case.
711     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
712     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
713     // Since the libcalls include locking, fold in the fences
714     setShouldFoldAtomicFences(true);
715   }
716
717   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
718
719   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
720   if (!Subtarget->hasV6Ops()) {
721     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
722     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
723   }
724   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
725
726   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
727       !Subtarget->isThumb1Only()) {
728     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
729     // iff target supports vfp2.
730     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
731     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
732   }
733
734   // We want to custom lower some of our intrinsics.
735   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
736   if (Subtarget->isTargetDarwin()) {
737     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
738     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
739     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
740   }
741
742   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
743   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
744   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
745   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
746   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
747   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
748   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
749   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
750   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
751
752   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
753   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
754   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
755   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
756   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
757
758   // We don't support sin/cos/fmod/copysign/pow
759   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
760   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
761   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
762   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
763   setOperationAction(ISD::FREM,      MVT::f64, Expand);
764   setOperationAction(ISD::FREM,      MVT::f32, Expand);
765   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766       !Subtarget->isThumb1Only()) {
767     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
768     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
769   }
770   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
771   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
772
773   if (!Subtarget->hasVFP4()) {
774     setOperationAction(ISD::FMA, MVT::f64, Expand);
775     setOperationAction(ISD::FMA, MVT::f32, Expand);
776   }
777
778   // Various VFP goodness
779   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
780     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
781     if (Subtarget->hasVFP2()) {
782       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
783       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
784       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
785       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
786     }
787     // Special handling for half-precision FP.
788     if (!Subtarget->hasFP16()) {
789       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
790       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
791     }
792   }
793
794   // We have target-specific dag combine patterns for the following nodes:
795   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
796   setTargetDAGCombine(ISD::ADD);
797   setTargetDAGCombine(ISD::SUB);
798   setTargetDAGCombine(ISD::MUL);
799
800   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
801     setTargetDAGCombine(ISD::AND);
802     setTargetDAGCombine(ISD::OR);
803     setTargetDAGCombine(ISD::XOR);
804   }
805
806   if (Subtarget->hasV6Ops())
807     setTargetDAGCombine(ISD::SRL);
808
809   setStackPointerRegisterToSaveRestore(ARM::SP);
810
811   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
812       !Subtarget->hasVFP2())
813     setSchedulingPreference(Sched::RegPressure);
814   else
815     setSchedulingPreference(Sched::Hybrid);
816
817   //// temporary - rewrite interface to use type
818   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
819   maxStoresPerMemset = 16;
820   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
821
822   // On ARM arguments smaller than 4 bytes are extended, so all arguments
823   // are at least 4 bytes aligned.
824   setMinStackArgumentAlignment(4);
825
826   benefitFromCodePlacementOpt = true;
827
828   // Prefer likely predicted branches to selects on out-of-order cores.
829   predictableSelectIsExpensive = Subtarget->isCortexA9();
830
831   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
832 }
833
834 // FIXME: It might make sense to define the representative register class as the
835 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
836 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
837 // SPR's representative would be DPR_VFP2. This should work well if register
838 // pressure tracking were modified such that a register use would increment the
839 // pressure of the register class's representative and all of it's super
840 // classes' representatives transitively. We have not implemented this because
841 // of the difficulty prior to coalescing of modeling operand register classes
842 // due to the common occurrence of cross class copies and subregister insertions
843 // and extractions.
844 std::pair<const TargetRegisterClass*, uint8_t>
845 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
846   const TargetRegisterClass *RRC = 0;
847   uint8_t Cost = 1;
848   switch (VT.getSimpleVT().SimpleTy) {
849   default:
850     return TargetLowering::findRepresentativeClass(VT);
851   // Use DPR as representative register class for all floating point
852   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
853   // the cost is 1 for both f32 and f64.
854   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
855   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
856     RRC = &ARM::DPRRegClass;
857     // When NEON is used for SP, only half of the register file is available
858     // because operations that define both SP and DP results will be constrained
859     // to the VFP2 class (D0-D15). We currently model this constraint prior to
860     // coalescing by double-counting the SP regs. See the FIXME above.
861     if (Subtarget->useNEONForSinglePrecisionFP())
862       Cost = 2;
863     break;
864   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
865   case MVT::v4f32: case MVT::v2f64:
866     RRC = &ARM::DPRRegClass;
867     Cost = 2;
868     break;
869   case MVT::v4i64:
870     RRC = &ARM::DPRRegClass;
871     Cost = 4;
872     break;
873   case MVT::v8i64:
874     RRC = &ARM::DPRRegClass;
875     Cost = 8;
876     break;
877   }
878   return std::make_pair(RRC, Cost);
879 }
880
881 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
882   switch (Opcode) {
883   default: return 0;
884   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
885   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
886   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
887   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
888   case ARMISD::CALL:          return "ARMISD::CALL";
889   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
890   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
891   case ARMISD::tCALL:         return "ARMISD::tCALL";
892   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
893   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
894   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
895   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
896   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
897   case ARMISD::CMP:           return "ARMISD::CMP";
898   case ARMISD::CMN:           return "ARMISD::CMN";
899   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
900   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
901   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
902   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
903   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
904
905   case ARMISD::CMOV:          return "ARMISD::CMOV";
906   case ARMISD::CAND:          return "ARMISD::CAND";
907   case ARMISD::COR:           return "ARMISD::COR";
908   case ARMISD::CXOR:          return "ARMISD::CXOR";
909
910   case ARMISD::RBIT:          return "ARMISD::RBIT";
911
912   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
913   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
914   case ARMISD::SITOF:         return "ARMISD::SITOF";
915   case ARMISD::UITOF:         return "ARMISD::UITOF";
916
917   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
918   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
919   case ARMISD::RRX:           return "ARMISD::RRX";
920
921   case ARMISD::ADDC:          return "ARMISD::ADDC";
922   case ARMISD::ADDE:          return "ARMISD::ADDE";
923   case ARMISD::SUBC:          return "ARMISD::SUBC";
924   case ARMISD::SUBE:          return "ARMISD::SUBE";
925
926   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
927   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
928
929   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
930   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
931
932   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
933
934   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
935
936   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
937
938   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
939   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
940
941   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
942
943   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
944   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
945   case ARMISD::VCGE:          return "ARMISD::VCGE";
946   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
947   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
948   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
949   case ARMISD::VCGT:          return "ARMISD::VCGT";
950   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
951   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
952   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
953   case ARMISD::VTST:          return "ARMISD::VTST";
954
955   case ARMISD::VSHL:          return "ARMISD::VSHL";
956   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
957   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
958   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
959   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
960   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
961   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
962   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
963   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
964   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
965   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
966   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
967   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
968   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
969   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
970   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
971   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
972   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
973   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
974   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
975   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
976   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
977   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
978   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
979   case ARMISD::VDUP:          return "ARMISD::VDUP";
980   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
981   case ARMISD::VEXT:          return "ARMISD::VEXT";
982   case ARMISD::VREV64:        return "ARMISD::VREV64";
983   case ARMISD::VREV32:        return "ARMISD::VREV32";
984   case ARMISD::VREV16:        return "ARMISD::VREV16";
985   case ARMISD::VZIP:          return "ARMISD::VZIP";
986   case ARMISD::VUZP:          return "ARMISD::VUZP";
987   case ARMISD::VTRN:          return "ARMISD::VTRN";
988   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
989   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
990   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
991   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
992   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
993   case ARMISD::FMAX:          return "ARMISD::FMAX";
994   case ARMISD::FMIN:          return "ARMISD::FMIN";
995   case ARMISD::BFI:           return "ARMISD::BFI";
996   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
997   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
998   case ARMISD::VBSL:          return "ARMISD::VBSL";
999   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1000   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1001   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1002   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1003   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1004   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1005   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1006   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1007   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1008   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1009   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1010   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1011   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1012   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1013   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1014   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1015   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1016   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1017   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1018   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1019   }
1020 }
1021
1022 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1023   if (!VT.isVector()) return getPointerTy();
1024   return VT.changeVectorElementTypeToInteger();
1025 }
1026
1027 /// getRegClassFor - Return the register class that should be used for the
1028 /// specified value type.
1029 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1030   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1031   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1032   // load / store 4 to 8 consecutive D registers.
1033   if (Subtarget->hasNEON()) {
1034     if (VT == MVT::v4i64)
1035       return &ARM::QQPRRegClass;
1036     if (VT == MVT::v8i64)
1037       return &ARM::QQQQPRRegClass;
1038   }
1039   return TargetLowering::getRegClassFor(VT);
1040 }
1041
1042 // Create a fast isel object.
1043 FastISel *
1044 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1045   return ARM::createFastISel(funcInfo);
1046 }
1047
1048 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1049 /// be used for loads / stores from the global.
1050 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1051   return (Subtarget->isThumb1Only() ? 127 : 4095);
1052 }
1053
1054 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1055   unsigned NumVals = N->getNumValues();
1056   if (!NumVals)
1057     return Sched::RegPressure;
1058
1059   for (unsigned i = 0; i != NumVals; ++i) {
1060     EVT VT = N->getValueType(i);
1061     if (VT == MVT::Glue || VT == MVT::Other)
1062       continue;
1063     if (VT.isFloatingPoint() || VT.isVector())
1064       return Sched::ILP;
1065   }
1066
1067   if (!N->isMachineOpcode())
1068     return Sched::RegPressure;
1069
1070   // Load are scheduled for latency even if there instruction itinerary
1071   // is not available.
1072   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1073   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1074
1075   if (MCID.getNumDefs() == 0)
1076     return Sched::RegPressure;
1077   if (!Itins->isEmpty() &&
1078       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1079     return Sched::ILP;
1080
1081   return Sched::RegPressure;
1082 }
1083
1084 //===----------------------------------------------------------------------===//
1085 // Lowering Code
1086 //===----------------------------------------------------------------------===//
1087
1088 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1089 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1090   switch (CC) {
1091   default: llvm_unreachable("Unknown condition code!");
1092   case ISD::SETNE:  return ARMCC::NE;
1093   case ISD::SETEQ:  return ARMCC::EQ;
1094   case ISD::SETGT:  return ARMCC::GT;
1095   case ISD::SETGE:  return ARMCC::GE;
1096   case ISD::SETLT:  return ARMCC::LT;
1097   case ISD::SETLE:  return ARMCC::LE;
1098   case ISD::SETUGT: return ARMCC::HI;
1099   case ISD::SETUGE: return ARMCC::HS;
1100   case ISD::SETULT: return ARMCC::LO;
1101   case ISD::SETULE: return ARMCC::LS;
1102   }
1103 }
1104
1105 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1106 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1107                         ARMCC::CondCodes &CondCode2) {
1108   CondCode2 = ARMCC::AL;
1109   switch (CC) {
1110   default: llvm_unreachable("Unknown FP condition!");
1111   case ISD::SETEQ:
1112   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1113   case ISD::SETGT:
1114   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1115   case ISD::SETGE:
1116   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1117   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1118   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1119   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1120   case ISD::SETO:   CondCode = ARMCC::VC; break;
1121   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1122   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1123   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1124   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1125   case ISD::SETLT:
1126   case ISD::SETULT: CondCode = ARMCC::LT; break;
1127   case ISD::SETLE:
1128   case ISD::SETULE: CondCode = ARMCC::LE; break;
1129   case ISD::SETNE:
1130   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1131   }
1132 }
1133
1134 //===----------------------------------------------------------------------===//
1135 //                      Calling Convention Implementation
1136 //===----------------------------------------------------------------------===//
1137
1138 #include "ARMGenCallingConv.inc"
1139
1140 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1141 /// given CallingConvention value.
1142 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1143                                                  bool Return,
1144                                                  bool isVarArg) const {
1145   switch (CC) {
1146   default:
1147     llvm_unreachable("Unsupported calling convention");
1148   case CallingConv::Fast:
1149     if (Subtarget->hasVFP2() && !isVarArg) {
1150       if (!Subtarget->isAAPCS_ABI())
1151         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1152       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1153       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1154     }
1155     // Fallthrough
1156   case CallingConv::C: {
1157     // Use target triple & subtarget features to do actual dispatch.
1158     if (!Subtarget->isAAPCS_ABI())
1159       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1160     else if (Subtarget->hasVFP2() &&
1161              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1162              !isVarArg)
1163       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1164     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1165   }
1166   case CallingConv::ARM_AAPCS_VFP:
1167     if (!isVarArg)
1168       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1169     // Fallthrough
1170   case CallingConv::ARM_AAPCS:
1171     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1172   case CallingConv::ARM_APCS:
1173     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1174   }
1175 }
1176
1177 /// LowerCallResult - Lower the result values of a call into the
1178 /// appropriate copies out of appropriate physical registers.
1179 SDValue
1180 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1181                                    CallingConv::ID CallConv, bool isVarArg,
1182                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1183                                    DebugLoc dl, SelectionDAG &DAG,
1184                                    SmallVectorImpl<SDValue> &InVals) const {
1185
1186   // Assign locations to each value returned by this call.
1187   SmallVector<CCValAssign, 16> RVLocs;
1188   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1189                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1190   CCInfo.AnalyzeCallResult(Ins,
1191                            CCAssignFnForNode(CallConv, /* Return*/ true,
1192                                              isVarArg));
1193
1194   // Copy all of the result registers out of their specified physreg.
1195   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1196     CCValAssign VA = RVLocs[i];
1197
1198     SDValue Val;
1199     if (VA.needsCustom()) {
1200       // Handle f64 or half of a v2f64.
1201       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1202                                       InFlag);
1203       Chain = Lo.getValue(1);
1204       InFlag = Lo.getValue(2);
1205       VA = RVLocs[++i]; // skip ahead to next loc
1206       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1207                                       InFlag);
1208       Chain = Hi.getValue(1);
1209       InFlag = Hi.getValue(2);
1210       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1211
1212       if (VA.getLocVT() == MVT::v2f64) {
1213         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1214         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1215                           DAG.getConstant(0, MVT::i32));
1216
1217         VA = RVLocs[++i]; // skip ahead to next loc
1218         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1219         Chain = Lo.getValue(1);
1220         InFlag = Lo.getValue(2);
1221         VA = RVLocs[++i]; // skip ahead to next loc
1222         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1223         Chain = Hi.getValue(1);
1224         InFlag = Hi.getValue(2);
1225         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1226         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1227                           DAG.getConstant(1, MVT::i32));
1228       }
1229     } else {
1230       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1231                                InFlag);
1232       Chain = Val.getValue(1);
1233       InFlag = Val.getValue(2);
1234     }
1235
1236     switch (VA.getLocInfo()) {
1237     default: llvm_unreachable("Unknown loc info!");
1238     case CCValAssign::Full: break;
1239     case CCValAssign::BCvt:
1240       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1241       break;
1242     }
1243
1244     InVals.push_back(Val);
1245   }
1246
1247   return Chain;
1248 }
1249
1250 /// LowerMemOpCallTo - Store the argument to the stack.
1251 SDValue
1252 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1253                                     SDValue StackPtr, SDValue Arg,
1254                                     DebugLoc dl, SelectionDAG &DAG,
1255                                     const CCValAssign &VA,
1256                                     ISD::ArgFlagsTy Flags) const {
1257   unsigned LocMemOffset = VA.getLocMemOffset();
1258   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1259   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1260   return DAG.getStore(Chain, dl, Arg, PtrOff,
1261                       MachinePointerInfo::getStack(LocMemOffset),
1262                       false, false, 0);
1263 }
1264
1265 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1266                                          SDValue Chain, SDValue &Arg,
1267                                          RegsToPassVector &RegsToPass,
1268                                          CCValAssign &VA, CCValAssign &NextVA,
1269                                          SDValue &StackPtr,
1270                                          SmallVector<SDValue, 8> &MemOpChains,
1271                                          ISD::ArgFlagsTy Flags) const {
1272
1273   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1274                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1275   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1276
1277   if (NextVA.isRegLoc())
1278     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1279   else {
1280     assert(NextVA.isMemLoc());
1281     if (StackPtr.getNode() == 0)
1282       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1283
1284     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1285                                            dl, DAG, NextVA,
1286                                            Flags));
1287   }
1288 }
1289
1290 /// LowerCall - Lowering a call into a callseq_start <-
1291 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1292 /// nodes.
1293 SDValue
1294 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1295                              SmallVectorImpl<SDValue> &InVals) const {
1296   SelectionDAG &DAG                     = CLI.DAG;
1297   DebugLoc &dl                          = CLI.DL;
1298   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1299   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1300   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1301   SDValue Chain                         = CLI.Chain;
1302   SDValue Callee                        = CLI.Callee;
1303   bool &isTailCall                      = CLI.IsTailCall;
1304   CallingConv::ID CallConv              = CLI.CallConv;
1305   bool doesNotRet                       = CLI.DoesNotReturn;
1306   bool isVarArg                         = CLI.IsVarArg;
1307
1308   MachineFunction &MF = DAG.getMachineFunction();
1309   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1310   bool IsSibCall = false;
1311   // Disable tail calls if they're not supported.
1312   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1313     isTailCall = false;
1314   if (isTailCall) {
1315     // Check if it's really possible to do a tail call.
1316     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1317                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1318                                                    Outs, OutVals, Ins, DAG);
1319     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1320     // detected sibcalls.
1321     if (isTailCall) {
1322       ++NumTailCalls;
1323       IsSibCall = true;
1324     }
1325   }
1326
1327   // Analyze operands of the call, assigning locations to each operand.
1328   SmallVector<CCValAssign, 16> ArgLocs;
1329   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1330                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1331   CCInfo.AnalyzeCallOperands(Outs,
1332                              CCAssignFnForNode(CallConv, /* Return*/ false,
1333                                                isVarArg));
1334
1335   // Get a count of how many bytes are to be pushed on the stack.
1336   unsigned NumBytes = CCInfo.getNextStackOffset();
1337
1338   // For tail calls, memory operands are available in our caller's stack.
1339   if (IsSibCall)
1340     NumBytes = 0;
1341
1342   // Adjust the stack pointer for the new arguments...
1343   // These operations are automatically eliminated by the prolog/epilog pass
1344   if (!IsSibCall)
1345     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1346
1347   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1348
1349   RegsToPassVector RegsToPass;
1350   SmallVector<SDValue, 8> MemOpChains;
1351
1352   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1353   // of tail call optimization, arguments are handled later.
1354   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1355        i != e;
1356        ++i, ++realArgIdx) {
1357     CCValAssign &VA = ArgLocs[i];
1358     SDValue Arg = OutVals[realArgIdx];
1359     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1360     bool isByVal = Flags.isByVal();
1361
1362     // Promote the value if needed.
1363     switch (VA.getLocInfo()) {
1364     default: llvm_unreachable("Unknown loc info!");
1365     case CCValAssign::Full: break;
1366     case CCValAssign::SExt:
1367       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1368       break;
1369     case CCValAssign::ZExt:
1370       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1371       break;
1372     case CCValAssign::AExt:
1373       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1374       break;
1375     case CCValAssign::BCvt:
1376       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1377       break;
1378     }
1379
1380     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1381     if (VA.needsCustom()) {
1382       if (VA.getLocVT() == MVT::v2f64) {
1383         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1384                                   DAG.getConstant(0, MVT::i32));
1385         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1386                                   DAG.getConstant(1, MVT::i32));
1387
1388         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1389                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1390
1391         VA = ArgLocs[++i]; // skip ahead to next loc
1392         if (VA.isRegLoc()) {
1393           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1394                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1395         } else {
1396           assert(VA.isMemLoc());
1397
1398           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1399                                                  dl, DAG, VA, Flags));
1400         }
1401       } else {
1402         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1403                          StackPtr, MemOpChains, Flags);
1404       }
1405     } else if (VA.isRegLoc()) {
1406       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1407     } else if (isByVal) {
1408       assert(VA.isMemLoc());
1409       unsigned offset = 0;
1410
1411       // True if this byval aggregate will be split between registers
1412       // and memory.
1413       if (CCInfo.isFirstByValRegValid()) {
1414         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1415         unsigned int i, j;
1416         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1417           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1418           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1419           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1420                                      MachinePointerInfo(),
1421                                      false, false, false, 0);
1422           MemOpChains.push_back(Load.getValue(1));
1423           RegsToPass.push_back(std::make_pair(j, Load));
1424         }
1425         offset = ARM::R4 - CCInfo.getFirstByValReg();
1426         CCInfo.clearFirstByValReg();
1427       }
1428
1429       if (Flags.getByValSize() - 4*offset > 0) {
1430         unsigned LocMemOffset = VA.getLocMemOffset();
1431         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1432         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1433                                   StkPtrOff);
1434         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1435         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1436         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1437                                            MVT::i32);
1438         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1439
1440         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1441         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1442         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1443                                           Ops, array_lengthof(Ops)));
1444       }
1445     } else if (!IsSibCall) {
1446       assert(VA.isMemLoc());
1447
1448       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1449                                              dl, DAG, VA, Flags));
1450     }
1451   }
1452
1453   if (!MemOpChains.empty())
1454     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1455                         &MemOpChains[0], MemOpChains.size());
1456
1457   // Build a sequence of copy-to-reg nodes chained together with token chain
1458   // and flag operands which copy the outgoing args into the appropriate regs.
1459   SDValue InFlag;
1460   // Tail call byval lowering might overwrite argument registers so in case of
1461   // tail call optimization the copies to registers are lowered later.
1462   if (!isTailCall)
1463     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1464       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1465                                RegsToPass[i].second, InFlag);
1466       InFlag = Chain.getValue(1);
1467     }
1468
1469   // For tail calls lower the arguments to the 'real' stack slot.
1470   if (isTailCall) {
1471     // Force all the incoming stack arguments to be loaded from the stack
1472     // before any new outgoing arguments are stored to the stack, because the
1473     // outgoing stack slots may alias the incoming argument stack slots, and
1474     // the alias isn't otherwise explicit. This is slightly more conservative
1475     // than necessary, because it means that each store effectively depends
1476     // on every argument instead of just those arguments it would clobber.
1477
1478     // Do not flag preceding copytoreg stuff together with the following stuff.
1479     InFlag = SDValue();
1480     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1481       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1482                                RegsToPass[i].second, InFlag);
1483       InFlag = Chain.getValue(1);
1484     }
1485     InFlag =SDValue();
1486   }
1487
1488   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1489   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1490   // node so that legalize doesn't hack it.
1491   bool isDirect = false;
1492   bool isARMFunc = false;
1493   bool isLocalARMFunc = false;
1494   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1495
1496   if (EnableARMLongCalls) {
1497     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1498             && "long-calls with non-static relocation model!");
1499     // Handle a global address or an external symbol. If it's not one of
1500     // those, the target's already in a register, so we don't need to do
1501     // anything extra.
1502     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1503       const GlobalValue *GV = G->getGlobal();
1504       // Create a constant pool entry for the callee address
1505       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1506       ARMConstantPoolValue *CPV =
1507         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1508
1509       // Get the address of the callee into a register
1510       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1511       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1512       Callee = DAG.getLoad(getPointerTy(), dl,
1513                            DAG.getEntryNode(), CPAddr,
1514                            MachinePointerInfo::getConstantPool(),
1515                            false, false, false, 0);
1516     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1517       const char *Sym = S->getSymbol();
1518
1519       // Create a constant pool entry for the callee address
1520       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1521       ARMConstantPoolValue *CPV =
1522         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1523                                       ARMPCLabelIndex, 0);
1524       // Get the address of the callee into a register
1525       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1526       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1527       Callee = DAG.getLoad(getPointerTy(), dl,
1528                            DAG.getEntryNode(), CPAddr,
1529                            MachinePointerInfo::getConstantPool(),
1530                            false, false, false, 0);
1531     }
1532   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1533     const GlobalValue *GV = G->getGlobal();
1534     isDirect = true;
1535     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1536     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1537                    getTargetMachine().getRelocationModel() != Reloc::Static;
1538     isARMFunc = !Subtarget->isThumb() || isStub;
1539     // ARM call to a local ARM function is predicable.
1540     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1541     // tBX takes a register source operand.
1542     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1543       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1544       ARMConstantPoolValue *CPV =
1545         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1546       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1547       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1548       Callee = DAG.getLoad(getPointerTy(), dl,
1549                            DAG.getEntryNode(), CPAddr,
1550                            MachinePointerInfo::getConstantPool(),
1551                            false, false, false, 0);
1552       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1553       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1554                            getPointerTy(), Callee, PICLabel);
1555     } else {
1556       // On ELF targets for PIC code, direct calls should go through the PLT
1557       unsigned OpFlags = 0;
1558       if (Subtarget->isTargetELF() &&
1559                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1560         OpFlags = ARMII::MO_PLT;
1561       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1562     }
1563   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1564     isDirect = true;
1565     bool isStub = Subtarget->isTargetDarwin() &&
1566                   getTargetMachine().getRelocationModel() != Reloc::Static;
1567     isARMFunc = !Subtarget->isThumb() || isStub;
1568     // tBX takes a register source operand.
1569     const char *Sym = S->getSymbol();
1570     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1571       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1572       ARMConstantPoolValue *CPV =
1573         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1574                                       ARMPCLabelIndex, 4);
1575       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1576       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1577       Callee = DAG.getLoad(getPointerTy(), dl,
1578                            DAG.getEntryNode(), CPAddr,
1579                            MachinePointerInfo::getConstantPool(),
1580                            false, false, false, 0);
1581       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1582       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1583                            getPointerTy(), Callee, PICLabel);
1584     } else {
1585       unsigned OpFlags = 0;
1586       // On ELF targets for PIC code, direct calls should go through the PLT
1587       if (Subtarget->isTargetELF() &&
1588                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1589         OpFlags = ARMII::MO_PLT;
1590       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1591     }
1592   }
1593
1594   // FIXME: handle tail calls differently.
1595   unsigned CallOpc;
1596   if (Subtarget->isThumb()) {
1597     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1598       CallOpc = ARMISD::CALL_NOLINK;
1599     else if (doesNotRet && isDirect && !isARMFunc &&
1600              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1601       // "mov lr, pc; b _foo" to avoid confusing the RSP
1602       CallOpc = ARMISD::CALL_NOLINK;
1603     else
1604       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1605   } else {
1606     if (!isDirect && !Subtarget->hasV5TOps()) {
1607       CallOpc = ARMISD::CALL_NOLINK;
1608     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1609       // "mov lr, pc; b _foo" to avoid confusing the RSP
1610       CallOpc = ARMISD::CALL_NOLINK;
1611     else
1612       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1613   }
1614
1615   std::vector<SDValue> Ops;
1616   Ops.push_back(Chain);
1617   Ops.push_back(Callee);
1618
1619   // Add argument registers to the end of the list so that they are known live
1620   // into the call.
1621   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1622     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1623                                   RegsToPass[i].second.getValueType()));
1624
1625   // Add a register mask operand representing the call-preserved registers.
1626   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1627   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1628   assert(Mask && "Missing call preserved mask for calling convention");
1629   Ops.push_back(DAG.getRegisterMask(Mask));
1630
1631   if (InFlag.getNode())
1632     Ops.push_back(InFlag);
1633
1634   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1635   if (isTailCall)
1636     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1637
1638   // Returns a chain and a flag for retval copy to use.
1639   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1640   InFlag = Chain.getValue(1);
1641
1642   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1643                              DAG.getIntPtrConstant(0, true), InFlag);
1644   if (!Ins.empty())
1645     InFlag = Chain.getValue(1);
1646
1647   // Handle result values, copying them out of physregs into vregs that we
1648   // return.
1649   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1650                          dl, DAG, InVals);
1651 }
1652
1653 /// HandleByVal - Every parameter *after* a byval parameter is passed
1654 /// on the stack.  Remember the next parameter register to allocate,
1655 /// and then confiscate the rest of the parameter registers to insure
1656 /// this.
1657 void
1658 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1659   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1660   assert((State->getCallOrPrologue() == Prologue ||
1661           State->getCallOrPrologue() == Call) &&
1662          "unhandled ParmContext");
1663   if ((!State->isFirstByValRegValid()) &&
1664       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1665     State->setFirstByValReg(reg);
1666     // At a call site, a byval parameter that is split between
1667     // registers and memory needs its size truncated here.  In a
1668     // function prologue, such byval parameters are reassembled in
1669     // memory, and are not truncated.
1670     if (State->getCallOrPrologue() == Call) {
1671       unsigned excess = 4 * (ARM::R4 - reg);
1672       assert(size >= excess && "expected larger existing stack allocation");
1673       size -= excess;
1674     }
1675   }
1676   // Confiscate any remaining parameter registers to preclude their
1677   // assignment to subsequent parameters.
1678   while (State->AllocateReg(GPRArgRegs, 4))
1679     ;
1680 }
1681
1682 /// MatchingStackOffset - Return true if the given stack call argument is
1683 /// already available in the same position (relatively) of the caller's
1684 /// incoming argument stack.
1685 static
1686 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1687                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1688                          const TargetInstrInfo *TII) {
1689   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1690   int FI = INT_MAX;
1691   if (Arg.getOpcode() == ISD::CopyFromReg) {
1692     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1693     if (!TargetRegisterInfo::isVirtualRegister(VR))
1694       return false;
1695     MachineInstr *Def = MRI->getVRegDef(VR);
1696     if (!Def)
1697       return false;
1698     if (!Flags.isByVal()) {
1699       if (!TII->isLoadFromStackSlot(Def, FI))
1700         return false;
1701     } else {
1702       return false;
1703     }
1704   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1705     if (Flags.isByVal())
1706       // ByVal argument is passed in as a pointer but it's now being
1707       // dereferenced. e.g.
1708       // define @foo(%struct.X* %A) {
1709       //   tail call @bar(%struct.X* byval %A)
1710       // }
1711       return false;
1712     SDValue Ptr = Ld->getBasePtr();
1713     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1714     if (!FINode)
1715       return false;
1716     FI = FINode->getIndex();
1717   } else
1718     return false;
1719
1720   assert(FI != INT_MAX);
1721   if (!MFI->isFixedObjectIndex(FI))
1722     return false;
1723   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1724 }
1725
1726 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1727 /// for tail call optimization. Targets which want to do tail call
1728 /// optimization should implement this function.
1729 bool
1730 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1731                                                      CallingConv::ID CalleeCC,
1732                                                      bool isVarArg,
1733                                                      bool isCalleeStructRet,
1734                                                      bool isCallerStructRet,
1735                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1736                                     const SmallVectorImpl<SDValue> &OutVals,
1737                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1738                                                      SelectionDAG& DAG) const {
1739   const Function *CallerF = DAG.getMachineFunction().getFunction();
1740   CallingConv::ID CallerCC = CallerF->getCallingConv();
1741   bool CCMatch = CallerCC == CalleeCC;
1742
1743   // Look for obvious safe cases to perform tail call optimization that do not
1744   // require ABI changes. This is what gcc calls sibcall.
1745
1746   // Do not sibcall optimize vararg calls unless the call site is not passing
1747   // any arguments.
1748   if (isVarArg && !Outs.empty())
1749     return false;
1750
1751   // Also avoid sibcall optimization if either caller or callee uses struct
1752   // return semantics.
1753   if (isCalleeStructRet || isCallerStructRet)
1754     return false;
1755
1756   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1757   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1758   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1759   // support in the assembler and linker to be used. This would need to be
1760   // fixed to fully support tail calls in Thumb1.
1761   //
1762   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1763   // LR.  This means if we need to reload LR, it takes an extra instructions,
1764   // which outweighs the value of the tail call; but here we don't know yet
1765   // whether LR is going to be used.  Probably the right approach is to
1766   // generate the tail call here and turn it back into CALL/RET in
1767   // emitEpilogue if LR is used.
1768
1769   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1770   // but we need to make sure there are enough registers; the only valid
1771   // registers are the 4 used for parameters.  We don't currently do this
1772   // case.
1773   if (Subtarget->isThumb1Only())
1774     return false;
1775
1776   // If the calling conventions do not match, then we'd better make sure the
1777   // results are returned in the same way as what the caller expects.
1778   if (!CCMatch) {
1779     SmallVector<CCValAssign, 16> RVLocs1;
1780     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1781                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1782     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1783
1784     SmallVector<CCValAssign, 16> RVLocs2;
1785     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1786                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1787     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1788
1789     if (RVLocs1.size() != RVLocs2.size())
1790       return false;
1791     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1792       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1793         return false;
1794       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1795         return false;
1796       if (RVLocs1[i].isRegLoc()) {
1797         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1798           return false;
1799       } else {
1800         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1801           return false;
1802       }
1803     }
1804   }
1805
1806   // If the callee takes no arguments then go on to check the results of the
1807   // call.
1808   if (!Outs.empty()) {
1809     // Check if stack adjustment is needed. For now, do not do this if any
1810     // argument is passed on the stack.
1811     SmallVector<CCValAssign, 16> ArgLocs;
1812     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1813                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1814     CCInfo.AnalyzeCallOperands(Outs,
1815                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1816     if (CCInfo.getNextStackOffset()) {
1817       MachineFunction &MF = DAG.getMachineFunction();
1818
1819       // Check if the arguments are already laid out in the right way as
1820       // the caller's fixed stack objects.
1821       MachineFrameInfo *MFI = MF.getFrameInfo();
1822       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1823       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1824       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1825            i != e;
1826            ++i, ++realArgIdx) {
1827         CCValAssign &VA = ArgLocs[i];
1828         EVT RegVT = VA.getLocVT();
1829         SDValue Arg = OutVals[realArgIdx];
1830         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831         if (VA.getLocInfo() == CCValAssign::Indirect)
1832           return false;
1833         if (VA.needsCustom()) {
1834           // f64 and vector types are split into multiple registers or
1835           // register/stack-slot combinations.  The types will not match
1836           // the registers; give up on memory f64 refs until we figure
1837           // out what to do about this.
1838           if (!VA.isRegLoc())
1839             return false;
1840           if (!ArgLocs[++i].isRegLoc())
1841             return false;
1842           if (RegVT == MVT::v2f64) {
1843             if (!ArgLocs[++i].isRegLoc())
1844               return false;
1845             if (!ArgLocs[++i].isRegLoc())
1846               return false;
1847           }
1848         } else if (!VA.isRegLoc()) {
1849           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1850                                    MFI, MRI, TII))
1851             return false;
1852         }
1853       }
1854     }
1855   }
1856
1857   return true;
1858 }
1859
1860 SDValue
1861 ARMTargetLowering::LowerReturn(SDValue Chain,
1862                                CallingConv::ID CallConv, bool isVarArg,
1863                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1864                                const SmallVectorImpl<SDValue> &OutVals,
1865                                DebugLoc dl, SelectionDAG &DAG) const {
1866
1867   // CCValAssign - represent the assignment of the return value to a location.
1868   SmallVector<CCValAssign, 16> RVLocs;
1869
1870   // CCState - Info about the registers and stack slots.
1871   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1872                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1873
1874   // Analyze outgoing return values.
1875   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1876                                                isVarArg));
1877
1878   // If this is the first return lowered for this function, add
1879   // the regs to the liveout set for the function.
1880   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1881     for (unsigned i = 0; i != RVLocs.size(); ++i)
1882       if (RVLocs[i].isRegLoc())
1883         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1884   }
1885
1886   SDValue Flag;
1887
1888   // Copy the result values into the output registers.
1889   for (unsigned i = 0, realRVLocIdx = 0;
1890        i != RVLocs.size();
1891        ++i, ++realRVLocIdx) {
1892     CCValAssign &VA = RVLocs[i];
1893     assert(VA.isRegLoc() && "Can only return in registers!");
1894
1895     SDValue Arg = OutVals[realRVLocIdx];
1896
1897     switch (VA.getLocInfo()) {
1898     default: llvm_unreachable("Unknown loc info!");
1899     case CCValAssign::Full: break;
1900     case CCValAssign::BCvt:
1901       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1902       break;
1903     }
1904
1905     if (VA.needsCustom()) {
1906       if (VA.getLocVT() == MVT::v2f64) {
1907         // Extract the first half and return it in two registers.
1908         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1909                                    DAG.getConstant(0, MVT::i32));
1910         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1911                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1912
1913         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1914         Flag = Chain.getValue(1);
1915         VA = RVLocs[++i]; // skip ahead to next loc
1916         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1917                                  HalfGPRs.getValue(1), Flag);
1918         Flag = Chain.getValue(1);
1919         VA = RVLocs[++i]; // skip ahead to next loc
1920
1921         // Extract the 2nd half and fall through to handle it as an f64 value.
1922         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1923                           DAG.getConstant(1, MVT::i32));
1924       }
1925       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1926       // available.
1927       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1928                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1929       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1930       Flag = Chain.getValue(1);
1931       VA = RVLocs[++i]; // skip ahead to next loc
1932       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1933                                Flag);
1934     } else
1935       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1936
1937     // Guarantee that all emitted copies are
1938     // stuck together, avoiding something bad.
1939     Flag = Chain.getValue(1);
1940   }
1941
1942   SDValue result;
1943   if (Flag.getNode())
1944     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1945   else // Return Void
1946     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1947
1948   return result;
1949 }
1950
1951 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1952   if (N->getNumValues() != 1)
1953     return false;
1954   if (!N->hasNUsesOfValue(1, 0))
1955     return false;
1956
1957   SDValue TCChain = Chain;
1958   SDNode *Copy = *N->use_begin();
1959   if (Copy->getOpcode() == ISD::CopyToReg) {
1960     // If the copy has a glue operand, we conservatively assume it isn't safe to
1961     // perform a tail call.
1962     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1963       return false;
1964     TCChain = Copy->getOperand(0);
1965   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1966     SDNode *VMov = Copy;
1967     // f64 returned in a pair of GPRs.
1968     SmallPtrSet<SDNode*, 2> Copies;
1969     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1970          UI != UE; ++UI) {
1971       if (UI->getOpcode() != ISD::CopyToReg)
1972         return false;
1973       Copies.insert(*UI);
1974     }
1975     if (Copies.size() > 2)
1976       return false;
1977
1978     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1979          UI != UE; ++UI) {
1980       SDValue UseChain = UI->getOperand(0);
1981       if (Copies.count(UseChain.getNode()))
1982         // Second CopyToReg
1983         Copy = *UI;
1984       else
1985         // First CopyToReg
1986         TCChain = UseChain;
1987     }
1988   } else if (Copy->getOpcode() == ISD::BITCAST) {
1989     // f32 returned in a single GPR.
1990     if (!Copy->hasOneUse())
1991       return false;
1992     Copy = *Copy->use_begin();
1993     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1994       return false;
1995     Chain = Copy->getOperand(0);
1996   } else {
1997     return false;
1998   }
1999
2000   bool HasRet = false;
2001   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2002        UI != UE; ++UI) {
2003     if (UI->getOpcode() != ARMISD::RET_FLAG)
2004       return false;
2005     HasRet = true;
2006   }
2007
2008   if (!HasRet)
2009     return false;
2010
2011   Chain = TCChain;
2012   return true;
2013 }
2014
2015 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2016   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2017     return false;
2018
2019   if (!CI->isTailCall())
2020     return false;
2021
2022   return !Subtarget->isThumb1Only();
2023 }
2024
2025 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2026 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2027 // one of the above mentioned nodes. It has to be wrapped because otherwise
2028 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2029 // be used to form addressing mode. These wrapped nodes will be selected
2030 // into MOVi.
2031 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2032   EVT PtrVT = Op.getValueType();
2033   // FIXME there is no actual debug info here
2034   DebugLoc dl = Op.getDebugLoc();
2035   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2036   SDValue Res;
2037   if (CP->isMachineConstantPoolEntry())
2038     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2039                                     CP->getAlignment());
2040   else
2041     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2042                                     CP->getAlignment());
2043   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2044 }
2045
2046 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2047   return MachineJumpTableInfo::EK_Inline;
2048 }
2049
2050 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2051                                              SelectionDAG &DAG) const {
2052   MachineFunction &MF = DAG.getMachineFunction();
2053   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2054   unsigned ARMPCLabelIndex = 0;
2055   DebugLoc DL = Op.getDebugLoc();
2056   EVT PtrVT = getPointerTy();
2057   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2058   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2059   SDValue CPAddr;
2060   if (RelocM == Reloc::Static) {
2061     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2062   } else {
2063     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2064     ARMPCLabelIndex = AFI->createPICLabelUId();
2065     ARMConstantPoolValue *CPV =
2066       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2067                                       ARMCP::CPBlockAddress, PCAdj);
2068     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2069   }
2070   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2071   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2072                                MachinePointerInfo::getConstantPool(),
2073                                false, false, false, 0);
2074   if (RelocM == Reloc::Static)
2075     return Result;
2076   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2077   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2078 }
2079
2080 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2081 SDValue
2082 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2083                                                  SelectionDAG &DAG) const {
2084   DebugLoc dl = GA->getDebugLoc();
2085   EVT PtrVT = getPointerTy();
2086   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2087   MachineFunction &MF = DAG.getMachineFunction();
2088   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2089   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2090   ARMConstantPoolValue *CPV =
2091     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2092                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2093   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2094   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2095   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2096                          MachinePointerInfo::getConstantPool(),
2097                          false, false, false, 0);
2098   SDValue Chain = Argument.getValue(1);
2099
2100   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2101   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2102
2103   // call __tls_get_addr.
2104   ArgListTy Args;
2105   ArgListEntry Entry;
2106   Entry.Node = Argument;
2107   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2108   Args.push_back(Entry);
2109   // FIXME: is there useful debug info available here?
2110   TargetLowering::CallLoweringInfo CLI(Chain,
2111                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2112                 false, false, false, false,
2113                 0, CallingConv::C, /*isTailCall=*/false,
2114                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2115                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2116   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2117   return CallResult.first;
2118 }
2119
2120 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2121 // "local exec" model.
2122 SDValue
2123 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2124                                         SelectionDAG &DAG,
2125                                         TLSModel::Model model) const {
2126   const GlobalValue *GV = GA->getGlobal();
2127   DebugLoc dl = GA->getDebugLoc();
2128   SDValue Offset;
2129   SDValue Chain = DAG.getEntryNode();
2130   EVT PtrVT = getPointerTy();
2131   // Get the Thread Pointer
2132   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2133
2134   if (model == TLSModel::InitialExec) {
2135     MachineFunction &MF = DAG.getMachineFunction();
2136     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2137     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2138     // Initial exec model.
2139     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2140     ARMConstantPoolValue *CPV =
2141       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2142                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2143                                       true);
2144     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2145     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2146     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2147                          MachinePointerInfo::getConstantPool(),
2148                          false, false, false, 0);
2149     Chain = Offset.getValue(1);
2150
2151     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2152     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2153
2154     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2155                          MachinePointerInfo::getConstantPool(),
2156                          false, false, false, 0);
2157   } else {
2158     // local exec model
2159     assert(model == TLSModel::LocalExec);
2160     ARMConstantPoolValue *CPV =
2161       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2162     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2163     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2164     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2165                          MachinePointerInfo::getConstantPool(),
2166                          false, false, false, 0);
2167   }
2168
2169   // The address of the thread local variable is the add of the thread
2170   // pointer with the offset of the variable.
2171   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2172 }
2173
2174 SDValue
2175 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2176   // TODO: implement the "local dynamic" model
2177   assert(Subtarget->isTargetELF() &&
2178          "TLS not implemented for non-ELF targets");
2179   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2180
2181   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2182
2183   switch (model) {
2184     case TLSModel::GeneralDynamic:
2185     case TLSModel::LocalDynamic:
2186       return LowerToTLSGeneralDynamicModel(GA, DAG);
2187     case TLSModel::InitialExec:
2188     case TLSModel::LocalExec:
2189       return LowerToTLSExecModels(GA, DAG, model);
2190   }
2191   llvm_unreachable("bogus TLS model");
2192 }
2193
2194 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2195                                                  SelectionDAG &DAG) const {
2196   EVT PtrVT = getPointerTy();
2197   DebugLoc dl = Op.getDebugLoc();
2198   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2199   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2200   if (RelocM == Reloc::PIC_) {
2201     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2202     ARMConstantPoolValue *CPV =
2203       ARMConstantPoolConstant::Create(GV,
2204                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2205     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2206     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2207     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2208                                  CPAddr,
2209                                  MachinePointerInfo::getConstantPool(),
2210                                  false, false, false, 0);
2211     SDValue Chain = Result.getValue(1);
2212     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2213     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2214     if (!UseGOTOFF)
2215       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2216                            MachinePointerInfo::getGOT(),
2217                            false, false, false, 0);
2218     return Result;
2219   }
2220
2221   // If we have T2 ops, we can materialize the address directly via movt/movw
2222   // pair. This is always cheaper.
2223   if (Subtarget->useMovt()) {
2224     ++NumMovwMovt;
2225     // FIXME: Once remat is capable of dealing with instructions with register
2226     // operands, expand this into two nodes.
2227     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2228                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2229   } else {
2230     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2231     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2232     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2233                        MachinePointerInfo::getConstantPool(),
2234                        false, false, false, 0);
2235   }
2236 }
2237
2238 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2239                                                     SelectionDAG &DAG) const {
2240   EVT PtrVT = getPointerTy();
2241   DebugLoc dl = Op.getDebugLoc();
2242   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2243   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2244   MachineFunction &MF = DAG.getMachineFunction();
2245   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2246
2247   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2248   // update ARMFastISel::ARMMaterializeGV.
2249   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2250     ++NumMovwMovt;
2251     // FIXME: Once remat is capable of dealing with instructions with register
2252     // operands, expand this into two nodes.
2253     if (RelocM == Reloc::Static)
2254       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2255                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2256
2257     unsigned Wrapper = (RelocM == Reloc::PIC_)
2258       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2259     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2260                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2261     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2262       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2263                            MachinePointerInfo::getGOT(),
2264                            false, false, false, 0);
2265     return Result;
2266   }
2267
2268   unsigned ARMPCLabelIndex = 0;
2269   SDValue CPAddr;
2270   if (RelocM == Reloc::Static) {
2271     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2272   } else {
2273     ARMPCLabelIndex = AFI->createPICLabelUId();
2274     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2275     ARMConstantPoolValue *CPV =
2276       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2277                                       PCAdj);
2278     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2279   }
2280   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2281
2282   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2283                                MachinePointerInfo::getConstantPool(),
2284                                false, false, false, 0);
2285   SDValue Chain = Result.getValue(1);
2286
2287   if (RelocM == Reloc::PIC_) {
2288     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2289     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2290   }
2291
2292   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2293     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2294                          false, false, false, 0);
2295
2296   return Result;
2297 }
2298
2299 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2300                                                     SelectionDAG &DAG) const {
2301   assert(Subtarget->isTargetELF() &&
2302          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2303   MachineFunction &MF = DAG.getMachineFunction();
2304   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2306   EVT PtrVT = getPointerTy();
2307   DebugLoc dl = Op.getDebugLoc();
2308   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2309   ARMConstantPoolValue *CPV =
2310     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2311                                   ARMPCLabelIndex, PCAdj);
2312   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2313   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2314   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2315                                MachinePointerInfo::getConstantPool(),
2316                                false, false, false, 0);
2317   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2318   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2319 }
2320
2321 SDValue
2322 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2323   DebugLoc dl = Op.getDebugLoc();
2324   SDValue Val = DAG.getConstant(0, MVT::i32);
2325   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2326                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2327                      Op.getOperand(1), Val);
2328 }
2329
2330 SDValue
2331 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2332   DebugLoc dl = Op.getDebugLoc();
2333   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2334                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2335 }
2336
2337 SDValue
2338 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2339                                           const ARMSubtarget *Subtarget) const {
2340   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2341   DebugLoc dl = Op.getDebugLoc();
2342   switch (IntNo) {
2343   default: return SDValue();    // Don't custom lower most intrinsics.
2344   case Intrinsic::arm_thread_pointer: {
2345     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2346     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2347   }
2348   case Intrinsic::eh_sjlj_lsda: {
2349     MachineFunction &MF = DAG.getMachineFunction();
2350     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2351     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2352     EVT PtrVT = getPointerTy();
2353     DebugLoc dl = Op.getDebugLoc();
2354     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2355     SDValue CPAddr;
2356     unsigned PCAdj = (RelocM != Reloc::PIC_)
2357       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2358     ARMConstantPoolValue *CPV =
2359       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2360                                       ARMCP::CPLSDA, PCAdj);
2361     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2362     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2363     SDValue Result =
2364       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2365                   MachinePointerInfo::getConstantPool(),
2366                   false, false, false, 0);
2367
2368     if (RelocM == Reloc::PIC_) {
2369       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2370       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2371     }
2372     return Result;
2373   }
2374   case Intrinsic::arm_neon_vmulls:
2375   case Intrinsic::arm_neon_vmullu: {
2376     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2377       ? ARMISD::VMULLs : ARMISD::VMULLu;
2378     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2379                        Op.getOperand(1), Op.getOperand(2));
2380   }
2381   }
2382 }
2383
2384 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2385                                const ARMSubtarget *Subtarget) {
2386   DebugLoc dl = Op.getDebugLoc();
2387   if (!Subtarget->hasDataBarrier()) {
2388     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2389     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2390     // here.
2391     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2392            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2393     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2394                        DAG.getConstant(0, MVT::i32));
2395   }
2396
2397   SDValue Op5 = Op.getOperand(5);
2398   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2399   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2400   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2401   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2402
2403   ARM_MB::MemBOpt DMBOpt;
2404   if (isDeviceBarrier)
2405     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2406   else
2407     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2408   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2409                      DAG.getConstant(DMBOpt, MVT::i32));
2410 }
2411
2412
2413 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2414                                  const ARMSubtarget *Subtarget) {
2415   // FIXME: handle "fence singlethread" more efficiently.
2416   DebugLoc dl = Op.getDebugLoc();
2417   if (!Subtarget->hasDataBarrier()) {
2418     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2419     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2420     // here.
2421     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2422            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2423     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2424                        DAG.getConstant(0, MVT::i32));
2425   }
2426
2427   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2428                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2429 }
2430
2431 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2432                              const ARMSubtarget *Subtarget) {
2433   // ARM pre v5TE and Thumb1 does not have preload instructions.
2434   if (!(Subtarget->isThumb2() ||
2435         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2436     // Just preserve the chain.
2437     return Op.getOperand(0);
2438
2439   DebugLoc dl = Op.getDebugLoc();
2440   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2441   if (!isRead &&
2442       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2443     // ARMv7 with MP extension has PLDW.
2444     return Op.getOperand(0);
2445
2446   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2447   if (Subtarget->isThumb()) {
2448     // Invert the bits.
2449     isRead = ~isRead & 1;
2450     isData = ~isData & 1;
2451   }
2452
2453   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2454                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2455                      DAG.getConstant(isData, MVT::i32));
2456 }
2457
2458 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2459   MachineFunction &MF = DAG.getMachineFunction();
2460   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2461
2462   // vastart just stores the address of the VarArgsFrameIndex slot into the
2463   // memory location argument.
2464   DebugLoc dl = Op.getDebugLoc();
2465   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2466   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2467   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2468   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2469                       MachinePointerInfo(SV), false, false, 0);
2470 }
2471
2472 SDValue
2473 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2474                                         SDValue &Root, SelectionDAG &DAG,
2475                                         DebugLoc dl) const {
2476   MachineFunction &MF = DAG.getMachineFunction();
2477   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2478
2479   const TargetRegisterClass *RC;
2480   if (AFI->isThumb1OnlyFunction())
2481     RC = &ARM::tGPRRegClass;
2482   else
2483     RC = &ARM::GPRRegClass;
2484
2485   // Transform the arguments stored in physical registers into virtual ones.
2486   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2487   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2488
2489   SDValue ArgValue2;
2490   if (NextVA.isMemLoc()) {
2491     MachineFrameInfo *MFI = MF.getFrameInfo();
2492     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2493
2494     // Create load node to retrieve arguments from the stack.
2495     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2496     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2497                             MachinePointerInfo::getFixedStack(FI),
2498                             false, false, false, 0);
2499   } else {
2500     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2501     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2502   }
2503
2504   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2505 }
2506
2507 void
2508 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2509                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2510   const {
2511   unsigned NumGPRs;
2512   if (CCInfo.isFirstByValRegValid())
2513     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2514   else {
2515     unsigned int firstUnalloced;
2516     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2517                                                 sizeof(GPRArgRegs) /
2518                                                 sizeof(GPRArgRegs[0]));
2519     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2520   }
2521
2522   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2523   VARegSize = NumGPRs * 4;
2524   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2525 }
2526
2527 // The remaining GPRs hold either the beginning of variable-argument
2528 // data, or the beginning of an aggregate passed by value (usuall
2529 // byval).  Either way, we allocate stack slots adjacent to the data
2530 // provided by our caller, and store the unallocated registers there.
2531 // If this is a variadic function, the va_list pointer will begin with
2532 // these values; otherwise, this reassembles a (byval) structure that
2533 // was split between registers and memory.
2534 void
2535 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2536                                         DebugLoc dl, SDValue &Chain,
2537                                         unsigned ArgOffset) const {
2538   MachineFunction &MF = DAG.getMachineFunction();
2539   MachineFrameInfo *MFI = MF.getFrameInfo();
2540   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2541   unsigned firstRegToSaveIndex;
2542   if (CCInfo.isFirstByValRegValid())
2543     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2544   else {
2545     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2546       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2547   }
2548
2549   unsigned VARegSize, VARegSaveSize;
2550   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2551   if (VARegSaveSize) {
2552     // If this function is vararg, store any remaining integer argument regs
2553     // to their spots on the stack so that they may be loaded by deferencing
2554     // the result of va_next.
2555     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2556     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2557                                                      ArgOffset + VARegSaveSize
2558                                                      - VARegSize,
2559                                                      false));
2560     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2561                                     getPointerTy());
2562
2563     SmallVector<SDValue, 4> MemOps;
2564     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2565       const TargetRegisterClass *RC;
2566       if (AFI->isThumb1OnlyFunction())
2567         RC = &ARM::tGPRRegClass;
2568       else
2569         RC = &ARM::GPRRegClass;
2570
2571       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2572       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2573       SDValue Store =
2574         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2575                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2576                      false, false, 0);
2577       MemOps.push_back(Store);
2578       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2579                         DAG.getConstant(4, getPointerTy()));
2580     }
2581     if (!MemOps.empty())
2582       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2583                           &MemOps[0], MemOps.size());
2584   } else
2585     // This will point to the next argument passed via stack.
2586     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2587 }
2588
2589 SDValue
2590 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2591                                         CallingConv::ID CallConv, bool isVarArg,
2592                                         const SmallVectorImpl<ISD::InputArg>
2593                                           &Ins,
2594                                         DebugLoc dl, SelectionDAG &DAG,
2595                                         SmallVectorImpl<SDValue> &InVals)
2596                                           const {
2597   MachineFunction &MF = DAG.getMachineFunction();
2598   MachineFrameInfo *MFI = MF.getFrameInfo();
2599
2600   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601
2602   // Assign locations to all of the incoming arguments.
2603   SmallVector<CCValAssign, 16> ArgLocs;
2604   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2605                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2606   CCInfo.AnalyzeFormalArguments(Ins,
2607                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2608                                                   isVarArg));
2609
2610   SmallVector<SDValue, 16> ArgValues;
2611   int lastInsIndex = -1;
2612
2613   SDValue ArgValue;
2614   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2615     CCValAssign &VA = ArgLocs[i];
2616
2617     // Arguments stored in registers.
2618     if (VA.isRegLoc()) {
2619       EVT RegVT = VA.getLocVT();
2620
2621       if (VA.needsCustom()) {
2622         // f64 and vector types are split up into multiple registers or
2623         // combinations of registers and stack slots.
2624         if (VA.getLocVT() == MVT::v2f64) {
2625           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2626                                                    Chain, DAG, dl);
2627           VA = ArgLocs[++i]; // skip ahead to next loc
2628           SDValue ArgValue2;
2629           if (VA.isMemLoc()) {
2630             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2631             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2632             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2633                                     MachinePointerInfo::getFixedStack(FI),
2634                                     false, false, false, 0);
2635           } else {
2636             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2637                                              Chain, DAG, dl);
2638           }
2639           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2640           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2641                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2642           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2643                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2644         } else
2645           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2646
2647       } else {
2648         const TargetRegisterClass *RC;
2649
2650         if (RegVT == MVT::f32)
2651           RC = &ARM::SPRRegClass;
2652         else if (RegVT == MVT::f64)
2653           RC = &ARM::DPRRegClass;
2654         else if (RegVT == MVT::v2f64)
2655           RC = &ARM::QPRRegClass;
2656         else if (RegVT == MVT::i32)
2657           RC = AFI->isThumb1OnlyFunction() ?
2658             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2659             (const TargetRegisterClass*)&ARM::GPRRegClass;
2660         else
2661           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2662
2663         // Transform the arguments in physical registers into virtual ones.
2664         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2665         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2666       }
2667
2668       // If this is an 8 or 16-bit value, it is really passed promoted
2669       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2670       // truncate to the right size.
2671       switch (VA.getLocInfo()) {
2672       default: llvm_unreachable("Unknown loc info!");
2673       case CCValAssign::Full: break;
2674       case CCValAssign::BCvt:
2675         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2676         break;
2677       case CCValAssign::SExt:
2678         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2679                                DAG.getValueType(VA.getValVT()));
2680         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2681         break;
2682       case CCValAssign::ZExt:
2683         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2684                                DAG.getValueType(VA.getValVT()));
2685         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2686         break;
2687       }
2688
2689       InVals.push_back(ArgValue);
2690
2691     } else { // VA.isRegLoc()
2692
2693       // sanity check
2694       assert(VA.isMemLoc());
2695       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2696
2697       int index = ArgLocs[i].getValNo();
2698
2699       // Some Ins[] entries become multiple ArgLoc[] entries.
2700       // Process them only once.
2701       if (index != lastInsIndex)
2702         {
2703           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2704           // FIXME: For now, all byval parameter objects are marked mutable.
2705           // This can be changed with more analysis.
2706           // In case of tail call optimization mark all arguments mutable.
2707           // Since they could be overwritten by lowering of arguments in case of
2708           // a tail call.
2709           if (Flags.isByVal()) {
2710             unsigned VARegSize, VARegSaveSize;
2711             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2712             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2713             unsigned Bytes = Flags.getByValSize() - VARegSize;
2714             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2715             int FI = MFI->CreateFixedObject(Bytes,
2716                                             VA.getLocMemOffset(), false);
2717             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2718           } else {
2719             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2720                                             VA.getLocMemOffset(), true);
2721
2722             // Create load nodes to retrieve arguments from the stack.
2723             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2724             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2725                                          MachinePointerInfo::getFixedStack(FI),
2726                                          false, false, false, 0));
2727           }
2728           lastInsIndex = index;
2729         }
2730     }
2731   }
2732
2733   // varargs
2734   if (isVarArg)
2735     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2736
2737   return Chain;
2738 }
2739
2740 /// isFloatingPointZero - Return true if this is +0.0.
2741 static bool isFloatingPointZero(SDValue Op) {
2742   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2743     return CFP->getValueAPF().isPosZero();
2744   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2745     // Maybe this has already been legalized into the constant pool?
2746     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2747       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2748       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2749         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2750           return CFP->getValueAPF().isPosZero();
2751     }
2752   }
2753   return false;
2754 }
2755
2756 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2757 /// the given operands.
2758 SDValue
2759 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2760                              SDValue &ARMcc, SelectionDAG &DAG,
2761                              DebugLoc dl) const {
2762   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2763     unsigned C = RHSC->getZExtValue();
2764     if (!isLegalICmpImmediate(C)) {
2765       // Constant does not fit, try adjusting it by one?
2766       switch (CC) {
2767       default: break;
2768       case ISD::SETLT:
2769       case ISD::SETGE:
2770         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2771           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2772           RHS = DAG.getConstant(C-1, MVT::i32);
2773         }
2774         break;
2775       case ISD::SETULT:
2776       case ISD::SETUGE:
2777         if (C != 0 && isLegalICmpImmediate(C-1)) {
2778           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2779           RHS = DAG.getConstant(C-1, MVT::i32);
2780         }
2781         break;
2782       case ISD::SETLE:
2783       case ISD::SETGT:
2784         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2785           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2786           RHS = DAG.getConstant(C+1, MVT::i32);
2787         }
2788         break;
2789       case ISD::SETULE:
2790       case ISD::SETUGT:
2791         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2792           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2793           RHS = DAG.getConstant(C+1, MVT::i32);
2794         }
2795         break;
2796       }
2797     }
2798   }
2799
2800   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2801   ARMISD::NodeType CompareType;
2802   switch (CondCode) {
2803   default:
2804     CompareType = ARMISD::CMP;
2805     break;
2806   case ARMCC::EQ:
2807   case ARMCC::NE:
2808     // Uses only Z Flag
2809     CompareType = ARMISD::CMPZ;
2810     break;
2811   }
2812   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2813   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2814 }
2815
2816 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2817 SDValue
2818 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2819                              DebugLoc dl) const {
2820   SDValue Cmp;
2821   if (!isFloatingPointZero(RHS))
2822     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2823   else
2824     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2825   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2826 }
2827
2828 /// duplicateCmp - Glue values can have only one use, so this function
2829 /// duplicates a comparison node.
2830 SDValue
2831 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2832   unsigned Opc = Cmp.getOpcode();
2833   DebugLoc DL = Cmp.getDebugLoc();
2834   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2835     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2836
2837   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2838   Cmp = Cmp.getOperand(0);
2839   Opc = Cmp.getOpcode();
2840   if (Opc == ARMISD::CMPFP)
2841     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2842   else {
2843     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2844     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2845   }
2846   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2847 }
2848
2849 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2850   SDValue Cond = Op.getOperand(0);
2851   SDValue SelectTrue = Op.getOperand(1);
2852   SDValue SelectFalse = Op.getOperand(2);
2853   DebugLoc dl = Op.getDebugLoc();
2854
2855   // Convert:
2856   //
2857   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2858   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2859   //
2860   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2861     const ConstantSDNode *CMOVTrue =
2862       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2863     const ConstantSDNode *CMOVFalse =
2864       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2865
2866     if (CMOVTrue && CMOVFalse) {
2867       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2868       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2869
2870       SDValue True;
2871       SDValue False;
2872       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2873         True = SelectTrue;
2874         False = SelectFalse;
2875       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2876         True = SelectFalse;
2877         False = SelectTrue;
2878       }
2879
2880       if (True.getNode() && False.getNode()) {
2881         EVT VT = Op.getValueType();
2882         SDValue ARMcc = Cond.getOperand(2);
2883         SDValue CCR = Cond.getOperand(3);
2884         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2885         assert(True.getValueType() == VT);
2886         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2887       }
2888     }
2889   }
2890
2891   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2892   // undefined bits before doing a full-word comparison with zero.
2893   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2894                      DAG.getConstant(1, Cond.getValueType()));
2895
2896   return DAG.getSelectCC(dl, Cond,
2897                          DAG.getConstant(0, Cond.getValueType()),
2898                          SelectTrue, SelectFalse, ISD::SETNE);
2899 }
2900
2901 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2902   EVT VT = Op.getValueType();
2903   SDValue LHS = Op.getOperand(0);
2904   SDValue RHS = Op.getOperand(1);
2905   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2906   SDValue TrueVal = Op.getOperand(2);
2907   SDValue FalseVal = Op.getOperand(3);
2908   DebugLoc dl = Op.getDebugLoc();
2909
2910   if (LHS.getValueType() == MVT::i32) {
2911     SDValue ARMcc;
2912     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2913     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2914     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2915   }
2916
2917   ARMCC::CondCodes CondCode, CondCode2;
2918   FPCCToARMCC(CC, CondCode, CondCode2);
2919
2920   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2921   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2922   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2923   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2924                                ARMcc, CCR, Cmp);
2925   if (CondCode2 != ARMCC::AL) {
2926     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2927     // FIXME: Needs another CMP because flag can have but one use.
2928     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2929     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2930                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2931   }
2932   return Result;
2933 }
2934
2935 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2936 /// to morph to an integer compare sequence.
2937 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2938                            const ARMSubtarget *Subtarget) {
2939   SDNode *N = Op.getNode();
2940   if (!N->hasOneUse())
2941     // Otherwise it requires moving the value from fp to integer registers.
2942     return false;
2943   if (!N->getNumValues())
2944     return false;
2945   EVT VT = Op.getValueType();
2946   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2947     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2948     // vmrs are very slow, e.g. cortex-a8.
2949     return false;
2950
2951   if (isFloatingPointZero(Op)) {
2952     SeenZero = true;
2953     return true;
2954   }
2955   return ISD::isNormalLoad(N);
2956 }
2957
2958 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2959   if (isFloatingPointZero(Op))
2960     return DAG.getConstant(0, MVT::i32);
2961
2962   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2963     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2964                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2965                        Ld->isVolatile(), Ld->isNonTemporal(),
2966                        Ld->isInvariant(), Ld->getAlignment());
2967
2968   llvm_unreachable("Unknown VFP cmp argument!");
2969 }
2970
2971 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2972                            SDValue &RetVal1, SDValue &RetVal2) {
2973   if (isFloatingPointZero(Op)) {
2974     RetVal1 = DAG.getConstant(0, MVT::i32);
2975     RetVal2 = DAG.getConstant(0, MVT::i32);
2976     return;
2977   }
2978
2979   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2980     SDValue Ptr = Ld->getBasePtr();
2981     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2982                           Ld->getChain(), Ptr,
2983                           Ld->getPointerInfo(),
2984                           Ld->isVolatile(), Ld->isNonTemporal(),
2985                           Ld->isInvariant(), Ld->getAlignment());
2986
2987     EVT PtrType = Ptr.getValueType();
2988     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2989     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2990                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2991     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2992                           Ld->getChain(), NewPtr,
2993                           Ld->getPointerInfo().getWithOffset(4),
2994                           Ld->isVolatile(), Ld->isNonTemporal(),
2995                           Ld->isInvariant(), NewAlign);
2996     return;
2997   }
2998
2999   llvm_unreachable("Unknown VFP cmp argument!");
3000 }
3001
3002 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3003 /// f32 and even f64 comparisons to integer ones.
3004 SDValue
3005 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3006   SDValue Chain = Op.getOperand(0);
3007   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3008   SDValue LHS = Op.getOperand(2);
3009   SDValue RHS = Op.getOperand(3);
3010   SDValue Dest = Op.getOperand(4);
3011   DebugLoc dl = Op.getDebugLoc();
3012
3013   bool LHSSeenZero = false;
3014   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3015   bool RHSSeenZero = false;
3016   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3017   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3018     // If unsafe fp math optimization is enabled and there are no other uses of
3019     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3020     // to an integer comparison.
3021     if (CC == ISD::SETOEQ)
3022       CC = ISD::SETEQ;
3023     else if (CC == ISD::SETUNE)
3024       CC = ISD::SETNE;
3025
3026     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3027     SDValue ARMcc;
3028     if (LHS.getValueType() == MVT::f32) {
3029       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3030                         bitcastf32Toi32(LHS, DAG), Mask);
3031       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3032                         bitcastf32Toi32(RHS, DAG), Mask);
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     SDValue LHS1, LHS2;
3040     SDValue RHS1, RHS2;
3041     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3042     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3043     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3044     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3045     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3046     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3047     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3048     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3049     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3050   }
3051
3052   return SDValue();
3053 }
3054
3055 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3056   SDValue Chain = Op.getOperand(0);
3057   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3058   SDValue LHS = Op.getOperand(2);
3059   SDValue RHS = Op.getOperand(3);
3060   SDValue Dest = Op.getOperand(4);
3061   DebugLoc dl = Op.getDebugLoc();
3062
3063   if (LHS.getValueType() == MVT::i32) {
3064     SDValue ARMcc;
3065     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3066     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3067     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3068                        Chain, Dest, ARMcc, CCR, Cmp);
3069   }
3070
3071   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3072
3073   if (getTargetMachine().Options.UnsafeFPMath &&
3074       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3075        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3076     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3077     if (Result.getNode())
3078       return Result;
3079   }
3080
3081   ARMCC::CondCodes CondCode, CondCode2;
3082   FPCCToARMCC(CC, CondCode, CondCode2);
3083
3084   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3085   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3086   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3087   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3088   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3089   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3090   if (CondCode2 != ARMCC::AL) {
3091     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3092     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3093     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3094   }
3095   return Res;
3096 }
3097
3098 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3099   SDValue Chain = Op.getOperand(0);
3100   SDValue Table = Op.getOperand(1);
3101   SDValue Index = Op.getOperand(2);
3102   DebugLoc dl = Op.getDebugLoc();
3103
3104   EVT PTy = getPointerTy();
3105   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3106   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3107   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3108   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3109   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3110   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3111   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3112   if (Subtarget->isThumb2()) {
3113     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3114     // which does another jump to the destination. This also makes it easier
3115     // to translate it to TBB / TBH later.
3116     // FIXME: This might not work if the function is extremely large.
3117     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3118                        Addr, Op.getOperand(2), JTI, UId);
3119   }
3120   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3121     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3122                        MachinePointerInfo::getJumpTable(),
3123                        false, false, false, 0);
3124     Chain = Addr.getValue(1);
3125     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3126     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3127   } else {
3128     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3129                        MachinePointerInfo::getJumpTable(),
3130                        false, false, false, 0);
3131     Chain = Addr.getValue(1);
3132     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3133   }
3134 }
3135
3136 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3137   EVT VT = Op.getValueType();
3138   DebugLoc dl = Op.getDebugLoc();
3139
3140   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3141     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3142       return Op;
3143     return DAG.UnrollVectorOp(Op.getNode());
3144   }
3145
3146   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3147          "Invalid type for custom lowering!");
3148   if (VT != MVT::v4i16)
3149     return DAG.UnrollVectorOp(Op.getNode());
3150
3151   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3152   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3153 }
3154
3155 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3156   EVT VT = Op.getValueType();
3157   if (VT.isVector())
3158     return LowerVectorFP_TO_INT(Op, DAG);
3159
3160   DebugLoc dl = Op.getDebugLoc();
3161   unsigned Opc;
3162
3163   switch (Op.getOpcode()) {
3164   default: llvm_unreachable("Invalid opcode!");
3165   case ISD::FP_TO_SINT:
3166     Opc = ARMISD::FTOSI;
3167     break;
3168   case ISD::FP_TO_UINT:
3169     Opc = ARMISD::FTOUI;
3170     break;
3171   }
3172   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3173   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3174 }
3175
3176 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3177   EVT VT = Op.getValueType();
3178   DebugLoc dl = Op.getDebugLoc();
3179
3180   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3181     if (VT.getVectorElementType() == MVT::f32)
3182       return Op;
3183     return DAG.UnrollVectorOp(Op.getNode());
3184   }
3185
3186   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3187          "Invalid type for custom lowering!");
3188   if (VT != MVT::v4f32)
3189     return DAG.UnrollVectorOp(Op.getNode());
3190
3191   unsigned CastOpc;
3192   unsigned Opc;
3193   switch (Op.getOpcode()) {
3194   default: llvm_unreachable("Invalid opcode!");
3195   case ISD::SINT_TO_FP:
3196     CastOpc = ISD::SIGN_EXTEND;
3197     Opc = ISD::SINT_TO_FP;
3198     break;
3199   case ISD::UINT_TO_FP:
3200     CastOpc = ISD::ZERO_EXTEND;
3201     Opc = ISD::UINT_TO_FP;
3202     break;
3203   }
3204
3205   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3206   return DAG.getNode(Opc, dl, VT, Op);
3207 }
3208
3209 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3210   EVT VT = Op.getValueType();
3211   if (VT.isVector())
3212     return LowerVectorINT_TO_FP(Op, DAG);
3213
3214   DebugLoc dl = Op.getDebugLoc();
3215   unsigned Opc;
3216
3217   switch (Op.getOpcode()) {
3218   default: llvm_unreachable("Invalid opcode!");
3219   case ISD::SINT_TO_FP:
3220     Opc = ARMISD::SITOF;
3221     break;
3222   case ISD::UINT_TO_FP:
3223     Opc = ARMISD::UITOF;
3224     break;
3225   }
3226
3227   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3228   return DAG.getNode(Opc, dl, VT, Op);
3229 }
3230
3231 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3232   // Implement fcopysign with a fabs and a conditional fneg.
3233   SDValue Tmp0 = Op.getOperand(0);
3234   SDValue Tmp1 = Op.getOperand(1);
3235   DebugLoc dl = Op.getDebugLoc();
3236   EVT VT = Op.getValueType();
3237   EVT SrcVT = Tmp1.getValueType();
3238   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3239     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3240   bool UseNEON = !InGPR && Subtarget->hasNEON();
3241
3242   if (UseNEON) {
3243     // Use VBSL to copy the sign bit.
3244     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3245     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3246                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3247     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3248     if (VT == MVT::f64)
3249       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3250                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3251                          DAG.getConstant(32, MVT::i32));
3252     else /*if (VT == MVT::f32)*/
3253       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3254     if (SrcVT == MVT::f32) {
3255       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3256       if (VT == MVT::f64)
3257         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3258                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3259                            DAG.getConstant(32, MVT::i32));
3260     } else if (VT == MVT::f32)
3261       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3262                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3263                          DAG.getConstant(32, MVT::i32));
3264     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3265     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3266
3267     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3268                                             MVT::i32);
3269     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3270     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3271                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3272
3273     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3274                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3275                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3276     if (VT == MVT::f32) {
3277       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3278       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3279                         DAG.getConstant(0, MVT::i32));
3280     } else {
3281       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3282     }
3283
3284     return Res;
3285   }
3286
3287   // Bitcast operand 1 to i32.
3288   if (SrcVT == MVT::f64)
3289     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3290                        &Tmp1, 1).getValue(1);
3291   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3292
3293   // Or in the signbit with integer operations.
3294   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3295   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3296   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3297   if (VT == MVT::f32) {
3298     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3299                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3300     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3301                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3302   }
3303
3304   // f64: Or the high part with signbit and then combine two parts.
3305   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3306                      &Tmp0, 1);
3307   SDValue Lo = Tmp0.getValue(0);
3308   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3309   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3310   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3311 }
3312
3313 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3314   MachineFunction &MF = DAG.getMachineFunction();
3315   MachineFrameInfo *MFI = MF.getFrameInfo();
3316   MFI->setReturnAddressIsTaken(true);
3317
3318   EVT VT = Op.getValueType();
3319   DebugLoc dl = Op.getDebugLoc();
3320   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3321   if (Depth) {
3322     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3323     SDValue Offset = DAG.getConstant(4, MVT::i32);
3324     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3325                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3326                        MachinePointerInfo(), false, false, false, 0);
3327   }
3328
3329   // Return LR, which contains the return address. Mark it an implicit live-in.
3330   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3331   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3332 }
3333
3334 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3335   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3336   MFI->setFrameAddressIsTaken(true);
3337
3338   EVT VT = Op.getValueType();
3339   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3340   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3341   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3342     ? ARM::R7 : ARM::R11;
3343   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3344   while (Depth--)
3345     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3346                             MachinePointerInfo(),
3347                             false, false, false, 0);
3348   return FrameAddr;
3349 }
3350
3351 /// ExpandBITCAST - If the target supports VFP, this function is called to
3352 /// expand a bit convert where either the source or destination type is i64 to
3353 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3354 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3355 /// vectors), since the legalizer won't know what to do with that.
3356 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3358   DebugLoc dl = N->getDebugLoc();
3359   SDValue Op = N->getOperand(0);
3360
3361   // This function is only supposed to be called for i64 types, either as the
3362   // source or destination of the bit convert.
3363   EVT SrcVT = Op.getValueType();
3364   EVT DstVT = N->getValueType(0);
3365   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3366          "ExpandBITCAST called for non-i64 type");
3367
3368   // Turn i64->f64 into VMOVDRR.
3369   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3370     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3371                              DAG.getConstant(0, MVT::i32));
3372     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3373                              DAG.getConstant(1, MVT::i32));
3374     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3375                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3376   }
3377
3378   // Turn f64->i64 into VMOVRRD.
3379   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3380     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3381                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3382     // Merge the pieces into a single i64 value.
3383     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3384   }
3385
3386   return SDValue();
3387 }
3388
3389 /// getZeroVector - Returns a vector of specified type with all zero elements.
3390 /// Zero vectors are used to represent vector negation and in those cases
3391 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3392 /// not support i64 elements, so sometimes the zero vectors will need to be
3393 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3394 /// zero vector.
3395 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3396   assert(VT.isVector() && "Expected a vector type");
3397   // The canonical modified immediate encoding of a zero vector is....0!
3398   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3399   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3400   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3401   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3402 }
3403
3404 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3405 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3406 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3407                                                 SelectionDAG &DAG) const {
3408   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3409   EVT VT = Op.getValueType();
3410   unsigned VTBits = VT.getSizeInBits();
3411   DebugLoc dl = Op.getDebugLoc();
3412   SDValue ShOpLo = Op.getOperand(0);
3413   SDValue ShOpHi = Op.getOperand(1);
3414   SDValue ShAmt  = Op.getOperand(2);
3415   SDValue ARMcc;
3416   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3417
3418   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3419
3420   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3421                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3422   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3423   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3424                                    DAG.getConstant(VTBits, MVT::i32));
3425   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3426   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3427   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3428
3429   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3430   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3431                           ARMcc, DAG, dl);
3432   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3433   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3434                            CCR, Cmp);
3435
3436   SDValue Ops[2] = { Lo, Hi };
3437   return DAG.getMergeValues(Ops, 2, dl);
3438 }
3439
3440 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3441 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3442 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3443                                                SelectionDAG &DAG) const {
3444   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3445   EVT VT = Op.getValueType();
3446   unsigned VTBits = VT.getSizeInBits();
3447   DebugLoc dl = Op.getDebugLoc();
3448   SDValue ShOpLo = Op.getOperand(0);
3449   SDValue ShOpHi = Op.getOperand(1);
3450   SDValue ShAmt  = Op.getOperand(2);
3451   SDValue ARMcc;
3452
3453   assert(Op.getOpcode() == ISD::SHL_PARTS);
3454   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3455                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3456   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3457   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3458                                    DAG.getConstant(VTBits, MVT::i32));
3459   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3460   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3461
3462   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3463   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3464   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3465                           ARMcc, DAG, dl);
3466   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3467   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3468                            CCR, Cmp);
3469
3470   SDValue Ops[2] = { Lo, Hi };
3471   return DAG.getMergeValues(Ops, 2, dl);
3472 }
3473
3474 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3475                                             SelectionDAG &DAG) const {
3476   // The rounding mode is in bits 23:22 of the FPSCR.
3477   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3478   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3479   // so that the shift + and get folded into a bitfield extract.
3480   DebugLoc dl = Op.getDebugLoc();
3481   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3482                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3483                                               MVT::i32));
3484   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3485                                   DAG.getConstant(1U << 22, MVT::i32));
3486   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3487                               DAG.getConstant(22, MVT::i32));
3488   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3489                      DAG.getConstant(3, MVT::i32));
3490 }
3491
3492 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3493                          const ARMSubtarget *ST) {
3494   EVT VT = N->getValueType(0);
3495   DebugLoc dl = N->getDebugLoc();
3496
3497   if (!ST->hasV6T2Ops())
3498     return SDValue();
3499
3500   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3501   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3502 }
3503
3504 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3505                           const ARMSubtarget *ST) {
3506   EVT VT = N->getValueType(0);
3507   DebugLoc dl = N->getDebugLoc();
3508
3509   if (!VT.isVector())
3510     return SDValue();
3511
3512   // Lower vector shifts on NEON to use VSHL.
3513   assert(ST->hasNEON() && "unexpected vector shift");
3514
3515   // Left shifts translate directly to the vshiftu intrinsic.
3516   if (N->getOpcode() == ISD::SHL)
3517     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3518                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3519                        N->getOperand(0), N->getOperand(1));
3520
3521   assert((N->getOpcode() == ISD::SRA ||
3522           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3523
3524   // NEON uses the same intrinsics for both left and right shifts.  For
3525   // right shifts, the shift amounts are negative, so negate the vector of
3526   // shift amounts.
3527   EVT ShiftVT = N->getOperand(1).getValueType();
3528   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3529                                      getZeroVector(ShiftVT, DAG, dl),
3530                                      N->getOperand(1));
3531   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3532                              Intrinsic::arm_neon_vshifts :
3533                              Intrinsic::arm_neon_vshiftu);
3534   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3535                      DAG.getConstant(vshiftInt, MVT::i32),
3536                      N->getOperand(0), NegatedCount);
3537 }
3538
3539 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3540                                 const ARMSubtarget *ST) {
3541   EVT VT = N->getValueType(0);
3542   DebugLoc dl = N->getDebugLoc();
3543
3544   // We can get here for a node like i32 = ISD::SHL i32, i64
3545   if (VT != MVT::i64)
3546     return SDValue();
3547
3548   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3549          "Unknown shift to lower!");
3550
3551   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3552   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3553       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3554     return SDValue();
3555
3556   // If we are in thumb mode, we don't have RRX.
3557   if (ST->isThumb1Only()) return SDValue();
3558
3559   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3560   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3561                            DAG.getConstant(0, MVT::i32));
3562   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3563                            DAG.getConstant(1, MVT::i32));
3564
3565   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3566   // captures the result into a carry flag.
3567   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3568   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3569
3570   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3571   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3572
3573   // Merge the pieces into a single i64 value.
3574  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3575 }
3576
3577 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3578   SDValue TmpOp0, TmpOp1;
3579   bool Invert = false;
3580   bool Swap = false;
3581   unsigned Opc = 0;
3582
3583   SDValue Op0 = Op.getOperand(0);
3584   SDValue Op1 = Op.getOperand(1);
3585   SDValue CC = Op.getOperand(2);
3586   EVT VT = Op.getValueType();
3587   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3588   DebugLoc dl = Op.getDebugLoc();
3589
3590   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3591     switch (SetCCOpcode) {
3592     default: llvm_unreachable("Illegal FP comparison");
3593     case ISD::SETUNE:
3594     case ISD::SETNE:  Invert = true; // Fallthrough
3595     case ISD::SETOEQ:
3596     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3597     case ISD::SETOLT:
3598     case ISD::SETLT: Swap = true; // Fallthrough
3599     case ISD::SETOGT:
3600     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3601     case ISD::SETOLE:
3602     case ISD::SETLE:  Swap = true; // Fallthrough
3603     case ISD::SETOGE:
3604     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3605     case ISD::SETUGE: Swap = true; // Fallthrough
3606     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3607     case ISD::SETUGT: Swap = true; // Fallthrough
3608     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3609     case ISD::SETUEQ: Invert = true; // Fallthrough
3610     case ISD::SETONE:
3611       // Expand this to (OLT | OGT).
3612       TmpOp0 = Op0;
3613       TmpOp1 = Op1;
3614       Opc = ISD::OR;
3615       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3616       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3617       break;
3618     case ISD::SETUO: Invert = true; // Fallthrough
3619     case ISD::SETO:
3620       // Expand this to (OLT | OGE).
3621       TmpOp0 = Op0;
3622       TmpOp1 = Op1;
3623       Opc = ISD::OR;
3624       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3625       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3626       break;
3627     }
3628   } else {
3629     // Integer comparisons.
3630     switch (SetCCOpcode) {
3631     default: llvm_unreachable("Illegal integer comparison");
3632     case ISD::SETNE:  Invert = true;
3633     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3634     case ISD::SETLT:  Swap = true;
3635     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3636     case ISD::SETLE:  Swap = true;
3637     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3638     case ISD::SETULT: Swap = true;
3639     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3640     case ISD::SETULE: Swap = true;
3641     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3642     }
3643
3644     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3645     if (Opc == ARMISD::VCEQ) {
3646
3647       SDValue AndOp;
3648       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3649         AndOp = Op0;
3650       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3651         AndOp = Op1;
3652
3653       // Ignore bitconvert.
3654       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3655         AndOp = AndOp.getOperand(0);
3656
3657       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3658         Opc = ARMISD::VTST;
3659         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3660         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3661         Invert = !Invert;
3662       }
3663     }
3664   }
3665
3666   if (Swap)
3667     std::swap(Op0, Op1);
3668
3669   // If one of the operands is a constant vector zero, attempt to fold the
3670   // comparison to a specialized compare-against-zero form.
3671   SDValue SingleOp;
3672   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3673     SingleOp = Op0;
3674   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3675     if (Opc == ARMISD::VCGE)
3676       Opc = ARMISD::VCLEZ;
3677     else if (Opc == ARMISD::VCGT)
3678       Opc = ARMISD::VCLTZ;
3679     SingleOp = Op1;
3680   }
3681
3682   SDValue Result;
3683   if (SingleOp.getNode()) {
3684     switch (Opc) {
3685     case ARMISD::VCEQ:
3686       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3687     case ARMISD::VCGE:
3688       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3689     case ARMISD::VCLEZ:
3690       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3691     case ARMISD::VCGT:
3692       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3693     case ARMISD::VCLTZ:
3694       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3695     default:
3696       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3697     }
3698   } else {
3699      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3700   }
3701
3702   if (Invert)
3703     Result = DAG.getNOT(dl, Result, VT);
3704
3705   return Result;
3706 }
3707
3708 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3709 /// valid vector constant for a NEON instruction with a "modified immediate"
3710 /// operand (e.g., VMOV).  If so, return the encoded value.
3711 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3712                                  unsigned SplatBitSize, SelectionDAG &DAG,
3713                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3714   unsigned OpCmode, Imm;
3715
3716   // SplatBitSize is set to the smallest size that splats the vector, so a
3717   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3718   // immediate instructions others than VMOV do not support the 8-bit encoding
3719   // of a zero vector, and the default encoding of zero is supposed to be the
3720   // 32-bit version.
3721   if (SplatBits == 0)
3722     SplatBitSize = 32;
3723
3724   switch (SplatBitSize) {
3725   case 8:
3726     if (type != VMOVModImm)
3727       return SDValue();
3728     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3729     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3730     OpCmode = 0xe;
3731     Imm = SplatBits;
3732     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3733     break;
3734
3735   case 16:
3736     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3737     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3738     if ((SplatBits & ~0xff) == 0) {
3739       // Value = 0x00nn: Op=x, Cmode=100x.
3740       OpCmode = 0x8;
3741       Imm = SplatBits;
3742       break;
3743     }
3744     if ((SplatBits & ~0xff00) == 0) {
3745       // Value = 0xnn00: Op=x, Cmode=101x.
3746       OpCmode = 0xa;
3747       Imm = SplatBits >> 8;
3748       break;
3749     }
3750     return SDValue();
3751
3752   case 32:
3753     // NEON's 32-bit VMOV supports splat values where:
3754     // * only one byte is nonzero, or
3755     // * the least significant byte is 0xff and the second byte is nonzero, or
3756     // * the least significant 2 bytes are 0xff and the third is nonzero.
3757     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3758     if ((SplatBits & ~0xff) == 0) {
3759       // Value = 0x000000nn: Op=x, Cmode=000x.
3760       OpCmode = 0;
3761       Imm = SplatBits;
3762       break;
3763     }
3764     if ((SplatBits & ~0xff00) == 0) {
3765       // Value = 0x0000nn00: Op=x, Cmode=001x.
3766       OpCmode = 0x2;
3767       Imm = SplatBits >> 8;
3768       break;
3769     }
3770     if ((SplatBits & ~0xff0000) == 0) {
3771       // Value = 0x00nn0000: Op=x, Cmode=010x.
3772       OpCmode = 0x4;
3773       Imm = SplatBits >> 16;
3774       break;
3775     }
3776     if ((SplatBits & ~0xff000000) == 0) {
3777       // Value = 0xnn000000: Op=x, Cmode=011x.
3778       OpCmode = 0x6;
3779       Imm = SplatBits >> 24;
3780       break;
3781     }
3782
3783     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3784     if (type == OtherModImm) return SDValue();
3785
3786     if ((SplatBits & ~0xffff) == 0 &&
3787         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3788       // Value = 0x0000nnff: Op=x, Cmode=1100.
3789       OpCmode = 0xc;
3790       Imm = SplatBits >> 8;
3791       SplatBits |= 0xff;
3792       break;
3793     }
3794
3795     if ((SplatBits & ~0xffffff) == 0 &&
3796         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3797       // Value = 0x00nnffff: Op=x, Cmode=1101.
3798       OpCmode = 0xd;
3799       Imm = SplatBits >> 16;
3800       SplatBits |= 0xffff;
3801       break;
3802     }
3803
3804     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3805     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3806     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3807     // and fall through here to test for a valid 64-bit splat.  But, then the
3808     // caller would also need to check and handle the change in size.
3809     return SDValue();
3810
3811   case 64: {
3812     if (type != VMOVModImm)
3813       return SDValue();
3814     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3815     uint64_t BitMask = 0xff;
3816     uint64_t Val = 0;
3817     unsigned ImmMask = 1;
3818     Imm = 0;
3819     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3820       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3821         Val |= BitMask;
3822         Imm |= ImmMask;
3823       } else if ((SplatBits & BitMask) != 0) {
3824         return SDValue();
3825       }
3826       BitMask <<= 8;
3827       ImmMask <<= 1;
3828     }
3829     // Op=1, Cmode=1110.
3830     OpCmode = 0x1e;
3831     SplatBits = Val;
3832     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3833     break;
3834   }
3835
3836   default:
3837     llvm_unreachable("unexpected size for isNEONModifiedImm");
3838   }
3839
3840   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3841   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3842 }
3843
3844 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3845                                            const ARMSubtarget *ST) const {
3846   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3847     return SDValue();
3848
3849   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3850   assert(Op.getValueType() == MVT::f32 &&
3851          "ConstantFP custom lowering should only occur for f32.");
3852
3853   // Try splatting with a VMOV.f32...
3854   APFloat FPVal = CFP->getValueAPF();
3855   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3856   if (ImmVal != -1) {
3857     DebugLoc DL = Op.getDebugLoc();
3858     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3859     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3860                                       NewVal);
3861     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3862                        DAG.getConstant(0, MVT::i32));
3863   }
3864
3865   // If that fails, try a VMOV.i32
3866   EVT VMovVT;
3867   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3868   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3869                                      VMOVModImm);
3870   if (NewVal != SDValue()) {
3871     DebugLoc DL = Op.getDebugLoc();
3872     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3873                                       NewVal);
3874     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3875                                        VecConstant);
3876     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3877                        DAG.getConstant(0, MVT::i32));
3878   }
3879
3880   // Finally, try a VMVN.i32
3881   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3882                              VMVNModImm);
3883   if (NewVal != SDValue()) {
3884     DebugLoc DL = Op.getDebugLoc();
3885     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3886     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3887                                        VecConstant);
3888     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3889                        DAG.getConstant(0, MVT::i32));
3890   }
3891
3892   return SDValue();
3893 }
3894
3895
3896 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3897                        bool &ReverseVEXT, unsigned &Imm) {
3898   unsigned NumElts = VT.getVectorNumElements();
3899   ReverseVEXT = false;
3900
3901   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3902   if (M[0] < 0)
3903     return false;
3904
3905   Imm = M[0];
3906
3907   // If this is a VEXT shuffle, the immediate value is the index of the first
3908   // element.  The other shuffle indices must be the successive elements after
3909   // the first one.
3910   unsigned ExpectedElt = Imm;
3911   for (unsigned i = 1; i < NumElts; ++i) {
3912     // Increment the expected index.  If it wraps around, it may still be
3913     // a VEXT but the source vectors must be swapped.
3914     ExpectedElt += 1;
3915     if (ExpectedElt == NumElts * 2) {
3916       ExpectedElt = 0;
3917       ReverseVEXT = true;
3918     }
3919
3920     if (M[i] < 0) continue; // ignore UNDEF indices
3921     if (ExpectedElt != static_cast<unsigned>(M[i]))
3922       return false;
3923   }
3924
3925   // Adjust the index value if the source operands will be swapped.
3926   if (ReverseVEXT)
3927     Imm -= NumElts;
3928
3929   return true;
3930 }
3931
3932 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3933 /// instruction with the specified blocksize.  (The order of the elements
3934 /// within each block of the vector is reversed.)
3935 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3936   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3937          "Only possible block sizes for VREV are: 16, 32, 64");
3938
3939   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3940   if (EltSz == 64)
3941     return false;
3942
3943   unsigned NumElts = VT.getVectorNumElements();
3944   unsigned BlockElts = M[0] + 1;
3945   // If the first shuffle index is UNDEF, be optimistic.
3946   if (M[0] < 0)
3947     BlockElts = BlockSize / EltSz;
3948
3949   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3950     return false;
3951
3952   for (unsigned i = 0; i < NumElts; ++i) {
3953     if (M[i] < 0) continue; // ignore UNDEF indices
3954     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3955       return false;
3956   }
3957
3958   return true;
3959 }
3960
3961 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3962   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3963   // range, then 0 is placed into the resulting vector. So pretty much any mask
3964   // of 8 elements can work here.
3965   return VT == MVT::v8i8 && M.size() == 8;
3966 }
3967
3968 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3969   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3970   if (EltSz == 64)
3971     return false;
3972
3973   unsigned NumElts = VT.getVectorNumElements();
3974   WhichResult = (M[0] == 0 ? 0 : 1);
3975   for (unsigned i = 0; i < NumElts; i += 2) {
3976     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3977         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3978       return false;
3979   }
3980   return true;
3981 }
3982
3983 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3984 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3985 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3986 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3987   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3988   if (EltSz == 64)
3989     return false;
3990
3991   unsigned NumElts = VT.getVectorNumElements();
3992   WhichResult = (M[0] == 0 ? 0 : 1);
3993   for (unsigned i = 0; i < NumElts; i += 2) {
3994     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3995         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3996       return false;
3997   }
3998   return true;
3999 }
4000
4001 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4002   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4003   if (EltSz == 64)
4004     return false;
4005
4006   unsigned NumElts = VT.getVectorNumElements();
4007   WhichResult = (M[0] == 0 ? 0 : 1);
4008   for (unsigned i = 0; i != NumElts; ++i) {
4009     if (M[i] < 0) continue; // ignore UNDEF indices
4010     if ((unsigned) M[i] != 2 * i + WhichResult)
4011       return false;
4012   }
4013
4014   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4015   if (VT.is64BitVector() && EltSz == 32)
4016     return false;
4017
4018   return true;
4019 }
4020
4021 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4022 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4023 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4024 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4025   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4026   if (EltSz == 64)
4027     return false;
4028
4029   unsigned Half = VT.getVectorNumElements() / 2;
4030   WhichResult = (M[0] == 0 ? 0 : 1);
4031   for (unsigned j = 0; j != 2; ++j) {
4032     unsigned Idx = WhichResult;
4033     for (unsigned i = 0; i != Half; ++i) {
4034       int MIdx = M[i + j * Half];
4035       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4036         return false;
4037       Idx += 2;
4038     }
4039   }
4040
4041   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4042   if (VT.is64BitVector() && EltSz == 32)
4043     return false;
4044
4045   return true;
4046 }
4047
4048 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4049   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4050   if (EltSz == 64)
4051     return false;
4052
4053   unsigned NumElts = VT.getVectorNumElements();
4054   WhichResult = (M[0] == 0 ? 0 : 1);
4055   unsigned Idx = WhichResult * NumElts / 2;
4056   for (unsigned i = 0; i != NumElts; i += 2) {
4057     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4058         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4059       return false;
4060     Idx += 1;
4061   }
4062
4063   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4064   if (VT.is64BitVector() && EltSz == 32)
4065     return false;
4066
4067   return true;
4068 }
4069
4070 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4071 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4072 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4073 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4074   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4075   if (EltSz == 64)
4076     return false;
4077
4078   unsigned NumElts = VT.getVectorNumElements();
4079   WhichResult = (M[0] == 0 ? 0 : 1);
4080   unsigned Idx = WhichResult * NumElts / 2;
4081   for (unsigned i = 0; i != NumElts; i += 2) {
4082     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4083         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4084       return false;
4085     Idx += 1;
4086   }
4087
4088   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4089   if (VT.is64BitVector() && EltSz == 32)
4090     return false;
4091
4092   return true;
4093 }
4094
4095 // If N is an integer constant that can be moved into a register in one
4096 // instruction, return an SDValue of such a constant (will become a MOV
4097 // instruction).  Otherwise return null.
4098 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4099                                      const ARMSubtarget *ST, DebugLoc dl) {
4100   uint64_t Val;
4101   if (!isa<ConstantSDNode>(N))
4102     return SDValue();
4103   Val = cast<ConstantSDNode>(N)->getZExtValue();
4104
4105   if (ST->isThumb1Only()) {
4106     if (Val <= 255 || ~Val <= 255)
4107       return DAG.getConstant(Val, MVT::i32);
4108   } else {
4109     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4110       return DAG.getConstant(Val, MVT::i32);
4111   }
4112   return SDValue();
4113 }
4114
4115 // If this is a case we can't handle, return null and let the default
4116 // expansion code take care of it.
4117 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4118                                              const ARMSubtarget *ST) const {
4119   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4120   DebugLoc dl = Op.getDebugLoc();
4121   EVT VT = Op.getValueType();
4122
4123   APInt SplatBits, SplatUndef;
4124   unsigned SplatBitSize;
4125   bool HasAnyUndefs;
4126   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4127     if (SplatBitSize <= 64) {
4128       // Check if an immediate VMOV works.
4129       EVT VmovVT;
4130       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4131                                       SplatUndef.getZExtValue(), SplatBitSize,
4132                                       DAG, VmovVT, VT.is128BitVector(),
4133                                       VMOVModImm);
4134       if (Val.getNode()) {
4135         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4136         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4137       }
4138
4139       // Try an immediate VMVN.
4140       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4141       Val = isNEONModifiedImm(NegatedImm,
4142                                       SplatUndef.getZExtValue(), SplatBitSize,
4143                                       DAG, VmovVT, VT.is128BitVector(),
4144                                       VMVNModImm);
4145       if (Val.getNode()) {
4146         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4147         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4148       }
4149
4150       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4151       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4152         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4153         if (ImmVal != -1) {
4154           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4155           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4156         }
4157       }
4158     }
4159   }
4160
4161   // Scan through the operands to see if only one value is used.
4162   unsigned NumElts = VT.getVectorNumElements();
4163   bool isOnlyLowElement = true;
4164   bool usesOnlyOneValue = true;
4165   bool isConstant = true;
4166   SDValue Value;
4167   for (unsigned i = 0; i < NumElts; ++i) {
4168     SDValue V = Op.getOperand(i);
4169     if (V.getOpcode() == ISD::UNDEF)
4170       continue;
4171     if (i > 0)
4172       isOnlyLowElement = false;
4173     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4174       isConstant = false;
4175
4176     if (!Value.getNode())
4177       Value = V;
4178     else if (V != Value)
4179       usesOnlyOneValue = false;
4180   }
4181
4182   if (!Value.getNode())
4183     return DAG.getUNDEF(VT);
4184
4185   if (isOnlyLowElement)
4186     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4187
4188   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4189
4190   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4191   // i32 and try again.
4192   if (usesOnlyOneValue && EltSize <= 32) {
4193     if (!isConstant)
4194       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4195     if (VT.getVectorElementType().isFloatingPoint()) {
4196       SmallVector<SDValue, 8> Ops;
4197       for (unsigned i = 0; i < NumElts; ++i)
4198         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4199                                   Op.getOperand(i)));
4200       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4201       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4202       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4203       if (Val.getNode())
4204         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4205     }
4206     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4207     if (Val.getNode())
4208       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4209   }
4210
4211   // If all elements are constants and the case above didn't get hit, fall back
4212   // to the default expansion, which will generate a load from the constant
4213   // pool.
4214   if (isConstant)
4215     return SDValue();
4216
4217   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4218   if (NumElts >= 4) {
4219     SDValue shuffle = ReconstructShuffle(Op, DAG);
4220     if (shuffle != SDValue())
4221       return shuffle;
4222   }
4223
4224   // Vectors with 32- or 64-bit elements can be built by directly assigning
4225   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4226   // will be legalized.
4227   if (EltSize >= 32) {
4228     // Do the expansion with floating-point types, since that is what the VFP
4229     // registers are defined to use, and since i64 is not legal.
4230     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4231     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4232     SmallVector<SDValue, 8> Ops;
4233     for (unsigned i = 0; i < NumElts; ++i)
4234       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4235     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4236     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4237   }
4238
4239   return SDValue();
4240 }
4241
4242 // Gather data to see if the operation can be modelled as a
4243 // shuffle in combination with VEXTs.
4244 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4245                                               SelectionDAG &DAG) const {
4246   DebugLoc dl = Op.getDebugLoc();
4247   EVT VT = Op.getValueType();
4248   unsigned NumElts = VT.getVectorNumElements();
4249
4250   SmallVector<SDValue, 2> SourceVecs;
4251   SmallVector<unsigned, 2> MinElts;
4252   SmallVector<unsigned, 2> MaxElts;
4253
4254   for (unsigned i = 0; i < NumElts; ++i) {
4255     SDValue V = Op.getOperand(i);
4256     if (V.getOpcode() == ISD::UNDEF)
4257       continue;
4258     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4259       // A shuffle can only come from building a vector from various
4260       // elements of other vectors.
4261       return SDValue();
4262     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4263                VT.getVectorElementType()) {
4264       // This code doesn't know how to handle shuffles where the vector
4265       // element types do not match (this happens because type legalization
4266       // promotes the return type of EXTRACT_VECTOR_ELT).
4267       // FIXME: It might be appropriate to extend this code to handle
4268       // mismatched types.
4269       return SDValue();
4270     }
4271
4272     // Record this extraction against the appropriate vector if possible...
4273     SDValue SourceVec = V.getOperand(0);
4274     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4275     bool FoundSource = false;
4276     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4277       if (SourceVecs[j] == SourceVec) {
4278         if (MinElts[j] > EltNo)
4279           MinElts[j] = EltNo;
4280         if (MaxElts[j] < EltNo)
4281           MaxElts[j] = EltNo;
4282         FoundSource = true;
4283         break;
4284       }
4285     }
4286
4287     // Or record a new source if not...
4288     if (!FoundSource) {
4289       SourceVecs.push_back(SourceVec);
4290       MinElts.push_back(EltNo);
4291       MaxElts.push_back(EltNo);
4292     }
4293   }
4294
4295   // Currently only do something sane when at most two source vectors
4296   // involved.
4297   if (SourceVecs.size() > 2)
4298     return SDValue();
4299
4300   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4301   int VEXTOffsets[2] = {0, 0};
4302
4303   // This loop extracts the usage patterns of the source vectors
4304   // and prepares appropriate SDValues for a shuffle if possible.
4305   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4306     if (SourceVecs[i].getValueType() == VT) {
4307       // No VEXT necessary
4308       ShuffleSrcs[i] = SourceVecs[i];
4309       VEXTOffsets[i] = 0;
4310       continue;
4311     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4312       // It probably isn't worth padding out a smaller vector just to
4313       // break it down again in a shuffle.
4314       return SDValue();
4315     }
4316
4317     // Since only 64-bit and 128-bit vectors are legal on ARM and
4318     // we've eliminated the other cases...
4319     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4320            "unexpected vector sizes in ReconstructShuffle");
4321
4322     if (MaxElts[i] - MinElts[i] >= NumElts) {
4323       // Span too large for a VEXT to cope
4324       return SDValue();
4325     }
4326
4327     if (MinElts[i] >= NumElts) {
4328       // The extraction can just take the second half
4329       VEXTOffsets[i] = NumElts;
4330       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4331                                    SourceVecs[i],
4332                                    DAG.getIntPtrConstant(NumElts));
4333     } else if (MaxElts[i] < NumElts) {
4334       // The extraction can just take the first half
4335       VEXTOffsets[i] = 0;
4336       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4337                                    SourceVecs[i],
4338                                    DAG.getIntPtrConstant(0));
4339     } else {
4340       // An actual VEXT is needed
4341       VEXTOffsets[i] = MinElts[i];
4342       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4343                                      SourceVecs[i],
4344                                      DAG.getIntPtrConstant(0));
4345       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4346                                      SourceVecs[i],
4347                                      DAG.getIntPtrConstant(NumElts));
4348       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4349                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4350     }
4351   }
4352
4353   SmallVector<int, 8> Mask;
4354
4355   for (unsigned i = 0; i < NumElts; ++i) {
4356     SDValue Entry = Op.getOperand(i);
4357     if (Entry.getOpcode() == ISD::UNDEF) {
4358       Mask.push_back(-1);
4359       continue;
4360     }
4361
4362     SDValue ExtractVec = Entry.getOperand(0);
4363     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4364                                           .getOperand(1))->getSExtValue();
4365     if (ExtractVec == SourceVecs[0]) {
4366       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4367     } else {
4368       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4369     }
4370   }
4371
4372   // Final check before we try to produce nonsense...
4373   if (isShuffleMaskLegal(Mask, VT))
4374     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4375                                 &Mask[0]);
4376
4377   return SDValue();
4378 }
4379
4380 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4381 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4382 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4383 /// are assumed to be legal.
4384 bool
4385 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4386                                       EVT VT) const {
4387   if (VT.getVectorNumElements() == 4 &&
4388       (VT.is128BitVector() || VT.is64BitVector())) {
4389     unsigned PFIndexes[4];
4390     for (unsigned i = 0; i != 4; ++i) {
4391       if (M[i] < 0)
4392         PFIndexes[i] = 8;
4393       else
4394         PFIndexes[i] = M[i];
4395     }
4396
4397     // Compute the index in the perfect shuffle table.
4398     unsigned PFTableIndex =
4399       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4400     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4401     unsigned Cost = (PFEntry >> 30);
4402
4403     if (Cost <= 4)
4404       return true;
4405   }
4406
4407   bool ReverseVEXT;
4408   unsigned Imm, WhichResult;
4409
4410   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4411   return (EltSize >= 32 ||
4412           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4413           isVREVMask(M, VT, 64) ||
4414           isVREVMask(M, VT, 32) ||
4415           isVREVMask(M, VT, 16) ||
4416           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4417           isVTBLMask(M, VT) ||
4418           isVTRNMask(M, VT, WhichResult) ||
4419           isVUZPMask(M, VT, WhichResult) ||
4420           isVZIPMask(M, VT, WhichResult) ||
4421           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4422           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4423           isVZIP_v_undef_Mask(M, VT, WhichResult));
4424 }
4425
4426 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4427 /// the specified operations to build the shuffle.
4428 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4429                                       SDValue RHS, SelectionDAG &DAG,
4430                                       DebugLoc dl) {
4431   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4432   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4433   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4434
4435   enum {
4436     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4437     OP_VREV,
4438     OP_VDUP0,
4439     OP_VDUP1,
4440     OP_VDUP2,
4441     OP_VDUP3,
4442     OP_VEXT1,
4443     OP_VEXT2,
4444     OP_VEXT3,
4445     OP_VUZPL, // VUZP, left result
4446     OP_VUZPR, // VUZP, right result
4447     OP_VZIPL, // VZIP, left result
4448     OP_VZIPR, // VZIP, right result
4449     OP_VTRNL, // VTRN, left result
4450     OP_VTRNR  // VTRN, right result
4451   };
4452
4453   if (OpNum == OP_COPY) {
4454     if (LHSID == (1*9+2)*9+3) return LHS;
4455     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4456     return RHS;
4457   }
4458
4459   SDValue OpLHS, OpRHS;
4460   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4461   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4462   EVT VT = OpLHS.getValueType();
4463
4464   switch (OpNum) {
4465   default: llvm_unreachable("Unknown shuffle opcode!");
4466   case OP_VREV:
4467     // VREV divides the vector in half and swaps within the half.
4468     if (VT.getVectorElementType() == MVT::i32 ||
4469         VT.getVectorElementType() == MVT::f32)
4470       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4471     // vrev <4 x i16> -> VREV32
4472     if (VT.getVectorElementType() == MVT::i16)
4473       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4474     // vrev <4 x i8> -> VREV16
4475     assert(VT.getVectorElementType() == MVT::i8);
4476     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4477   case OP_VDUP0:
4478   case OP_VDUP1:
4479   case OP_VDUP2:
4480   case OP_VDUP3:
4481     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4482                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4483   case OP_VEXT1:
4484   case OP_VEXT2:
4485   case OP_VEXT3:
4486     return DAG.getNode(ARMISD::VEXT, dl, VT,
4487                        OpLHS, OpRHS,
4488                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4489   case OP_VUZPL:
4490   case OP_VUZPR:
4491     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4492                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4493   case OP_VZIPL:
4494   case OP_VZIPR:
4495     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4496                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4497   case OP_VTRNL:
4498   case OP_VTRNR:
4499     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4500                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4501   }
4502 }
4503
4504 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4505                                        ArrayRef<int> ShuffleMask,
4506                                        SelectionDAG &DAG) {
4507   // Check to see if we can use the VTBL instruction.
4508   SDValue V1 = Op.getOperand(0);
4509   SDValue V2 = Op.getOperand(1);
4510   DebugLoc DL = Op.getDebugLoc();
4511
4512   SmallVector<SDValue, 8> VTBLMask;
4513   for (ArrayRef<int>::iterator
4514          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4515     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4516
4517   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4518     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4519                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4520                                    &VTBLMask[0], 8));
4521
4522   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4523                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4524                                  &VTBLMask[0], 8));
4525 }
4526
4527 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4528   SDValue V1 = Op.getOperand(0);
4529   SDValue V2 = Op.getOperand(1);
4530   DebugLoc dl = Op.getDebugLoc();
4531   EVT VT = Op.getValueType();
4532   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4533
4534   // Convert shuffles that are directly supported on NEON to target-specific
4535   // DAG nodes, instead of keeping them as shuffles and matching them again
4536   // during code selection.  This is more efficient and avoids the possibility
4537   // of inconsistencies between legalization and selection.
4538   // FIXME: floating-point vectors should be canonicalized to integer vectors
4539   // of the same time so that they get CSEd properly.
4540   ArrayRef<int> ShuffleMask = SVN->getMask();
4541
4542   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4543   if (EltSize <= 32) {
4544     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4545       int Lane = SVN->getSplatIndex();
4546       // If this is undef splat, generate it via "just" vdup, if possible.
4547       if (Lane == -1) Lane = 0;
4548
4549       // Test if V1 is a SCALAR_TO_VECTOR.
4550       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4551         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4552       }
4553       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4554       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4555       // reaches it).
4556       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4557           !isa<ConstantSDNode>(V1.getOperand(0))) {
4558         bool IsScalarToVector = true;
4559         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4560           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4561             IsScalarToVector = false;
4562             break;
4563           }
4564         if (IsScalarToVector)
4565           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4566       }
4567       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4568                          DAG.getConstant(Lane, MVT::i32));
4569     }
4570
4571     bool ReverseVEXT;
4572     unsigned Imm;
4573     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4574       if (ReverseVEXT)
4575         std::swap(V1, V2);
4576       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4577                          DAG.getConstant(Imm, MVT::i32));
4578     }
4579
4580     if (isVREVMask(ShuffleMask, VT, 64))
4581       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4582     if (isVREVMask(ShuffleMask, VT, 32))
4583       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4584     if (isVREVMask(ShuffleMask, VT, 16))
4585       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4586
4587     // Check for Neon shuffles that modify both input vectors in place.
4588     // If both results are used, i.e., if there are two shuffles with the same
4589     // source operands and with masks corresponding to both results of one of
4590     // these operations, DAG memoization will ensure that a single node is
4591     // used for both shuffles.
4592     unsigned WhichResult;
4593     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4594       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4595                          V1, V2).getValue(WhichResult);
4596     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4597       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4598                          V1, V2).getValue(WhichResult);
4599     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4600       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4601                          V1, V2).getValue(WhichResult);
4602
4603     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4604       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4605                          V1, V1).getValue(WhichResult);
4606     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4607       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4608                          V1, V1).getValue(WhichResult);
4609     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4610       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4611                          V1, V1).getValue(WhichResult);
4612   }
4613
4614   // If the shuffle is not directly supported and it has 4 elements, use
4615   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4616   unsigned NumElts = VT.getVectorNumElements();
4617   if (NumElts == 4) {
4618     unsigned PFIndexes[4];
4619     for (unsigned i = 0; i != 4; ++i) {
4620       if (ShuffleMask[i] < 0)
4621         PFIndexes[i] = 8;
4622       else
4623         PFIndexes[i] = ShuffleMask[i];
4624     }
4625
4626     // Compute the index in the perfect shuffle table.
4627     unsigned PFTableIndex =
4628       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4629     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4630     unsigned Cost = (PFEntry >> 30);
4631
4632     if (Cost <= 4)
4633       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4634   }
4635
4636   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4637   if (EltSize >= 32) {
4638     // Do the expansion with floating-point types, since that is what the VFP
4639     // registers are defined to use, and since i64 is not legal.
4640     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4641     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4642     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4643     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4644     SmallVector<SDValue, 8> Ops;
4645     for (unsigned i = 0; i < NumElts; ++i) {
4646       if (ShuffleMask[i] < 0)
4647         Ops.push_back(DAG.getUNDEF(EltVT));
4648       else
4649         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4650                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4651                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4652                                                   MVT::i32)));
4653     }
4654     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4655     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4656   }
4657
4658   if (VT == MVT::v8i8) {
4659     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4660     if (NewOp.getNode())
4661       return NewOp;
4662   }
4663
4664   return SDValue();
4665 }
4666
4667 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4668   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4669   SDValue Lane = Op.getOperand(2);
4670   if (!isa<ConstantSDNode>(Lane))
4671     return SDValue();
4672
4673   return Op;
4674 }
4675
4676 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4677   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4678   SDValue Lane = Op.getOperand(1);
4679   if (!isa<ConstantSDNode>(Lane))
4680     return SDValue();
4681
4682   SDValue Vec = Op.getOperand(0);
4683   if (Op.getValueType() == MVT::i32 &&
4684       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4685     DebugLoc dl = Op.getDebugLoc();
4686     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4687   }
4688
4689   return Op;
4690 }
4691
4692 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4693   // The only time a CONCAT_VECTORS operation can have legal types is when
4694   // two 64-bit vectors are concatenated to a 128-bit vector.
4695   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4696          "unexpected CONCAT_VECTORS");
4697   DebugLoc dl = Op.getDebugLoc();
4698   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4699   SDValue Op0 = Op.getOperand(0);
4700   SDValue Op1 = Op.getOperand(1);
4701   if (Op0.getOpcode() != ISD::UNDEF)
4702     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4703                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4704                       DAG.getIntPtrConstant(0));
4705   if (Op1.getOpcode() != ISD::UNDEF)
4706     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4707                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4708                       DAG.getIntPtrConstant(1));
4709   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4710 }
4711
4712 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4713 /// element has been zero/sign-extended, depending on the isSigned parameter,
4714 /// from an integer type half its size.
4715 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4716                                    bool isSigned) {
4717   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4718   EVT VT = N->getValueType(0);
4719   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4720     SDNode *BVN = N->getOperand(0).getNode();
4721     if (BVN->getValueType(0) != MVT::v4i32 ||
4722         BVN->getOpcode() != ISD::BUILD_VECTOR)
4723       return false;
4724     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4725     unsigned HiElt = 1 - LoElt;
4726     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4727     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4728     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4729     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4730     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4731       return false;
4732     if (isSigned) {
4733       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4734           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4735         return true;
4736     } else {
4737       if (Hi0->isNullValue() && Hi1->isNullValue())
4738         return true;
4739     }
4740     return false;
4741   }
4742
4743   if (N->getOpcode() != ISD::BUILD_VECTOR)
4744     return false;
4745
4746   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4747     SDNode *Elt = N->getOperand(i).getNode();
4748     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4749       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4750       unsigned HalfSize = EltSize / 2;
4751       if (isSigned) {
4752         if (!isIntN(HalfSize, C->getSExtValue()))
4753           return false;
4754       } else {
4755         if (!isUIntN(HalfSize, C->getZExtValue()))
4756           return false;
4757       }
4758       continue;
4759     }
4760     return false;
4761   }
4762
4763   return true;
4764 }
4765
4766 /// isSignExtended - Check if a node is a vector value that is sign-extended
4767 /// or a constant BUILD_VECTOR with sign-extended elements.
4768 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4769   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4770     return true;
4771   if (isExtendedBUILD_VECTOR(N, DAG, true))
4772     return true;
4773   return false;
4774 }
4775
4776 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4777 /// or a constant BUILD_VECTOR with zero-extended elements.
4778 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4779   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4780     return true;
4781   if (isExtendedBUILD_VECTOR(N, DAG, false))
4782     return true;
4783   return false;
4784 }
4785
4786 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4787 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4788 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4789   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4790     return N->getOperand(0);
4791   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4792     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4793                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4794                        LD->isNonTemporal(), LD->isInvariant(),
4795                        LD->getAlignment());
4796   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4797   // have been legalized as a BITCAST from v4i32.
4798   if (N->getOpcode() == ISD::BITCAST) {
4799     SDNode *BVN = N->getOperand(0).getNode();
4800     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4801            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4802     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4803     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4804                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4805   }
4806   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4807   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4808   EVT VT = N->getValueType(0);
4809   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4810   unsigned NumElts = VT.getVectorNumElements();
4811   MVT TruncVT = MVT::getIntegerVT(EltSize);
4812   SmallVector<SDValue, 8> Ops;
4813   for (unsigned i = 0; i != NumElts; ++i) {
4814     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4815     const APInt &CInt = C->getAPIntValue();
4816     // Element types smaller than 32 bits are not legal, so use i32 elements.
4817     // The values are implicitly truncated so sext vs. zext doesn't matter.
4818     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4819   }
4820   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4821                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4822 }
4823
4824 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4825   unsigned Opcode = N->getOpcode();
4826   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4827     SDNode *N0 = N->getOperand(0).getNode();
4828     SDNode *N1 = N->getOperand(1).getNode();
4829     return N0->hasOneUse() && N1->hasOneUse() &&
4830       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4831   }
4832   return false;
4833 }
4834
4835 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4836   unsigned Opcode = N->getOpcode();
4837   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4838     SDNode *N0 = N->getOperand(0).getNode();
4839     SDNode *N1 = N->getOperand(1).getNode();
4840     return N0->hasOneUse() && N1->hasOneUse() &&
4841       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4842   }
4843   return false;
4844 }
4845
4846 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4847   // Multiplications are only custom-lowered for 128-bit vectors so that
4848   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4849   EVT VT = Op.getValueType();
4850   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4851   SDNode *N0 = Op.getOperand(0).getNode();
4852   SDNode *N1 = Op.getOperand(1).getNode();
4853   unsigned NewOpc = 0;
4854   bool isMLA = false;
4855   bool isN0SExt = isSignExtended(N0, DAG);
4856   bool isN1SExt = isSignExtended(N1, DAG);
4857   if (isN0SExt && isN1SExt)
4858     NewOpc = ARMISD::VMULLs;
4859   else {
4860     bool isN0ZExt = isZeroExtended(N0, DAG);
4861     bool isN1ZExt = isZeroExtended(N1, DAG);
4862     if (isN0ZExt && isN1ZExt)
4863       NewOpc = ARMISD::VMULLu;
4864     else if (isN1SExt || isN1ZExt) {
4865       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4866       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4867       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4868         NewOpc = ARMISD::VMULLs;
4869         isMLA = true;
4870       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4871         NewOpc = ARMISD::VMULLu;
4872         isMLA = true;
4873       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4874         std::swap(N0, N1);
4875         NewOpc = ARMISD::VMULLu;
4876         isMLA = true;
4877       }
4878     }
4879
4880     if (!NewOpc) {
4881       if (VT == MVT::v2i64)
4882         // Fall through to expand this.  It is not legal.
4883         return SDValue();
4884       else
4885         // Other vector multiplications are legal.
4886         return Op;
4887     }
4888   }
4889
4890   // Legalize to a VMULL instruction.
4891   DebugLoc DL = Op.getDebugLoc();
4892   SDValue Op0;
4893   SDValue Op1 = SkipExtension(N1, DAG);
4894   if (!isMLA) {
4895     Op0 = SkipExtension(N0, DAG);
4896     assert(Op0.getValueType().is64BitVector() &&
4897            Op1.getValueType().is64BitVector() &&
4898            "unexpected types for extended operands to VMULL");
4899     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4900   }
4901
4902   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4903   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4904   //   vmull q0, d4, d6
4905   //   vmlal q0, d5, d6
4906   // is faster than
4907   //   vaddl q0, d4, d5
4908   //   vmovl q1, d6
4909   //   vmul  q0, q0, q1
4910   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4911   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4912   EVT Op1VT = Op1.getValueType();
4913   return DAG.getNode(N0->getOpcode(), DL, VT,
4914                      DAG.getNode(NewOpc, DL, VT,
4915                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4916                      DAG.getNode(NewOpc, DL, VT,
4917                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4918 }
4919
4920 static SDValue
4921 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4922   // Convert to float
4923   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4924   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4925   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4926   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4927   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4928   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4929   // Get reciprocal estimate.
4930   // float4 recip = vrecpeq_f32(yf);
4931   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4932                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4933   // Because char has a smaller range than uchar, we can actually get away
4934   // without any newton steps.  This requires that we use a weird bias
4935   // of 0xb000, however (again, this has been exhaustively tested).
4936   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4937   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4938   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4939   Y = DAG.getConstant(0xb000, MVT::i32);
4940   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4941   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4942   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4943   // Convert back to short.
4944   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4945   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4946   return X;
4947 }
4948
4949 static SDValue
4950 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4951   SDValue N2;
4952   // Convert to float.
4953   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4954   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4955   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4956   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4957   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4958   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4959
4960   // Use reciprocal estimate and one refinement step.
4961   // float4 recip = vrecpeq_f32(yf);
4962   // recip *= vrecpsq_f32(yf, recip);
4963   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4964                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4965   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4966                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4967                    N1, N2);
4968   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4969   // Because short has a smaller range than ushort, we can actually get away
4970   // with only a single newton step.  This requires that we use a weird bias
4971   // of 89, however (again, this has been exhaustively tested).
4972   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4973   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4974   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4975   N1 = DAG.getConstant(0x89, MVT::i32);
4976   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4977   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4978   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4979   // Convert back to integer and return.
4980   // return vmovn_s32(vcvt_s32_f32(result));
4981   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4982   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4983   return N0;
4984 }
4985
4986 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4987   EVT VT = Op.getValueType();
4988   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4989          "unexpected type for custom-lowering ISD::SDIV");
4990
4991   DebugLoc dl = Op.getDebugLoc();
4992   SDValue N0 = Op.getOperand(0);
4993   SDValue N1 = Op.getOperand(1);
4994   SDValue N2, N3;
4995
4996   if (VT == MVT::v8i8) {
4997     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4998     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4999
5000     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5001                      DAG.getIntPtrConstant(4));
5002     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5003                      DAG.getIntPtrConstant(4));
5004     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5005                      DAG.getIntPtrConstant(0));
5006     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5007                      DAG.getIntPtrConstant(0));
5008
5009     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5010     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5011
5012     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5013     N0 = LowerCONCAT_VECTORS(N0, DAG);
5014
5015     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5016     return N0;
5017   }
5018   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5019 }
5020
5021 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5022   EVT VT = Op.getValueType();
5023   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5024          "unexpected type for custom-lowering ISD::UDIV");
5025
5026   DebugLoc dl = Op.getDebugLoc();
5027   SDValue N0 = Op.getOperand(0);
5028   SDValue N1 = Op.getOperand(1);
5029   SDValue N2, N3;
5030
5031   if (VT == MVT::v8i8) {
5032     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5033     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5034
5035     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5036                      DAG.getIntPtrConstant(4));
5037     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5038                      DAG.getIntPtrConstant(4));
5039     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5040                      DAG.getIntPtrConstant(0));
5041     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5042                      DAG.getIntPtrConstant(0));
5043
5044     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5045     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5046
5047     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5048     N0 = LowerCONCAT_VECTORS(N0, DAG);
5049
5050     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5051                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5052                      N0);
5053     return N0;
5054   }
5055
5056   // v4i16 sdiv ... Convert to float.
5057   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5058   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5059   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5060   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5061   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5062   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5063
5064   // Use reciprocal estimate and two refinement steps.
5065   // float4 recip = vrecpeq_f32(yf);
5066   // recip *= vrecpsq_f32(yf, recip);
5067   // recip *= vrecpsq_f32(yf, recip);
5068   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5069                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5070   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5071                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5072                    BN1, N2);
5073   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5074   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5075                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5076                    BN1, N2);
5077   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5078   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5079   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5080   // and that it will never cause us to return an answer too large).
5081   // float4 result = as_float4(as_int4(xf*recip) + 2);
5082   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5083   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5084   N1 = DAG.getConstant(2, MVT::i32);
5085   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5086   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5087   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5088   // Convert back to integer and return.
5089   // return vmovn_u32(vcvt_s32_f32(result));
5090   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5091   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5092   return N0;
5093 }
5094
5095 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5096   EVT VT = Op.getNode()->getValueType(0);
5097   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5098
5099   unsigned Opc;
5100   bool ExtraOp = false;
5101   switch (Op.getOpcode()) {
5102   default: llvm_unreachable("Invalid code");
5103   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5104   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5105   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5106   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5107   }
5108
5109   if (!ExtraOp)
5110     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5111                        Op.getOperand(1));
5112   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5113                      Op.getOperand(1), Op.getOperand(2));
5114 }
5115
5116 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5117   // Monotonic load/store is legal for all targets
5118   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5119     return Op;
5120
5121   // Aquire/Release load/store is not legal for targets without a
5122   // dmb or equivalent available.
5123   return SDValue();
5124 }
5125
5126
5127 static void
5128 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5129                     SelectionDAG &DAG, unsigned NewOp) {
5130   DebugLoc dl = Node->getDebugLoc();
5131   assert (Node->getValueType(0) == MVT::i64 &&
5132           "Only know how to expand i64 atomics");
5133
5134   SmallVector<SDValue, 6> Ops;
5135   Ops.push_back(Node->getOperand(0)); // Chain
5136   Ops.push_back(Node->getOperand(1)); // Ptr
5137   // Low part of Val1
5138   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5139                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5140   // High part of Val1
5141   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5142                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5143   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5144     // High part of Val1
5145     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5146                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5147     // High part of Val2
5148     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5149                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5150   }
5151   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5152   SDValue Result =
5153     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5154                             cast<MemSDNode>(Node)->getMemOperand());
5155   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5156   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5157   Results.push_back(Result.getValue(2));
5158 }
5159
5160 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5161   switch (Op.getOpcode()) {
5162   default: llvm_unreachable("Don't know how to custom lower this!");
5163   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5164   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5165   case ISD::GlobalAddress:
5166     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5167       LowerGlobalAddressELF(Op, DAG);
5168   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5169   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5170   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5171   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5172   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5173   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5174   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5175   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5176   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5177   case ISD::SINT_TO_FP:
5178   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5179   case ISD::FP_TO_SINT:
5180   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5181   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5182   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5183   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5184   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5185   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5186   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5187   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5188                                                                Subtarget);
5189   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5190   case ISD::SHL:
5191   case ISD::SRL:
5192   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5193   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5194   case ISD::SRL_PARTS:
5195   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5196   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5197   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5198   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5199   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5200   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5201   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5202   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5203   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5204   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5205   case ISD::MUL:           return LowerMUL(Op, DAG);
5206   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5207   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5208   case ISD::ADDC:
5209   case ISD::ADDE:
5210   case ISD::SUBC:
5211   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5212   case ISD::ATOMIC_LOAD:
5213   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5214   }
5215 }
5216
5217 /// ReplaceNodeResults - Replace the results of node with an illegal result
5218 /// type with new values built out of custom code.
5219 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5220                                            SmallVectorImpl<SDValue>&Results,
5221                                            SelectionDAG &DAG) const {
5222   SDValue Res;
5223   switch (N->getOpcode()) {
5224   default:
5225     llvm_unreachable("Don't know how to custom expand this!");
5226   case ISD::BITCAST:
5227     Res = ExpandBITCAST(N, DAG);
5228     break;
5229   case ISD::SRL:
5230   case ISD::SRA:
5231     Res = Expand64BitShift(N, DAG, Subtarget);
5232     break;
5233   case ISD::ATOMIC_LOAD_ADD:
5234     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5235     return;
5236   case ISD::ATOMIC_LOAD_AND:
5237     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5238     return;
5239   case ISD::ATOMIC_LOAD_NAND:
5240     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5241     return;
5242   case ISD::ATOMIC_LOAD_OR:
5243     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5244     return;
5245   case ISD::ATOMIC_LOAD_SUB:
5246     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5247     return;
5248   case ISD::ATOMIC_LOAD_XOR:
5249     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5250     return;
5251   case ISD::ATOMIC_SWAP:
5252     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5253     return;
5254   case ISD::ATOMIC_CMP_SWAP:
5255     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5256     return;
5257   }
5258   if (Res.getNode())
5259     Results.push_back(Res);
5260 }
5261
5262 //===----------------------------------------------------------------------===//
5263 //                           ARM Scheduler Hooks
5264 //===----------------------------------------------------------------------===//
5265
5266 MachineBasicBlock *
5267 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5268                                      MachineBasicBlock *BB,
5269                                      unsigned Size) const {
5270   unsigned dest    = MI->getOperand(0).getReg();
5271   unsigned ptr     = MI->getOperand(1).getReg();
5272   unsigned oldval  = MI->getOperand(2).getReg();
5273   unsigned newval  = MI->getOperand(3).getReg();
5274   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5275   DebugLoc dl = MI->getDebugLoc();
5276   bool isThumb2 = Subtarget->isThumb2();
5277
5278   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5279   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5280     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5281     (const TargetRegisterClass*)&ARM::GPRRegClass);
5282
5283   if (isThumb2) {
5284     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5285     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5286     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5287   }
5288
5289   unsigned ldrOpc, strOpc;
5290   switch (Size) {
5291   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5292   case 1:
5293     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5294     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5295     break;
5296   case 2:
5297     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5298     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5299     break;
5300   case 4:
5301     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5302     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5303     break;
5304   }
5305
5306   MachineFunction *MF = BB->getParent();
5307   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5308   MachineFunction::iterator It = BB;
5309   ++It; // insert the new blocks after the current block
5310
5311   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5312   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5313   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5314   MF->insert(It, loop1MBB);
5315   MF->insert(It, loop2MBB);
5316   MF->insert(It, exitMBB);
5317
5318   // Transfer the remainder of BB and its successor edges to exitMBB.
5319   exitMBB->splice(exitMBB->begin(), BB,
5320                   llvm::next(MachineBasicBlock::iterator(MI)),
5321                   BB->end());
5322   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5323
5324   //  thisMBB:
5325   //   ...
5326   //   fallthrough --> loop1MBB
5327   BB->addSuccessor(loop1MBB);
5328
5329   // loop1MBB:
5330   //   ldrex dest, [ptr]
5331   //   cmp dest, oldval
5332   //   bne exitMBB
5333   BB = loop1MBB;
5334   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5335   if (ldrOpc == ARM::t2LDREX)
5336     MIB.addImm(0);
5337   AddDefaultPred(MIB);
5338   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5339                  .addReg(dest).addReg(oldval));
5340   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5341     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5342   BB->addSuccessor(loop2MBB);
5343   BB->addSuccessor(exitMBB);
5344
5345   // loop2MBB:
5346   //   strex scratch, newval, [ptr]
5347   //   cmp scratch, #0
5348   //   bne loop1MBB
5349   BB = loop2MBB;
5350   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5351   if (strOpc == ARM::t2STREX)
5352     MIB.addImm(0);
5353   AddDefaultPred(MIB);
5354   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5355                  .addReg(scratch).addImm(0));
5356   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5357     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5358   BB->addSuccessor(loop1MBB);
5359   BB->addSuccessor(exitMBB);
5360
5361   //  exitMBB:
5362   //   ...
5363   BB = exitMBB;
5364
5365   MI->eraseFromParent();   // The instruction is gone now.
5366
5367   return BB;
5368 }
5369
5370 MachineBasicBlock *
5371 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5372                                     unsigned Size, unsigned BinOpcode) const {
5373   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5374   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5375
5376   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5377   MachineFunction *MF = BB->getParent();
5378   MachineFunction::iterator It = BB;
5379   ++It;
5380
5381   unsigned dest = MI->getOperand(0).getReg();
5382   unsigned ptr = MI->getOperand(1).getReg();
5383   unsigned incr = MI->getOperand(2).getReg();
5384   DebugLoc dl = MI->getDebugLoc();
5385   bool isThumb2 = Subtarget->isThumb2();
5386
5387   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5388   if (isThumb2) {
5389     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5390     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5391   }
5392
5393   unsigned ldrOpc, strOpc;
5394   switch (Size) {
5395   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5396   case 1:
5397     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5398     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5399     break;
5400   case 2:
5401     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5402     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5403     break;
5404   case 4:
5405     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5406     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5407     break;
5408   }
5409
5410   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5411   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5412   MF->insert(It, loopMBB);
5413   MF->insert(It, exitMBB);
5414
5415   // Transfer the remainder of BB and its successor edges to exitMBB.
5416   exitMBB->splice(exitMBB->begin(), BB,
5417                   llvm::next(MachineBasicBlock::iterator(MI)),
5418                   BB->end());
5419   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5420
5421   const TargetRegisterClass *TRC = isThumb2 ?
5422     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5423     (const TargetRegisterClass*)&ARM::GPRRegClass;
5424   unsigned scratch = MRI.createVirtualRegister(TRC);
5425   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5426
5427   //  thisMBB:
5428   //   ...
5429   //   fallthrough --> loopMBB
5430   BB->addSuccessor(loopMBB);
5431
5432   //  loopMBB:
5433   //   ldrex dest, ptr
5434   //   <binop> scratch2, dest, incr
5435   //   strex scratch, scratch2, ptr
5436   //   cmp scratch, #0
5437   //   bne- loopMBB
5438   //   fallthrough --> exitMBB
5439   BB = loopMBB;
5440   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5441   if (ldrOpc == ARM::t2LDREX)
5442     MIB.addImm(0);
5443   AddDefaultPred(MIB);
5444   if (BinOpcode) {
5445     // operand order needs to go the other way for NAND
5446     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5447       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5448                      addReg(incr).addReg(dest)).addReg(0);
5449     else
5450       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5451                      addReg(dest).addReg(incr)).addReg(0);
5452   }
5453
5454   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5455   if (strOpc == ARM::t2STREX)
5456     MIB.addImm(0);
5457   AddDefaultPred(MIB);
5458   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5459                  .addReg(scratch).addImm(0));
5460   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5461     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5462
5463   BB->addSuccessor(loopMBB);
5464   BB->addSuccessor(exitMBB);
5465
5466   //  exitMBB:
5467   //   ...
5468   BB = exitMBB;
5469
5470   MI->eraseFromParent();   // The instruction is gone now.
5471
5472   return BB;
5473 }
5474
5475 MachineBasicBlock *
5476 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5477                                           MachineBasicBlock *BB,
5478                                           unsigned Size,
5479                                           bool signExtend,
5480                                           ARMCC::CondCodes Cond) const {
5481   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5482
5483   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5484   MachineFunction *MF = BB->getParent();
5485   MachineFunction::iterator It = BB;
5486   ++It;
5487
5488   unsigned dest = MI->getOperand(0).getReg();
5489   unsigned ptr = MI->getOperand(1).getReg();
5490   unsigned incr = MI->getOperand(2).getReg();
5491   unsigned oldval = dest;
5492   DebugLoc dl = MI->getDebugLoc();
5493   bool isThumb2 = Subtarget->isThumb2();
5494
5495   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5496   if (isThumb2) {
5497     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5498     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5499   }
5500
5501   unsigned ldrOpc, strOpc, extendOpc;
5502   switch (Size) {
5503   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5504   case 1:
5505     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5506     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5507     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5508     break;
5509   case 2:
5510     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5511     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5512     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5513     break;
5514   case 4:
5515     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5516     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5517     extendOpc = 0;
5518     break;
5519   }
5520
5521   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5522   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5523   MF->insert(It, loopMBB);
5524   MF->insert(It, exitMBB);
5525
5526   // Transfer the remainder of BB and its successor edges to exitMBB.
5527   exitMBB->splice(exitMBB->begin(), BB,
5528                   llvm::next(MachineBasicBlock::iterator(MI)),
5529                   BB->end());
5530   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5531
5532   const TargetRegisterClass *TRC = isThumb2 ?
5533     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5534     (const TargetRegisterClass*)&ARM::GPRRegClass;
5535   unsigned scratch = MRI.createVirtualRegister(TRC);
5536   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5537
5538   //  thisMBB:
5539   //   ...
5540   //   fallthrough --> loopMBB
5541   BB->addSuccessor(loopMBB);
5542
5543   //  loopMBB:
5544   //   ldrex dest, ptr
5545   //   (sign extend dest, if required)
5546   //   cmp dest, incr
5547   //   cmov.cond scratch2, dest, incr
5548   //   strex scratch, scratch2, ptr
5549   //   cmp scratch, #0
5550   //   bne- loopMBB
5551   //   fallthrough --> exitMBB
5552   BB = loopMBB;
5553   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5554   if (ldrOpc == ARM::t2LDREX)
5555     MIB.addImm(0);
5556   AddDefaultPred(MIB);
5557
5558   // Sign extend the value, if necessary.
5559   if (signExtend && extendOpc) {
5560     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5561     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5562                      .addReg(dest)
5563                      .addImm(0));
5564   }
5565
5566   // Build compare and cmov instructions.
5567   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5568                  .addReg(oldval).addReg(incr));
5569   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5570          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5571
5572   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5573   if (strOpc == ARM::t2STREX)
5574     MIB.addImm(0);
5575   AddDefaultPred(MIB);
5576   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5577                  .addReg(scratch).addImm(0));
5578   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5579     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5580
5581   BB->addSuccessor(loopMBB);
5582   BB->addSuccessor(exitMBB);
5583
5584   //  exitMBB:
5585   //   ...
5586   BB = exitMBB;
5587
5588   MI->eraseFromParent();   // The instruction is gone now.
5589
5590   return BB;
5591 }
5592
5593 MachineBasicBlock *
5594 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5595                                       unsigned Op1, unsigned Op2,
5596                                       bool NeedsCarry, bool IsCmpxchg) const {
5597   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5598   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5599
5600   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5601   MachineFunction *MF = BB->getParent();
5602   MachineFunction::iterator It = BB;
5603   ++It;
5604
5605   unsigned destlo = MI->getOperand(0).getReg();
5606   unsigned desthi = MI->getOperand(1).getReg();
5607   unsigned ptr = MI->getOperand(2).getReg();
5608   unsigned vallo = MI->getOperand(3).getReg();
5609   unsigned valhi = MI->getOperand(4).getReg();
5610   DebugLoc dl = MI->getDebugLoc();
5611   bool isThumb2 = Subtarget->isThumb2();
5612
5613   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5614   if (isThumb2) {
5615     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5616     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5617     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5618   }
5619
5620   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5621   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5622
5623   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5624   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5625   if (IsCmpxchg) {
5626     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5627     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5628   }
5629   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5630   MF->insert(It, loopMBB);
5631   if (IsCmpxchg) {
5632     MF->insert(It, contBB);
5633     MF->insert(It, cont2BB);
5634   }
5635   MF->insert(It, exitMBB);
5636
5637   // Transfer the remainder of BB and its successor edges to exitMBB.
5638   exitMBB->splice(exitMBB->begin(), BB,
5639                   llvm::next(MachineBasicBlock::iterator(MI)),
5640                   BB->end());
5641   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5642
5643   const TargetRegisterClass *TRC = isThumb2 ?
5644     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5645     (const TargetRegisterClass*)&ARM::GPRRegClass;
5646   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5647
5648   //  thisMBB:
5649   //   ...
5650   //   fallthrough --> loopMBB
5651   BB->addSuccessor(loopMBB);
5652
5653   //  loopMBB:
5654   //   ldrexd r2, r3, ptr
5655   //   <binopa> r0, r2, incr
5656   //   <binopb> r1, r3, incr
5657   //   strexd storesuccess, r0, r1, ptr
5658   //   cmp storesuccess, #0
5659   //   bne- loopMBB
5660   //   fallthrough --> exitMBB
5661   //
5662   // Note that the registers are explicitly specified because there is not any
5663   // way to force the register allocator to allocate a register pair.
5664   //
5665   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5666   // need to properly enforce the restriction that the two output registers
5667   // for ldrexd must be different.
5668   BB = loopMBB;
5669   // Load
5670   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5671                  .addReg(ARM::R2, RegState::Define)
5672                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5673   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5674   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5675   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5676
5677   if (IsCmpxchg) {
5678     // Add early exit
5679     for (unsigned i = 0; i < 2; i++) {
5680       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5681                                                          ARM::CMPrr))
5682                      .addReg(i == 0 ? destlo : desthi)
5683                      .addReg(i == 0 ? vallo : valhi));
5684       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5685         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5686       BB->addSuccessor(exitMBB);
5687       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5688       BB = (i == 0 ? contBB : cont2BB);
5689     }
5690
5691     // Copy to physregs for strexd
5692     unsigned setlo = MI->getOperand(5).getReg();
5693     unsigned sethi = MI->getOperand(6).getReg();
5694     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5695     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5696   } else if (Op1) {
5697     // Perform binary operation
5698     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5699                    .addReg(destlo).addReg(vallo))
5700         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5701     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5702                    .addReg(desthi).addReg(valhi)).addReg(0);
5703   } else {
5704     // Copy to physregs for strexd
5705     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5706     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5707   }
5708
5709   // Store
5710   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5711                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5712   // Cmp+jump
5713   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5714                  .addReg(storesuccess).addImm(0));
5715   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5716     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5717
5718   BB->addSuccessor(loopMBB);
5719   BB->addSuccessor(exitMBB);
5720
5721   //  exitMBB:
5722   //   ...
5723   BB = exitMBB;
5724
5725   MI->eraseFromParent();   // The instruction is gone now.
5726
5727   return BB;
5728 }
5729
5730 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5731 /// registers the function context.
5732 void ARMTargetLowering::
5733 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5734                        MachineBasicBlock *DispatchBB, int FI) const {
5735   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5736   DebugLoc dl = MI->getDebugLoc();
5737   MachineFunction *MF = MBB->getParent();
5738   MachineRegisterInfo *MRI = &MF->getRegInfo();
5739   MachineConstantPool *MCP = MF->getConstantPool();
5740   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5741   const Function *F = MF->getFunction();
5742
5743   bool isThumb = Subtarget->isThumb();
5744   bool isThumb2 = Subtarget->isThumb2();
5745
5746   unsigned PCLabelId = AFI->createPICLabelUId();
5747   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5748   ARMConstantPoolValue *CPV =
5749     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5750   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5751
5752   const TargetRegisterClass *TRC = isThumb ?
5753     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5754     (const TargetRegisterClass*)&ARM::GPRRegClass;
5755
5756   // Grab constant pool and fixed stack memory operands.
5757   MachineMemOperand *CPMMO =
5758     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5759                              MachineMemOperand::MOLoad, 4, 4);
5760
5761   MachineMemOperand *FIMMOSt =
5762     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5763                              MachineMemOperand::MOStore, 4, 4);
5764
5765   // Load the address of the dispatch MBB into the jump buffer.
5766   if (isThumb2) {
5767     // Incoming value: jbuf
5768     //   ldr.n  r5, LCPI1_1
5769     //   orr    r5, r5, #1
5770     //   add    r5, pc
5771     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5772     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5773     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5774                    .addConstantPoolIndex(CPI)
5775                    .addMemOperand(CPMMO));
5776     // Set the low bit because of thumb mode.
5777     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5778     AddDefaultCC(
5779       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5780                      .addReg(NewVReg1, RegState::Kill)
5781                      .addImm(0x01)));
5782     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5783     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5784       .addReg(NewVReg2, RegState::Kill)
5785       .addImm(PCLabelId);
5786     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5787                    .addReg(NewVReg3, RegState::Kill)
5788                    .addFrameIndex(FI)
5789                    .addImm(36)  // &jbuf[1] :: pc
5790                    .addMemOperand(FIMMOSt));
5791   } else if (isThumb) {
5792     // Incoming value: jbuf
5793     //   ldr.n  r1, LCPI1_4
5794     //   add    r1, pc
5795     //   mov    r2, #1
5796     //   orrs   r1, r2
5797     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5798     //   str    r1, [r2]
5799     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5800     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5801                    .addConstantPoolIndex(CPI)
5802                    .addMemOperand(CPMMO));
5803     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5804     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5805       .addReg(NewVReg1, RegState::Kill)
5806       .addImm(PCLabelId);
5807     // Set the low bit because of thumb mode.
5808     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5809     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5810                    .addReg(ARM::CPSR, RegState::Define)
5811                    .addImm(1));
5812     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5813     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5814                    .addReg(ARM::CPSR, RegState::Define)
5815                    .addReg(NewVReg2, RegState::Kill)
5816                    .addReg(NewVReg3, RegState::Kill));
5817     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5818     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5819                    .addFrameIndex(FI)
5820                    .addImm(36)); // &jbuf[1] :: pc
5821     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5822                    .addReg(NewVReg4, RegState::Kill)
5823                    .addReg(NewVReg5, RegState::Kill)
5824                    .addImm(0)
5825                    .addMemOperand(FIMMOSt));
5826   } else {
5827     // Incoming value: jbuf
5828     //   ldr  r1, LCPI1_1
5829     //   add  r1, pc, r1
5830     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5831     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5832     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5833                    .addConstantPoolIndex(CPI)
5834                    .addImm(0)
5835                    .addMemOperand(CPMMO));
5836     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5837     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5838                    .addReg(NewVReg1, RegState::Kill)
5839                    .addImm(PCLabelId));
5840     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5841                    .addReg(NewVReg2, RegState::Kill)
5842                    .addFrameIndex(FI)
5843                    .addImm(36)  // &jbuf[1] :: pc
5844                    .addMemOperand(FIMMOSt));
5845   }
5846 }
5847
5848 MachineBasicBlock *ARMTargetLowering::
5849 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5850   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5851   DebugLoc dl = MI->getDebugLoc();
5852   MachineFunction *MF = MBB->getParent();
5853   MachineRegisterInfo *MRI = &MF->getRegInfo();
5854   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5855   MachineFrameInfo *MFI = MF->getFrameInfo();
5856   int FI = MFI->getFunctionContextIndex();
5857
5858   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5859     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5860     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5861
5862   // Get a mapping of the call site numbers to all of the landing pads they're
5863   // associated with.
5864   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5865   unsigned MaxCSNum = 0;
5866   MachineModuleInfo &MMI = MF->getMMI();
5867   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5868        ++BB) {
5869     if (!BB->isLandingPad()) continue;
5870
5871     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5872     // pad.
5873     for (MachineBasicBlock::iterator
5874            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5875       if (!II->isEHLabel()) continue;
5876
5877       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5878       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5879
5880       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5881       for (SmallVectorImpl<unsigned>::iterator
5882              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5883            CSI != CSE; ++CSI) {
5884         CallSiteNumToLPad[*CSI].push_back(BB);
5885         MaxCSNum = std::max(MaxCSNum, *CSI);
5886       }
5887       break;
5888     }
5889   }
5890
5891   // Get an ordered list of the machine basic blocks for the jump table.
5892   std::vector<MachineBasicBlock*> LPadList;
5893   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5894   LPadList.reserve(CallSiteNumToLPad.size());
5895   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5896     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5897     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5898            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5899       LPadList.push_back(*II);
5900       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5901     }
5902   }
5903
5904   assert(!LPadList.empty() &&
5905          "No landing pad destinations for the dispatch jump table!");
5906
5907   // Create the jump table and associated information.
5908   MachineJumpTableInfo *JTI =
5909     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5910   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5911   unsigned UId = AFI->createJumpTableUId();
5912
5913   // Create the MBBs for the dispatch code.
5914
5915   // Shove the dispatch's address into the return slot in the function context.
5916   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5917   DispatchBB->setIsLandingPad();
5918
5919   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5920   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5921   DispatchBB->addSuccessor(TrapBB);
5922
5923   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5924   DispatchBB->addSuccessor(DispContBB);
5925
5926   // Insert and MBBs.
5927   MF->insert(MF->end(), DispatchBB);
5928   MF->insert(MF->end(), DispContBB);
5929   MF->insert(MF->end(), TrapBB);
5930
5931   // Insert code into the entry block that creates and registers the function
5932   // context.
5933   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5934
5935   MachineMemOperand *FIMMOLd =
5936     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5937                              MachineMemOperand::MOLoad |
5938                              MachineMemOperand::MOVolatile, 4, 4);
5939
5940   if (AFI->isThumb1OnlyFunction())
5941     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5942   else if (!Subtarget->hasVFP2())
5943     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5944   else
5945     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5946
5947   unsigned NumLPads = LPadList.size();
5948   if (Subtarget->isThumb2()) {
5949     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5950     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5951                    .addFrameIndex(FI)
5952                    .addImm(4)
5953                    .addMemOperand(FIMMOLd));
5954
5955     if (NumLPads < 256) {
5956       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5957                      .addReg(NewVReg1)
5958                      .addImm(LPadList.size()));
5959     } else {
5960       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5961       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5962                      .addImm(NumLPads & 0xFFFF));
5963
5964       unsigned VReg2 = VReg1;
5965       if ((NumLPads & 0xFFFF0000) != 0) {
5966         VReg2 = MRI->createVirtualRegister(TRC);
5967         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5968                        .addReg(VReg1)
5969                        .addImm(NumLPads >> 16));
5970       }
5971
5972       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5973                      .addReg(NewVReg1)
5974                      .addReg(VReg2));
5975     }
5976
5977     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5978       .addMBB(TrapBB)
5979       .addImm(ARMCC::HI)
5980       .addReg(ARM::CPSR);
5981
5982     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5983     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5984                    .addJumpTableIndex(MJTI)
5985                    .addImm(UId));
5986
5987     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5988     AddDefaultCC(
5989       AddDefaultPred(
5990         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5991         .addReg(NewVReg3, RegState::Kill)
5992         .addReg(NewVReg1)
5993         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5994
5995     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5996       .addReg(NewVReg4, RegState::Kill)
5997       .addReg(NewVReg1)
5998       .addJumpTableIndex(MJTI)
5999       .addImm(UId);
6000   } else if (Subtarget->isThumb()) {
6001     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6002     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6003                    .addFrameIndex(FI)
6004                    .addImm(1)
6005                    .addMemOperand(FIMMOLd));
6006
6007     if (NumLPads < 256) {
6008       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6009                      .addReg(NewVReg1)
6010                      .addImm(NumLPads));
6011     } else {
6012       MachineConstantPool *ConstantPool = MF->getConstantPool();
6013       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6014       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6015
6016       // MachineConstantPool wants an explicit alignment.
6017       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6018       if (Align == 0)
6019         Align = getTargetData()->getTypeAllocSize(C->getType());
6020       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6021
6022       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6023       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6024                      .addReg(VReg1, RegState::Define)
6025                      .addConstantPoolIndex(Idx));
6026       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6027                      .addReg(NewVReg1)
6028                      .addReg(VReg1));
6029     }
6030
6031     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6032       .addMBB(TrapBB)
6033       .addImm(ARMCC::HI)
6034       .addReg(ARM::CPSR);
6035
6036     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6037     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6038                    .addReg(ARM::CPSR, RegState::Define)
6039                    .addReg(NewVReg1)
6040                    .addImm(2));
6041
6042     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6043     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6044                    .addJumpTableIndex(MJTI)
6045                    .addImm(UId));
6046
6047     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6048     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6049                    .addReg(ARM::CPSR, RegState::Define)
6050                    .addReg(NewVReg2, RegState::Kill)
6051                    .addReg(NewVReg3));
6052
6053     MachineMemOperand *JTMMOLd =
6054       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6055                                MachineMemOperand::MOLoad, 4, 4);
6056
6057     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6058     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6059                    .addReg(NewVReg4, RegState::Kill)
6060                    .addImm(0)
6061                    .addMemOperand(JTMMOLd));
6062
6063     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6064     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6065                    .addReg(ARM::CPSR, RegState::Define)
6066                    .addReg(NewVReg5, RegState::Kill)
6067                    .addReg(NewVReg3));
6068
6069     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6070       .addReg(NewVReg6, RegState::Kill)
6071       .addJumpTableIndex(MJTI)
6072       .addImm(UId);
6073   } else {
6074     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6075     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6076                    .addFrameIndex(FI)
6077                    .addImm(4)
6078                    .addMemOperand(FIMMOLd));
6079
6080     if (NumLPads < 256) {
6081       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6082                      .addReg(NewVReg1)
6083                      .addImm(NumLPads));
6084     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6085       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6086       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6087                      .addImm(NumLPads & 0xFFFF));
6088
6089       unsigned VReg2 = VReg1;
6090       if ((NumLPads & 0xFFFF0000) != 0) {
6091         VReg2 = MRI->createVirtualRegister(TRC);
6092         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6093                        .addReg(VReg1)
6094                        .addImm(NumLPads >> 16));
6095       }
6096
6097       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6098                      .addReg(NewVReg1)
6099                      .addReg(VReg2));
6100     } else {
6101       MachineConstantPool *ConstantPool = MF->getConstantPool();
6102       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6103       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6104
6105       // MachineConstantPool wants an explicit alignment.
6106       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6107       if (Align == 0)
6108         Align = getTargetData()->getTypeAllocSize(C->getType());
6109       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6110
6111       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6112       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6113                      .addReg(VReg1, RegState::Define)
6114                      .addConstantPoolIndex(Idx)
6115                      .addImm(0));
6116       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6117                      .addReg(NewVReg1)
6118                      .addReg(VReg1, RegState::Kill));
6119     }
6120
6121     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6122       .addMBB(TrapBB)
6123       .addImm(ARMCC::HI)
6124       .addReg(ARM::CPSR);
6125
6126     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6127     AddDefaultCC(
6128       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6129                      .addReg(NewVReg1)
6130                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6131     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6132     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6133                    .addJumpTableIndex(MJTI)
6134                    .addImm(UId));
6135
6136     MachineMemOperand *JTMMOLd =
6137       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6138                                MachineMemOperand::MOLoad, 4, 4);
6139     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6140     AddDefaultPred(
6141       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6142       .addReg(NewVReg3, RegState::Kill)
6143       .addReg(NewVReg4)
6144       .addImm(0)
6145       .addMemOperand(JTMMOLd));
6146
6147     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6148       .addReg(NewVReg5, RegState::Kill)
6149       .addReg(NewVReg4)
6150       .addJumpTableIndex(MJTI)
6151       .addImm(UId);
6152   }
6153
6154   // Add the jump table entries as successors to the MBB.
6155   MachineBasicBlock *PrevMBB = 0;
6156   for (std::vector<MachineBasicBlock*>::iterator
6157          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6158     MachineBasicBlock *CurMBB = *I;
6159     if (PrevMBB != CurMBB)
6160       DispContBB->addSuccessor(CurMBB);
6161     PrevMBB = CurMBB;
6162   }
6163
6164   // N.B. the order the invoke BBs are processed in doesn't matter here.
6165   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6166   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6167   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6168   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6169   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6170          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6171     MachineBasicBlock *BB = *I;
6172
6173     // Remove the landing pad successor from the invoke block and replace it
6174     // with the new dispatch block.
6175     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6176                                                   BB->succ_end());
6177     while (!Successors.empty()) {
6178       MachineBasicBlock *SMBB = Successors.pop_back_val();
6179       if (SMBB->isLandingPad()) {
6180         BB->removeSuccessor(SMBB);
6181         MBBLPads.push_back(SMBB);
6182       }
6183     }
6184
6185     BB->addSuccessor(DispatchBB);
6186
6187     // Find the invoke call and mark all of the callee-saved registers as
6188     // 'implicit defined' so that they're spilled. This prevents code from
6189     // moving instructions to before the EH block, where they will never be
6190     // executed.
6191     for (MachineBasicBlock::reverse_iterator
6192            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6193       if (!II->isCall()) continue;
6194
6195       DenseMap<unsigned, bool> DefRegs;
6196       for (MachineInstr::mop_iterator
6197              OI = II->operands_begin(), OE = II->operands_end();
6198            OI != OE; ++OI) {
6199         if (!OI->isReg()) continue;
6200         DefRegs[OI->getReg()] = true;
6201       }
6202
6203       MachineInstrBuilder MIB(&*II);
6204
6205       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6206         unsigned Reg = SavedRegs[i];
6207         if (Subtarget->isThumb2() &&
6208             !ARM::tGPRRegClass.contains(Reg) &&
6209             !ARM::hGPRRegClass.contains(Reg))
6210           continue;
6211         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6212           continue;
6213         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6214           continue;
6215         if (!DefRegs[Reg])
6216           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6217       }
6218
6219       break;
6220     }
6221   }
6222
6223   // Mark all former landing pads as non-landing pads. The dispatch is the only
6224   // landing pad now.
6225   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6226          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6227     (*I)->setIsLandingPad(false);
6228
6229   // The instruction is gone now.
6230   MI->eraseFromParent();
6231
6232   return MBB;
6233 }
6234
6235 static
6236 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6237   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6238        E = MBB->succ_end(); I != E; ++I)
6239     if (*I != Succ)
6240       return *I;
6241   llvm_unreachable("Expecting a BB with two successors!");
6242 }
6243
6244 MachineBasicBlock *ARMTargetLowering::
6245 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6246   // This pseudo instruction has 3 operands: dst, src, size
6247   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6248   // Otherwise, we will generate unrolled scalar copies.
6249   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6250   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6251   MachineFunction::iterator It = BB;
6252   ++It;
6253
6254   unsigned dest = MI->getOperand(0).getReg();
6255   unsigned src = MI->getOperand(1).getReg();
6256   unsigned SizeVal = MI->getOperand(2).getImm();
6257   unsigned Align = MI->getOperand(3).getImm();
6258   DebugLoc dl = MI->getDebugLoc();
6259
6260   bool isThumb2 = Subtarget->isThumb2();
6261   MachineFunction *MF = BB->getParent();
6262   MachineRegisterInfo &MRI = MF->getRegInfo();
6263   unsigned ldrOpc, strOpc, UnitSize = 0;
6264
6265   const TargetRegisterClass *TRC = isThumb2 ?
6266     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6267     (const TargetRegisterClass*)&ARM::GPRRegClass;
6268   const TargetRegisterClass *TRC_Vec = 0;
6269
6270   if (Align & 1) {
6271     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6272     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6273     UnitSize = 1;
6274   } else if (Align & 2) {
6275     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6276     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6277     UnitSize = 2;
6278   } else {
6279     // Check whether we can use NEON instructions.
6280     if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6281         Subtarget->hasNEON()) {
6282       if ((Align % 16 == 0) && SizeVal >= 16) {
6283         ldrOpc = ARM::VLD1q32wb_fixed;
6284         strOpc = ARM::VST1q32wb_fixed;
6285         UnitSize = 16;
6286         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6287       }
6288       else if ((Align % 8 == 0) && SizeVal >= 8) {
6289         ldrOpc = ARM::VLD1d32wb_fixed;
6290         strOpc = ARM::VST1d32wb_fixed;
6291         UnitSize = 8;
6292         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6293       }
6294     }
6295     // Can't use NEON instructions.
6296     if (UnitSize == 0) {
6297       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6298       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6299       UnitSize = 4;
6300     }
6301   }
6302
6303   unsigned BytesLeft = SizeVal % UnitSize;
6304   unsigned LoopSize = SizeVal - BytesLeft;
6305
6306   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6307     // Use LDR and STR to copy.
6308     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6309     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6310     unsigned srcIn = src;
6311     unsigned destIn = dest;
6312     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6313       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6314       unsigned srcOut = MRI.createVirtualRegister(TRC);
6315       unsigned destOut = MRI.createVirtualRegister(TRC);
6316       if (UnitSize >= 8) {
6317         AddDefaultPred(BuildMI(*BB, MI, dl,
6318           TII->get(ldrOpc), scratch)
6319           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6320
6321         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6322           .addReg(destIn).addImm(0).addReg(scratch));
6323       } else if (isThumb2) {
6324         AddDefaultPred(BuildMI(*BB, MI, dl,
6325           TII->get(ldrOpc), scratch)
6326           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6327
6328         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6329           .addReg(scratch).addReg(destIn)
6330           .addImm(UnitSize));
6331       } else {
6332         AddDefaultPred(BuildMI(*BB, MI, dl,
6333           TII->get(ldrOpc), scratch)
6334           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6335           .addImm(UnitSize));
6336
6337         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6338           .addReg(scratch).addReg(destIn)
6339           .addReg(0).addImm(UnitSize));
6340       }
6341       srcIn = srcOut;
6342       destIn = destOut;
6343     }
6344
6345     // Handle the leftover bytes with LDRB and STRB.
6346     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6347     // [destOut] = STRB_POST(scratch, destIn, 1)
6348     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6349     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6350     for (unsigned i = 0; i < BytesLeft; i++) {
6351       unsigned scratch = MRI.createVirtualRegister(TRC);
6352       unsigned srcOut = MRI.createVirtualRegister(TRC);
6353       unsigned destOut = MRI.createVirtualRegister(TRC);
6354       if (isThumb2) {
6355         AddDefaultPred(BuildMI(*BB, MI, dl,
6356           TII->get(ldrOpc),scratch)
6357           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6358
6359         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6360           .addReg(scratch).addReg(destIn)
6361           .addReg(0).addImm(1));
6362       } else {
6363         AddDefaultPred(BuildMI(*BB, MI, dl,
6364           TII->get(ldrOpc),scratch)
6365           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6366
6367         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6368           .addReg(scratch).addReg(destIn)
6369           .addReg(0).addImm(1));
6370       }
6371       srcIn = srcOut;
6372       destIn = destOut;
6373     }
6374     MI->eraseFromParent();   // The instruction is gone now.
6375     return BB;
6376   }
6377
6378   // Expand the pseudo op to a loop.
6379   // thisMBB:
6380   //   ...
6381   //   movw varEnd, # --> with thumb2
6382   //   movt varEnd, #
6383   //   ldrcp varEnd, idx --> without thumb2
6384   //   fallthrough --> loopMBB
6385   // loopMBB:
6386   //   PHI varPhi, varEnd, varLoop
6387   //   PHI srcPhi, src, srcLoop
6388   //   PHI destPhi, dst, destLoop
6389   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6390   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6391   //   subs varLoop, varPhi, #UnitSize
6392   //   bne loopMBB
6393   //   fallthrough --> exitMBB
6394   // exitMBB:
6395   //   epilogue to handle left-over bytes
6396   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6397   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6398   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6399   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6400   MF->insert(It, loopMBB);
6401   MF->insert(It, exitMBB);
6402
6403   // Transfer the remainder of BB and its successor edges to exitMBB.
6404   exitMBB->splice(exitMBB->begin(), BB,
6405                   llvm::next(MachineBasicBlock::iterator(MI)),
6406                   BB->end());
6407   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6408
6409   // Load an immediate to varEnd.
6410   unsigned varEnd = MRI.createVirtualRegister(TRC);
6411   if (isThumb2) {
6412     unsigned VReg1 = varEnd;
6413     if ((LoopSize & 0xFFFF0000) != 0)
6414       VReg1 = MRI.createVirtualRegister(TRC);
6415     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6416                    .addImm(LoopSize & 0xFFFF));
6417
6418     if ((LoopSize & 0xFFFF0000) != 0)
6419       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6420                      .addReg(VReg1)
6421                      .addImm(LoopSize >> 16));
6422   } else {
6423     MachineConstantPool *ConstantPool = MF->getConstantPool();
6424     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6425     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6426
6427     // MachineConstantPool wants an explicit alignment.
6428     unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6429     if (Align == 0)
6430       Align = getTargetData()->getTypeAllocSize(C->getType());
6431     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6432
6433     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6434                    .addReg(varEnd, RegState::Define)
6435                    .addConstantPoolIndex(Idx)
6436                    .addImm(0));
6437   }
6438   BB->addSuccessor(loopMBB);
6439
6440   // Generate the loop body:
6441   //   varPhi = PHI(varLoop, varEnd)
6442   //   srcPhi = PHI(srcLoop, src)
6443   //   destPhi = PHI(destLoop, dst)
6444   MachineBasicBlock *entryBB = BB;
6445   BB = loopMBB;
6446   unsigned varLoop = MRI.createVirtualRegister(TRC);
6447   unsigned varPhi = MRI.createVirtualRegister(TRC);
6448   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6449   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6450   unsigned destLoop = MRI.createVirtualRegister(TRC);
6451   unsigned destPhi = MRI.createVirtualRegister(TRC);
6452
6453   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6454     .addReg(varLoop).addMBB(loopMBB)
6455     .addReg(varEnd).addMBB(entryBB);
6456   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6457     .addReg(srcLoop).addMBB(loopMBB)
6458     .addReg(src).addMBB(entryBB);
6459   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6460     .addReg(destLoop).addMBB(loopMBB)
6461     .addReg(dest).addMBB(entryBB);
6462
6463   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6464   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6465   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6466   if (UnitSize >= 8) {
6467     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6468       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6469
6470     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6471       .addReg(destPhi).addImm(0).addReg(scratch));
6472   } else if (isThumb2) {
6473     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6474       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6475
6476     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6477       .addReg(scratch).addReg(destPhi)
6478       .addImm(UnitSize));
6479   } else {
6480     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6481       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6482       .addImm(UnitSize));
6483
6484     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6485       .addReg(scratch).addReg(destPhi)
6486       .addReg(0).addImm(UnitSize));
6487   }
6488
6489   // Decrement loop variable by UnitSize.
6490   MachineInstrBuilder MIB = BuildMI(BB, dl,
6491     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6492   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6493   MIB->getOperand(5).setReg(ARM::CPSR);
6494   MIB->getOperand(5).setIsDef(true);
6495
6496   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6497     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6498
6499   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6500   BB->addSuccessor(loopMBB);
6501   BB->addSuccessor(exitMBB);
6502
6503   // Add epilogue to handle BytesLeft.
6504   BB = exitMBB;
6505   MachineInstr *StartOfExit = exitMBB->begin();
6506   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6507   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6508
6509   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6510   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6511   unsigned srcIn = srcLoop;
6512   unsigned destIn = destLoop;
6513   for (unsigned i = 0; i < BytesLeft; i++) {
6514     unsigned scratch = MRI.createVirtualRegister(TRC);
6515     unsigned srcOut = MRI.createVirtualRegister(TRC);
6516     unsigned destOut = MRI.createVirtualRegister(TRC);
6517     if (isThumb2) {
6518       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6519         TII->get(ldrOpc),scratch)
6520         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6521
6522       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6523         .addReg(scratch).addReg(destIn)
6524         .addImm(1));
6525     } else {
6526       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6527         TII->get(ldrOpc),scratch)
6528         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6529
6530       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6531         .addReg(scratch).addReg(destIn)
6532         .addReg(0).addImm(1));
6533     }
6534     srcIn = srcOut;
6535     destIn = destOut;
6536   }
6537
6538   MI->eraseFromParent();   // The instruction is gone now.
6539   return BB;
6540 }
6541
6542 MachineBasicBlock *
6543 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6544                                                MachineBasicBlock *BB) const {
6545   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6546   DebugLoc dl = MI->getDebugLoc();
6547   bool isThumb2 = Subtarget->isThumb2();
6548   switch (MI->getOpcode()) {
6549   default: {
6550     MI->dump();
6551     llvm_unreachable("Unexpected instr type to insert");
6552   }
6553   // The Thumb2 pre-indexed stores have the same MI operands, they just
6554   // define them differently in the .td files from the isel patterns, so
6555   // they need pseudos.
6556   case ARM::t2STR_preidx:
6557     MI->setDesc(TII->get(ARM::t2STR_PRE));
6558     return BB;
6559   case ARM::t2STRB_preidx:
6560     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6561     return BB;
6562   case ARM::t2STRH_preidx:
6563     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6564     return BB;
6565
6566   case ARM::STRi_preidx:
6567   case ARM::STRBi_preidx: {
6568     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6569       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6570     // Decode the offset.
6571     unsigned Offset = MI->getOperand(4).getImm();
6572     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6573     Offset = ARM_AM::getAM2Offset(Offset);
6574     if (isSub)
6575       Offset = -Offset;
6576
6577     MachineMemOperand *MMO = *MI->memoperands_begin();
6578     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6579       .addOperand(MI->getOperand(0))  // Rn_wb
6580       .addOperand(MI->getOperand(1))  // Rt
6581       .addOperand(MI->getOperand(2))  // Rn
6582       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6583       .addOperand(MI->getOperand(5))  // pred
6584       .addOperand(MI->getOperand(6))
6585       .addMemOperand(MMO);
6586     MI->eraseFromParent();
6587     return BB;
6588   }
6589   case ARM::STRr_preidx:
6590   case ARM::STRBr_preidx:
6591   case ARM::STRH_preidx: {
6592     unsigned NewOpc;
6593     switch (MI->getOpcode()) {
6594     default: llvm_unreachable("unexpected opcode!");
6595     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6596     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6597     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6598     }
6599     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6600     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6601       MIB.addOperand(MI->getOperand(i));
6602     MI->eraseFromParent();
6603     return BB;
6604   }
6605   case ARM::ATOMIC_LOAD_ADD_I8:
6606      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6607   case ARM::ATOMIC_LOAD_ADD_I16:
6608      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6609   case ARM::ATOMIC_LOAD_ADD_I32:
6610      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6611
6612   case ARM::ATOMIC_LOAD_AND_I8:
6613      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6614   case ARM::ATOMIC_LOAD_AND_I16:
6615      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6616   case ARM::ATOMIC_LOAD_AND_I32:
6617      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6618
6619   case ARM::ATOMIC_LOAD_OR_I8:
6620      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6621   case ARM::ATOMIC_LOAD_OR_I16:
6622      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6623   case ARM::ATOMIC_LOAD_OR_I32:
6624      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6625
6626   case ARM::ATOMIC_LOAD_XOR_I8:
6627      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6628   case ARM::ATOMIC_LOAD_XOR_I16:
6629      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6630   case ARM::ATOMIC_LOAD_XOR_I32:
6631      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6632
6633   case ARM::ATOMIC_LOAD_NAND_I8:
6634      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6635   case ARM::ATOMIC_LOAD_NAND_I16:
6636      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6637   case ARM::ATOMIC_LOAD_NAND_I32:
6638      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6639
6640   case ARM::ATOMIC_LOAD_SUB_I8:
6641      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6642   case ARM::ATOMIC_LOAD_SUB_I16:
6643      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6644   case ARM::ATOMIC_LOAD_SUB_I32:
6645      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6646
6647   case ARM::ATOMIC_LOAD_MIN_I8:
6648      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6649   case ARM::ATOMIC_LOAD_MIN_I16:
6650      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6651   case ARM::ATOMIC_LOAD_MIN_I32:
6652      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6653
6654   case ARM::ATOMIC_LOAD_MAX_I8:
6655      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6656   case ARM::ATOMIC_LOAD_MAX_I16:
6657      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6658   case ARM::ATOMIC_LOAD_MAX_I32:
6659      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6660
6661   case ARM::ATOMIC_LOAD_UMIN_I8:
6662      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6663   case ARM::ATOMIC_LOAD_UMIN_I16:
6664      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6665   case ARM::ATOMIC_LOAD_UMIN_I32:
6666      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6667
6668   case ARM::ATOMIC_LOAD_UMAX_I8:
6669      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6670   case ARM::ATOMIC_LOAD_UMAX_I16:
6671      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6672   case ARM::ATOMIC_LOAD_UMAX_I32:
6673      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6674
6675   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6676   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6677   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6678
6679   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6680   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6681   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6682
6683
6684   case ARM::ATOMADD6432:
6685     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6686                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6687                               /*NeedsCarry*/ true);
6688   case ARM::ATOMSUB6432:
6689     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6690                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6691                               /*NeedsCarry*/ true);
6692   case ARM::ATOMOR6432:
6693     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6694                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6695   case ARM::ATOMXOR6432:
6696     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6697                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6698   case ARM::ATOMAND6432:
6699     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6700                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6701   case ARM::ATOMSWAP6432:
6702     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6703   case ARM::ATOMCMPXCHG6432:
6704     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6705                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6706                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6707
6708   case ARM::tMOVCCr_pseudo: {
6709     // To "insert" a SELECT_CC instruction, we actually have to insert the
6710     // diamond control-flow pattern.  The incoming instruction knows the
6711     // destination vreg to set, the condition code register to branch on, the
6712     // true/false values to select between, and a branch opcode to use.
6713     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6714     MachineFunction::iterator It = BB;
6715     ++It;
6716
6717     //  thisMBB:
6718     //  ...
6719     //   TrueVal = ...
6720     //   cmpTY ccX, r1, r2
6721     //   bCC copy1MBB
6722     //   fallthrough --> copy0MBB
6723     MachineBasicBlock *thisMBB  = BB;
6724     MachineFunction *F = BB->getParent();
6725     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6726     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6727     F->insert(It, copy0MBB);
6728     F->insert(It, sinkMBB);
6729
6730     // Transfer the remainder of BB and its successor edges to sinkMBB.
6731     sinkMBB->splice(sinkMBB->begin(), BB,
6732                     llvm::next(MachineBasicBlock::iterator(MI)),
6733                     BB->end());
6734     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6735
6736     BB->addSuccessor(copy0MBB);
6737     BB->addSuccessor(sinkMBB);
6738
6739     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6740       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6741
6742     //  copy0MBB:
6743     //   %FalseValue = ...
6744     //   # fallthrough to sinkMBB
6745     BB = copy0MBB;
6746
6747     // Update machine-CFG edges
6748     BB->addSuccessor(sinkMBB);
6749
6750     //  sinkMBB:
6751     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6752     //  ...
6753     BB = sinkMBB;
6754     BuildMI(*BB, BB->begin(), dl,
6755             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6756       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6757       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6758
6759     MI->eraseFromParent();   // The pseudo instruction is gone now.
6760     return BB;
6761   }
6762
6763   case ARM::BCCi64:
6764   case ARM::BCCZi64: {
6765     // If there is an unconditional branch to the other successor, remove it.
6766     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6767
6768     // Compare both parts that make up the double comparison separately for
6769     // equality.
6770     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6771
6772     unsigned LHS1 = MI->getOperand(1).getReg();
6773     unsigned LHS2 = MI->getOperand(2).getReg();
6774     if (RHSisZero) {
6775       AddDefaultPred(BuildMI(BB, dl,
6776                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6777                      .addReg(LHS1).addImm(0));
6778       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6779         .addReg(LHS2).addImm(0)
6780         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6781     } else {
6782       unsigned RHS1 = MI->getOperand(3).getReg();
6783       unsigned RHS2 = MI->getOperand(4).getReg();
6784       AddDefaultPred(BuildMI(BB, dl,
6785                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6786                      .addReg(LHS1).addReg(RHS1));
6787       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6788         .addReg(LHS2).addReg(RHS2)
6789         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6790     }
6791
6792     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6793     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6794     if (MI->getOperand(0).getImm() == ARMCC::NE)
6795       std::swap(destMBB, exitMBB);
6796
6797     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6798       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6799     if (isThumb2)
6800       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6801     else
6802       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6803
6804     MI->eraseFromParent();   // The pseudo instruction is gone now.
6805     return BB;
6806   }
6807
6808   case ARM::Int_eh_sjlj_setjmp:
6809   case ARM::Int_eh_sjlj_setjmp_nofp:
6810   case ARM::tInt_eh_sjlj_setjmp:
6811   case ARM::t2Int_eh_sjlj_setjmp:
6812   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6813     EmitSjLjDispatchBlock(MI, BB);
6814     return BB;
6815
6816   case ARM::ABS:
6817   case ARM::t2ABS: {
6818     // To insert an ABS instruction, we have to insert the
6819     // diamond control-flow pattern.  The incoming instruction knows the
6820     // source vreg to test against 0, the destination vreg to set,
6821     // the condition code register to branch on, the
6822     // true/false values to select between, and a branch opcode to use.
6823     // It transforms
6824     //     V1 = ABS V0
6825     // into
6826     //     V2 = MOVS V0
6827     //     BCC                      (branch to SinkBB if V0 >= 0)
6828     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6829     //     SinkBB: V1 = PHI(V2, V3)
6830     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6831     MachineFunction::iterator BBI = BB;
6832     ++BBI;
6833     MachineFunction *Fn = BB->getParent();
6834     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6835     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6836     Fn->insert(BBI, RSBBB);
6837     Fn->insert(BBI, SinkBB);
6838
6839     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6840     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6841     bool isThumb2 = Subtarget->isThumb2();
6842     MachineRegisterInfo &MRI = Fn->getRegInfo();
6843     // In Thumb mode S must not be specified if source register is the SP or
6844     // PC and if destination register is the SP, so restrict register class
6845     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6846       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6847       (const TargetRegisterClass*)&ARM::GPRRegClass);
6848
6849     // Transfer the remainder of BB and its successor edges to sinkMBB.
6850     SinkBB->splice(SinkBB->begin(), BB,
6851       llvm::next(MachineBasicBlock::iterator(MI)),
6852       BB->end());
6853     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6854
6855     BB->addSuccessor(RSBBB);
6856     BB->addSuccessor(SinkBB);
6857
6858     // fall through to SinkMBB
6859     RSBBB->addSuccessor(SinkBB);
6860
6861     // insert a cmp at the end of BB
6862     AddDefaultPred(BuildMI(BB, dl, 
6863                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6864                    .addReg(ABSSrcReg).addImm(0));
6865
6866     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6867     BuildMI(BB, dl,
6868       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6869       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6870
6871     // insert rsbri in RSBBB
6872     // Note: BCC and rsbri will be converted into predicated rsbmi
6873     // by if-conversion pass
6874     BuildMI(*RSBBB, RSBBB->begin(), dl,
6875       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6876       .addReg(ABSSrcReg, RegState::Kill)
6877       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6878
6879     // insert PHI in SinkBB,
6880     // reuse ABSDstReg to not change uses of ABS instruction
6881     BuildMI(*SinkBB, SinkBB->begin(), dl,
6882       TII->get(ARM::PHI), ABSDstReg)
6883       .addReg(NewRsbDstReg).addMBB(RSBBB)
6884       .addReg(ABSSrcReg).addMBB(BB);
6885
6886     // remove ABS instruction
6887     MI->eraseFromParent();
6888
6889     // return last added BB
6890     return SinkBB;
6891   }
6892   case ARM::COPY_STRUCT_BYVAL_I32:
6893     ++NumLoopByVals;
6894     return EmitStructByval(MI, BB);
6895   }
6896 }
6897
6898 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6899                                                       SDNode *Node) const {
6900   if (!MI->hasPostISelHook()) {
6901     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6902            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6903     return;
6904   }
6905
6906   const MCInstrDesc *MCID = &MI->getDesc();
6907   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6908   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6909   // operand is still set to noreg. If needed, set the optional operand's
6910   // register to CPSR, and remove the redundant implicit def.
6911   //
6912   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6913
6914   // Rename pseudo opcodes.
6915   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6916   if (NewOpc) {
6917     const ARMBaseInstrInfo *TII =
6918       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6919     MCID = &TII->get(NewOpc);
6920
6921     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6922            "converted opcode should be the same except for cc_out");
6923
6924     MI->setDesc(*MCID);
6925
6926     // Add the optional cc_out operand
6927     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6928   }
6929   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6930
6931   // Any ARM instruction that sets the 's' bit should specify an optional
6932   // "cc_out" operand in the last operand position.
6933   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6934     assert(!NewOpc && "Optional cc_out operand required");
6935     return;
6936   }
6937   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6938   // since we already have an optional CPSR def.
6939   bool definesCPSR = false;
6940   bool deadCPSR = false;
6941   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6942        i != e; ++i) {
6943     const MachineOperand &MO = MI->getOperand(i);
6944     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6945       definesCPSR = true;
6946       if (MO.isDead())
6947         deadCPSR = true;
6948       MI->RemoveOperand(i);
6949       break;
6950     }
6951   }
6952   if (!definesCPSR) {
6953     assert(!NewOpc && "Optional cc_out operand required");
6954     return;
6955   }
6956   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6957   if (deadCPSR) {
6958     assert(!MI->getOperand(ccOutIdx).getReg() &&
6959            "expect uninitialized optional cc_out operand");
6960     return;
6961   }
6962
6963   // If this instruction was defined with an optional CPSR def and its dag node
6964   // had a live implicit CPSR def, then activate the optional CPSR def.
6965   MachineOperand &MO = MI->getOperand(ccOutIdx);
6966   MO.setReg(ARM::CPSR);
6967   MO.setIsDef(true);
6968 }
6969
6970 //===----------------------------------------------------------------------===//
6971 //                           ARM Optimization Hooks
6972 //===----------------------------------------------------------------------===//
6973
6974 static
6975 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6976                             TargetLowering::DAGCombinerInfo &DCI) {
6977   SelectionDAG &DAG = DCI.DAG;
6978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6979   EVT VT = N->getValueType(0);
6980   unsigned Opc = N->getOpcode();
6981   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6982   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6983   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6984   ISD::CondCode CC = ISD::SETCC_INVALID;
6985
6986   if (isSlctCC) {
6987     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6988   } else {
6989     SDValue CCOp = Slct.getOperand(0);
6990     if (CCOp.getOpcode() == ISD::SETCC)
6991       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6992   }
6993
6994   bool DoXform = false;
6995   bool InvCC = false;
6996   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6997           "Bad input!");
6998
6999   if (LHS.getOpcode() == ISD::Constant &&
7000       cast<ConstantSDNode>(LHS)->isNullValue()) {
7001     DoXform = true;
7002   } else if (CC != ISD::SETCC_INVALID &&
7003              RHS.getOpcode() == ISD::Constant &&
7004              cast<ConstantSDNode>(RHS)->isNullValue()) {
7005     std::swap(LHS, RHS);
7006     SDValue Op0 = Slct.getOperand(0);
7007     EVT OpVT = isSlctCC ? Op0.getValueType() :
7008                           Op0.getOperand(0).getValueType();
7009     bool isInt = OpVT.isInteger();
7010     CC = ISD::getSetCCInverse(CC, isInt);
7011
7012     if (!TLI.isCondCodeLegal(CC, OpVT))
7013       return SDValue();         // Inverse operator isn't legal.
7014
7015     DoXform = true;
7016     InvCC = true;
7017   }
7018
7019   if (DoXform) {
7020     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
7021     if (isSlctCC)
7022       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
7023                              Slct.getOperand(0), Slct.getOperand(1), CC);
7024     SDValue CCOp = Slct.getOperand(0);
7025     if (InvCC)
7026       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
7027                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
7028     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7029                        CCOp, OtherOp, Result);
7030   }
7031   return SDValue();
7032 }
7033
7034 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7035 // (only after legalization).
7036 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7037                                  TargetLowering::DAGCombinerInfo &DCI,
7038                                  const ARMSubtarget *Subtarget) {
7039
7040   // Only perform optimization if after legalize, and if NEON is available. We
7041   // also expected both operands to be BUILD_VECTORs.
7042   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7043       || N0.getOpcode() != ISD::BUILD_VECTOR
7044       || N1.getOpcode() != ISD::BUILD_VECTOR)
7045     return SDValue();
7046
7047   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7048   EVT VT = N->getValueType(0);
7049   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7050     return SDValue();
7051
7052   // Check that the vector operands are of the right form.
7053   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7054   // operands, where N is the size of the formed vector.
7055   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7056   // index such that we have a pair wise add pattern.
7057
7058   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7059   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7060     return SDValue();
7061   SDValue Vec = N0->getOperand(0)->getOperand(0);
7062   SDNode *V = Vec.getNode();
7063   unsigned nextIndex = 0;
7064
7065   // For each operands to the ADD which are BUILD_VECTORs,
7066   // check to see if each of their operands are an EXTRACT_VECTOR with
7067   // the same vector and appropriate index.
7068   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7069     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7070         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7071
7072       SDValue ExtVec0 = N0->getOperand(i);
7073       SDValue ExtVec1 = N1->getOperand(i);
7074
7075       // First operand is the vector, verify its the same.
7076       if (V != ExtVec0->getOperand(0).getNode() ||
7077           V != ExtVec1->getOperand(0).getNode())
7078         return SDValue();
7079
7080       // Second is the constant, verify its correct.
7081       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7082       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7083
7084       // For the constant, we want to see all the even or all the odd.
7085       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7086           || C1->getZExtValue() != nextIndex+1)
7087         return SDValue();
7088
7089       // Increment index.
7090       nextIndex+=2;
7091     } else
7092       return SDValue();
7093   }
7094
7095   // Create VPADDL node.
7096   SelectionDAG &DAG = DCI.DAG;
7097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7098
7099   // Build operand list.
7100   SmallVector<SDValue, 8> Ops;
7101   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7102                                 TLI.getPointerTy()));
7103
7104   // Input is the vector.
7105   Ops.push_back(Vec);
7106
7107   // Get widened type and narrowed type.
7108   MVT widenType;
7109   unsigned numElem = VT.getVectorNumElements();
7110   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7111     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7112     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7113     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7114     default:
7115       llvm_unreachable("Invalid vector element type for padd optimization.");
7116   }
7117
7118   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7119                             widenType, &Ops[0], Ops.size());
7120   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7121 }
7122
7123 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7124 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7125 /// called with the default operands, and if that fails, with commuted
7126 /// operands.
7127 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7128                                           TargetLowering::DAGCombinerInfo &DCI,
7129                                           const ARMSubtarget *Subtarget){
7130
7131   // Attempt to create vpaddl for this add.
7132   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7133   if (Result.getNode())
7134     return Result;
7135
7136   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7137   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
7138     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7139     if (Result.getNode()) return Result;
7140   }
7141   return SDValue();
7142 }
7143
7144 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7145 ///
7146 static SDValue PerformADDCombine(SDNode *N,
7147                                  TargetLowering::DAGCombinerInfo &DCI,
7148                                  const ARMSubtarget *Subtarget) {
7149   SDValue N0 = N->getOperand(0);
7150   SDValue N1 = N->getOperand(1);
7151
7152   // First try with the default operand order.
7153   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7154   if (Result.getNode())
7155     return Result;
7156
7157   // If that didn't work, try again with the operands commuted.
7158   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7159 }
7160
7161 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7162 ///
7163 static SDValue PerformSUBCombine(SDNode *N,
7164                                  TargetLowering::DAGCombinerInfo &DCI) {
7165   SDValue N0 = N->getOperand(0);
7166   SDValue N1 = N->getOperand(1);
7167
7168   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7169   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
7170     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7171     if (Result.getNode()) return Result;
7172   }
7173
7174   return SDValue();
7175 }
7176
7177 /// PerformVMULCombine
7178 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7179 /// special multiplier accumulator forwarding.
7180 ///   vmul d3, d0, d2
7181 ///   vmla d3, d1, d2
7182 /// is faster than
7183 ///   vadd d3, d0, d1
7184 ///   vmul d3, d3, d2
7185 static SDValue PerformVMULCombine(SDNode *N,
7186                                   TargetLowering::DAGCombinerInfo &DCI,
7187                                   const ARMSubtarget *Subtarget) {
7188   if (!Subtarget->hasVMLxForwarding())
7189     return SDValue();
7190
7191   SelectionDAG &DAG = DCI.DAG;
7192   SDValue N0 = N->getOperand(0);
7193   SDValue N1 = N->getOperand(1);
7194   unsigned Opcode = N0.getOpcode();
7195   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7196       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7197     Opcode = N1.getOpcode();
7198     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7199         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7200       return SDValue();
7201     std::swap(N0, N1);
7202   }
7203
7204   EVT VT = N->getValueType(0);
7205   DebugLoc DL = N->getDebugLoc();
7206   SDValue N00 = N0->getOperand(0);
7207   SDValue N01 = N0->getOperand(1);
7208   return DAG.getNode(Opcode, DL, VT,
7209                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7210                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7211 }
7212
7213 static SDValue PerformMULCombine(SDNode *N,
7214                                  TargetLowering::DAGCombinerInfo &DCI,
7215                                  const ARMSubtarget *Subtarget) {
7216   SelectionDAG &DAG = DCI.DAG;
7217
7218   if (Subtarget->isThumb1Only())
7219     return SDValue();
7220
7221   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7222     return SDValue();
7223
7224   EVT VT = N->getValueType(0);
7225   if (VT.is64BitVector() || VT.is128BitVector())
7226     return PerformVMULCombine(N, DCI, Subtarget);
7227   if (VT != MVT::i32)
7228     return SDValue();
7229
7230   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7231   if (!C)
7232     return SDValue();
7233
7234   int64_t MulAmt = C->getSExtValue();
7235   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7236
7237   ShiftAmt = ShiftAmt & (32 - 1);
7238   SDValue V = N->getOperand(0);
7239   DebugLoc DL = N->getDebugLoc();
7240
7241   SDValue Res;
7242   MulAmt >>= ShiftAmt;
7243
7244   if (MulAmt >= 0) {
7245     if (isPowerOf2_32(MulAmt - 1)) {
7246       // (mul x, 2^N + 1) => (add (shl x, N), x)
7247       Res = DAG.getNode(ISD::ADD, DL, VT,
7248                         V,
7249                         DAG.getNode(ISD::SHL, DL, VT,
7250                                     V,
7251                                     DAG.getConstant(Log2_32(MulAmt - 1),
7252                                                     MVT::i32)));
7253     } else if (isPowerOf2_32(MulAmt + 1)) {
7254       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7255       Res = DAG.getNode(ISD::SUB, DL, VT,
7256                         DAG.getNode(ISD::SHL, DL, VT,
7257                                     V,
7258                                     DAG.getConstant(Log2_32(MulAmt + 1),
7259                                                     MVT::i32)),
7260                         V);
7261     } else
7262       return SDValue();
7263   } else {
7264     uint64_t MulAmtAbs = -MulAmt;
7265     if (isPowerOf2_32(MulAmtAbs + 1)) {
7266       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7267       Res = DAG.getNode(ISD::SUB, DL, VT,
7268                         V,
7269                         DAG.getNode(ISD::SHL, DL, VT,
7270                                     V,
7271                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7272                                                     MVT::i32)));
7273     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7274       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7275       Res = DAG.getNode(ISD::ADD, DL, VT,
7276                         V,
7277                         DAG.getNode(ISD::SHL, DL, VT,
7278                                     V,
7279                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7280                                                     MVT::i32)));
7281       Res = DAG.getNode(ISD::SUB, DL, VT,
7282                         DAG.getConstant(0, MVT::i32),Res);
7283
7284     } else
7285       return SDValue();
7286   }
7287
7288   if (ShiftAmt != 0)
7289     Res = DAG.getNode(ISD::SHL, DL, VT,
7290                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7291
7292   // Do not add new nodes to DAG combiner worklist.
7293   DCI.CombineTo(N, Res, false);
7294   return SDValue();
7295 }
7296
7297 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
7298   if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
7299     return false;
7300
7301   SDValue FalseVal = N.getOperand(0);
7302   ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
7303   if (!C)
7304     return false;
7305   if (AllOnes)
7306     return C->isAllOnesValue();
7307   return C->isNullValue();
7308 }
7309
7310 /// formConditionalOp - Combine an operation with a conditional move operand
7311 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7312 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7313 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7314                                  bool Commutable) {
7315   SDValue N0 = N->getOperand(0);
7316   SDValue N1 = N->getOperand(1);
7317
7318   bool isAND = N->getOpcode() == ISD::AND;
7319   bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7320   if (!isCand && Commutable) {
7321     isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7322     if (isCand)
7323       std::swap(N0, N1);
7324   }
7325   if (!isCand)
7326     return SDValue();
7327
7328   unsigned Opc = 0;
7329   switch (N->getOpcode()) {
7330   default: llvm_unreachable("Unexpected node");
7331   case ISD::AND: Opc = ARMISD::CAND; break;
7332   case ISD::OR:  Opc = ARMISD::COR; break;
7333   case ISD::XOR: Opc = ARMISD::CXOR; break;
7334   }
7335   return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7336                      N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7337                      N1.getOperand(4));
7338 }
7339
7340 static SDValue PerformANDCombine(SDNode *N,
7341                                  TargetLowering::DAGCombinerInfo &DCI,
7342                                  const ARMSubtarget *Subtarget) {
7343
7344   // Attempt to use immediate-form VBIC
7345   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7346   DebugLoc dl = N->getDebugLoc();
7347   EVT VT = N->getValueType(0);
7348   SelectionDAG &DAG = DCI.DAG;
7349
7350   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7351     return SDValue();
7352
7353   APInt SplatBits, SplatUndef;
7354   unsigned SplatBitSize;
7355   bool HasAnyUndefs;
7356   if (BVN &&
7357       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7358     if (SplatBitSize <= 64) {
7359       EVT VbicVT;
7360       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7361                                       SplatUndef.getZExtValue(), SplatBitSize,
7362                                       DAG, VbicVT, VT.is128BitVector(),
7363                                       OtherModImm);
7364       if (Val.getNode()) {
7365         SDValue Input =
7366           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7367         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7368         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7369       }
7370     }
7371   }
7372
7373   if (!Subtarget->isThumb1Only()) {
7374     // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7375     SDValue CAND = formConditionalOp(N, DAG, true);
7376     if (CAND.getNode())
7377       return CAND;
7378   }
7379
7380   return SDValue();
7381 }
7382
7383 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7384 static SDValue PerformORCombine(SDNode *N,
7385                                 TargetLowering::DAGCombinerInfo &DCI,
7386                                 const ARMSubtarget *Subtarget) {
7387   // Attempt to use immediate-form VORR
7388   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7389   DebugLoc dl = N->getDebugLoc();
7390   EVT VT = N->getValueType(0);
7391   SelectionDAG &DAG = DCI.DAG;
7392
7393   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7394     return SDValue();
7395
7396   APInt SplatBits, SplatUndef;
7397   unsigned SplatBitSize;
7398   bool HasAnyUndefs;
7399   if (BVN && Subtarget->hasNEON() &&
7400       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7401     if (SplatBitSize <= 64) {
7402       EVT VorrVT;
7403       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7404                                       SplatUndef.getZExtValue(), SplatBitSize,
7405                                       DAG, VorrVT, VT.is128BitVector(),
7406                                       OtherModImm);
7407       if (Val.getNode()) {
7408         SDValue Input =
7409           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7410         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7411         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7412       }
7413     }
7414   }
7415
7416   if (!Subtarget->isThumb1Only()) {
7417     // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7418     SDValue COR = formConditionalOp(N, DAG, true);
7419     if (COR.getNode())
7420       return COR;
7421   }
7422
7423   SDValue N0 = N->getOperand(0);
7424   if (N0.getOpcode() != ISD::AND)
7425     return SDValue();
7426   SDValue N1 = N->getOperand(1);
7427
7428   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7429   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7430       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7431     APInt SplatUndef;
7432     unsigned SplatBitSize;
7433     bool HasAnyUndefs;
7434
7435     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7436     APInt SplatBits0;
7437     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7438                                   HasAnyUndefs) && !HasAnyUndefs) {
7439       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7440       APInt SplatBits1;
7441       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7442                                     HasAnyUndefs) && !HasAnyUndefs &&
7443           SplatBits0 == ~SplatBits1) {
7444         // Canonicalize the vector type to make instruction selection simpler.
7445         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7446         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7447                                      N0->getOperand(1), N0->getOperand(0),
7448                                      N1->getOperand(0));
7449         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7450       }
7451     }
7452   }
7453
7454   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7455   // reasonable.
7456
7457   // BFI is only available on V6T2+
7458   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7459     return SDValue();
7460
7461   DebugLoc DL = N->getDebugLoc();
7462   // 1) or (and A, mask), val => ARMbfi A, val, mask
7463   //      iff (val & mask) == val
7464   //
7465   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7466   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7467   //          && mask == ~mask2
7468   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7469   //          && ~mask == mask2
7470   //  (i.e., copy a bitfield value into another bitfield of the same width)
7471
7472   if (VT != MVT::i32)
7473     return SDValue();
7474
7475   SDValue N00 = N0.getOperand(0);
7476
7477   // The value and the mask need to be constants so we can verify this is
7478   // actually a bitfield set. If the mask is 0xffff, we can do better
7479   // via a movt instruction, so don't use BFI in that case.
7480   SDValue MaskOp = N0.getOperand(1);
7481   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7482   if (!MaskC)
7483     return SDValue();
7484   unsigned Mask = MaskC->getZExtValue();
7485   if (Mask == 0xffff)
7486     return SDValue();
7487   SDValue Res;
7488   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7489   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7490   if (N1C) {
7491     unsigned Val = N1C->getZExtValue();
7492     if ((Val & ~Mask) != Val)
7493       return SDValue();
7494
7495     if (ARM::isBitFieldInvertedMask(Mask)) {
7496       Val >>= CountTrailingZeros_32(~Mask);
7497
7498       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7499                         DAG.getConstant(Val, MVT::i32),
7500                         DAG.getConstant(Mask, MVT::i32));
7501
7502       // Do not add new nodes to DAG combiner worklist.
7503       DCI.CombineTo(N, Res, false);
7504       return SDValue();
7505     }
7506   } else if (N1.getOpcode() == ISD::AND) {
7507     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7508     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7509     if (!N11C)
7510       return SDValue();
7511     unsigned Mask2 = N11C->getZExtValue();
7512
7513     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7514     // as is to match.
7515     if (ARM::isBitFieldInvertedMask(Mask) &&
7516         (Mask == ~Mask2)) {
7517       // The pack halfword instruction works better for masks that fit it,
7518       // so use that when it's available.
7519       if (Subtarget->hasT2ExtractPack() &&
7520           (Mask == 0xffff || Mask == 0xffff0000))
7521         return SDValue();
7522       // 2a
7523       unsigned amt = CountTrailingZeros_32(Mask2);
7524       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7525                         DAG.getConstant(amt, MVT::i32));
7526       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7527                         DAG.getConstant(Mask, MVT::i32));
7528       // Do not add new nodes to DAG combiner worklist.
7529       DCI.CombineTo(N, Res, false);
7530       return SDValue();
7531     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7532                (~Mask == Mask2)) {
7533       // The pack halfword instruction works better for masks that fit it,
7534       // so use that when it's available.
7535       if (Subtarget->hasT2ExtractPack() &&
7536           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7537         return SDValue();
7538       // 2b
7539       unsigned lsb = CountTrailingZeros_32(Mask);
7540       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7541                         DAG.getConstant(lsb, MVT::i32));
7542       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7543                         DAG.getConstant(Mask2, MVT::i32));
7544       // Do not add new nodes to DAG combiner worklist.
7545       DCI.CombineTo(N, Res, false);
7546       return SDValue();
7547     }
7548   }
7549
7550   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7551       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7552       ARM::isBitFieldInvertedMask(~Mask)) {
7553     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7554     // where lsb(mask) == #shamt and masked bits of B are known zero.
7555     SDValue ShAmt = N00.getOperand(1);
7556     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7557     unsigned LSB = CountTrailingZeros_32(Mask);
7558     if (ShAmtC != LSB)
7559       return SDValue();
7560
7561     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7562                       DAG.getConstant(~Mask, MVT::i32));
7563
7564     // Do not add new nodes to DAG combiner worklist.
7565     DCI.CombineTo(N, Res, false);
7566   }
7567
7568   return SDValue();
7569 }
7570
7571 static SDValue PerformXORCombine(SDNode *N,
7572                                  TargetLowering::DAGCombinerInfo &DCI,
7573                                  const ARMSubtarget *Subtarget) {
7574   EVT VT = N->getValueType(0);
7575   SelectionDAG &DAG = DCI.DAG;
7576
7577   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7578     return SDValue();
7579
7580   if (!Subtarget->isThumb1Only()) {
7581     // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7582     SDValue CXOR = formConditionalOp(N, DAG, true);
7583     if (CXOR.getNode())
7584       return CXOR;
7585   }
7586
7587   return SDValue();
7588 }
7589
7590 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7591 /// the bits being cleared by the AND are not demanded by the BFI.
7592 static SDValue PerformBFICombine(SDNode *N,
7593                                  TargetLowering::DAGCombinerInfo &DCI) {
7594   SDValue N1 = N->getOperand(1);
7595   if (N1.getOpcode() == ISD::AND) {
7596     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7597     if (!N11C)
7598       return SDValue();
7599     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7600     unsigned LSB = CountTrailingZeros_32(~InvMask);
7601     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7602     unsigned Mask = (1 << Width)-1;
7603     unsigned Mask2 = N11C->getZExtValue();
7604     if ((Mask & (~Mask2)) == 0)
7605       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7606                              N->getOperand(0), N1.getOperand(0),
7607                              N->getOperand(2));
7608   }
7609   return SDValue();
7610 }
7611
7612 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7613 /// ARMISD::VMOVRRD.
7614 static SDValue PerformVMOVRRDCombine(SDNode *N,
7615                                      TargetLowering::DAGCombinerInfo &DCI) {
7616   // vmovrrd(vmovdrr x, y) -> x,y
7617   SDValue InDouble = N->getOperand(0);
7618   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7619     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7620
7621   // vmovrrd(load f64) -> (load i32), (load i32)
7622   SDNode *InNode = InDouble.getNode();
7623   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7624       InNode->getValueType(0) == MVT::f64 &&
7625       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7626       !cast<LoadSDNode>(InNode)->isVolatile()) {
7627     // TODO: Should this be done for non-FrameIndex operands?
7628     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7629
7630     SelectionDAG &DAG = DCI.DAG;
7631     DebugLoc DL = LD->getDebugLoc();
7632     SDValue BasePtr = LD->getBasePtr();
7633     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7634                                  LD->getPointerInfo(), LD->isVolatile(),
7635                                  LD->isNonTemporal(), LD->isInvariant(),
7636                                  LD->getAlignment());
7637
7638     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7639                                     DAG.getConstant(4, MVT::i32));
7640     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7641                                  LD->getPointerInfo(), LD->isVolatile(),
7642                                  LD->isNonTemporal(), LD->isInvariant(),
7643                                  std::min(4U, LD->getAlignment() / 2));
7644
7645     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7646     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7647     DCI.RemoveFromWorklist(LD);
7648     DAG.DeleteNode(LD);
7649     return Result;
7650   }
7651
7652   return SDValue();
7653 }
7654
7655 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7656 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7657 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7658   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7659   SDValue Op0 = N->getOperand(0);
7660   SDValue Op1 = N->getOperand(1);
7661   if (Op0.getOpcode() == ISD::BITCAST)
7662     Op0 = Op0.getOperand(0);
7663   if (Op1.getOpcode() == ISD::BITCAST)
7664     Op1 = Op1.getOperand(0);
7665   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7666       Op0.getNode() == Op1.getNode() &&
7667       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7668     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7669                        N->getValueType(0), Op0.getOperand(0));
7670   return SDValue();
7671 }
7672
7673 /// PerformSTORECombine - Target-specific dag combine xforms for
7674 /// ISD::STORE.
7675 static SDValue PerformSTORECombine(SDNode *N,
7676                                    TargetLowering::DAGCombinerInfo &DCI) {
7677   StoreSDNode *St = cast<StoreSDNode>(N);
7678   if (St->isVolatile())
7679     return SDValue();
7680
7681   // Optimize trunc store (of multiple scalars) to shuffle and store.  First, 
7682   // pack all of the elements in one place.  Next, store to memory in fewer
7683   // chunks.
7684   SDValue StVal = St->getValue();
7685   EVT VT = StVal.getValueType();
7686   if (St->isTruncatingStore() && VT.isVector()) {
7687     SelectionDAG &DAG = DCI.DAG;
7688     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7689     EVT StVT = St->getMemoryVT();
7690     unsigned NumElems = VT.getVectorNumElements();
7691     assert(StVT != VT && "Cannot truncate to the same type");
7692     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7693     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7694
7695     // From, To sizes and ElemCount must be pow of two
7696     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7697
7698     // We are going to use the original vector elt for storing.
7699     // Accumulated smaller vector elements must be a multiple of the store size.
7700     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7701
7702     unsigned SizeRatio  = FromEltSz / ToEltSz;
7703     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7704
7705     // Create a type on which we perform the shuffle.
7706     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7707                                      NumElems*SizeRatio);
7708     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7709
7710     DebugLoc DL = St->getDebugLoc();
7711     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7712     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7713     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7714
7715     // Can't shuffle using an illegal type.
7716     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7717
7718     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7719                                 DAG.getUNDEF(WideVec.getValueType()),
7720                                 ShuffleVec.data());
7721     // At this point all of the data is stored at the bottom of the
7722     // register. We now need to save it to mem.
7723
7724     // Find the largest store unit
7725     MVT StoreType = MVT::i8;
7726     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7727          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7728       MVT Tp = (MVT::SimpleValueType)tp;
7729       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7730         StoreType = Tp;
7731     }
7732     // Didn't find a legal store type.
7733     if (!TLI.isTypeLegal(StoreType))
7734       return SDValue();
7735
7736     // Bitcast the original vector into a vector of store-size units
7737     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7738             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7739     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7740     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7741     SmallVector<SDValue, 8> Chains;
7742     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7743                                         TLI.getPointerTy());
7744     SDValue BasePtr = St->getBasePtr();
7745
7746     // Perform one or more big stores into memory.
7747     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7748     for (unsigned I = 0; I < E; I++) {
7749       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7750                                    StoreType, ShuffWide,
7751                                    DAG.getIntPtrConstant(I));
7752       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7753                                 St->getPointerInfo(), St->isVolatile(),
7754                                 St->isNonTemporal(), St->getAlignment());
7755       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7756                             Increment);
7757       Chains.push_back(Ch);
7758     }
7759     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7760                        Chains.size());
7761   }
7762
7763   if (!ISD::isNormalStore(St))
7764     return SDValue();
7765
7766   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7767   // ARM stores of arguments in the same cache line.
7768   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7769       StVal.getNode()->hasOneUse()) {
7770     SelectionDAG  &DAG = DCI.DAG;
7771     DebugLoc DL = St->getDebugLoc();
7772     SDValue BasePtr = St->getBasePtr();
7773     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7774                                   StVal.getNode()->getOperand(0), BasePtr,
7775                                   St->getPointerInfo(), St->isVolatile(),
7776                                   St->isNonTemporal(), St->getAlignment());
7777
7778     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7779                                     DAG.getConstant(4, MVT::i32));
7780     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7781                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7782                         St->isNonTemporal(),
7783                         std::min(4U, St->getAlignment() / 2));
7784   }
7785
7786   if (StVal.getValueType() != MVT::i64 ||
7787       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7788     return SDValue();
7789
7790   // Bitcast an i64 store extracted from a vector to f64.
7791   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7792   SelectionDAG &DAG = DCI.DAG;
7793   DebugLoc dl = StVal.getDebugLoc();
7794   SDValue IntVec = StVal.getOperand(0);
7795   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7796                                  IntVec.getValueType().getVectorNumElements());
7797   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7798   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7799                                Vec, StVal.getOperand(1));
7800   dl = N->getDebugLoc();
7801   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7802   // Make the DAGCombiner fold the bitcasts.
7803   DCI.AddToWorklist(Vec.getNode());
7804   DCI.AddToWorklist(ExtElt.getNode());
7805   DCI.AddToWorklist(V.getNode());
7806   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7807                       St->getPointerInfo(), St->isVolatile(),
7808                       St->isNonTemporal(), St->getAlignment(),
7809                       St->getTBAAInfo());
7810 }
7811
7812 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7813 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7814 /// i64 vector to have f64 elements, since the value can then be loaded
7815 /// directly into a VFP register.
7816 static bool hasNormalLoadOperand(SDNode *N) {
7817   unsigned NumElts = N->getValueType(0).getVectorNumElements();
7818   for (unsigned i = 0; i < NumElts; ++i) {
7819     SDNode *Elt = N->getOperand(i).getNode();
7820     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7821       return true;
7822   }
7823   return false;
7824 }
7825
7826 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7827 /// ISD::BUILD_VECTOR.
7828 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7829                                           TargetLowering::DAGCombinerInfo &DCI){
7830   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7831   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7832   // into a pair of GPRs, which is fine when the value is used as a scalar,
7833   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7834   SelectionDAG &DAG = DCI.DAG;
7835   if (N->getNumOperands() == 2) {
7836     SDValue RV = PerformVMOVDRRCombine(N, DAG);
7837     if (RV.getNode())
7838       return RV;
7839   }
7840
7841   // Load i64 elements as f64 values so that type legalization does not split
7842   // them up into i32 values.
7843   EVT VT = N->getValueType(0);
7844   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7845     return SDValue();
7846   DebugLoc dl = N->getDebugLoc();
7847   SmallVector<SDValue, 8> Ops;
7848   unsigned NumElts = VT.getVectorNumElements();
7849   for (unsigned i = 0; i < NumElts; ++i) {
7850     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7851     Ops.push_back(V);
7852     // Make the DAGCombiner fold the bitcast.
7853     DCI.AddToWorklist(V.getNode());
7854   }
7855   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7856   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7857   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7858 }
7859
7860 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7861 /// ISD::INSERT_VECTOR_ELT.
7862 static SDValue PerformInsertEltCombine(SDNode *N,
7863                                        TargetLowering::DAGCombinerInfo &DCI) {
7864   // Bitcast an i64 load inserted into a vector to f64.
7865   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7866   EVT VT = N->getValueType(0);
7867   SDNode *Elt = N->getOperand(1).getNode();
7868   if (VT.getVectorElementType() != MVT::i64 ||
7869       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7870     return SDValue();
7871
7872   SelectionDAG &DAG = DCI.DAG;
7873   DebugLoc dl = N->getDebugLoc();
7874   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7875                                  VT.getVectorNumElements());
7876   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7877   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7878   // Make the DAGCombiner fold the bitcasts.
7879   DCI.AddToWorklist(Vec.getNode());
7880   DCI.AddToWorklist(V.getNode());
7881   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7882                                Vec, V, N->getOperand(2));
7883   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7884 }
7885
7886 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7887 /// ISD::VECTOR_SHUFFLE.
7888 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7889   // The LLVM shufflevector instruction does not require the shuffle mask
7890   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7891   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7892   // operands do not match the mask length, they are extended by concatenating
7893   // them with undef vectors.  That is probably the right thing for other
7894   // targets, but for NEON it is better to concatenate two double-register
7895   // size vector operands into a single quad-register size vector.  Do that
7896   // transformation here:
7897   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7898   //   shuffle(concat(v1, v2), undef)
7899   SDValue Op0 = N->getOperand(0);
7900   SDValue Op1 = N->getOperand(1);
7901   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7902       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7903       Op0.getNumOperands() != 2 ||
7904       Op1.getNumOperands() != 2)
7905     return SDValue();
7906   SDValue Concat0Op1 = Op0.getOperand(1);
7907   SDValue Concat1Op1 = Op1.getOperand(1);
7908   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7909       Concat1Op1.getOpcode() != ISD::UNDEF)
7910     return SDValue();
7911   // Skip the transformation if any of the types are illegal.
7912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7913   EVT VT = N->getValueType(0);
7914   if (!TLI.isTypeLegal(VT) ||
7915       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7916       !TLI.isTypeLegal(Concat1Op1.getValueType()))
7917     return SDValue();
7918
7919   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7920                                   Op0.getOperand(0), Op1.getOperand(0));
7921   // Translate the shuffle mask.
7922   SmallVector<int, 16> NewMask;
7923   unsigned NumElts = VT.getVectorNumElements();
7924   unsigned HalfElts = NumElts/2;
7925   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7926   for (unsigned n = 0; n < NumElts; ++n) {
7927     int MaskElt = SVN->getMaskElt(n);
7928     int NewElt = -1;
7929     if (MaskElt < (int)HalfElts)
7930       NewElt = MaskElt;
7931     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7932       NewElt = HalfElts + MaskElt - NumElts;
7933     NewMask.push_back(NewElt);
7934   }
7935   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7936                               DAG.getUNDEF(VT), NewMask.data());
7937 }
7938
7939 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7940 /// NEON load/store intrinsics to merge base address updates.
7941 static SDValue CombineBaseUpdate(SDNode *N,
7942                                  TargetLowering::DAGCombinerInfo &DCI) {
7943   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7944     return SDValue();
7945
7946   SelectionDAG &DAG = DCI.DAG;
7947   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7948                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7949   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7950   SDValue Addr = N->getOperand(AddrOpIdx);
7951
7952   // Search for a use of the address operand that is an increment.
7953   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7954          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7955     SDNode *User = *UI;
7956     if (User->getOpcode() != ISD::ADD ||
7957         UI.getUse().getResNo() != Addr.getResNo())
7958       continue;
7959
7960     // Check that the add is independent of the load/store.  Otherwise, folding
7961     // it would create a cycle.
7962     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7963       continue;
7964
7965     // Find the new opcode for the updating load/store.
7966     bool isLoad = true;
7967     bool isLaneOp = false;
7968     unsigned NewOpc = 0;
7969     unsigned NumVecs = 0;
7970     if (isIntrinsic) {
7971       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7972       switch (IntNo) {
7973       default: llvm_unreachable("unexpected intrinsic for Neon base update");
7974       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
7975         NumVecs = 1; break;
7976       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
7977         NumVecs = 2; break;
7978       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
7979         NumVecs = 3; break;
7980       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
7981         NumVecs = 4; break;
7982       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7983         NumVecs = 2; isLaneOp = true; break;
7984       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7985         NumVecs = 3; isLaneOp = true; break;
7986       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7987         NumVecs = 4; isLaneOp = true; break;
7988       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
7989         NumVecs = 1; isLoad = false; break;
7990       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
7991         NumVecs = 2; isLoad = false; break;
7992       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
7993         NumVecs = 3; isLoad = false; break;
7994       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
7995         NumVecs = 4; isLoad = false; break;
7996       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7997         NumVecs = 2; isLoad = false; isLaneOp = true; break;
7998       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7999         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8000       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8001         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8002       }
8003     } else {
8004       isLaneOp = true;
8005       switch (N->getOpcode()) {
8006       default: llvm_unreachable("unexpected opcode for Neon base update");
8007       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8008       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8009       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8010       }
8011     }
8012
8013     // Find the size of memory referenced by the load/store.
8014     EVT VecTy;
8015     if (isLoad)
8016       VecTy = N->getValueType(0);
8017     else
8018       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8019     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8020     if (isLaneOp)
8021       NumBytes /= VecTy.getVectorNumElements();
8022
8023     // If the increment is a constant, it must match the memory ref size.
8024     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8025     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8026       uint64_t IncVal = CInc->getZExtValue();
8027       if (IncVal != NumBytes)
8028         continue;
8029     } else if (NumBytes >= 3 * 16) {
8030       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8031       // separate instructions that make it harder to use a non-constant update.
8032       continue;
8033     }
8034
8035     // Create the new updating load/store node.
8036     EVT Tys[6];
8037     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8038     unsigned n;
8039     for (n = 0; n < NumResultVecs; ++n)
8040       Tys[n] = VecTy;
8041     Tys[n++] = MVT::i32;
8042     Tys[n] = MVT::Other;
8043     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8044     SmallVector<SDValue, 8> Ops;
8045     Ops.push_back(N->getOperand(0)); // incoming chain
8046     Ops.push_back(N->getOperand(AddrOpIdx));
8047     Ops.push_back(Inc);
8048     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8049       Ops.push_back(N->getOperand(i));
8050     }
8051     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8052     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8053                                            Ops.data(), Ops.size(),
8054                                            MemInt->getMemoryVT(),
8055                                            MemInt->getMemOperand());
8056
8057     // Update the uses.
8058     std::vector<SDValue> NewResults;
8059     for (unsigned i = 0; i < NumResultVecs; ++i) {
8060       NewResults.push_back(SDValue(UpdN.getNode(), i));
8061     }
8062     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8063     DCI.CombineTo(N, NewResults);
8064     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8065
8066     break;
8067   }
8068   return SDValue();
8069 }
8070
8071 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8072 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8073 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8074 /// return true.
8075 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8076   SelectionDAG &DAG = DCI.DAG;
8077   EVT VT = N->getValueType(0);
8078   // vldN-dup instructions only support 64-bit vectors for N > 1.
8079   if (!VT.is64BitVector())
8080     return false;
8081
8082   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8083   SDNode *VLD = N->getOperand(0).getNode();
8084   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8085     return false;
8086   unsigned NumVecs = 0;
8087   unsigned NewOpc = 0;
8088   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8089   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8090     NumVecs = 2;
8091     NewOpc = ARMISD::VLD2DUP;
8092   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8093     NumVecs = 3;
8094     NewOpc = ARMISD::VLD3DUP;
8095   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8096     NumVecs = 4;
8097     NewOpc = ARMISD::VLD4DUP;
8098   } else {
8099     return false;
8100   }
8101
8102   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8103   // numbers match the load.
8104   unsigned VLDLaneNo =
8105     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8106   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8107        UI != UE; ++UI) {
8108     // Ignore uses of the chain result.
8109     if (UI.getUse().getResNo() == NumVecs)
8110       continue;
8111     SDNode *User = *UI;
8112     if (User->getOpcode() != ARMISD::VDUPLANE ||
8113         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8114       return false;
8115   }
8116
8117   // Create the vldN-dup node.
8118   EVT Tys[5];
8119   unsigned n;
8120   for (n = 0; n < NumVecs; ++n)
8121     Tys[n] = VT;
8122   Tys[n] = MVT::Other;
8123   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8124   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8125   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8126   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8127                                            Ops, 2, VLDMemInt->getMemoryVT(),
8128                                            VLDMemInt->getMemOperand());
8129
8130   // Update the uses.
8131   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8132        UI != UE; ++UI) {
8133     unsigned ResNo = UI.getUse().getResNo();
8134     // Ignore uses of the chain result.
8135     if (ResNo == NumVecs)
8136       continue;
8137     SDNode *User = *UI;
8138     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8139   }
8140
8141   // Now the vldN-lane intrinsic is dead except for its chain result.
8142   // Update uses of the chain.
8143   std::vector<SDValue> VLDDupResults;
8144   for (unsigned n = 0; n < NumVecs; ++n)
8145     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8146   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8147   DCI.CombineTo(VLD, VLDDupResults);
8148
8149   return true;
8150 }
8151
8152 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8153 /// ARMISD::VDUPLANE.
8154 static SDValue PerformVDUPLANECombine(SDNode *N,
8155                                       TargetLowering::DAGCombinerInfo &DCI) {
8156   SDValue Op = N->getOperand(0);
8157
8158   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8159   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8160   if (CombineVLDDUP(N, DCI))
8161     return SDValue(N, 0);
8162
8163   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8164   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8165   while (Op.getOpcode() == ISD::BITCAST)
8166     Op = Op.getOperand(0);
8167   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8168     return SDValue();
8169
8170   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8171   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8172   // The canonical VMOV for a zero vector uses a 32-bit element size.
8173   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8174   unsigned EltBits;
8175   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8176     EltSize = 8;
8177   EVT VT = N->getValueType(0);
8178   if (EltSize > VT.getVectorElementType().getSizeInBits())
8179     return SDValue();
8180
8181   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8182 }
8183
8184 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8185 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8186 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8187 {
8188   integerPart cN;
8189   integerPart c0 = 0;
8190   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8191        I != E; I++) {
8192     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8193     if (!C)
8194       return false;
8195
8196     bool isExact;
8197     APFloat APF = C->getValueAPF();
8198     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8199         != APFloat::opOK || !isExact)
8200       return false;
8201
8202     c0 = (I == 0) ? cN : c0;
8203     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8204       return false;
8205   }
8206   C = c0;
8207   return true;
8208 }
8209
8210 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8211 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8212 /// when the VMUL has a constant operand that is a power of 2.
8213 ///
8214 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8215 ///  vmul.f32        d16, d17, d16
8216 ///  vcvt.s32.f32    d16, d16
8217 /// becomes:
8218 ///  vcvt.s32.f32    d16, d16, #3
8219 static SDValue PerformVCVTCombine(SDNode *N,
8220                                   TargetLowering::DAGCombinerInfo &DCI,
8221                                   const ARMSubtarget *Subtarget) {
8222   SelectionDAG &DAG = DCI.DAG;
8223   SDValue Op = N->getOperand(0);
8224
8225   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8226       Op.getOpcode() != ISD::FMUL)
8227     return SDValue();
8228
8229   uint64_t C;
8230   SDValue N0 = Op->getOperand(0);
8231   SDValue ConstVec = Op->getOperand(1);
8232   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8233
8234   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8235       !isConstVecPow2(ConstVec, isSigned, C))
8236     return SDValue();
8237
8238   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8239     Intrinsic::arm_neon_vcvtfp2fxu;
8240   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8241                      N->getValueType(0),
8242                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8243                      DAG.getConstant(Log2_64(C), MVT::i32));
8244 }
8245
8246 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8247 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8248 /// when the VDIV has a constant operand that is a power of 2.
8249 ///
8250 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8251 ///  vcvt.f32.s32    d16, d16
8252 ///  vdiv.f32        d16, d17, d16
8253 /// becomes:
8254 ///  vcvt.f32.s32    d16, d16, #3
8255 static SDValue PerformVDIVCombine(SDNode *N,
8256                                   TargetLowering::DAGCombinerInfo &DCI,
8257                                   const ARMSubtarget *Subtarget) {
8258   SelectionDAG &DAG = DCI.DAG;
8259   SDValue Op = N->getOperand(0);
8260   unsigned OpOpcode = Op.getNode()->getOpcode();
8261
8262   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8263       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8264     return SDValue();
8265
8266   uint64_t C;
8267   SDValue ConstVec = N->getOperand(1);
8268   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8269
8270   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8271       !isConstVecPow2(ConstVec, isSigned, C))
8272     return SDValue();
8273
8274   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8275     Intrinsic::arm_neon_vcvtfxu2fp;
8276   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8277                      Op.getValueType(),
8278                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8279                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8280 }
8281
8282 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8283 /// operand of a vector shift operation, where all the elements of the
8284 /// build_vector must have the same constant integer value.
8285 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8286   // Ignore bit_converts.
8287   while (Op.getOpcode() == ISD::BITCAST)
8288     Op = Op.getOperand(0);
8289   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8290   APInt SplatBits, SplatUndef;
8291   unsigned SplatBitSize;
8292   bool HasAnyUndefs;
8293   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8294                                       HasAnyUndefs, ElementBits) ||
8295       SplatBitSize > ElementBits)
8296     return false;
8297   Cnt = SplatBits.getSExtValue();
8298   return true;
8299 }
8300
8301 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8302 /// operand of a vector shift left operation.  That value must be in the range:
8303 ///   0 <= Value < ElementBits for a left shift; or
8304 ///   0 <= Value <= ElementBits for a long left shift.
8305 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8306   assert(VT.isVector() && "vector shift count is not a vector type");
8307   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8308   if (! getVShiftImm(Op, ElementBits, Cnt))
8309     return false;
8310   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8311 }
8312
8313 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8314 /// operand of a vector shift right operation.  For a shift opcode, the value
8315 /// is positive, but for an intrinsic the value count must be negative. The
8316 /// absolute value must be in the range:
8317 ///   1 <= |Value| <= ElementBits for a right shift; or
8318 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8319 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8320                          int64_t &Cnt) {
8321   assert(VT.isVector() && "vector shift count is not a vector type");
8322   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8323   if (! getVShiftImm(Op, ElementBits, Cnt))
8324     return false;
8325   if (isIntrinsic)
8326     Cnt = -Cnt;
8327   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8328 }
8329
8330 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8331 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8332   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8333   switch (IntNo) {
8334   default:
8335     // Don't do anything for most intrinsics.
8336     break;
8337
8338   // Vector shifts: check for immediate versions and lower them.
8339   // Note: This is done during DAG combining instead of DAG legalizing because
8340   // the build_vectors for 64-bit vector element shift counts are generally
8341   // not legal, and it is hard to see their values after they get legalized to
8342   // loads from a constant pool.
8343   case Intrinsic::arm_neon_vshifts:
8344   case Intrinsic::arm_neon_vshiftu:
8345   case Intrinsic::arm_neon_vshiftls:
8346   case Intrinsic::arm_neon_vshiftlu:
8347   case Intrinsic::arm_neon_vshiftn:
8348   case Intrinsic::arm_neon_vrshifts:
8349   case Intrinsic::arm_neon_vrshiftu:
8350   case Intrinsic::arm_neon_vrshiftn:
8351   case Intrinsic::arm_neon_vqshifts:
8352   case Intrinsic::arm_neon_vqshiftu:
8353   case Intrinsic::arm_neon_vqshiftsu:
8354   case Intrinsic::arm_neon_vqshiftns:
8355   case Intrinsic::arm_neon_vqshiftnu:
8356   case Intrinsic::arm_neon_vqshiftnsu:
8357   case Intrinsic::arm_neon_vqrshiftns:
8358   case Intrinsic::arm_neon_vqrshiftnu:
8359   case Intrinsic::arm_neon_vqrshiftnsu: {
8360     EVT VT = N->getOperand(1).getValueType();
8361     int64_t Cnt;
8362     unsigned VShiftOpc = 0;
8363
8364     switch (IntNo) {
8365     case Intrinsic::arm_neon_vshifts:
8366     case Intrinsic::arm_neon_vshiftu:
8367       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8368         VShiftOpc = ARMISD::VSHL;
8369         break;
8370       }
8371       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8372         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8373                      ARMISD::VSHRs : ARMISD::VSHRu);
8374         break;
8375       }
8376       return SDValue();
8377
8378     case Intrinsic::arm_neon_vshiftls:
8379     case Intrinsic::arm_neon_vshiftlu:
8380       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8381         break;
8382       llvm_unreachable("invalid shift count for vshll intrinsic");
8383
8384     case Intrinsic::arm_neon_vrshifts:
8385     case Intrinsic::arm_neon_vrshiftu:
8386       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8387         break;
8388       return SDValue();
8389
8390     case Intrinsic::arm_neon_vqshifts:
8391     case Intrinsic::arm_neon_vqshiftu:
8392       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8393         break;
8394       return SDValue();
8395
8396     case Intrinsic::arm_neon_vqshiftsu:
8397       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8398         break;
8399       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8400
8401     case Intrinsic::arm_neon_vshiftn:
8402     case Intrinsic::arm_neon_vrshiftn:
8403     case Intrinsic::arm_neon_vqshiftns:
8404     case Intrinsic::arm_neon_vqshiftnu:
8405     case Intrinsic::arm_neon_vqshiftnsu:
8406     case Intrinsic::arm_neon_vqrshiftns:
8407     case Intrinsic::arm_neon_vqrshiftnu:
8408     case Intrinsic::arm_neon_vqrshiftnsu:
8409       // Narrowing shifts require an immediate right shift.
8410       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8411         break;
8412       llvm_unreachable("invalid shift count for narrowing vector shift "
8413                        "intrinsic");
8414
8415     default:
8416       llvm_unreachable("unhandled vector shift");
8417     }
8418
8419     switch (IntNo) {
8420     case Intrinsic::arm_neon_vshifts:
8421     case Intrinsic::arm_neon_vshiftu:
8422       // Opcode already set above.
8423       break;
8424     case Intrinsic::arm_neon_vshiftls:
8425     case Intrinsic::arm_neon_vshiftlu:
8426       if (Cnt == VT.getVectorElementType().getSizeInBits())
8427         VShiftOpc = ARMISD::VSHLLi;
8428       else
8429         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8430                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8431       break;
8432     case Intrinsic::arm_neon_vshiftn:
8433       VShiftOpc = ARMISD::VSHRN; break;
8434     case Intrinsic::arm_neon_vrshifts:
8435       VShiftOpc = ARMISD::VRSHRs; break;
8436     case Intrinsic::arm_neon_vrshiftu:
8437       VShiftOpc = ARMISD::VRSHRu; break;
8438     case Intrinsic::arm_neon_vrshiftn:
8439       VShiftOpc = ARMISD::VRSHRN; break;
8440     case Intrinsic::arm_neon_vqshifts:
8441       VShiftOpc = ARMISD::VQSHLs; break;
8442     case Intrinsic::arm_neon_vqshiftu:
8443       VShiftOpc = ARMISD::VQSHLu; break;
8444     case Intrinsic::arm_neon_vqshiftsu:
8445       VShiftOpc = ARMISD::VQSHLsu; break;
8446     case Intrinsic::arm_neon_vqshiftns:
8447       VShiftOpc = ARMISD::VQSHRNs; break;
8448     case Intrinsic::arm_neon_vqshiftnu:
8449       VShiftOpc = ARMISD::VQSHRNu; break;
8450     case Intrinsic::arm_neon_vqshiftnsu:
8451       VShiftOpc = ARMISD::VQSHRNsu; break;
8452     case Intrinsic::arm_neon_vqrshiftns:
8453       VShiftOpc = ARMISD::VQRSHRNs; break;
8454     case Intrinsic::arm_neon_vqrshiftnu:
8455       VShiftOpc = ARMISD::VQRSHRNu; break;
8456     case Intrinsic::arm_neon_vqrshiftnsu:
8457       VShiftOpc = ARMISD::VQRSHRNsu; break;
8458     }
8459
8460     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8461                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8462   }
8463
8464   case Intrinsic::arm_neon_vshiftins: {
8465     EVT VT = N->getOperand(1).getValueType();
8466     int64_t Cnt;
8467     unsigned VShiftOpc = 0;
8468
8469     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8470       VShiftOpc = ARMISD::VSLI;
8471     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8472       VShiftOpc = ARMISD::VSRI;
8473     else {
8474       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8475     }
8476
8477     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8478                        N->getOperand(1), N->getOperand(2),
8479                        DAG.getConstant(Cnt, MVT::i32));
8480   }
8481
8482   case Intrinsic::arm_neon_vqrshifts:
8483   case Intrinsic::arm_neon_vqrshiftu:
8484     // No immediate versions of these to check for.
8485     break;
8486   }
8487
8488   return SDValue();
8489 }
8490
8491 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8492 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8493 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8494 /// vector element shift counts are generally not legal, and it is hard to see
8495 /// their values after they get legalized to loads from a constant pool.
8496 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8497                                    const ARMSubtarget *ST) {
8498   EVT VT = N->getValueType(0);
8499   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8500     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8501     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8502     SDValue N1 = N->getOperand(1);
8503     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8504       SDValue N0 = N->getOperand(0);
8505       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8506           DAG.MaskedValueIsZero(N0.getOperand(0),
8507                                 APInt::getHighBitsSet(32, 16)))
8508         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8509     }
8510   }
8511
8512   // Nothing to be done for scalar shifts.
8513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8514   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8515     return SDValue();
8516
8517   assert(ST->hasNEON() && "unexpected vector shift");
8518   int64_t Cnt;
8519
8520   switch (N->getOpcode()) {
8521   default: llvm_unreachable("unexpected shift opcode");
8522
8523   case ISD::SHL:
8524     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8525       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8526                          DAG.getConstant(Cnt, MVT::i32));
8527     break;
8528
8529   case ISD::SRA:
8530   case ISD::SRL:
8531     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8532       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8533                             ARMISD::VSHRs : ARMISD::VSHRu);
8534       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8535                          DAG.getConstant(Cnt, MVT::i32));
8536     }
8537   }
8538   return SDValue();
8539 }
8540
8541 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8542 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8543 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8544                                     const ARMSubtarget *ST) {
8545   SDValue N0 = N->getOperand(0);
8546
8547   // Check for sign- and zero-extensions of vector extract operations of 8-
8548   // and 16-bit vector elements.  NEON supports these directly.  They are
8549   // handled during DAG combining because type legalization will promote them
8550   // to 32-bit types and it is messy to recognize the operations after that.
8551   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8552     SDValue Vec = N0.getOperand(0);
8553     SDValue Lane = N0.getOperand(1);
8554     EVT VT = N->getValueType(0);
8555     EVT EltVT = N0.getValueType();
8556     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8557
8558     if (VT == MVT::i32 &&
8559         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8560         TLI.isTypeLegal(Vec.getValueType()) &&
8561         isa<ConstantSDNode>(Lane)) {
8562
8563       unsigned Opc = 0;
8564       switch (N->getOpcode()) {
8565       default: llvm_unreachable("unexpected opcode");
8566       case ISD::SIGN_EXTEND:
8567         Opc = ARMISD::VGETLANEs;
8568         break;
8569       case ISD::ZERO_EXTEND:
8570       case ISD::ANY_EXTEND:
8571         Opc = ARMISD::VGETLANEu;
8572         break;
8573       }
8574       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8575     }
8576   }
8577
8578   return SDValue();
8579 }
8580
8581 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8582 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8583 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8584                                        const ARMSubtarget *ST) {
8585   // If the target supports NEON, try to use vmax/vmin instructions for f32
8586   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8587   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8588   // a NaN; only do the transformation when it matches that behavior.
8589
8590   // For now only do this when using NEON for FP operations; if using VFP, it
8591   // is not obvious that the benefit outweighs the cost of switching to the
8592   // NEON pipeline.
8593   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8594       N->getValueType(0) != MVT::f32)
8595     return SDValue();
8596
8597   SDValue CondLHS = N->getOperand(0);
8598   SDValue CondRHS = N->getOperand(1);
8599   SDValue LHS = N->getOperand(2);
8600   SDValue RHS = N->getOperand(3);
8601   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8602
8603   unsigned Opcode = 0;
8604   bool IsReversed;
8605   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8606     IsReversed = false; // x CC y ? x : y
8607   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8608     IsReversed = true ; // x CC y ? y : x
8609   } else {
8610     return SDValue();
8611   }
8612
8613   bool IsUnordered;
8614   switch (CC) {
8615   default: break;
8616   case ISD::SETOLT:
8617   case ISD::SETOLE:
8618   case ISD::SETLT:
8619   case ISD::SETLE:
8620   case ISD::SETULT:
8621   case ISD::SETULE:
8622     // If LHS is NaN, an ordered comparison will be false and the result will
8623     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8624     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8625     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8626     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8627       break;
8628     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8629     // will return -0, so vmin can only be used for unsafe math or if one of
8630     // the operands is known to be nonzero.
8631     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8632         !DAG.getTarget().Options.UnsafeFPMath &&
8633         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8634       break;
8635     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8636     break;
8637
8638   case ISD::SETOGT:
8639   case ISD::SETOGE:
8640   case ISD::SETGT:
8641   case ISD::SETGE:
8642   case ISD::SETUGT:
8643   case ISD::SETUGE:
8644     // If LHS is NaN, an ordered comparison will be false and the result will
8645     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8646     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8647     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8648     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8649       break;
8650     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8651     // will return +0, so vmax can only be used for unsafe math or if one of
8652     // the operands is known to be nonzero.
8653     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8654         !DAG.getTarget().Options.UnsafeFPMath &&
8655         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8656       break;
8657     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8658     break;
8659   }
8660
8661   if (!Opcode)
8662     return SDValue();
8663   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8664 }
8665
8666 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8667 SDValue
8668 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8669   SDValue Cmp = N->getOperand(4);
8670   if (Cmp.getOpcode() != ARMISD::CMPZ)
8671     // Only looking at EQ and NE cases.
8672     return SDValue();
8673
8674   EVT VT = N->getValueType(0);
8675   DebugLoc dl = N->getDebugLoc();
8676   SDValue LHS = Cmp.getOperand(0);
8677   SDValue RHS = Cmp.getOperand(1);
8678   SDValue FalseVal = N->getOperand(0);
8679   SDValue TrueVal = N->getOperand(1);
8680   SDValue ARMcc = N->getOperand(2);
8681   ARMCC::CondCodes CC =
8682     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8683
8684   // Simplify
8685   //   mov     r1, r0
8686   //   cmp     r1, x
8687   //   mov     r0, y
8688   //   moveq   r0, x
8689   // to
8690   //   cmp     r0, x
8691   //   movne   r0, y
8692   //
8693   //   mov     r1, r0
8694   //   cmp     r1, x
8695   //   mov     r0, x
8696   //   movne   r0, y
8697   // to
8698   //   cmp     r0, x
8699   //   movne   r0, y
8700   /// FIXME: Turn this into a target neutral optimization?
8701   SDValue Res;
8702   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8703     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8704                       N->getOperand(3), Cmp);
8705   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8706     SDValue ARMcc;
8707     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8708     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8709                       N->getOperand(3), NewCmp);
8710   }
8711
8712   if (Res.getNode()) {
8713     APInt KnownZero, KnownOne;
8714     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8715     // Capture demanded bits information that would be otherwise lost.
8716     if (KnownZero == 0xfffffffe)
8717       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8718                         DAG.getValueType(MVT::i1));
8719     else if (KnownZero == 0xffffff00)
8720       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8721                         DAG.getValueType(MVT::i8));
8722     else if (KnownZero == 0xffff0000)
8723       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8724                         DAG.getValueType(MVT::i16));
8725   }
8726
8727   return Res;
8728 }
8729
8730 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8731                                              DAGCombinerInfo &DCI) const {
8732   switch (N->getOpcode()) {
8733   default: break;
8734   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8735   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8736   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8737   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8738   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8739   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8740   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8741   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8742   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8743   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8744   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8745   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8746   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8747   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8748   case ISD::FP_TO_SINT:
8749   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8750   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8751   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8752   case ISD::SHL:
8753   case ISD::SRA:
8754   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8755   case ISD::SIGN_EXTEND:
8756   case ISD::ZERO_EXTEND:
8757   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8758   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8759   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8760   case ARMISD::VLD2DUP:
8761   case ARMISD::VLD3DUP:
8762   case ARMISD::VLD4DUP:
8763     return CombineBaseUpdate(N, DCI);
8764   case ISD::INTRINSIC_VOID:
8765   case ISD::INTRINSIC_W_CHAIN:
8766     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8767     case Intrinsic::arm_neon_vld1:
8768     case Intrinsic::arm_neon_vld2:
8769     case Intrinsic::arm_neon_vld3:
8770     case Intrinsic::arm_neon_vld4:
8771     case Intrinsic::arm_neon_vld2lane:
8772     case Intrinsic::arm_neon_vld3lane:
8773     case Intrinsic::arm_neon_vld4lane:
8774     case Intrinsic::arm_neon_vst1:
8775     case Intrinsic::arm_neon_vst2:
8776     case Intrinsic::arm_neon_vst3:
8777     case Intrinsic::arm_neon_vst4:
8778     case Intrinsic::arm_neon_vst2lane:
8779     case Intrinsic::arm_neon_vst3lane:
8780     case Intrinsic::arm_neon_vst4lane:
8781       return CombineBaseUpdate(N, DCI);
8782     default: break;
8783     }
8784     break;
8785   }
8786   return SDValue();
8787 }
8788
8789 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8790                                                           EVT VT) const {
8791   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8792 }
8793
8794 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8795   if (!Subtarget->allowsUnalignedMem())
8796     return false;
8797
8798   switch (VT.getSimpleVT().SimpleTy) {
8799   default:
8800     return false;
8801   case MVT::i8:
8802   case MVT::i16:
8803   case MVT::i32:
8804     return true;
8805   // FIXME: VLD1 etc with standard alignment is legal.
8806   }
8807 }
8808
8809 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8810                        unsigned AlignCheck) {
8811   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8812           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8813 }
8814
8815 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8816                                            unsigned DstAlign, unsigned SrcAlign,
8817                                            bool IsZeroVal,
8818                                            bool MemcpyStrSrc,
8819                                            MachineFunction &MF) const {
8820   const Function *F = MF.getFunction();
8821
8822   // See if we can use NEON instructions for this...
8823   if (IsZeroVal &&
8824       !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8825       Subtarget->hasNEON()) {
8826     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8827       return MVT::v4i32;
8828     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8829       return MVT::v2i32;
8830     }
8831   }
8832
8833   // Lowering to i32/i16 if the size permits.
8834   if (Size >= 4) {
8835     return MVT::i32;
8836   } else if (Size >= 2) {
8837     return MVT::i16;
8838   }
8839
8840   // Let the target-independent logic figure it out.
8841   return MVT::Other;
8842 }
8843
8844 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8845   if (V < 0)
8846     return false;
8847
8848   unsigned Scale = 1;
8849   switch (VT.getSimpleVT().SimpleTy) {
8850   default: return false;
8851   case MVT::i1:
8852   case MVT::i8:
8853     // Scale == 1;
8854     break;
8855   case MVT::i16:
8856     // Scale == 2;
8857     Scale = 2;
8858     break;
8859   case MVT::i32:
8860     // Scale == 4;
8861     Scale = 4;
8862     break;
8863   }
8864
8865   if ((V & (Scale - 1)) != 0)
8866     return false;
8867   V /= Scale;
8868   return V == (V & ((1LL << 5) - 1));
8869 }
8870
8871 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8872                                       const ARMSubtarget *Subtarget) {
8873   bool isNeg = false;
8874   if (V < 0) {
8875     isNeg = true;
8876     V = - V;
8877   }
8878
8879   switch (VT.getSimpleVT().SimpleTy) {
8880   default: return false;
8881   case MVT::i1:
8882   case MVT::i8:
8883   case MVT::i16:
8884   case MVT::i32:
8885     // + imm12 or - imm8
8886     if (isNeg)
8887       return V == (V & ((1LL << 8) - 1));
8888     return V == (V & ((1LL << 12) - 1));
8889   case MVT::f32:
8890   case MVT::f64:
8891     // Same as ARM mode. FIXME: NEON?
8892     if (!Subtarget->hasVFP2())
8893       return false;
8894     if ((V & 3) != 0)
8895       return false;
8896     V >>= 2;
8897     return V == (V & ((1LL << 8) - 1));
8898   }
8899 }
8900
8901 /// isLegalAddressImmediate - Return true if the integer value can be used
8902 /// as the offset of the target addressing mode for load / store of the
8903 /// given type.
8904 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8905                                     const ARMSubtarget *Subtarget) {
8906   if (V == 0)
8907     return true;
8908
8909   if (!VT.isSimple())
8910     return false;
8911
8912   if (Subtarget->isThumb1Only())
8913     return isLegalT1AddressImmediate(V, VT);
8914   else if (Subtarget->isThumb2())
8915     return isLegalT2AddressImmediate(V, VT, Subtarget);
8916
8917   // ARM mode.
8918   if (V < 0)
8919     V = - V;
8920   switch (VT.getSimpleVT().SimpleTy) {
8921   default: return false;
8922   case MVT::i1:
8923   case MVT::i8:
8924   case MVT::i32:
8925     // +- imm12
8926     return V == (V & ((1LL << 12) - 1));
8927   case MVT::i16:
8928     // +- imm8
8929     return V == (V & ((1LL << 8) - 1));
8930   case MVT::f32:
8931   case MVT::f64:
8932     if (!Subtarget->hasVFP2()) // FIXME: NEON?
8933       return false;
8934     if ((V & 3) != 0)
8935       return false;
8936     V >>= 2;
8937     return V == (V & ((1LL << 8) - 1));
8938   }
8939 }
8940
8941 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8942                                                       EVT VT) const {
8943   int Scale = AM.Scale;
8944   if (Scale < 0)
8945     return false;
8946
8947   switch (VT.getSimpleVT().SimpleTy) {
8948   default: return false;
8949   case MVT::i1:
8950   case MVT::i8:
8951   case MVT::i16:
8952   case MVT::i32:
8953     if (Scale == 1)
8954       return true;
8955     // r + r << imm
8956     Scale = Scale & ~1;
8957     return Scale == 2 || Scale == 4 || Scale == 8;
8958   case MVT::i64:
8959     // r + r
8960     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8961       return true;
8962     return false;
8963   case MVT::isVoid:
8964     // Note, we allow "void" uses (basically, uses that aren't loads or
8965     // stores), because arm allows folding a scale into many arithmetic
8966     // operations.  This should be made more precise and revisited later.
8967
8968     // Allow r << imm, but the imm has to be a multiple of two.
8969     if (Scale & 1) return false;
8970     return isPowerOf2_32(Scale);
8971   }
8972 }
8973
8974 /// isLegalAddressingMode - Return true if the addressing mode represented
8975 /// by AM is legal for this target, for a load/store of the specified type.
8976 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8977                                               Type *Ty) const {
8978   EVT VT = getValueType(Ty, true);
8979   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8980     return false;
8981
8982   // Can never fold addr of global into load/store.
8983   if (AM.BaseGV)
8984     return false;
8985
8986   switch (AM.Scale) {
8987   case 0:  // no scale reg, must be "r+i" or "r", or "i".
8988     break;
8989   case 1:
8990     if (Subtarget->isThumb1Only())
8991       return false;
8992     // FALL THROUGH.
8993   default:
8994     // ARM doesn't support any R+R*scale+imm addr modes.
8995     if (AM.BaseOffs)
8996       return false;
8997
8998     if (!VT.isSimple())
8999       return false;
9000
9001     if (Subtarget->isThumb2())
9002       return isLegalT2ScaledAddressingMode(AM, VT);
9003
9004     int Scale = AM.Scale;
9005     switch (VT.getSimpleVT().SimpleTy) {
9006     default: return false;
9007     case MVT::i1:
9008     case MVT::i8:
9009     case MVT::i32:
9010       if (Scale < 0) Scale = -Scale;
9011       if (Scale == 1)
9012         return true;
9013       // r + r << imm
9014       return isPowerOf2_32(Scale & ~1);
9015     case MVT::i16:
9016     case MVT::i64:
9017       // r + r
9018       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9019         return true;
9020       return false;
9021
9022     case MVT::isVoid:
9023       // Note, we allow "void" uses (basically, uses that aren't loads or
9024       // stores), because arm allows folding a scale into many arithmetic
9025       // operations.  This should be made more precise and revisited later.
9026
9027       // Allow r << imm, but the imm has to be a multiple of two.
9028       if (Scale & 1) return false;
9029       return isPowerOf2_32(Scale);
9030     }
9031   }
9032   return true;
9033 }
9034
9035 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9036 /// icmp immediate, that is the target has icmp instructions which can compare
9037 /// a register against the immediate without having to materialize the
9038 /// immediate into a register.
9039 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9040   // Thumb2 and ARM modes can use cmn for negative immediates.
9041   if (!Subtarget->isThumb())
9042     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9043   if (Subtarget->isThumb2())
9044     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9045   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9046   return Imm >= 0 && Imm <= 255;
9047 }
9048
9049 /// isLegalAddImmediate - Return true if the specified immediate is legal
9050 /// add immediate, that is the target has add instructions which can add
9051 /// a register with the immediate without having to materialize the
9052 /// immediate into a register.
9053 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9054   return ARM_AM::getSOImmVal(Imm) != -1;
9055 }
9056
9057 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9058                                       bool isSEXTLoad, SDValue &Base,
9059                                       SDValue &Offset, bool &isInc,
9060                                       SelectionDAG &DAG) {
9061   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9062     return false;
9063
9064   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9065     // AddressingMode 3
9066     Base = Ptr->getOperand(0);
9067     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9068       int RHSC = (int)RHS->getZExtValue();
9069       if (RHSC < 0 && RHSC > -256) {
9070         assert(Ptr->getOpcode() == ISD::ADD);
9071         isInc = false;
9072         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9073         return true;
9074       }
9075     }
9076     isInc = (Ptr->getOpcode() == ISD::ADD);
9077     Offset = Ptr->getOperand(1);
9078     return true;
9079   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9080     // AddressingMode 2
9081     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9082       int RHSC = (int)RHS->getZExtValue();
9083       if (RHSC < 0 && RHSC > -0x1000) {
9084         assert(Ptr->getOpcode() == ISD::ADD);
9085         isInc = false;
9086         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9087         Base = Ptr->getOperand(0);
9088         return true;
9089       }
9090     }
9091
9092     if (Ptr->getOpcode() == ISD::ADD) {
9093       isInc = true;
9094       ARM_AM::ShiftOpc ShOpcVal=
9095         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9096       if (ShOpcVal != ARM_AM::no_shift) {
9097         Base = Ptr->getOperand(1);
9098         Offset = Ptr->getOperand(0);
9099       } else {
9100         Base = Ptr->getOperand(0);
9101         Offset = Ptr->getOperand(1);
9102       }
9103       return true;
9104     }
9105
9106     isInc = (Ptr->getOpcode() == ISD::ADD);
9107     Base = Ptr->getOperand(0);
9108     Offset = Ptr->getOperand(1);
9109     return true;
9110   }
9111
9112   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9113   return false;
9114 }
9115
9116 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9117                                      bool isSEXTLoad, SDValue &Base,
9118                                      SDValue &Offset, bool &isInc,
9119                                      SelectionDAG &DAG) {
9120   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9121     return false;
9122
9123   Base = Ptr->getOperand(0);
9124   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9125     int RHSC = (int)RHS->getZExtValue();
9126     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9127       assert(Ptr->getOpcode() == ISD::ADD);
9128       isInc = false;
9129       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9130       return true;
9131     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9132       isInc = Ptr->getOpcode() == ISD::ADD;
9133       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9134       return true;
9135     }
9136   }
9137
9138   return false;
9139 }
9140
9141 /// getPreIndexedAddressParts - returns true by value, base pointer and
9142 /// offset pointer and addressing mode by reference if the node's address
9143 /// can be legally represented as pre-indexed load / store address.
9144 bool
9145 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9146                                              SDValue &Offset,
9147                                              ISD::MemIndexedMode &AM,
9148                                              SelectionDAG &DAG) const {
9149   if (Subtarget->isThumb1Only())
9150     return false;
9151
9152   EVT VT;
9153   SDValue Ptr;
9154   bool isSEXTLoad = false;
9155   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9156     Ptr = LD->getBasePtr();
9157     VT  = LD->getMemoryVT();
9158     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9159   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9160     Ptr = ST->getBasePtr();
9161     VT  = ST->getMemoryVT();
9162   } else
9163     return false;
9164
9165   bool isInc;
9166   bool isLegal = false;
9167   if (Subtarget->isThumb2())
9168     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9169                                        Offset, isInc, DAG);
9170   else
9171     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9172                                         Offset, isInc, DAG);
9173   if (!isLegal)
9174     return false;
9175
9176   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9177   return true;
9178 }
9179
9180 /// getPostIndexedAddressParts - returns true by value, base pointer and
9181 /// offset pointer and addressing mode by reference if this node can be
9182 /// combined with a load / store to form a post-indexed load / store.
9183 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9184                                                    SDValue &Base,
9185                                                    SDValue &Offset,
9186                                                    ISD::MemIndexedMode &AM,
9187                                                    SelectionDAG &DAG) const {
9188   if (Subtarget->isThumb1Only())
9189     return false;
9190
9191   EVT VT;
9192   SDValue Ptr;
9193   bool isSEXTLoad = false;
9194   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9195     VT  = LD->getMemoryVT();
9196     Ptr = LD->getBasePtr();
9197     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9198   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9199     VT  = ST->getMemoryVT();
9200     Ptr = ST->getBasePtr();
9201   } else
9202     return false;
9203
9204   bool isInc;
9205   bool isLegal = false;
9206   if (Subtarget->isThumb2())
9207     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9208                                        isInc, DAG);
9209   else
9210     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9211                                         isInc, DAG);
9212   if (!isLegal)
9213     return false;
9214
9215   if (Ptr != Base) {
9216     // Swap base ptr and offset to catch more post-index load / store when
9217     // it's legal. In Thumb2 mode, offset must be an immediate.
9218     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9219         !Subtarget->isThumb2())
9220       std::swap(Base, Offset);
9221
9222     // Post-indexed load / store update the base pointer.
9223     if (Ptr != Base)
9224       return false;
9225   }
9226
9227   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9228   return true;
9229 }
9230
9231 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9232                                                        APInt &KnownZero,
9233                                                        APInt &KnownOne,
9234                                                        const SelectionDAG &DAG,
9235                                                        unsigned Depth) const {
9236   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9237   switch (Op.getOpcode()) {
9238   default: break;
9239   case ARMISD::CMOV: {
9240     // Bits are known zero/one if known on the LHS and RHS.
9241     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9242     if (KnownZero == 0 && KnownOne == 0) return;
9243
9244     APInt KnownZeroRHS, KnownOneRHS;
9245     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9246     KnownZero &= KnownZeroRHS;
9247     KnownOne  &= KnownOneRHS;
9248     return;
9249   }
9250   }
9251 }
9252
9253 //===----------------------------------------------------------------------===//
9254 //                           ARM Inline Assembly Support
9255 //===----------------------------------------------------------------------===//
9256
9257 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9258   // Looking for "rev" which is V6+.
9259   if (!Subtarget->hasV6Ops())
9260     return false;
9261
9262   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9263   std::string AsmStr = IA->getAsmString();
9264   SmallVector<StringRef, 4> AsmPieces;
9265   SplitString(AsmStr, AsmPieces, ";\n");
9266
9267   switch (AsmPieces.size()) {
9268   default: return false;
9269   case 1:
9270     AsmStr = AsmPieces[0];
9271     AsmPieces.clear();
9272     SplitString(AsmStr, AsmPieces, " \t,");
9273
9274     // rev $0, $1
9275     if (AsmPieces.size() == 3 &&
9276         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9277         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9278       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9279       if (Ty && Ty->getBitWidth() == 32)
9280         return IntrinsicLowering::LowerToByteSwap(CI);
9281     }
9282     break;
9283   }
9284
9285   return false;
9286 }
9287
9288 /// getConstraintType - Given a constraint letter, return the type of
9289 /// constraint it is for this target.
9290 ARMTargetLowering::ConstraintType
9291 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9292   if (Constraint.size() == 1) {
9293     switch (Constraint[0]) {
9294     default:  break;
9295     case 'l': return C_RegisterClass;
9296     case 'w': return C_RegisterClass;
9297     case 'h': return C_RegisterClass;
9298     case 'x': return C_RegisterClass;
9299     case 't': return C_RegisterClass;
9300     case 'j': return C_Other; // Constant for movw.
9301       // An address with a single base register. Due to the way we
9302       // currently handle addresses it is the same as an 'r' memory constraint.
9303     case 'Q': return C_Memory;
9304     }
9305   } else if (Constraint.size() == 2) {
9306     switch (Constraint[0]) {
9307     default: break;
9308     // All 'U+' constraints are addresses.
9309     case 'U': return C_Memory;
9310     }
9311   }
9312   return TargetLowering::getConstraintType(Constraint);
9313 }
9314
9315 /// Examine constraint type and operand type and determine a weight value.
9316 /// This object must already have been set up with the operand type
9317 /// and the current alternative constraint selected.
9318 TargetLowering::ConstraintWeight
9319 ARMTargetLowering::getSingleConstraintMatchWeight(
9320     AsmOperandInfo &info, const char *constraint) const {
9321   ConstraintWeight weight = CW_Invalid;
9322   Value *CallOperandVal = info.CallOperandVal;
9323     // If we don't have a value, we can't do a match,
9324     // but allow it at the lowest weight.
9325   if (CallOperandVal == NULL)
9326     return CW_Default;
9327   Type *type = CallOperandVal->getType();
9328   // Look at the constraint type.
9329   switch (*constraint) {
9330   default:
9331     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9332     break;
9333   case 'l':
9334     if (type->isIntegerTy()) {
9335       if (Subtarget->isThumb())
9336         weight = CW_SpecificReg;
9337       else
9338         weight = CW_Register;
9339     }
9340     break;
9341   case 'w':
9342     if (type->isFloatingPointTy())
9343       weight = CW_Register;
9344     break;
9345   }
9346   return weight;
9347 }
9348
9349 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9350 RCPair
9351 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9352                                                 EVT VT) const {
9353   if (Constraint.size() == 1) {
9354     // GCC ARM Constraint Letters
9355     switch (Constraint[0]) {
9356     case 'l': // Low regs or general regs.
9357       if (Subtarget->isThumb())
9358         return RCPair(0U, &ARM::tGPRRegClass);
9359       return RCPair(0U, &ARM::GPRRegClass);
9360     case 'h': // High regs or no regs.
9361       if (Subtarget->isThumb())
9362         return RCPair(0U, &ARM::hGPRRegClass);
9363       break;
9364     case 'r':
9365       return RCPair(0U, &ARM::GPRRegClass);
9366     case 'w':
9367       if (VT == MVT::f32)
9368         return RCPair(0U, &ARM::SPRRegClass);
9369       if (VT.getSizeInBits() == 64)
9370         return RCPair(0U, &ARM::DPRRegClass);
9371       if (VT.getSizeInBits() == 128)
9372         return RCPair(0U, &ARM::QPRRegClass);
9373       break;
9374     case 'x':
9375       if (VT == MVT::f32)
9376         return RCPair(0U, &ARM::SPR_8RegClass);
9377       if (VT.getSizeInBits() == 64)
9378         return RCPair(0U, &ARM::DPR_8RegClass);
9379       if (VT.getSizeInBits() == 128)
9380         return RCPair(0U, &ARM::QPR_8RegClass);
9381       break;
9382     case 't':
9383       if (VT == MVT::f32)
9384         return RCPair(0U, &ARM::SPRRegClass);
9385       break;
9386     }
9387   }
9388   if (StringRef("{cc}").equals_lower(Constraint))
9389     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9390
9391   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9392 }
9393
9394 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9395 /// vector.  If it is invalid, don't add anything to Ops.
9396 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9397                                                      std::string &Constraint,
9398                                                      std::vector<SDValue>&Ops,
9399                                                      SelectionDAG &DAG) const {
9400   SDValue Result(0, 0);
9401
9402   // Currently only support length 1 constraints.
9403   if (Constraint.length() != 1) return;
9404
9405   char ConstraintLetter = Constraint[0];
9406   switch (ConstraintLetter) {
9407   default: break;
9408   case 'j':
9409   case 'I': case 'J': case 'K': case 'L':
9410   case 'M': case 'N': case 'O':
9411     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9412     if (!C)
9413       return;
9414
9415     int64_t CVal64 = C->getSExtValue();
9416     int CVal = (int) CVal64;
9417     // None of these constraints allow values larger than 32 bits.  Check
9418     // that the value fits in an int.
9419     if (CVal != CVal64)
9420       return;
9421
9422     switch (ConstraintLetter) {
9423       case 'j':
9424         // Constant suitable for movw, must be between 0 and
9425         // 65535.
9426         if (Subtarget->hasV6T2Ops())
9427           if (CVal >= 0 && CVal <= 65535)
9428             break;
9429         return;
9430       case 'I':
9431         if (Subtarget->isThumb1Only()) {
9432           // This must be a constant between 0 and 255, for ADD
9433           // immediates.
9434           if (CVal >= 0 && CVal <= 255)
9435             break;
9436         } else if (Subtarget->isThumb2()) {
9437           // A constant that can be used as an immediate value in a
9438           // data-processing instruction.
9439           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9440             break;
9441         } else {
9442           // A constant that can be used as an immediate value in a
9443           // data-processing instruction.
9444           if (ARM_AM::getSOImmVal(CVal) != -1)
9445             break;
9446         }
9447         return;
9448
9449       case 'J':
9450         if (Subtarget->isThumb()) {  // FIXME thumb2
9451           // This must be a constant between -255 and -1, for negated ADD
9452           // immediates. This can be used in GCC with an "n" modifier that
9453           // prints the negated value, for use with SUB instructions. It is
9454           // not useful otherwise but is implemented for compatibility.
9455           if (CVal >= -255 && CVal <= -1)
9456             break;
9457         } else {
9458           // This must be a constant between -4095 and 4095. It is not clear
9459           // what this constraint is intended for. Implemented for
9460           // compatibility with GCC.
9461           if (CVal >= -4095 && CVal <= 4095)
9462             break;
9463         }
9464         return;
9465
9466       case 'K':
9467         if (Subtarget->isThumb1Only()) {
9468           // A 32-bit value where only one byte has a nonzero value. Exclude
9469           // zero to match GCC. This constraint is used by GCC internally for
9470           // constants that can be loaded with a move/shift combination.
9471           // It is not useful otherwise but is implemented for compatibility.
9472           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9473             break;
9474         } else if (Subtarget->isThumb2()) {
9475           // A constant whose bitwise inverse can be used as an immediate
9476           // value in a data-processing instruction. This can be used in GCC
9477           // with a "B" modifier that prints the inverted value, for use with
9478           // BIC and MVN instructions. It is not useful otherwise but is
9479           // implemented for compatibility.
9480           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9481             break;
9482         } else {
9483           // A constant whose bitwise inverse can be used as an immediate
9484           // value in a data-processing instruction. This can be used in GCC
9485           // with a "B" modifier that prints the inverted value, for use with
9486           // BIC and MVN instructions. It is not useful otherwise but is
9487           // implemented for compatibility.
9488           if (ARM_AM::getSOImmVal(~CVal) != -1)
9489             break;
9490         }
9491         return;
9492
9493       case 'L':
9494         if (Subtarget->isThumb1Only()) {
9495           // This must be a constant between -7 and 7,
9496           // for 3-operand ADD/SUB immediate instructions.
9497           if (CVal >= -7 && CVal < 7)
9498             break;
9499         } else if (Subtarget->isThumb2()) {
9500           // A constant whose negation can be used as an immediate value in a
9501           // data-processing instruction. This can be used in GCC with an "n"
9502           // modifier that prints the negated value, for use with SUB
9503           // instructions. It is not useful otherwise but is implemented for
9504           // compatibility.
9505           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9506             break;
9507         } else {
9508           // A constant whose negation can be used as an immediate value in a
9509           // data-processing instruction. This can be used in GCC with an "n"
9510           // modifier that prints the negated value, for use with SUB
9511           // instructions. It is not useful otherwise but is implemented for
9512           // compatibility.
9513           if (ARM_AM::getSOImmVal(-CVal) != -1)
9514             break;
9515         }
9516         return;
9517
9518       case 'M':
9519         if (Subtarget->isThumb()) { // FIXME thumb2
9520           // This must be a multiple of 4 between 0 and 1020, for
9521           // ADD sp + immediate.
9522           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9523             break;
9524         } else {
9525           // A power of two or a constant between 0 and 32.  This is used in
9526           // GCC for the shift amount on shifted register operands, but it is
9527           // useful in general for any shift amounts.
9528           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9529             break;
9530         }
9531         return;
9532
9533       case 'N':
9534         if (Subtarget->isThumb()) {  // FIXME thumb2
9535           // This must be a constant between 0 and 31, for shift amounts.
9536           if (CVal >= 0 && CVal <= 31)
9537             break;
9538         }
9539         return;
9540
9541       case 'O':
9542         if (Subtarget->isThumb()) {  // FIXME thumb2
9543           // This must be a multiple of 4 between -508 and 508, for
9544           // ADD/SUB sp = sp + immediate.
9545           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9546             break;
9547         }
9548         return;
9549     }
9550     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9551     break;
9552   }
9553
9554   if (Result.getNode()) {
9555     Ops.push_back(Result);
9556     return;
9557   }
9558   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9559 }
9560
9561 bool
9562 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9563   // The ARM target isn't yet aware of offsets.
9564   return false;
9565 }
9566
9567 bool ARM::isBitFieldInvertedMask(unsigned v) {
9568   if (v == 0xffffffff)
9569     return 0;
9570   // there can be 1's on either or both "outsides", all the "inside"
9571   // bits must be 0's
9572   unsigned int lsb = 0, msb = 31;
9573   while (v & (1 << msb)) --msb;
9574   while (v & (1 << lsb)) ++lsb;
9575   for (unsigned int i = lsb; i <= msb; ++i) {
9576     if (v & (1 << i))
9577       return 0;
9578   }
9579   return 1;
9580 }
9581
9582 /// isFPImmLegal - Returns true if the target can instruction select the
9583 /// specified FP immediate natively. If false, the legalizer will
9584 /// materialize the FP immediate as a load from a constant pool.
9585 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9586   if (!Subtarget->hasVFP3())
9587     return false;
9588   if (VT == MVT::f32)
9589     return ARM_AM::getFP32Imm(Imm) != -1;
9590   if (VT == MVT::f64)
9591     return ARM_AM::getFP64Imm(Imm) != -1;
9592   return false;
9593 }
9594
9595 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9596 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9597 /// specified in the intrinsic calls.
9598 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9599                                            const CallInst &I,
9600                                            unsigned Intrinsic) const {
9601   switch (Intrinsic) {
9602   case Intrinsic::arm_neon_vld1:
9603   case Intrinsic::arm_neon_vld2:
9604   case Intrinsic::arm_neon_vld3:
9605   case Intrinsic::arm_neon_vld4:
9606   case Intrinsic::arm_neon_vld2lane:
9607   case Intrinsic::arm_neon_vld3lane:
9608   case Intrinsic::arm_neon_vld4lane: {
9609     Info.opc = ISD::INTRINSIC_W_CHAIN;
9610     // Conservatively set memVT to the entire set of vectors loaded.
9611     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9612     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9613     Info.ptrVal = I.getArgOperand(0);
9614     Info.offset = 0;
9615     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9616     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9617     Info.vol = false; // volatile loads with NEON intrinsics not supported
9618     Info.readMem = true;
9619     Info.writeMem = false;
9620     return true;
9621   }
9622   case Intrinsic::arm_neon_vst1:
9623   case Intrinsic::arm_neon_vst2:
9624   case Intrinsic::arm_neon_vst3:
9625   case Intrinsic::arm_neon_vst4:
9626   case Intrinsic::arm_neon_vst2lane:
9627   case Intrinsic::arm_neon_vst3lane:
9628   case Intrinsic::arm_neon_vst4lane: {
9629     Info.opc = ISD::INTRINSIC_VOID;
9630     // Conservatively set memVT to the entire set of vectors stored.
9631     unsigned NumElts = 0;
9632     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9633       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9634       if (!ArgTy->isVectorTy())
9635         break;
9636       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9637     }
9638     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9639     Info.ptrVal = I.getArgOperand(0);
9640     Info.offset = 0;
9641     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9642     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9643     Info.vol = false; // volatile stores with NEON intrinsics not supported
9644     Info.readMem = false;
9645     Info.writeMem = true;
9646     return true;
9647   }
9648   case Intrinsic::arm_strexd: {
9649     Info.opc = ISD::INTRINSIC_W_CHAIN;
9650     Info.memVT = MVT::i64;
9651     Info.ptrVal = I.getArgOperand(2);
9652     Info.offset = 0;
9653     Info.align = 8;
9654     Info.vol = true;
9655     Info.readMem = false;
9656     Info.writeMem = true;
9657     return true;
9658   }
9659   case Intrinsic::arm_ldrexd: {
9660     Info.opc = ISD::INTRINSIC_W_CHAIN;
9661     Info.memVT = MVT::i64;
9662     Info.ptrVal = I.getArgOperand(0);
9663     Info.offset = 0;
9664     Info.align = 8;
9665     Info.vol = true;
9666     Info.readMem = true;
9667     Info.writeMem = false;
9668     return true;
9669   }
9670   default:
9671     break;
9672   }
9673
9674   return false;
9675 }