ARM: remove unused v(add|sub)hn and vqdml[as]l intrinsics.
[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/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.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, SmallVectorImpl<CCValAssign> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
456
457   if (Subtarget->hasNEON()) {
458     addDRTypeForNEON(MVT::v2f32);
459     addDRTypeForNEON(MVT::v8i8);
460     addDRTypeForNEON(MVT::v4i16);
461     addDRTypeForNEON(MVT::v2i32);
462     addDRTypeForNEON(MVT::v1i64);
463
464     addQRTypeForNEON(MVT::v4f32);
465     addQRTypeForNEON(MVT::v2f64);
466     addQRTypeForNEON(MVT::v16i8);
467     addQRTypeForNEON(MVT::v8i16);
468     addQRTypeForNEON(MVT::v4i32);
469     addQRTypeForNEON(MVT::v2i64);
470
471     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
472     // neither Neon nor VFP support any arithmetic operations on it.
473     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
474     // supported for v4f32.
475     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
476     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
477     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
478     // FIXME: Code duplication: FDIV and FREM are expanded always, see
479     // ARMTargetLowering::addTypeForNEON method for details.
480     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
481     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
482     // FIXME: Create unittest.
483     // In another words, find a way when "copysign" appears in DAG with vector
484     // operands.
485     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
486     // FIXME: Code duplication: SETCC has custom operation action, see
487     // ARMTargetLowering::addTypeForNEON method for details.
488     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
489     // FIXME: Create unittest for FNEG and for FABS.
490     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
491     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
493     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
494     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
496     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
501     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
502     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
503     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
504     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
505     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
507     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
508     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
509
510     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
511     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
512     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
514     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
519     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
520     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
521     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
522     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
524     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
525
526     // Mark v2f32 intrinsics.
527     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
528     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
529     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
531     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
534     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
536     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
537     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
538     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
539     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
541     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
542
543     // Neon does not support some operations on v1i64 and v2i64 types.
544     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
545     // Custom handling for some quad-vector types to detect VMULL.
546     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
547     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
548     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
549     // Custom handling for some vector types to avoid expensive expansions
550     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
551     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
552     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
553     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
554     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
555     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
556     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
557     // a destination type that is wider than the source, and nor does
558     // it have a FP_TO_[SU]INT instruction with a narrower destination than
559     // source.
560     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
563     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
564
565     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
566     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
567
568     // Custom expand long extensions to vectors.
569     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
571     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
573     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
575     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
576     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
577
578     // NEON does not have single instruction CTPOP for vectors with element
579     // types wider than 8-bits.  However, custom lowering can leverage the
580     // v8i8/v16i8 vcnt instruction.
581     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
584     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
585
586     // NEON only has FMA instructions as of VFP4.
587     if (!Subtarget->hasVFP4()) {
588       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
589       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
590     }
591
592     setTargetDAGCombine(ISD::INTRINSIC_VOID);
593     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
594     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
595     setTargetDAGCombine(ISD::SHL);
596     setTargetDAGCombine(ISD::SRL);
597     setTargetDAGCombine(ISD::SRA);
598     setTargetDAGCombine(ISD::SIGN_EXTEND);
599     setTargetDAGCombine(ISD::ZERO_EXTEND);
600     setTargetDAGCombine(ISD::ANY_EXTEND);
601     setTargetDAGCombine(ISD::SELECT_CC);
602     setTargetDAGCombine(ISD::BUILD_VECTOR);
603     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
604     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
605     setTargetDAGCombine(ISD::STORE);
606     setTargetDAGCombine(ISD::FP_TO_SINT);
607     setTargetDAGCombine(ISD::FP_TO_UINT);
608     setTargetDAGCombine(ISD::FDIV);
609
610     // It is legal to extload from v4i8 to v4i16 or v4i32.
611     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
612                   MVT::v4i16, MVT::v2i16,
613                   MVT::v2i32};
614     for (unsigned i = 0; i < 6; ++i) {
615       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
617       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
618     }
619   }
620
621   // ARM and Thumb2 support UMLAL/SMLAL.
622   if (!Subtarget->isThumb1Only())
623     setTargetDAGCombine(ISD::ADDC);
624
625
626   computeRegisterProperties();
627
628   // ARM does not have f32 extending load.
629   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
630
631   // ARM does not have i1 sign extending load.
632   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
633
634   // ARM supports all 4 flavors of integer indexed load / store.
635   if (!Subtarget->isThumb1Only()) {
636     for (unsigned im = (unsigned)ISD::PRE_INC;
637          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
638       setIndexedLoadAction(im,  MVT::i1,  Legal);
639       setIndexedLoadAction(im,  MVT::i8,  Legal);
640       setIndexedLoadAction(im,  MVT::i16, Legal);
641       setIndexedLoadAction(im,  MVT::i32, Legal);
642       setIndexedStoreAction(im, MVT::i1,  Legal);
643       setIndexedStoreAction(im, MVT::i8,  Legal);
644       setIndexedStoreAction(im, MVT::i16, Legal);
645       setIndexedStoreAction(im, MVT::i32, Legal);
646     }
647   }
648
649   // i64 operation support.
650   setOperationAction(ISD::MUL,     MVT::i64, Expand);
651   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
652   if (Subtarget->isThumb1Only()) {
653     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
654     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
655   }
656   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
657       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
658     setOperationAction(ISD::MULHS, MVT::i32, Expand);
659
660   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
663   setOperationAction(ISD::SRL,       MVT::i64, Custom);
664   setOperationAction(ISD::SRA,       MVT::i64, Custom);
665
666   if (!Subtarget->isThumb1Only()) {
667     // FIXME: We should do this for Thumb1 as well.
668     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
669     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
671     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
672   }
673
674   // ARM does not have ROTL.
675   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
676   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
677   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
678   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
679     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
680
681   // These just redirect to CTTZ and CTLZ on ARM.
682   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
683   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
684
685   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
686
687   // Only ARMv6 has BSWAP.
688   if (!Subtarget->hasV6Ops())
689     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
690
691   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
692       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
693     // These are expanded into libcalls if the cpu doesn't have HW divider.
694     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
695     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
696   }
697
698   // FIXME: Also set divmod for SREM on EABI
699   setOperationAction(ISD::SREM,  MVT::i32, Expand);
700   setOperationAction(ISD::UREM,  MVT::i32, Expand);
701   // Register based DivRem for AEABI (RTABI 4.2)
702   if (Subtarget->isTargetAEABI()) {
703     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
704     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
705     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
706     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
707     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
708     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
709     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
710     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
711
712     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
713     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
714     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
715     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
716     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
717     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
718     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
719     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
720
721     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
722     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
723   } else {
724     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
725     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
726   }
727
728   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
729   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
730   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
731   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
732   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
733
734   setOperationAction(ISD::TRAP, MVT::Other, Legal);
735
736   // Use the default implementation.
737   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
738   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
739   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
740   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
741   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
742   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
743
744   if (!Subtarget->isTargetDarwin()) {
745     // Non-Darwin platforms may return values in these registers via the
746     // personality function.
747     setExceptionPointerRegister(ARM::R0);
748     setExceptionSelectorRegister(ARM::R1);
749   }
750
751   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
752   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
753   // the default expansion.
754   // FIXME: This should be checking for v6k, not just v6.
755   if (Subtarget->hasDataBarrier() ||
756       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
757     // membarrier needs custom lowering; the rest are legal and handled
758     // normally.
759     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
760     // Custom lowering for 64-bit ops
761     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
762     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
763     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
764     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
765     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
766     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
767     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
768     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
769     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
770     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
771     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
772     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
773     setInsertFencesForAtomic(true);
774   } else {
775     // Set them all for expansion, which will force libcalls.
776     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
777     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
782     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
783     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
784     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
785     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
788     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
789     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
790     // Unordered/Monotonic case.
791     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
792     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
793   }
794
795   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
796
797   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
798   if (!Subtarget->hasV6Ops()) {
799     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
800     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
801   }
802   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
803
804   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
805       !Subtarget->isThumb1Only()) {
806     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
807     // iff target supports vfp2.
808     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
809     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
810   }
811
812   // We want to custom lower some of our intrinsics.
813   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
814   if (Subtarget->isTargetDarwin()) {
815     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
816     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
817     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
818   }
819
820   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
821   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
822   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
823   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
824   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
825   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
826   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
827   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
828   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
829
830   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
831   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
832   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
833   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
834   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
835
836   // We don't support sin/cos/fmod/copysign/pow
837   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
838   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
839   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
840   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
841   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
842   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
843   setOperationAction(ISD::FREM,      MVT::f64, Expand);
844   setOperationAction(ISD::FREM,      MVT::f32, Expand);
845   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
846       !Subtarget->isThumb1Only()) {
847     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
848     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
849   }
850   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
851   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
852
853   if (!Subtarget->hasVFP4()) {
854     setOperationAction(ISD::FMA, MVT::f64, Expand);
855     setOperationAction(ISD::FMA, MVT::f32, Expand);
856   }
857
858   // Various VFP goodness
859   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
860     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
861     if (Subtarget->hasVFP2()) {
862       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
863       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
864       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
865       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
866     }
867     // Special handling for half-precision FP.
868     if (!Subtarget->hasFP16()) {
869       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
870       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
871     }
872   }
873
874   // We have target-specific dag combine patterns for the following nodes:
875   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
876   setTargetDAGCombine(ISD::ADD);
877   setTargetDAGCombine(ISD::SUB);
878   setTargetDAGCombine(ISD::MUL);
879   setTargetDAGCombine(ISD::AND);
880   setTargetDAGCombine(ISD::OR);
881   setTargetDAGCombine(ISD::XOR);
882
883   if (Subtarget->hasV6Ops())
884     setTargetDAGCombine(ISD::SRL);
885
886   setStackPointerRegisterToSaveRestore(ARM::SP);
887
888   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
889       !Subtarget->hasVFP2())
890     setSchedulingPreference(Sched::RegPressure);
891   else
892     setSchedulingPreference(Sched::Hybrid);
893
894   //// temporary - rewrite interface to use type
895   MaxStoresPerMemset = 8;
896   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
897   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
898   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
899   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
900   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
901
902   // On ARM arguments smaller than 4 bytes are extended, so all arguments
903   // are at least 4 bytes aligned.
904   setMinStackArgumentAlignment(4);
905
906   // Prefer likely predicted branches to selects on out-of-order cores.
907   PredictableSelectIsExpensive = Subtarget->isLikeA9();
908
909   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
910 }
911
912 // FIXME: It might make sense to define the representative register class as the
913 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
914 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
915 // SPR's representative would be DPR_VFP2. This should work well if register
916 // pressure tracking were modified such that a register use would increment the
917 // pressure of the register class's representative and all of it's super
918 // classes' representatives transitively. We have not implemented this because
919 // of the difficulty prior to coalescing of modeling operand register classes
920 // due to the common occurrence of cross class copies and subregister insertions
921 // and extractions.
922 std::pair<const TargetRegisterClass*, uint8_t>
923 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
924   const TargetRegisterClass *RRC = 0;
925   uint8_t Cost = 1;
926   switch (VT.SimpleTy) {
927   default:
928     return TargetLowering::findRepresentativeClass(VT);
929   // Use DPR as representative register class for all floating point
930   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
931   // the cost is 1 for both f32 and f64.
932   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
933   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
934     RRC = &ARM::DPRRegClass;
935     // When NEON is used for SP, only half of the register file is available
936     // because operations that define both SP and DP results will be constrained
937     // to the VFP2 class (D0-D15). We currently model this constraint prior to
938     // coalescing by double-counting the SP regs. See the FIXME above.
939     if (Subtarget->useNEONForSinglePrecisionFP())
940       Cost = 2;
941     break;
942   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
943   case MVT::v4f32: case MVT::v2f64:
944     RRC = &ARM::DPRRegClass;
945     Cost = 2;
946     break;
947   case MVT::v4i64:
948     RRC = &ARM::DPRRegClass;
949     Cost = 4;
950     break;
951   case MVT::v8i64:
952     RRC = &ARM::DPRRegClass;
953     Cost = 8;
954     break;
955   }
956   return std::make_pair(RRC, Cost);
957 }
958
959 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
960   switch (Opcode) {
961   default: return 0;
962   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
963   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
964   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
965   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
966   case ARMISD::CALL:          return "ARMISD::CALL";
967   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
968   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
969   case ARMISD::tCALL:         return "ARMISD::tCALL";
970   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
971   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
972   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
973   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
974   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
975   case ARMISD::CMP:           return "ARMISD::CMP";
976   case ARMISD::CMN:           return "ARMISD::CMN";
977   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
978   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
979   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
980   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
981   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
982
983   case ARMISD::CMOV:          return "ARMISD::CMOV";
984
985   case ARMISD::RBIT:          return "ARMISD::RBIT";
986
987   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
988   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
989   case ARMISD::SITOF:         return "ARMISD::SITOF";
990   case ARMISD::UITOF:         return "ARMISD::UITOF";
991
992   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
993   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
994   case ARMISD::RRX:           return "ARMISD::RRX";
995
996   case ARMISD::ADDC:          return "ARMISD::ADDC";
997   case ARMISD::ADDE:          return "ARMISD::ADDE";
998   case ARMISD::SUBC:          return "ARMISD::SUBC";
999   case ARMISD::SUBE:          return "ARMISD::SUBE";
1000
1001   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1002   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1003
1004   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1005   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1006
1007   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1008
1009   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1010
1011   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1012
1013   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
1014   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1015
1016   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1017
1018   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1019   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1020   case ARMISD::VCGE:          return "ARMISD::VCGE";
1021   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1022   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1023   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1024   case ARMISD::VCGT:          return "ARMISD::VCGT";
1025   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1026   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1027   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1028   case ARMISD::VTST:          return "ARMISD::VTST";
1029
1030   case ARMISD::VSHL:          return "ARMISD::VSHL";
1031   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1032   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1033   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1034   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1035   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1036   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1037   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1038   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1039   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1040   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1041   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1042   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1043   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1044   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1045   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1046   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1047   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1048   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1049   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1050   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1051   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1052   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1053   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1054   case ARMISD::VDUP:          return "ARMISD::VDUP";
1055   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1056   case ARMISD::VEXT:          return "ARMISD::VEXT";
1057   case ARMISD::VREV64:        return "ARMISD::VREV64";
1058   case ARMISD::VREV32:        return "ARMISD::VREV32";
1059   case ARMISD::VREV16:        return "ARMISD::VREV16";
1060   case ARMISD::VZIP:          return "ARMISD::VZIP";
1061   case ARMISD::VUZP:          return "ARMISD::VUZP";
1062   case ARMISD::VTRN:          return "ARMISD::VTRN";
1063   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1064   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1065   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1066   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1067   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1068   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1069   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1070   case ARMISD::FMAX:          return "ARMISD::FMAX";
1071   case ARMISD::FMIN:          return "ARMISD::FMIN";
1072   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1073   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1074   case ARMISD::BFI:           return "ARMISD::BFI";
1075   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1076   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1077   case ARMISD::VBSL:          return "ARMISD::VBSL";
1078   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1079   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1080   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1081   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1082   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1083   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1084   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1085   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1086   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1087   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1088   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1089   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1090   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1091   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1092   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1093   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1094   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1095   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1096   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1097   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1098
1099   case ARMISD::ATOMADD64_DAG:     return "ATOMADD64_DAG";
1100   case ARMISD::ATOMSUB64_DAG:     return "ATOMSUB64_DAG";
1101   case ARMISD::ATOMOR64_DAG:      return "ATOMOR64_DAG";
1102   case ARMISD::ATOMXOR64_DAG:     return "ATOMXOR64_DAG";
1103   case ARMISD::ATOMAND64_DAG:     return "ATOMAND64_DAG";
1104   case ARMISD::ATOMNAND64_DAG:    return "ATOMNAND64_DAG";
1105   case ARMISD::ATOMSWAP64_DAG:    return "ATOMSWAP64_DAG";
1106   case ARMISD::ATOMCMPXCHG64_DAG: return "ATOMCMPXCHG64_DAG";
1107   case ARMISD::ATOMMIN64_DAG:     return "ATOMMIN64_DAG";
1108   case ARMISD::ATOMUMIN64_DAG:    return "ATOMUMIN64_DAG";
1109   case ARMISD::ATOMMAX64_DAG:     return "ATOMMAX64_DAG";
1110   case ARMISD::ATOMUMAX64_DAG:    return "ATOMUMAX64_DAG";
1111   }
1112 }
1113
1114 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1115   if (!VT.isVector()) return getPointerTy();
1116   return VT.changeVectorElementTypeToInteger();
1117 }
1118
1119 /// getRegClassFor - Return the register class that should be used for the
1120 /// specified value type.
1121 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1122   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1123   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1124   // load / store 4 to 8 consecutive D registers.
1125   if (Subtarget->hasNEON()) {
1126     if (VT == MVT::v4i64)
1127       return &ARM::QQPRRegClass;
1128     if (VT == MVT::v8i64)
1129       return &ARM::QQQQPRRegClass;
1130   }
1131   return TargetLowering::getRegClassFor(VT);
1132 }
1133
1134 // Create a fast isel object.
1135 FastISel *
1136 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1137                                   const TargetLibraryInfo *libInfo) const {
1138   return ARM::createFastISel(funcInfo, libInfo);
1139 }
1140
1141 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1142 /// be used for loads / stores from the global.
1143 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1144   return (Subtarget->isThumb1Only() ? 127 : 4095);
1145 }
1146
1147 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1148   unsigned NumVals = N->getNumValues();
1149   if (!NumVals)
1150     return Sched::RegPressure;
1151
1152   for (unsigned i = 0; i != NumVals; ++i) {
1153     EVT VT = N->getValueType(i);
1154     if (VT == MVT::Glue || VT == MVT::Other)
1155       continue;
1156     if (VT.isFloatingPoint() || VT.isVector())
1157       return Sched::ILP;
1158   }
1159
1160   if (!N->isMachineOpcode())
1161     return Sched::RegPressure;
1162
1163   // Load are scheduled for latency even if there instruction itinerary
1164   // is not available.
1165   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1166   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1167
1168   if (MCID.getNumDefs() == 0)
1169     return Sched::RegPressure;
1170   if (!Itins->isEmpty() &&
1171       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1172     return Sched::ILP;
1173
1174   return Sched::RegPressure;
1175 }
1176
1177 //===----------------------------------------------------------------------===//
1178 // Lowering Code
1179 //===----------------------------------------------------------------------===//
1180
1181 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1182 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1183   switch (CC) {
1184   default: llvm_unreachable("Unknown condition code!");
1185   case ISD::SETNE:  return ARMCC::NE;
1186   case ISD::SETEQ:  return ARMCC::EQ;
1187   case ISD::SETGT:  return ARMCC::GT;
1188   case ISD::SETGE:  return ARMCC::GE;
1189   case ISD::SETLT:  return ARMCC::LT;
1190   case ISD::SETLE:  return ARMCC::LE;
1191   case ISD::SETUGT: return ARMCC::HI;
1192   case ISD::SETUGE: return ARMCC::HS;
1193   case ISD::SETULT: return ARMCC::LO;
1194   case ISD::SETULE: return ARMCC::LS;
1195   }
1196 }
1197
1198 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1199 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1200                         ARMCC::CondCodes &CondCode2) {
1201   CondCode2 = ARMCC::AL;
1202   switch (CC) {
1203   default: llvm_unreachable("Unknown FP condition!");
1204   case ISD::SETEQ:
1205   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1206   case ISD::SETGT:
1207   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1208   case ISD::SETGE:
1209   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1210   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1211   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1212   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1213   case ISD::SETO:   CondCode = ARMCC::VC; break;
1214   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1215   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1216   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1217   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1218   case ISD::SETLT:
1219   case ISD::SETULT: CondCode = ARMCC::LT; break;
1220   case ISD::SETLE:
1221   case ISD::SETULE: CondCode = ARMCC::LE; break;
1222   case ISD::SETNE:
1223   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1224   }
1225 }
1226
1227 //===----------------------------------------------------------------------===//
1228 //                      Calling Convention Implementation
1229 //===----------------------------------------------------------------------===//
1230
1231 #include "ARMGenCallingConv.inc"
1232
1233 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1234 /// given CallingConvention value.
1235 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1236                                                  bool Return,
1237                                                  bool isVarArg) const {
1238   switch (CC) {
1239   default:
1240     llvm_unreachable("Unsupported calling convention");
1241   case CallingConv::Fast:
1242     if (Subtarget->hasVFP2() && !isVarArg) {
1243       if (!Subtarget->isAAPCS_ABI())
1244         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1245       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1246       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1247     }
1248     // Fallthrough
1249   case CallingConv::C: {
1250     // Use target triple & subtarget features to do actual dispatch.
1251     if (!Subtarget->isAAPCS_ABI())
1252       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1253     else if (Subtarget->hasVFP2() &&
1254              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1255              !isVarArg)
1256       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1257     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1258   }
1259   case CallingConv::ARM_AAPCS_VFP:
1260     if (!isVarArg)
1261       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1262     // Fallthrough
1263   case CallingConv::ARM_AAPCS:
1264     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1265   case CallingConv::ARM_APCS:
1266     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1267   case CallingConv::GHC:
1268     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1269   }
1270 }
1271
1272 /// LowerCallResult - Lower the result values of a call into the
1273 /// appropriate copies out of appropriate physical registers.
1274 SDValue
1275 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1276                                    CallingConv::ID CallConv, bool isVarArg,
1277                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1278                                    SDLoc dl, SelectionDAG &DAG,
1279                                    SmallVectorImpl<SDValue> &InVals,
1280                                    bool isThisReturn, SDValue ThisVal) const {
1281
1282   // Assign locations to each value returned by this call.
1283   SmallVector<CCValAssign, 16> RVLocs;
1284   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1285                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1286   CCInfo.AnalyzeCallResult(Ins,
1287                            CCAssignFnForNode(CallConv, /* Return*/ true,
1288                                              isVarArg));
1289
1290   // Copy all of the result registers out of their specified physreg.
1291   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1292     CCValAssign VA = RVLocs[i];
1293
1294     // Pass 'this' value directly from the argument to return value, to avoid
1295     // reg unit interference
1296     if (i == 0 && isThisReturn) {
1297       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1298              "unexpected return calling convention register assignment");
1299       InVals.push_back(ThisVal);
1300       continue;
1301     }
1302
1303     SDValue Val;
1304     if (VA.needsCustom()) {
1305       // Handle f64 or half of a v2f64.
1306       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1307                                       InFlag);
1308       Chain = Lo.getValue(1);
1309       InFlag = Lo.getValue(2);
1310       VA = RVLocs[++i]; // skip ahead to next loc
1311       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1312                                       InFlag);
1313       Chain = Hi.getValue(1);
1314       InFlag = Hi.getValue(2);
1315       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1316
1317       if (VA.getLocVT() == MVT::v2f64) {
1318         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1319         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1320                           DAG.getConstant(0, MVT::i32));
1321
1322         VA = RVLocs[++i]; // skip ahead to next loc
1323         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1324         Chain = Lo.getValue(1);
1325         InFlag = Lo.getValue(2);
1326         VA = RVLocs[++i]; // skip ahead to next loc
1327         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1328         Chain = Hi.getValue(1);
1329         InFlag = Hi.getValue(2);
1330         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1331         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1332                           DAG.getConstant(1, MVT::i32));
1333       }
1334     } else {
1335       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1336                                InFlag);
1337       Chain = Val.getValue(1);
1338       InFlag = Val.getValue(2);
1339     }
1340
1341     switch (VA.getLocInfo()) {
1342     default: llvm_unreachable("Unknown loc info!");
1343     case CCValAssign::Full: break;
1344     case CCValAssign::BCvt:
1345       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1346       break;
1347     }
1348
1349     InVals.push_back(Val);
1350   }
1351
1352   return Chain;
1353 }
1354
1355 /// LowerMemOpCallTo - Store the argument to the stack.
1356 SDValue
1357 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1358                                     SDValue StackPtr, SDValue Arg,
1359                                     SDLoc dl, SelectionDAG &DAG,
1360                                     const CCValAssign &VA,
1361                                     ISD::ArgFlagsTy Flags) const {
1362   unsigned LocMemOffset = VA.getLocMemOffset();
1363   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1364   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1365   return DAG.getStore(Chain, dl, Arg, PtrOff,
1366                       MachinePointerInfo::getStack(LocMemOffset),
1367                       false, false, 0);
1368 }
1369
1370 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1371                                          SDValue Chain, SDValue &Arg,
1372                                          RegsToPassVector &RegsToPass,
1373                                          CCValAssign &VA, CCValAssign &NextVA,
1374                                          SDValue &StackPtr,
1375                                          SmallVectorImpl<SDValue> &MemOpChains,
1376                                          ISD::ArgFlagsTy Flags) const {
1377
1378   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1379                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1380   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1381
1382   if (NextVA.isRegLoc())
1383     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1384   else {
1385     assert(NextVA.isMemLoc());
1386     if (StackPtr.getNode() == 0)
1387       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1388
1389     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1390                                            dl, DAG, NextVA,
1391                                            Flags));
1392   }
1393 }
1394
1395 /// LowerCall - Lowering a call into a callseq_start <-
1396 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1397 /// nodes.
1398 SDValue
1399 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1400                              SmallVectorImpl<SDValue> &InVals) const {
1401   SelectionDAG &DAG                     = CLI.DAG;
1402   SDLoc &dl                          = CLI.DL;
1403   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1404   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1405   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1406   SDValue Chain                         = CLI.Chain;
1407   SDValue Callee                        = CLI.Callee;
1408   bool &isTailCall                      = CLI.IsTailCall;
1409   CallingConv::ID CallConv              = CLI.CallConv;
1410   bool doesNotRet                       = CLI.DoesNotReturn;
1411   bool isVarArg                         = CLI.IsVarArg;
1412
1413   MachineFunction &MF = DAG.getMachineFunction();
1414   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1415   bool isThisReturn   = false;
1416   bool isSibCall      = false;
1417   // Disable tail calls if they're not supported.
1418   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1419     isTailCall = false;
1420   if (isTailCall) {
1421     // Check if it's really possible to do a tail call.
1422     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1423                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1424                                                    Outs, OutVals, Ins, DAG);
1425     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1426     // detected sibcalls.
1427     if (isTailCall) {
1428       ++NumTailCalls;
1429       isSibCall = true;
1430     }
1431   }
1432
1433   // Analyze operands of the call, assigning locations to each operand.
1434   SmallVector<CCValAssign, 16> ArgLocs;
1435   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1436                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1437   CCInfo.AnalyzeCallOperands(Outs,
1438                              CCAssignFnForNode(CallConv, /* Return*/ false,
1439                                                isVarArg));
1440
1441   // Get a count of how many bytes are to be pushed on the stack.
1442   unsigned NumBytes = CCInfo.getNextStackOffset();
1443
1444   // For tail calls, memory operands are available in our caller's stack.
1445   if (isSibCall)
1446     NumBytes = 0;
1447
1448   // Adjust the stack pointer for the new arguments...
1449   // These operations are automatically eliminated by the prolog/epilog pass
1450   if (!isSibCall)
1451     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1452                                  dl);
1453
1454   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1455
1456   RegsToPassVector RegsToPass;
1457   SmallVector<SDValue, 8> MemOpChains;
1458
1459   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1460   // of tail call optimization, arguments are handled later.
1461   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1462        i != e;
1463        ++i, ++realArgIdx) {
1464     CCValAssign &VA = ArgLocs[i];
1465     SDValue Arg = OutVals[realArgIdx];
1466     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1467     bool isByVal = Flags.isByVal();
1468
1469     // Promote the value if needed.
1470     switch (VA.getLocInfo()) {
1471     default: llvm_unreachable("Unknown loc info!");
1472     case CCValAssign::Full: break;
1473     case CCValAssign::SExt:
1474       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1475       break;
1476     case CCValAssign::ZExt:
1477       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1478       break;
1479     case CCValAssign::AExt:
1480       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1481       break;
1482     case CCValAssign::BCvt:
1483       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1484       break;
1485     }
1486
1487     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1488     if (VA.needsCustom()) {
1489       if (VA.getLocVT() == MVT::v2f64) {
1490         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1491                                   DAG.getConstant(0, MVT::i32));
1492         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1493                                   DAG.getConstant(1, MVT::i32));
1494
1495         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1496                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1497
1498         VA = ArgLocs[++i]; // skip ahead to next loc
1499         if (VA.isRegLoc()) {
1500           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1501                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1502         } else {
1503           assert(VA.isMemLoc());
1504
1505           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1506                                                  dl, DAG, VA, Flags));
1507         }
1508       } else {
1509         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1510                          StackPtr, MemOpChains, Flags);
1511       }
1512     } else if (VA.isRegLoc()) {
1513       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1514         assert(VA.getLocVT() == MVT::i32 &&
1515                "unexpected calling convention register assignment");
1516         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1517                "unexpected use of 'returned'");
1518         isThisReturn = true;
1519       }
1520       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1521     } else if (isByVal) {
1522       assert(VA.isMemLoc());
1523       unsigned offset = 0;
1524
1525       // True if this byval aggregate will be split between registers
1526       // and memory.
1527       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1528       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1529
1530       if (CurByValIdx < ByValArgsCount) {
1531
1532         unsigned RegBegin, RegEnd;
1533         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1534
1535         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1536         unsigned int i, j;
1537         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1538           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1539           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1540           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1541                                      MachinePointerInfo(),
1542                                      false, false, false, 0);
1543           MemOpChains.push_back(Load.getValue(1));
1544           RegsToPass.push_back(std::make_pair(j, Load));
1545         }
1546
1547         // If parameter size outsides register area, "offset" value
1548         // helps us to calculate stack slot for remained part properly.
1549         offset = RegEnd - RegBegin;
1550
1551         CCInfo.nextInRegsParam();
1552       }
1553
1554       if (Flags.getByValSize() > 4*offset) {
1555         unsigned LocMemOffset = VA.getLocMemOffset();
1556         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1557         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1558                                   StkPtrOff);
1559         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1560         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1561         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1562                                            MVT::i32);
1563         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1564
1565         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1566         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1567         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1568                                           Ops, array_lengthof(Ops)));
1569       }
1570     } else if (!isSibCall) {
1571       assert(VA.isMemLoc());
1572
1573       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1574                                              dl, DAG, VA, Flags));
1575     }
1576   }
1577
1578   if (!MemOpChains.empty())
1579     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1580                         &MemOpChains[0], MemOpChains.size());
1581
1582   // Build a sequence of copy-to-reg nodes chained together with token chain
1583   // and flag operands which copy the outgoing args into the appropriate regs.
1584   SDValue InFlag;
1585   // Tail call byval lowering might overwrite argument registers so in case of
1586   // tail call optimization the copies to registers are lowered later.
1587   if (!isTailCall)
1588     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1589       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1590                                RegsToPass[i].second, InFlag);
1591       InFlag = Chain.getValue(1);
1592     }
1593
1594   // For tail calls lower the arguments to the 'real' stack slot.
1595   if (isTailCall) {
1596     // Force all the incoming stack arguments to be loaded from the stack
1597     // before any new outgoing arguments are stored to the stack, because the
1598     // outgoing stack slots may alias the incoming argument stack slots, and
1599     // the alias isn't otherwise explicit. This is slightly more conservative
1600     // than necessary, because it means that each store effectively depends
1601     // on every argument instead of just those arguments it would clobber.
1602
1603     // Do not flag preceding copytoreg stuff together with the following stuff.
1604     InFlag = SDValue();
1605     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1606       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1607                                RegsToPass[i].second, InFlag);
1608       InFlag = Chain.getValue(1);
1609     }
1610     InFlag = SDValue();
1611   }
1612
1613   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1614   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1615   // node so that legalize doesn't hack it.
1616   bool isDirect = false;
1617   bool isARMFunc = false;
1618   bool isLocalARMFunc = false;
1619   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1620
1621   if (EnableARMLongCalls) {
1622     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1623             && "long-calls with non-static relocation model!");
1624     // Handle a global address or an external symbol. If it's not one of
1625     // those, the target's already in a register, so we don't need to do
1626     // anything extra.
1627     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1628       const GlobalValue *GV = G->getGlobal();
1629       // Create a constant pool entry for the callee address
1630       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1631       ARMConstantPoolValue *CPV =
1632         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1633
1634       // Get the address of the callee into a register
1635       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1636       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1637       Callee = DAG.getLoad(getPointerTy(), dl,
1638                            DAG.getEntryNode(), CPAddr,
1639                            MachinePointerInfo::getConstantPool(),
1640                            false, false, false, 0);
1641     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1642       const char *Sym = S->getSymbol();
1643
1644       // Create a constant pool entry for the callee address
1645       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1646       ARMConstantPoolValue *CPV =
1647         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1648                                       ARMPCLabelIndex, 0);
1649       // Get the address of the callee into a register
1650       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1651       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1652       Callee = DAG.getLoad(getPointerTy(), dl,
1653                            DAG.getEntryNode(), CPAddr,
1654                            MachinePointerInfo::getConstantPool(),
1655                            false, false, false, 0);
1656     }
1657   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1658     const GlobalValue *GV = G->getGlobal();
1659     isDirect = true;
1660     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1661     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1662                    getTargetMachine().getRelocationModel() != Reloc::Static;
1663     isARMFunc = !Subtarget->isThumb() || isStub;
1664     // ARM call to a local ARM function is predicable.
1665     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1666     // tBX takes a register source operand.
1667     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1668       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1669       ARMConstantPoolValue *CPV =
1670         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1671       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1672       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1673       Callee = DAG.getLoad(getPointerTy(), dl,
1674                            DAG.getEntryNode(), CPAddr,
1675                            MachinePointerInfo::getConstantPool(),
1676                            false, false, false, 0);
1677       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1678       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1679                            getPointerTy(), Callee, PICLabel);
1680     } else {
1681       // On ELF targets for PIC code, direct calls should go through the PLT
1682       unsigned OpFlags = 0;
1683       if (Subtarget->isTargetELF() &&
1684           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1685         OpFlags = ARMII::MO_PLT;
1686       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1687     }
1688   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1689     isDirect = true;
1690     bool isStub = Subtarget->isTargetDarwin() &&
1691                   getTargetMachine().getRelocationModel() != Reloc::Static;
1692     isARMFunc = !Subtarget->isThumb() || isStub;
1693     // tBX takes a register source operand.
1694     const char *Sym = S->getSymbol();
1695     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1696       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1697       ARMConstantPoolValue *CPV =
1698         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1699                                       ARMPCLabelIndex, 4);
1700       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1701       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1702       Callee = DAG.getLoad(getPointerTy(), dl,
1703                            DAG.getEntryNode(), CPAddr,
1704                            MachinePointerInfo::getConstantPool(),
1705                            false, false, false, 0);
1706       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1707       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1708                            getPointerTy(), Callee, PICLabel);
1709     } else {
1710       unsigned OpFlags = 0;
1711       // On ELF targets for PIC code, direct calls should go through the PLT
1712       if (Subtarget->isTargetELF() &&
1713                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1714         OpFlags = ARMII::MO_PLT;
1715       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1716     }
1717   }
1718
1719   // FIXME: handle tail calls differently.
1720   unsigned CallOpc;
1721   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1722     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1723   if (Subtarget->isThumb()) {
1724     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1725       CallOpc = ARMISD::CALL_NOLINK;
1726     else
1727       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1728   } else {
1729     if (!isDirect && !Subtarget->hasV5TOps())
1730       CallOpc = ARMISD::CALL_NOLINK;
1731     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1732                // Emit regular call when code size is the priority
1733                !HasMinSizeAttr)
1734       // "mov lr, pc; b _foo" to avoid confusing the RSP
1735       CallOpc = ARMISD::CALL_NOLINK;
1736     else
1737       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1738   }
1739
1740   std::vector<SDValue> Ops;
1741   Ops.push_back(Chain);
1742   Ops.push_back(Callee);
1743
1744   // Add argument registers to the end of the list so that they are known live
1745   // into the call.
1746   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1747     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1748                                   RegsToPass[i].second.getValueType()));
1749
1750   // Add a register mask operand representing the call-preserved registers.
1751   const uint32_t *Mask;
1752   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1753   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1754   if (isThisReturn) {
1755     // For 'this' returns, use the R0-preserving mask if applicable
1756     Mask = ARI->getThisReturnPreservedMask(CallConv);
1757     if (!Mask) {
1758       // Set isThisReturn to false if the calling convention is not one that
1759       // allows 'returned' to be modeled in this way, so LowerCallResult does
1760       // not try to pass 'this' straight through 
1761       isThisReturn = false;
1762       Mask = ARI->getCallPreservedMask(CallConv);
1763     }
1764   } else
1765     Mask = ARI->getCallPreservedMask(CallConv);
1766
1767   assert(Mask && "Missing call preserved mask for calling convention");
1768   Ops.push_back(DAG.getRegisterMask(Mask));
1769
1770   if (InFlag.getNode())
1771     Ops.push_back(InFlag);
1772
1773   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1774   if (isTailCall)
1775     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1776
1777   // Returns a chain and a flag for retval copy to use.
1778   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1779   InFlag = Chain.getValue(1);
1780
1781   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1782                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1783   if (!Ins.empty())
1784     InFlag = Chain.getValue(1);
1785
1786   // Handle result values, copying them out of physregs into vregs that we
1787   // return.
1788   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1789                          InVals, isThisReturn,
1790                          isThisReturn ? OutVals[0] : SDValue());
1791 }
1792
1793 /// HandleByVal - Every parameter *after* a byval parameter is passed
1794 /// on the stack.  Remember the next parameter register to allocate,
1795 /// and then confiscate the rest of the parameter registers to insure
1796 /// this.
1797 void
1798 ARMTargetLowering::HandleByVal(
1799     CCState *State, unsigned &size, unsigned Align) const {
1800   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1801   assert((State->getCallOrPrologue() == Prologue ||
1802           State->getCallOrPrologue() == Call) &&
1803          "unhandled ParmContext");
1804
1805   // For in-prologue parameters handling, we also introduce stack offset
1806   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1807   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1808   // NSAA should be evaluted (NSAA means "next stacked argument address").
1809   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1810   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1811   unsigned NSAAOffset = State->getNextStackOffset();
1812   if (State->getCallOrPrologue() != Call) {
1813     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1814       unsigned RB, RE;
1815       State->getInRegsParamInfo(i, RB, RE);
1816       assert(NSAAOffset >= (RE-RB)*4 &&
1817              "Stack offset for byval regs doesn't introduced anymore?");
1818       NSAAOffset -= (RE-RB)*4;
1819     }
1820   }
1821   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1822     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1823       unsigned AlignInRegs = Align / 4;
1824       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1825       for (unsigned i = 0; i < Waste; ++i)
1826         reg = State->AllocateReg(GPRArgRegs, 4);
1827     }
1828     if (reg != 0) {
1829       unsigned excess = 4 * (ARM::R4 - reg);
1830
1831       // Special case when NSAA != SP and parameter size greater than size of
1832       // all remained GPR regs. In that case we can't split parameter, we must
1833       // send it to stack. We also must set NCRN to R4, so waste all
1834       // remained registers.
1835       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1836         while (State->AllocateReg(GPRArgRegs, 4))
1837           ;
1838         return;
1839       }
1840
1841       // First register for byval parameter is the first register that wasn't
1842       // allocated before this method call, so it would be "reg".
1843       // If parameter is small enough to be saved in range [reg, r4), then
1844       // the end (first after last) register would be reg + param-size-in-regs,
1845       // else parameter would be splitted between registers and stack,
1846       // end register would be r4 in this case.
1847       unsigned ByValRegBegin = reg;
1848       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1849       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1850       // Note, first register is allocated in the beginning of function already,
1851       // allocate remained amount of registers we need.
1852       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1853         State->AllocateReg(GPRArgRegs, 4);
1854       // At a call site, a byval parameter that is split between
1855       // registers and memory needs its size truncated here.  In a
1856       // function prologue, such byval parameters are reassembled in
1857       // memory, and are not truncated.
1858       if (State->getCallOrPrologue() == Call) {
1859         // Make remained size equal to 0 in case, when
1860         // the whole structure may be stored into registers.
1861         if (size < excess)
1862           size = 0;
1863         else
1864           size -= excess;
1865       }
1866     }
1867   }
1868 }
1869
1870 /// MatchingStackOffset - Return true if the given stack call argument is
1871 /// already available in the same position (relatively) of the caller's
1872 /// incoming argument stack.
1873 static
1874 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1875                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1876                          const TargetInstrInfo *TII) {
1877   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1878   int FI = INT_MAX;
1879   if (Arg.getOpcode() == ISD::CopyFromReg) {
1880     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1881     if (!TargetRegisterInfo::isVirtualRegister(VR))
1882       return false;
1883     MachineInstr *Def = MRI->getVRegDef(VR);
1884     if (!Def)
1885       return false;
1886     if (!Flags.isByVal()) {
1887       if (!TII->isLoadFromStackSlot(Def, FI))
1888         return false;
1889     } else {
1890       return false;
1891     }
1892   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1893     if (Flags.isByVal())
1894       // ByVal argument is passed in as a pointer but it's now being
1895       // dereferenced. e.g.
1896       // define @foo(%struct.X* %A) {
1897       //   tail call @bar(%struct.X* byval %A)
1898       // }
1899       return false;
1900     SDValue Ptr = Ld->getBasePtr();
1901     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1902     if (!FINode)
1903       return false;
1904     FI = FINode->getIndex();
1905   } else
1906     return false;
1907
1908   assert(FI != INT_MAX);
1909   if (!MFI->isFixedObjectIndex(FI))
1910     return false;
1911   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1912 }
1913
1914 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1915 /// for tail call optimization. Targets which want to do tail call
1916 /// optimization should implement this function.
1917 bool
1918 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1919                                                      CallingConv::ID CalleeCC,
1920                                                      bool isVarArg,
1921                                                      bool isCalleeStructRet,
1922                                                      bool isCallerStructRet,
1923                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1924                                     const SmallVectorImpl<SDValue> &OutVals,
1925                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1926                                                      SelectionDAG& DAG) const {
1927   const Function *CallerF = DAG.getMachineFunction().getFunction();
1928   CallingConv::ID CallerCC = CallerF->getCallingConv();
1929   bool CCMatch = CallerCC == CalleeCC;
1930
1931   // Look for obvious safe cases to perform tail call optimization that do not
1932   // require ABI changes. This is what gcc calls sibcall.
1933
1934   // Do not sibcall optimize vararg calls unless the call site is not passing
1935   // any arguments.
1936   if (isVarArg && !Outs.empty())
1937     return false;
1938
1939   // Also avoid sibcall optimization if either caller or callee uses struct
1940   // return semantics.
1941   if (isCalleeStructRet || isCallerStructRet)
1942     return false;
1943
1944   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1945   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1946   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1947   // support in the assembler and linker to be used. This would need to be
1948   // fixed to fully support tail calls in Thumb1.
1949   //
1950   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1951   // LR.  This means if we need to reload LR, it takes an extra instructions,
1952   // which outweighs the value of the tail call; but here we don't know yet
1953   // whether LR is going to be used.  Probably the right approach is to
1954   // generate the tail call here and turn it back into CALL/RET in
1955   // emitEpilogue if LR is used.
1956
1957   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1958   // but we need to make sure there are enough registers; the only valid
1959   // registers are the 4 used for parameters.  We don't currently do this
1960   // case.
1961   if (Subtarget->isThumb1Only())
1962     return false;
1963
1964   // If the calling conventions do not match, then we'd better make sure the
1965   // results are returned in the same way as what the caller expects.
1966   if (!CCMatch) {
1967     SmallVector<CCValAssign, 16> RVLocs1;
1968     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1969                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1970     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1971
1972     SmallVector<CCValAssign, 16> RVLocs2;
1973     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1974                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1975     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1976
1977     if (RVLocs1.size() != RVLocs2.size())
1978       return false;
1979     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1980       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1981         return false;
1982       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1983         return false;
1984       if (RVLocs1[i].isRegLoc()) {
1985         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1986           return false;
1987       } else {
1988         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1989           return false;
1990       }
1991     }
1992   }
1993
1994   // If Caller's vararg or byval argument has been split between registers and
1995   // stack, do not perform tail call, since part of the argument is in caller's
1996   // local frame.
1997   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1998                                       getInfo<ARMFunctionInfo>();
1999   if (AFI_Caller->getArgRegsSaveSize())
2000     return false;
2001
2002   // If the callee takes no arguments then go on to check the results of the
2003   // call.
2004   if (!Outs.empty()) {
2005     // Check if stack adjustment is needed. For now, do not do this if any
2006     // argument is passed on the stack.
2007     SmallVector<CCValAssign, 16> ArgLocs;
2008     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2009                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2010     CCInfo.AnalyzeCallOperands(Outs,
2011                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2012     if (CCInfo.getNextStackOffset()) {
2013       MachineFunction &MF = DAG.getMachineFunction();
2014
2015       // Check if the arguments are already laid out in the right way as
2016       // the caller's fixed stack objects.
2017       MachineFrameInfo *MFI = MF.getFrameInfo();
2018       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2019       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2020       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2021            i != e;
2022            ++i, ++realArgIdx) {
2023         CCValAssign &VA = ArgLocs[i];
2024         EVT RegVT = VA.getLocVT();
2025         SDValue Arg = OutVals[realArgIdx];
2026         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2027         if (VA.getLocInfo() == CCValAssign::Indirect)
2028           return false;
2029         if (VA.needsCustom()) {
2030           // f64 and vector types are split into multiple registers or
2031           // register/stack-slot combinations.  The types will not match
2032           // the registers; give up on memory f64 refs until we figure
2033           // out what to do about this.
2034           if (!VA.isRegLoc())
2035             return false;
2036           if (!ArgLocs[++i].isRegLoc())
2037             return false;
2038           if (RegVT == MVT::v2f64) {
2039             if (!ArgLocs[++i].isRegLoc())
2040               return false;
2041             if (!ArgLocs[++i].isRegLoc())
2042               return false;
2043           }
2044         } else if (!VA.isRegLoc()) {
2045           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2046                                    MFI, MRI, TII))
2047             return false;
2048         }
2049       }
2050     }
2051   }
2052
2053   return true;
2054 }
2055
2056 bool
2057 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2058                                   MachineFunction &MF, bool isVarArg,
2059                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2060                                   LLVMContext &Context) const {
2061   SmallVector<CCValAssign, 16> RVLocs;
2062   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2063   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2064                                                     isVarArg));
2065 }
2066
2067 SDValue
2068 ARMTargetLowering::LowerReturn(SDValue Chain,
2069                                CallingConv::ID CallConv, bool isVarArg,
2070                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2071                                const SmallVectorImpl<SDValue> &OutVals,
2072                                SDLoc dl, SelectionDAG &DAG) const {
2073
2074   // CCValAssign - represent the assignment of the return value to a location.
2075   SmallVector<CCValAssign, 16> RVLocs;
2076
2077   // CCState - Info about the registers and stack slots.
2078   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2079                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2080
2081   // Analyze outgoing return values.
2082   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2083                                                isVarArg));
2084
2085   SDValue Flag;
2086   SmallVector<SDValue, 4> RetOps;
2087   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2088
2089   // Copy the result values into the output registers.
2090   for (unsigned i = 0, realRVLocIdx = 0;
2091        i != RVLocs.size();
2092        ++i, ++realRVLocIdx) {
2093     CCValAssign &VA = RVLocs[i];
2094     assert(VA.isRegLoc() && "Can only return in registers!");
2095
2096     SDValue Arg = OutVals[realRVLocIdx];
2097
2098     switch (VA.getLocInfo()) {
2099     default: llvm_unreachable("Unknown loc info!");
2100     case CCValAssign::Full: break;
2101     case CCValAssign::BCvt:
2102       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2103       break;
2104     }
2105
2106     if (VA.needsCustom()) {
2107       if (VA.getLocVT() == MVT::v2f64) {
2108         // Extract the first half and return it in two registers.
2109         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2110                                    DAG.getConstant(0, MVT::i32));
2111         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2112                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2113
2114         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2115         Flag = Chain.getValue(1);
2116         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2117         VA = RVLocs[++i]; // skip ahead to next loc
2118         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2119                                  HalfGPRs.getValue(1), Flag);
2120         Flag = Chain.getValue(1);
2121         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2122         VA = RVLocs[++i]; // skip ahead to next loc
2123
2124         // Extract the 2nd half and fall through to handle it as an f64 value.
2125         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2126                           DAG.getConstant(1, MVT::i32));
2127       }
2128       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2129       // available.
2130       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2131                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2132       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2133       Flag = Chain.getValue(1);
2134       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2135       VA = RVLocs[++i]; // skip ahead to next loc
2136       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2137                                Flag);
2138     } else
2139       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2140
2141     // Guarantee that all emitted copies are
2142     // stuck together, avoiding something bad.
2143     Flag = Chain.getValue(1);
2144     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2145   }
2146
2147   // Update chain and glue.
2148   RetOps[0] = Chain;
2149   if (Flag.getNode())
2150     RetOps.push_back(Flag);
2151
2152   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2153                      RetOps.data(), RetOps.size());
2154 }
2155
2156 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2157   if (N->getNumValues() != 1)
2158     return false;
2159   if (!N->hasNUsesOfValue(1, 0))
2160     return false;
2161
2162   SDValue TCChain = Chain;
2163   SDNode *Copy = *N->use_begin();
2164   if (Copy->getOpcode() == ISD::CopyToReg) {
2165     // If the copy has a glue operand, we conservatively assume it isn't safe to
2166     // perform a tail call.
2167     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2168       return false;
2169     TCChain = Copy->getOperand(0);
2170   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2171     SDNode *VMov = Copy;
2172     // f64 returned in a pair of GPRs.
2173     SmallPtrSet<SDNode*, 2> Copies;
2174     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2175          UI != UE; ++UI) {
2176       if (UI->getOpcode() != ISD::CopyToReg)
2177         return false;
2178       Copies.insert(*UI);
2179     }
2180     if (Copies.size() > 2)
2181       return false;
2182
2183     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2184          UI != UE; ++UI) {
2185       SDValue UseChain = UI->getOperand(0);
2186       if (Copies.count(UseChain.getNode()))
2187         // Second CopyToReg
2188         Copy = *UI;
2189       else
2190         // First CopyToReg
2191         TCChain = UseChain;
2192     }
2193   } else if (Copy->getOpcode() == ISD::BITCAST) {
2194     // f32 returned in a single GPR.
2195     if (!Copy->hasOneUse())
2196       return false;
2197     Copy = *Copy->use_begin();
2198     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2199       return false;
2200     TCChain = Copy->getOperand(0);
2201   } else {
2202     return false;
2203   }
2204
2205   bool HasRet = false;
2206   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2207        UI != UE; ++UI) {
2208     if (UI->getOpcode() != ARMISD::RET_FLAG)
2209       return false;
2210     HasRet = true;
2211   }
2212
2213   if (!HasRet)
2214     return false;
2215
2216   Chain = TCChain;
2217   return true;
2218 }
2219
2220 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2221   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2222     return false;
2223
2224   if (!CI->isTailCall())
2225     return false;
2226
2227   return !Subtarget->isThumb1Only();
2228 }
2229
2230 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2231 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2232 // one of the above mentioned nodes. It has to be wrapped because otherwise
2233 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2234 // be used to form addressing mode. These wrapped nodes will be selected
2235 // into MOVi.
2236 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2237   EVT PtrVT = Op.getValueType();
2238   // FIXME there is no actual debug info here
2239   SDLoc dl(Op);
2240   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2241   SDValue Res;
2242   if (CP->isMachineConstantPoolEntry())
2243     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2244                                     CP->getAlignment());
2245   else
2246     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2247                                     CP->getAlignment());
2248   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2249 }
2250
2251 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2252   return MachineJumpTableInfo::EK_Inline;
2253 }
2254
2255 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2256                                              SelectionDAG &DAG) const {
2257   MachineFunction &MF = DAG.getMachineFunction();
2258   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2259   unsigned ARMPCLabelIndex = 0;
2260   SDLoc DL(Op);
2261   EVT PtrVT = getPointerTy();
2262   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2263   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2264   SDValue CPAddr;
2265   if (RelocM == Reloc::Static) {
2266     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2267   } else {
2268     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2269     ARMPCLabelIndex = AFI->createPICLabelUId();
2270     ARMConstantPoolValue *CPV =
2271       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2272                                       ARMCP::CPBlockAddress, PCAdj);
2273     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2274   }
2275   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2276   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2277                                MachinePointerInfo::getConstantPool(),
2278                                false, false, false, 0);
2279   if (RelocM == Reloc::Static)
2280     return Result;
2281   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2282   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2283 }
2284
2285 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2286 SDValue
2287 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2288                                                  SelectionDAG &DAG) const {
2289   SDLoc dl(GA);
2290   EVT PtrVT = getPointerTy();
2291   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2292   MachineFunction &MF = DAG.getMachineFunction();
2293   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2294   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2295   ARMConstantPoolValue *CPV =
2296     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2297                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2298   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2299   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2300   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2301                          MachinePointerInfo::getConstantPool(),
2302                          false, false, false, 0);
2303   SDValue Chain = Argument.getValue(1);
2304
2305   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2306   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2307
2308   // call __tls_get_addr.
2309   ArgListTy Args;
2310   ArgListEntry Entry;
2311   Entry.Node = Argument;
2312   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2313   Args.push_back(Entry);
2314   // FIXME: is there useful debug info available here?
2315   TargetLowering::CallLoweringInfo CLI(Chain,
2316                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2317                 false, false, false, false,
2318                 0, CallingConv::C, /*isTailCall=*/false,
2319                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2320                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2321   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2322   return CallResult.first;
2323 }
2324
2325 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2326 // "local exec" model.
2327 SDValue
2328 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2329                                         SelectionDAG &DAG,
2330                                         TLSModel::Model model) const {
2331   const GlobalValue *GV = GA->getGlobal();
2332   SDLoc dl(GA);
2333   SDValue Offset;
2334   SDValue Chain = DAG.getEntryNode();
2335   EVT PtrVT = getPointerTy();
2336   // Get the Thread Pointer
2337   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2338
2339   if (model == TLSModel::InitialExec) {
2340     MachineFunction &MF = DAG.getMachineFunction();
2341     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2342     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2343     // Initial exec model.
2344     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2345     ARMConstantPoolValue *CPV =
2346       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2347                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2348                                       true);
2349     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2350     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2351     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2352                          MachinePointerInfo::getConstantPool(),
2353                          false, false, false, 0);
2354     Chain = Offset.getValue(1);
2355
2356     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2357     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2358
2359     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2360                          MachinePointerInfo::getConstantPool(),
2361                          false, false, false, 0);
2362   } else {
2363     // local exec model
2364     assert(model == TLSModel::LocalExec);
2365     ARMConstantPoolValue *CPV =
2366       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2367     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2369     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2370                          MachinePointerInfo::getConstantPool(),
2371                          false, false, false, 0);
2372   }
2373
2374   // The address of the thread local variable is the add of the thread
2375   // pointer with the offset of the variable.
2376   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2377 }
2378
2379 SDValue
2380 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2381   // TODO: implement the "local dynamic" model
2382   assert(Subtarget->isTargetELF() &&
2383          "TLS not implemented for non-ELF targets");
2384   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2385
2386   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2387
2388   switch (model) {
2389     case TLSModel::GeneralDynamic:
2390     case TLSModel::LocalDynamic:
2391       return LowerToTLSGeneralDynamicModel(GA, DAG);
2392     case TLSModel::InitialExec:
2393     case TLSModel::LocalExec:
2394       return LowerToTLSExecModels(GA, DAG, model);
2395   }
2396   llvm_unreachable("bogus TLS model");
2397 }
2398
2399 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2400                                                  SelectionDAG &DAG) const {
2401   EVT PtrVT = getPointerTy();
2402   SDLoc dl(Op);
2403   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2404   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2405     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2406     ARMConstantPoolValue *CPV =
2407       ARMConstantPoolConstant::Create(GV,
2408                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2409     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2410     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2411     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2412                                  CPAddr,
2413                                  MachinePointerInfo::getConstantPool(),
2414                                  false, false, false, 0);
2415     SDValue Chain = Result.getValue(1);
2416     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2417     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2418     if (!UseGOTOFF)
2419       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2420                            MachinePointerInfo::getGOT(),
2421                            false, false, false, 0);
2422     return Result;
2423   }
2424
2425   // If we have T2 ops, we can materialize the address directly via movt/movw
2426   // pair. This is always cheaper.
2427   if (Subtarget->useMovt()) {
2428     ++NumMovwMovt;
2429     // FIXME: Once remat is capable of dealing with instructions with register
2430     // operands, expand this into two nodes.
2431     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2432                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2433   } else {
2434     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2435     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2436     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2437                        MachinePointerInfo::getConstantPool(),
2438                        false, false, false, 0);
2439   }
2440 }
2441
2442 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2443                                                     SelectionDAG &DAG) const {
2444   EVT PtrVT = getPointerTy();
2445   SDLoc dl(Op);
2446   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2447   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2448
2449   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2450   // update ARMFastISel::ARMMaterializeGV.
2451   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2452     ++NumMovwMovt;
2453     // FIXME: Once remat is capable of dealing with instructions with register
2454     // operands, expand this into two nodes.
2455     if (RelocM == Reloc::Static)
2456       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2457                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2458
2459     unsigned Wrapper = (RelocM == Reloc::PIC_)
2460       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2461     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2462                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2463     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2464       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2465                            MachinePointerInfo::getGOT(),
2466                            false, false, false, 0);
2467     return Result;
2468   }
2469
2470   unsigned ARMPCLabelIndex = 0;
2471   SDValue CPAddr;
2472   if (RelocM == Reloc::Static) {
2473     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2474   } else {
2475     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2476     ARMPCLabelIndex = AFI->createPICLabelUId();
2477     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2478     ARMConstantPoolValue *CPV =
2479       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2480                                       PCAdj);
2481     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2482   }
2483   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2484
2485   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2486                                MachinePointerInfo::getConstantPool(),
2487                                false, false, false, 0);
2488   SDValue Chain = Result.getValue(1);
2489
2490   if (RelocM == Reloc::PIC_) {
2491     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2492     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2493   }
2494
2495   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2496     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2497                          false, false, false, 0);
2498
2499   return Result;
2500 }
2501
2502 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2503                                                     SelectionDAG &DAG) const {
2504   assert(Subtarget->isTargetELF() &&
2505          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2506   MachineFunction &MF = DAG.getMachineFunction();
2507   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2508   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2509   EVT PtrVT = getPointerTy();
2510   SDLoc dl(Op);
2511   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2512   ARMConstantPoolValue *CPV =
2513     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2514                                   ARMPCLabelIndex, PCAdj);
2515   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2516   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2517   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2518                                MachinePointerInfo::getConstantPool(),
2519                                false, false, false, 0);
2520   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2521   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2522 }
2523
2524 SDValue
2525 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2526   SDLoc dl(Op);
2527   SDValue Val = DAG.getConstant(0, MVT::i32);
2528   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2529                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2530                      Op.getOperand(1), Val);
2531 }
2532
2533 SDValue
2534 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2535   SDLoc dl(Op);
2536   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2537                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2538 }
2539
2540 SDValue
2541 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2542                                           const ARMSubtarget *Subtarget) const {
2543   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2544   SDLoc dl(Op);
2545   switch (IntNo) {
2546   default: return SDValue();    // Don't custom lower most intrinsics.
2547   case Intrinsic::arm_thread_pointer: {
2548     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2549     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2550   }
2551   case Intrinsic::eh_sjlj_lsda: {
2552     MachineFunction &MF = DAG.getMachineFunction();
2553     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2554     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2555     EVT PtrVT = getPointerTy();
2556     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2557     SDValue CPAddr;
2558     unsigned PCAdj = (RelocM != Reloc::PIC_)
2559       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2560     ARMConstantPoolValue *CPV =
2561       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2562                                       ARMCP::CPLSDA, PCAdj);
2563     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2564     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2565     SDValue Result =
2566       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2567                   MachinePointerInfo::getConstantPool(),
2568                   false, false, false, 0);
2569
2570     if (RelocM == Reloc::PIC_) {
2571       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2572       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2573     }
2574     return Result;
2575   }
2576   case Intrinsic::arm_neon_vmulls:
2577   case Intrinsic::arm_neon_vmullu: {
2578     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2579       ? ARMISD::VMULLs : ARMISD::VMULLu;
2580     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2581                        Op.getOperand(1), Op.getOperand(2));
2582   }
2583   }
2584 }
2585
2586 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2587                                  const ARMSubtarget *Subtarget) {
2588   // FIXME: handle "fence singlethread" more efficiently.
2589   SDLoc dl(Op);
2590   if (!Subtarget->hasDataBarrier()) {
2591     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2592     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2593     // here.
2594     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2595            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2596     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2597                        DAG.getConstant(0, MVT::i32));
2598   }
2599
2600   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2601   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2602   unsigned Domain = ARM_MB::ISH;
2603   if (Subtarget->isSwift() && Ord == Release) {
2604     // Swift happens to implement ISHST barriers in a way that's compatible with
2605     // Release semantics but weaker than ISH so we'd be fools not to use
2606     // it. Beware: other processors probably don't!
2607     Domain = ARM_MB::ISHST;
2608   }
2609
2610   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2611                      DAG.getConstant(Domain, MVT::i32));
2612 }
2613
2614 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2615                              const ARMSubtarget *Subtarget) {
2616   // ARM pre v5TE and Thumb1 does not have preload instructions.
2617   if (!(Subtarget->isThumb2() ||
2618         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2619     // Just preserve the chain.
2620     return Op.getOperand(0);
2621
2622   SDLoc dl(Op);
2623   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2624   if (!isRead &&
2625       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2626     // ARMv7 with MP extension has PLDW.
2627     return Op.getOperand(0);
2628
2629   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2630   if (Subtarget->isThumb()) {
2631     // Invert the bits.
2632     isRead = ~isRead & 1;
2633     isData = ~isData & 1;
2634   }
2635
2636   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2637                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2638                      DAG.getConstant(isData, MVT::i32));
2639 }
2640
2641 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2642   MachineFunction &MF = DAG.getMachineFunction();
2643   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2644
2645   // vastart just stores the address of the VarArgsFrameIndex slot into the
2646   // memory location argument.
2647   SDLoc dl(Op);
2648   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2649   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2650   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2651   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2652                       MachinePointerInfo(SV), false, false, 0);
2653 }
2654
2655 SDValue
2656 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2657                                         SDValue &Root, SelectionDAG &DAG,
2658                                         SDLoc dl) const {
2659   MachineFunction &MF = DAG.getMachineFunction();
2660   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2661
2662   const TargetRegisterClass *RC;
2663   if (AFI->isThumb1OnlyFunction())
2664     RC = &ARM::tGPRRegClass;
2665   else
2666     RC = &ARM::GPRRegClass;
2667
2668   // Transform the arguments stored in physical registers into virtual ones.
2669   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2670   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2671
2672   SDValue ArgValue2;
2673   if (NextVA.isMemLoc()) {
2674     MachineFrameInfo *MFI = MF.getFrameInfo();
2675     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2676
2677     // Create load node to retrieve arguments from the stack.
2678     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2679     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2680                             MachinePointerInfo::getFixedStack(FI),
2681                             false, false, false, 0);
2682   } else {
2683     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2684     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2685   }
2686
2687   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2688 }
2689
2690 void
2691 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2692                                   unsigned InRegsParamRecordIdx,
2693                                   unsigned ArgSize,
2694                                   unsigned &ArgRegsSize,
2695                                   unsigned &ArgRegsSaveSize)
2696   const {
2697   unsigned NumGPRs;
2698   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2699     unsigned RBegin, REnd;
2700     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2701     NumGPRs = REnd - RBegin;
2702   } else {
2703     unsigned int firstUnalloced;
2704     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2705                                                 sizeof(GPRArgRegs) /
2706                                                 sizeof(GPRArgRegs[0]));
2707     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2708   }
2709
2710   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2711   ArgRegsSize = NumGPRs * 4;
2712
2713   // If parameter is split between stack and GPRs...
2714   if (NumGPRs && Align == 8 &&
2715       (ArgRegsSize < ArgSize ||
2716         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2717     // Add padding for part of param recovered from GPRs, so
2718     // its last byte must be at address K*8 - 1.
2719     // We need to do it, since remained (stack) part of parameter has
2720     // stack alignment, and we need to "attach" "GPRs head" without gaps
2721     // to it:
2722     // Stack:
2723     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2724     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2725     //
2726     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2727     unsigned Padding =
2728         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2729         (ArgRegsSize + AFI->getArgRegsSaveSize());
2730     ArgRegsSaveSize = ArgRegsSize + Padding;
2731   } else
2732     // We don't need to extend regs save size for byval parameters if they
2733     // are passed via GPRs only.
2734     ArgRegsSaveSize = ArgRegsSize;
2735 }
2736
2737 // The remaining GPRs hold either the beginning of variable-argument
2738 // data, or the beginning of an aggregate passed by value (usually
2739 // byval).  Either way, we allocate stack slots adjacent to the data
2740 // provided by our caller, and store the unallocated registers there.
2741 // If this is a variadic function, the va_list pointer will begin with
2742 // these values; otherwise, this reassembles a (byval) structure that
2743 // was split between registers and memory.
2744 // Return: The frame index registers were stored into.
2745 int
2746 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2747                                   SDLoc dl, SDValue &Chain,
2748                                   const Value *OrigArg,
2749                                   unsigned InRegsParamRecordIdx,
2750                                   unsigned OffsetFromOrigArg,
2751                                   unsigned ArgOffset,
2752                                   unsigned ArgSize,
2753                                   bool ForceMutable) const {
2754
2755   // Currently, two use-cases possible:
2756   // Case #1. Non var-args function, and we meet first byval parameter.
2757   //          Setup first unallocated register as first byval register;
2758   //          eat all remained registers
2759   //          (these two actions are performed by HandleByVal method).
2760   //          Then, here, we initialize stack frame with
2761   //          "store-reg" instructions.
2762   // Case #2. Var-args function, that doesn't contain byval parameters.
2763   //          The same: eat all remained unallocated registers,
2764   //          initialize stack frame.
2765
2766   MachineFunction &MF = DAG.getMachineFunction();
2767   MachineFrameInfo *MFI = MF.getFrameInfo();
2768   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2769   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2770   unsigned RBegin, REnd;
2771   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2772     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2773     firstRegToSaveIndex = RBegin - ARM::R0;
2774     lastRegToSaveIndex = REnd - ARM::R0;
2775   } else {
2776     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2777       (GPRArgRegs, array_lengthof(GPRArgRegs));
2778     lastRegToSaveIndex = 4;
2779   }
2780
2781   unsigned ArgRegsSize, ArgRegsSaveSize;
2782   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2783                  ArgRegsSize, ArgRegsSaveSize);
2784
2785   // Store any by-val regs to their spots on the stack so that they may be
2786   // loaded by deferencing the result of formal parameter pointer or va_next.
2787   // Note: once stack area for byval/varargs registers
2788   // was initialized, it can't be initialized again.
2789   if (ArgRegsSaveSize) {
2790
2791     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2792
2793     if (Padding) {
2794       assert(AFI->getStoredByValParamsPadding() == 0 &&
2795              "The only parameter may be padded.");
2796       AFI->setStoredByValParamsPadding(Padding);
2797     }
2798
2799     int FrameIndex = MFI->CreateFixedObject(
2800                       ArgRegsSaveSize,
2801                       Padding + ArgOffset,
2802                       false);
2803     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2804
2805     SmallVector<SDValue, 4> MemOps;
2806     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2807          ++firstRegToSaveIndex, ++i) {
2808       const TargetRegisterClass *RC;
2809       if (AFI->isThumb1OnlyFunction())
2810         RC = &ARM::tGPRRegClass;
2811       else
2812         RC = &ARM::GPRRegClass;
2813
2814       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2815       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2816       SDValue Store =
2817         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2818                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2819                      false, false, 0);
2820       MemOps.push_back(Store);
2821       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2822                         DAG.getConstant(4, getPointerTy()));
2823     }
2824
2825     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2826
2827     if (!MemOps.empty())
2828       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2829                           &MemOps[0], MemOps.size());
2830     return FrameIndex;
2831   } else
2832     // This will point to the next argument passed via stack.
2833     return MFI->CreateFixedObject(
2834         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2835 }
2836
2837 // Setup stack frame, the va_list pointer will start from.
2838 void
2839 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2840                                         SDLoc dl, SDValue &Chain,
2841                                         unsigned ArgOffset,
2842                                         bool ForceMutable) const {
2843   MachineFunction &MF = DAG.getMachineFunction();
2844   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2845
2846   // Try to store any remaining integer argument regs
2847   // to their spots on the stack so that they may be loaded by deferencing
2848   // the result of va_next.
2849   // If there is no regs to be stored, just point address after last
2850   // argument passed via stack.
2851   int FrameIndex =
2852     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2853                    0, ArgOffset, 0, ForceMutable);
2854
2855   AFI->setVarArgsFrameIndex(FrameIndex);
2856 }
2857
2858 SDValue
2859 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2860                                         CallingConv::ID CallConv, bool isVarArg,
2861                                         const SmallVectorImpl<ISD::InputArg>
2862                                           &Ins,
2863                                         SDLoc dl, SelectionDAG &DAG,
2864                                         SmallVectorImpl<SDValue> &InVals)
2865                                           const {
2866   MachineFunction &MF = DAG.getMachineFunction();
2867   MachineFrameInfo *MFI = MF.getFrameInfo();
2868
2869   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2870
2871   // Assign locations to all of the incoming arguments.
2872   SmallVector<CCValAssign, 16> ArgLocs;
2873   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2874                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2875   CCInfo.AnalyzeFormalArguments(Ins,
2876                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2877                                                   isVarArg));
2878
2879   SmallVector<SDValue, 16> ArgValues;
2880   int lastInsIndex = -1;
2881   SDValue ArgValue;
2882   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2883   unsigned CurArgIdx = 0;
2884
2885   // Initially ArgRegsSaveSize is zero.
2886   // Then we increase this value each time we meet byval parameter.
2887   // We also increase this value in case of varargs function.
2888   AFI->setArgRegsSaveSize(0);
2889
2890   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2891     CCValAssign &VA = ArgLocs[i];
2892     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2893     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2894     // Arguments stored in registers.
2895     if (VA.isRegLoc()) {
2896       EVT RegVT = VA.getLocVT();
2897
2898       if (VA.needsCustom()) {
2899         // f64 and vector types are split up into multiple registers or
2900         // combinations of registers and stack slots.
2901         if (VA.getLocVT() == MVT::v2f64) {
2902           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2903                                                    Chain, DAG, dl);
2904           VA = ArgLocs[++i]; // skip ahead to next loc
2905           SDValue ArgValue2;
2906           if (VA.isMemLoc()) {
2907             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2908             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2909             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2910                                     MachinePointerInfo::getFixedStack(FI),
2911                                     false, false, false, 0);
2912           } else {
2913             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2914                                              Chain, DAG, dl);
2915           }
2916           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2917           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2918                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2919           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2920                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2921         } else
2922           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2923
2924       } else {
2925         const TargetRegisterClass *RC;
2926
2927         if (RegVT == MVT::f32)
2928           RC = &ARM::SPRRegClass;
2929         else if (RegVT == MVT::f64)
2930           RC = &ARM::DPRRegClass;
2931         else if (RegVT == MVT::v2f64)
2932           RC = &ARM::QPRRegClass;
2933         else if (RegVT == MVT::i32)
2934           RC = AFI->isThumb1OnlyFunction() ?
2935             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2936             (const TargetRegisterClass*)&ARM::GPRRegClass;
2937         else
2938           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2939
2940         // Transform the arguments in physical registers into virtual ones.
2941         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2942         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2943       }
2944
2945       // If this is an 8 or 16-bit value, it is really passed promoted
2946       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2947       // truncate to the right size.
2948       switch (VA.getLocInfo()) {
2949       default: llvm_unreachable("Unknown loc info!");
2950       case CCValAssign::Full: break;
2951       case CCValAssign::BCvt:
2952         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2953         break;
2954       case CCValAssign::SExt:
2955         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2956                                DAG.getValueType(VA.getValVT()));
2957         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2958         break;
2959       case CCValAssign::ZExt:
2960         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2961                                DAG.getValueType(VA.getValVT()));
2962         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2963         break;
2964       }
2965
2966       InVals.push_back(ArgValue);
2967
2968     } else { // VA.isRegLoc()
2969
2970       // sanity check
2971       assert(VA.isMemLoc());
2972       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2973
2974       int index = ArgLocs[i].getValNo();
2975
2976       // Some Ins[] entries become multiple ArgLoc[] entries.
2977       // Process them only once.
2978       if (index != lastInsIndex)
2979         {
2980           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2981           // FIXME: For now, all byval parameter objects are marked mutable.
2982           // This can be changed with more analysis.
2983           // In case of tail call optimization mark all arguments mutable.
2984           // Since they could be overwritten by lowering of arguments in case of
2985           // a tail call.
2986           if (Flags.isByVal()) {
2987             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2988             int FrameIndex = StoreByValRegs(
2989                 CCInfo, DAG, dl, Chain, CurOrigArg,
2990                 CurByValIndex,
2991                 Ins[VA.getValNo()].PartOffset,
2992                 VA.getLocMemOffset(),
2993                 Flags.getByValSize(),
2994                 true /*force mutable frames*/);
2995             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2996             CCInfo.nextInRegsParam();
2997           } else {
2998             unsigned FIOffset = VA.getLocMemOffset() +
2999                                 AFI->getStoredByValParamsPadding();
3000             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3001                                             FIOffset, true);
3002
3003             // Create load nodes to retrieve arguments from the stack.
3004             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3005             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3006                                          MachinePointerInfo::getFixedStack(FI),
3007                                          false, false, false, 0));
3008           }
3009           lastInsIndex = index;
3010         }
3011     }
3012   }
3013
3014   // varargs
3015   if (isVarArg)
3016     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3017                          CCInfo.getNextStackOffset());
3018
3019   return Chain;
3020 }
3021
3022 /// isFloatingPointZero - Return true if this is +0.0.
3023 static bool isFloatingPointZero(SDValue Op) {
3024   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3025     return CFP->getValueAPF().isPosZero();
3026   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3027     // Maybe this has already been legalized into the constant pool?
3028     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3029       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3030       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3031         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3032           return CFP->getValueAPF().isPosZero();
3033     }
3034   }
3035   return false;
3036 }
3037
3038 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3039 /// the given operands.
3040 SDValue
3041 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3042                              SDValue &ARMcc, SelectionDAG &DAG,
3043                              SDLoc dl) const {
3044   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3045     unsigned C = RHSC->getZExtValue();
3046     if (!isLegalICmpImmediate(C)) {
3047       // Constant does not fit, try adjusting it by one?
3048       switch (CC) {
3049       default: break;
3050       case ISD::SETLT:
3051       case ISD::SETGE:
3052         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3053           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3054           RHS = DAG.getConstant(C-1, MVT::i32);
3055         }
3056         break;
3057       case ISD::SETULT:
3058       case ISD::SETUGE:
3059         if (C != 0 && isLegalICmpImmediate(C-1)) {
3060           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3061           RHS = DAG.getConstant(C-1, MVT::i32);
3062         }
3063         break;
3064       case ISD::SETLE:
3065       case ISD::SETGT:
3066         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3067           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3068           RHS = DAG.getConstant(C+1, MVT::i32);
3069         }
3070         break;
3071       case ISD::SETULE:
3072       case ISD::SETUGT:
3073         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3074           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3075           RHS = DAG.getConstant(C+1, MVT::i32);
3076         }
3077         break;
3078       }
3079     }
3080   }
3081
3082   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3083   ARMISD::NodeType CompareType;
3084   switch (CondCode) {
3085   default:
3086     CompareType = ARMISD::CMP;
3087     break;
3088   case ARMCC::EQ:
3089   case ARMCC::NE:
3090     // Uses only Z Flag
3091     CompareType = ARMISD::CMPZ;
3092     break;
3093   }
3094   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3095   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3096 }
3097
3098 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3099 SDValue
3100 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3101                              SDLoc dl) const {
3102   SDValue Cmp;
3103   if (!isFloatingPointZero(RHS))
3104     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3105   else
3106     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3107   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3108 }
3109
3110 /// duplicateCmp - Glue values can have only one use, so this function
3111 /// duplicates a comparison node.
3112 SDValue
3113 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3114   unsigned Opc = Cmp.getOpcode();
3115   SDLoc DL(Cmp);
3116   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3117     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3118
3119   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3120   Cmp = Cmp.getOperand(0);
3121   Opc = Cmp.getOpcode();
3122   if (Opc == ARMISD::CMPFP)
3123     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3124   else {
3125     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3126     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3127   }
3128   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3129 }
3130
3131 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3132   SDValue Cond = Op.getOperand(0);
3133   SDValue SelectTrue = Op.getOperand(1);
3134   SDValue SelectFalse = Op.getOperand(2);
3135   SDLoc dl(Op);
3136
3137   // Convert:
3138   //
3139   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3140   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3141   //
3142   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3143     const ConstantSDNode *CMOVTrue =
3144       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3145     const ConstantSDNode *CMOVFalse =
3146       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3147
3148     if (CMOVTrue && CMOVFalse) {
3149       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3150       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3151
3152       SDValue True;
3153       SDValue False;
3154       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3155         True = SelectTrue;
3156         False = SelectFalse;
3157       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3158         True = SelectFalse;
3159         False = SelectTrue;
3160       }
3161
3162       if (True.getNode() && False.getNode()) {
3163         EVT VT = Op.getValueType();
3164         SDValue ARMcc = Cond.getOperand(2);
3165         SDValue CCR = Cond.getOperand(3);
3166         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3167         assert(True.getValueType() == VT);
3168         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3169       }
3170     }
3171   }
3172
3173   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3174   // undefined bits before doing a full-word comparison with zero.
3175   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3176                      DAG.getConstant(1, Cond.getValueType()));
3177
3178   return DAG.getSelectCC(dl, Cond,
3179                          DAG.getConstant(0, Cond.getValueType()),
3180                          SelectTrue, SelectFalse, ISD::SETNE);
3181 }
3182
3183 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3184   if (CC == ISD::SETNE)
3185     return ISD::SETEQ;
3186   return ISD::getSetCCSwappedOperands(CC);
3187 }
3188
3189 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3190                                  bool &swpCmpOps, bool &swpVselOps) {
3191   // Start by selecting the GE condition code for opcodes that return true for
3192   // 'equality'
3193   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3194       CC == ISD::SETULE)
3195     CondCode = ARMCC::GE;
3196
3197   // and GT for opcodes that return false for 'equality'.
3198   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3199            CC == ISD::SETULT)
3200     CondCode = ARMCC::GT;
3201
3202   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3203   // to swap the compare operands.
3204   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3205       CC == ISD::SETULT)
3206     swpCmpOps = true;
3207
3208   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3209   // If we have an unordered opcode, we need to swap the operands to the VSEL
3210   // instruction (effectively negating the condition).
3211   //
3212   // This also has the effect of swapping which one of 'less' or 'greater'
3213   // returns true, so we also swap the compare operands. It also switches
3214   // whether we return true for 'equality', so we compensate by picking the
3215   // opposite condition code to our original choice.
3216   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3217       CC == ISD::SETUGT) {
3218     swpCmpOps = !swpCmpOps;
3219     swpVselOps = !swpVselOps;
3220     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3221   }
3222
3223   // 'ordered' is 'anything but unordered', so use the VS condition code and
3224   // swap the VSEL operands.
3225   if (CC == ISD::SETO) {
3226     CondCode = ARMCC::VS;
3227     swpVselOps = true;
3228   }
3229
3230   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3231   // code and swap the VSEL operands.
3232   if (CC == ISD::SETUNE) {
3233     CondCode = ARMCC::EQ;
3234     swpVselOps = true;
3235   }
3236 }
3237
3238 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3239   EVT VT = Op.getValueType();
3240   SDValue LHS = Op.getOperand(0);
3241   SDValue RHS = Op.getOperand(1);
3242   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3243   SDValue TrueVal = Op.getOperand(2);
3244   SDValue FalseVal = Op.getOperand(3);
3245   SDLoc dl(Op);
3246
3247   if (LHS.getValueType() == MVT::i32) {
3248     // Try to generate VSEL on ARMv8.
3249     // The VSEL instruction can't use all the usual ARM condition
3250     // codes: it only has two bits to select the condition code, so it's
3251     // constrained to use only GE, GT, VS and EQ.
3252     //
3253     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3254     // swap the operands of the previous compare instruction (effectively
3255     // inverting the compare condition, swapping 'less' and 'greater') and
3256     // sometimes need to swap the operands to the VSEL (which inverts the
3257     // condition in the sense of firing whenever the previous condition didn't)
3258     if (getSubtarget()->hasV8FP() && (TrueVal.getValueType() == MVT::f32 ||
3259                                       TrueVal.getValueType() == MVT::f64)) {
3260       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3261       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3262           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3263         CC = getInverseCCForVSEL(CC);
3264         std::swap(TrueVal, FalseVal);
3265       }
3266     }
3267
3268     SDValue ARMcc;
3269     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3270     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3271     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3272                        Cmp);
3273   }
3274
3275   ARMCC::CondCodes CondCode, CondCode2;
3276   FPCCToARMCC(CC, CondCode, CondCode2);
3277
3278   // Try to generate VSEL on ARMv8.
3279   if (getSubtarget()->hasV8FP() && (TrueVal.getValueType() == MVT::f32 ||
3280                                     TrueVal.getValueType() == MVT::f64)) {
3281     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3282     // same operands, as follows:
3283     //   c = fcmp [ogt, olt, ugt, ult] a, b
3284     //   select c, a, b
3285     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3286     // handled differently than the original code sequence.
3287     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3288         RHS == FalseVal) {
3289       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3290         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3291       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3292         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3293     }
3294
3295     bool swpCmpOps = false;
3296     bool swpVselOps = false;
3297     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3298
3299     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3300         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3301       if (swpCmpOps)
3302         std::swap(LHS, RHS);
3303       if (swpVselOps)
3304         std::swap(TrueVal, FalseVal);
3305     }
3306   }
3307
3308   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3309   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3310   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3311   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3312                                ARMcc, CCR, Cmp);
3313   if (CondCode2 != ARMCC::AL) {
3314     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3315     // FIXME: Needs another CMP because flag can have but one use.
3316     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3317     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3318                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3319   }
3320   return Result;
3321 }
3322
3323 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3324 /// to morph to an integer compare sequence.
3325 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3326                            const ARMSubtarget *Subtarget) {
3327   SDNode *N = Op.getNode();
3328   if (!N->hasOneUse())
3329     // Otherwise it requires moving the value from fp to integer registers.
3330     return false;
3331   if (!N->getNumValues())
3332     return false;
3333   EVT VT = Op.getValueType();
3334   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3335     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3336     // vmrs are very slow, e.g. cortex-a8.
3337     return false;
3338
3339   if (isFloatingPointZero(Op)) {
3340     SeenZero = true;
3341     return true;
3342   }
3343   return ISD::isNormalLoad(N);
3344 }
3345
3346 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3347   if (isFloatingPointZero(Op))
3348     return DAG.getConstant(0, MVT::i32);
3349
3350   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3351     return DAG.getLoad(MVT::i32, SDLoc(Op),
3352                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3353                        Ld->isVolatile(), Ld->isNonTemporal(),
3354                        Ld->isInvariant(), Ld->getAlignment());
3355
3356   llvm_unreachable("Unknown VFP cmp argument!");
3357 }
3358
3359 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3360                            SDValue &RetVal1, SDValue &RetVal2) {
3361   if (isFloatingPointZero(Op)) {
3362     RetVal1 = DAG.getConstant(0, MVT::i32);
3363     RetVal2 = DAG.getConstant(0, MVT::i32);
3364     return;
3365   }
3366
3367   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3368     SDValue Ptr = Ld->getBasePtr();
3369     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3370                           Ld->getChain(), Ptr,
3371                           Ld->getPointerInfo(),
3372                           Ld->isVolatile(), Ld->isNonTemporal(),
3373                           Ld->isInvariant(), Ld->getAlignment());
3374
3375     EVT PtrType = Ptr.getValueType();
3376     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3377     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3378                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3379     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3380                           Ld->getChain(), NewPtr,
3381                           Ld->getPointerInfo().getWithOffset(4),
3382                           Ld->isVolatile(), Ld->isNonTemporal(),
3383                           Ld->isInvariant(), NewAlign);
3384     return;
3385   }
3386
3387   llvm_unreachable("Unknown VFP cmp argument!");
3388 }
3389
3390 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3391 /// f32 and even f64 comparisons to integer ones.
3392 SDValue
3393 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3394   SDValue Chain = Op.getOperand(0);
3395   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3396   SDValue LHS = Op.getOperand(2);
3397   SDValue RHS = Op.getOperand(3);
3398   SDValue Dest = Op.getOperand(4);
3399   SDLoc dl(Op);
3400
3401   bool LHSSeenZero = false;
3402   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3403   bool RHSSeenZero = false;
3404   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3405   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3406     // If unsafe fp math optimization is enabled and there are no other uses of
3407     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3408     // to an integer comparison.
3409     if (CC == ISD::SETOEQ)
3410       CC = ISD::SETEQ;
3411     else if (CC == ISD::SETUNE)
3412       CC = ISD::SETNE;
3413
3414     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3415     SDValue ARMcc;
3416     if (LHS.getValueType() == MVT::f32) {
3417       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3418                         bitcastf32Toi32(LHS, DAG), Mask);
3419       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3420                         bitcastf32Toi32(RHS, DAG), Mask);
3421       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3422       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3423       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3424                          Chain, Dest, ARMcc, CCR, Cmp);
3425     }
3426
3427     SDValue LHS1, LHS2;
3428     SDValue RHS1, RHS2;
3429     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3430     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3431     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3432     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3433     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3434     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3435     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3436     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3437     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3438   }
3439
3440   return SDValue();
3441 }
3442
3443 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3444   SDValue Chain = Op.getOperand(0);
3445   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3446   SDValue LHS = Op.getOperand(2);
3447   SDValue RHS = Op.getOperand(3);
3448   SDValue Dest = Op.getOperand(4);
3449   SDLoc dl(Op);
3450
3451   if (LHS.getValueType() == MVT::i32) {
3452     SDValue ARMcc;
3453     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3454     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3455     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3456                        Chain, Dest, ARMcc, CCR, Cmp);
3457   }
3458
3459   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3460
3461   if (getTargetMachine().Options.UnsafeFPMath &&
3462       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3463        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3464     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3465     if (Result.getNode())
3466       return Result;
3467   }
3468
3469   ARMCC::CondCodes CondCode, CondCode2;
3470   FPCCToARMCC(CC, CondCode, CondCode2);
3471
3472   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3473   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3474   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3475   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3476   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3477   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3478   if (CondCode2 != ARMCC::AL) {
3479     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3480     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3481     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3482   }
3483   return Res;
3484 }
3485
3486 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3487   SDValue Chain = Op.getOperand(0);
3488   SDValue Table = Op.getOperand(1);
3489   SDValue Index = Op.getOperand(2);
3490   SDLoc dl(Op);
3491
3492   EVT PTy = getPointerTy();
3493   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3494   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3495   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3496   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3497   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3498   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3499   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3500   if (Subtarget->isThumb2()) {
3501     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3502     // which does another jump to the destination. This also makes it easier
3503     // to translate it to TBB / TBH later.
3504     // FIXME: This might not work if the function is extremely large.
3505     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3506                        Addr, Op.getOperand(2), JTI, UId);
3507   }
3508   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3509     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3510                        MachinePointerInfo::getJumpTable(),
3511                        false, false, false, 0);
3512     Chain = Addr.getValue(1);
3513     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3514     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3515   } else {
3516     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3517                        MachinePointerInfo::getJumpTable(),
3518                        false, false, false, 0);
3519     Chain = Addr.getValue(1);
3520     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3521   }
3522 }
3523
3524 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3525   EVT VT = Op.getValueType();
3526   SDLoc dl(Op);
3527
3528   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3529     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3530       return Op;
3531     return DAG.UnrollVectorOp(Op.getNode());
3532   }
3533
3534   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3535          "Invalid type for custom lowering!");
3536   if (VT != MVT::v4i16)
3537     return DAG.UnrollVectorOp(Op.getNode());
3538
3539   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3540   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3541 }
3542
3543 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3544   EVT VT = Op.getValueType();
3545   if (VT.isVector())
3546     return LowerVectorFP_TO_INT(Op, DAG);
3547
3548   SDLoc dl(Op);
3549   unsigned Opc;
3550
3551   switch (Op.getOpcode()) {
3552   default: llvm_unreachable("Invalid opcode!");
3553   case ISD::FP_TO_SINT:
3554     Opc = ARMISD::FTOSI;
3555     break;
3556   case ISD::FP_TO_UINT:
3557     Opc = ARMISD::FTOUI;
3558     break;
3559   }
3560   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3561   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3562 }
3563
3564 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3565   EVT VT = Op.getValueType();
3566   SDLoc dl(Op);
3567
3568   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3569     if (VT.getVectorElementType() == MVT::f32)
3570       return Op;
3571     return DAG.UnrollVectorOp(Op.getNode());
3572   }
3573
3574   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3575          "Invalid type for custom lowering!");
3576   if (VT != MVT::v4f32)
3577     return DAG.UnrollVectorOp(Op.getNode());
3578
3579   unsigned CastOpc;
3580   unsigned Opc;
3581   switch (Op.getOpcode()) {
3582   default: llvm_unreachable("Invalid opcode!");
3583   case ISD::SINT_TO_FP:
3584     CastOpc = ISD::SIGN_EXTEND;
3585     Opc = ISD::SINT_TO_FP;
3586     break;
3587   case ISD::UINT_TO_FP:
3588     CastOpc = ISD::ZERO_EXTEND;
3589     Opc = ISD::UINT_TO_FP;
3590     break;
3591   }
3592
3593   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3594   return DAG.getNode(Opc, dl, VT, Op);
3595 }
3596
3597 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3598   EVT VT = Op.getValueType();
3599   if (VT.isVector())
3600     return LowerVectorINT_TO_FP(Op, DAG);
3601
3602   SDLoc dl(Op);
3603   unsigned Opc;
3604
3605   switch (Op.getOpcode()) {
3606   default: llvm_unreachable("Invalid opcode!");
3607   case ISD::SINT_TO_FP:
3608     Opc = ARMISD::SITOF;
3609     break;
3610   case ISD::UINT_TO_FP:
3611     Opc = ARMISD::UITOF;
3612     break;
3613   }
3614
3615   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3616   return DAG.getNode(Opc, dl, VT, Op);
3617 }
3618
3619 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3620   // Implement fcopysign with a fabs and a conditional fneg.
3621   SDValue Tmp0 = Op.getOperand(0);
3622   SDValue Tmp1 = Op.getOperand(1);
3623   SDLoc dl(Op);
3624   EVT VT = Op.getValueType();
3625   EVT SrcVT = Tmp1.getValueType();
3626   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3627     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3628   bool UseNEON = !InGPR && Subtarget->hasNEON();
3629
3630   if (UseNEON) {
3631     // Use VBSL to copy the sign bit.
3632     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3633     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3634                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3635     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3636     if (VT == MVT::f64)
3637       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3638                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3639                          DAG.getConstant(32, MVT::i32));
3640     else /*if (VT == MVT::f32)*/
3641       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3642     if (SrcVT == MVT::f32) {
3643       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3644       if (VT == MVT::f64)
3645         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3646                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3647                            DAG.getConstant(32, MVT::i32));
3648     } else if (VT == MVT::f32)
3649       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3650                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3651                          DAG.getConstant(32, MVT::i32));
3652     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3653     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3654
3655     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3656                                             MVT::i32);
3657     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3658     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3659                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3660
3661     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3662                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3663                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3664     if (VT == MVT::f32) {
3665       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3666       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3667                         DAG.getConstant(0, MVT::i32));
3668     } else {
3669       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3670     }
3671
3672     return Res;
3673   }
3674
3675   // Bitcast operand 1 to i32.
3676   if (SrcVT == MVT::f64)
3677     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3678                        &Tmp1, 1).getValue(1);
3679   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3680
3681   // Or in the signbit with integer operations.
3682   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3683   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3684   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3685   if (VT == MVT::f32) {
3686     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3687                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3688     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3689                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3690   }
3691
3692   // f64: Or the high part with signbit and then combine two parts.
3693   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3694                      &Tmp0, 1);
3695   SDValue Lo = Tmp0.getValue(0);
3696   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3697   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3698   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3699 }
3700
3701 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3702   MachineFunction &MF = DAG.getMachineFunction();
3703   MachineFrameInfo *MFI = MF.getFrameInfo();
3704   MFI->setReturnAddressIsTaken(true);
3705
3706   EVT VT = Op.getValueType();
3707   SDLoc dl(Op);
3708   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3709   if (Depth) {
3710     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3711     SDValue Offset = DAG.getConstant(4, MVT::i32);
3712     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3713                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3714                        MachinePointerInfo(), false, false, false, 0);
3715   }
3716
3717   // Return LR, which contains the return address. Mark it an implicit live-in.
3718   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3719   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3720 }
3721
3722 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3723   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3724   MFI->setFrameAddressIsTaken(true);
3725
3726   EVT VT = Op.getValueType();
3727   SDLoc dl(Op);  // FIXME probably not meaningful
3728   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3729   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3730     ? ARM::R7 : ARM::R11;
3731   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3732   while (Depth--)
3733     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3734                             MachinePointerInfo(),
3735                             false, false, false, 0);
3736   return FrameAddr;
3737 }
3738
3739 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3740 /// and size(DestVec) > 128-bits.
3741 /// This is achieved by doing the one extension from the SrcVec, splitting the
3742 /// result, extending these parts, and then concatenating these into the
3743 /// destination.
3744 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3745   SDValue Op = N->getOperand(0);
3746   EVT SrcVT = Op.getValueType();
3747   EVT DestVT = N->getValueType(0);
3748
3749   assert(DestVT.getSizeInBits() > 128 &&
3750          "Custom sext/zext expansion needs >128-bit vector.");
3751   // If this is a normal length extension, use the default expansion.
3752   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3753       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3754     return SDValue();
3755
3756   SDLoc dl(N);
3757   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3758   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3759   unsigned NumElts = SrcVT.getVectorNumElements();
3760   LLVMContext &Ctx = *DAG.getContext();
3761   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3762
3763   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3764                                NumElts);
3765   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3766                                  NumElts/2);
3767   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3768                                NumElts/2);
3769
3770   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3771   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3772                         DAG.getIntPtrConstant(0));
3773   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3774                         DAG.getIntPtrConstant(NumElts/2));
3775   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3776   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3777   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3778 }
3779
3780 /// ExpandBITCAST - If the target supports VFP, this function is called to
3781 /// expand a bit convert where either the source or destination type is i64 to
3782 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3783 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3784 /// vectors), since the legalizer won't know what to do with that.
3785 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3787   SDLoc dl(N);
3788   SDValue Op = N->getOperand(0);
3789
3790   // This function is only supposed to be called for i64 types, either as the
3791   // source or destination of the bit convert.
3792   EVT SrcVT = Op.getValueType();
3793   EVT DstVT = N->getValueType(0);
3794   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3795          "ExpandBITCAST called for non-i64 type");
3796
3797   // Turn i64->f64 into VMOVDRR.
3798   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3799     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3800                              DAG.getConstant(0, MVT::i32));
3801     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3802                              DAG.getConstant(1, MVT::i32));
3803     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3804                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3805   }
3806
3807   // Turn f64->i64 into VMOVRRD.
3808   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3809     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3810                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3811     // Merge the pieces into a single i64 value.
3812     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3813   }
3814
3815   return SDValue();
3816 }
3817
3818 /// getZeroVector - Returns a vector of specified type with all zero elements.
3819 /// Zero vectors are used to represent vector negation and in those cases
3820 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3821 /// not support i64 elements, so sometimes the zero vectors will need to be
3822 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3823 /// zero vector.
3824 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3825   assert(VT.isVector() && "Expected a vector type");
3826   // The canonical modified immediate encoding of a zero vector is....0!
3827   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3828   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3829   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3830   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3831 }
3832
3833 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3834 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3835 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3836                                                 SelectionDAG &DAG) const {
3837   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3838   EVT VT = Op.getValueType();
3839   unsigned VTBits = VT.getSizeInBits();
3840   SDLoc dl(Op);
3841   SDValue ShOpLo = Op.getOperand(0);
3842   SDValue ShOpHi = Op.getOperand(1);
3843   SDValue ShAmt  = Op.getOperand(2);
3844   SDValue ARMcc;
3845   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3846
3847   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3848
3849   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3850                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3851   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3852   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3853                                    DAG.getConstant(VTBits, MVT::i32));
3854   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3855   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3856   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3857
3858   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3859   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3860                           ARMcc, DAG, dl);
3861   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3862   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3863                            CCR, Cmp);
3864
3865   SDValue Ops[2] = { Lo, Hi };
3866   return DAG.getMergeValues(Ops, 2, dl);
3867 }
3868
3869 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3870 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3871 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3872                                                SelectionDAG &DAG) const {
3873   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3874   EVT VT = Op.getValueType();
3875   unsigned VTBits = VT.getSizeInBits();
3876   SDLoc dl(Op);
3877   SDValue ShOpLo = Op.getOperand(0);
3878   SDValue ShOpHi = Op.getOperand(1);
3879   SDValue ShAmt  = Op.getOperand(2);
3880   SDValue ARMcc;
3881
3882   assert(Op.getOpcode() == ISD::SHL_PARTS);
3883   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3884                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3885   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3886   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3887                                    DAG.getConstant(VTBits, MVT::i32));
3888   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3889   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3890
3891   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3892   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3893   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3894                           ARMcc, DAG, dl);
3895   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3896   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3897                            CCR, Cmp);
3898
3899   SDValue Ops[2] = { Lo, Hi };
3900   return DAG.getMergeValues(Ops, 2, dl);
3901 }
3902
3903 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3904                                             SelectionDAG &DAG) const {
3905   // The rounding mode is in bits 23:22 of the FPSCR.
3906   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3907   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3908   // so that the shift + and get folded into a bitfield extract.
3909   SDLoc dl(Op);
3910   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3911                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3912                                               MVT::i32));
3913   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3914                                   DAG.getConstant(1U << 22, MVT::i32));
3915   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3916                               DAG.getConstant(22, MVT::i32));
3917   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3918                      DAG.getConstant(3, MVT::i32));
3919 }
3920
3921 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3922                          const ARMSubtarget *ST) {
3923   EVT VT = N->getValueType(0);
3924   SDLoc dl(N);
3925
3926   if (!ST->hasV6T2Ops())
3927     return SDValue();
3928
3929   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3930   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3931 }
3932
3933 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3934 /// for each 16-bit element from operand, repeated.  The basic idea is to
3935 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3936 ///
3937 /// Trace for v4i16:
3938 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3939 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3940 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3941 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3942 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3943 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3944 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3945 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3946 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3947   EVT VT = N->getValueType(0);
3948   SDLoc DL(N);
3949
3950   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3951   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3952   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3953   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3954   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3955   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3956 }
3957
3958 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3959 /// bit-count for each 16-bit element from the operand.  We need slightly
3960 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3961 /// 64/128-bit registers.
3962 ///
3963 /// Trace for v4i16:
3964 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3965 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3966 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3967 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3968 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3969   EVT VT = N->getValueType(0);
3970   SDLoc DL(N);
3971
3972   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3973   if (VT.is64BitVector()) {
3974     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3975     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3976                        DAG.getIntPtrConstant(0));
3977   } else {
3978     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3979                                     BitCounts, DAG.getIntPtrConstant(0));
3980     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3981   }
3982 }
3983
3984 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3985 /// bit-count for each 32-bit element from the operand.  The idea here is
3986 /// to split the vector into 16-bit elements, leverage the 16-bit count
3987 /// routine, and then combine the results.
3988 ///
3989 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3990 /// input    = [v0    v1    ] (vi: 32-bit elements)
3991 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3992 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3993 /// vrev: N0 = [k1 k0 k3 k2 ]
3994 ///            [k0 k1 k2 k3 ]
3995 ///       N1 =+[k1 k0 k3 k2 ]
3996 ///            [k0 k2 k1 k3 ]
3997 ///       N2 =+[k1 k3 k0 k2 ]
3998 ///            [k0    k2    k1    k3    ]
3999 /// Extended =+[k1    k3    k0    k2    ]
4000 ///            [k0    k2    ]
4001 /// Extracted=+[k1    k3    ]
4002 ///
4003 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4004   EVT VT = N->getValueType(0);
4005   SDLoc DL(N);
4006
4007   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4008
4009   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4010   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4011   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4012   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4013   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4014
4015   if (VT.is64BitVector()) {
4016     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4017     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4018                        DAG.getIntPtrConstant(0));
4019   } else {
4020     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4021                                     DAG.getIntPtrConstant(0));
4022     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4023   }
4024 }
4025
4026 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4027                           const ARMSubtarget *ST) {
4028   EVT VT = N->getValueType(0);
4029
4030   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4031   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4032           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4033          "Unexpected type for custom ctpop lowering");
4034
4035   if (VT.getVectorElementType() == MVT::i32)
4036     return lowerCTPOP32BitElements(N, DAG);
4037   else
4038     return lowerCTPOP16BitElements(N, DAG);
4039 }
4040
4041 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4042                           const ARMSubtarget *ST) {
4043   EVT VT = N->getValueType(0);
4044   SDLoc dl(N);
4045
4046   if (!VT.isVector())
4047     return SDValue();
4048
4049   // Lower vector shifts on NEON to use VSHL.
4050   assert(ST->hasNEON() && "unexpected vector shift");
4051
4052   // Left shifts translate directly to the vshiftu intrinsic.
4053   if (N->getOpcode() == ISD::SHL)
4054     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4055                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4056                        N->getOperand(0), N->getOperand(1));
4057
4058   assert((N->getOpcode() == ISD::SRA ||
4059           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4060
4061   // NEON uses the same intrinsics for both left and right shifts.  For
4062   // right shifts, the shift amounts are negative, so negate the vector of
4063   // shift amounts.
4064   EVT ShiftVT = N->getOperand(1).getValueType();
4065   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4066                                      getZeroVector(ShiftVT, DAG, dl),
4067                                      N->getOperand(1));
4068   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4069                              Intrinsic::arm_neon_vshifts :
4070                              Intrinsic::arm_neon_vshiftu);
4071   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4072                      DAG.getConstant(vshiftInt, MVT::i32),
4073                      N->getOperand(0), NegatedCount);
4074 }
4075
4076 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4077                                 const ARMSubtarget *ST) {
4078   EVT VT = N->getValueType(0);
4079   SDLoc dl(N);
4080
4081   // We can get here for a node like i32 = ISD::SHL i32, i64
4082   if (VT != MVT::i64)
4083     return SDValue();
4084
4085   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4086          "Unknown shift to lower!");
4087
4088   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4089   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4090       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4091     return SDValue();
4092
4093   // If we are in thumb mode, we don't have RRX.
4094   if (ST->isThumb1Only()) return SDValue();
4095
4096   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4097   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4098                            DAG.getConstant(0, MVT::i32));
4099   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4100                            DAG.getConstant(1, MVT::i32));
4101
4102   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4103   // captures the result into a carry flag.
4104   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4105   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4106
4107   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4108   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4109
4110   // Merge the pieces into a single i64 value.
4111  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4112 }
4113
4114 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4115   SDValue TmpOp0, TmpOp1;
4116   bool Invert = false;
4117   bool Swap = false;
4118   unsigned Opc = 0;
4119
4120   SDValue Op0 = Op.getOperand(0);
4121   SDValue Op1 = Op.getOperand(1);
4122   SDValue CC = Op.getOperand(2);
4123   EVT VT = Op.getValueType();
4124   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4125   SDLoc dl(Op);
4126
4127   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4128     switch (SetCCOpcode) {
4129     default: llvm_unreachable("Illegal FP comparison");
4130     case ISD::SETUNE:
4131     case ISD::SETNE:  Invert = true; // Fallthrough
4132     case ISD::SETOEQ:
4133     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4134     case ISD::SETOLT:
4135     case ISD::SETLT: Swap = true; // Fallthrough
4136     case ISD::SETOGT:
4137     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4138     case ISD::SETOLE:
4139     case ISD::SETLE:  Swap = true; // Fallthrough
4140     case ISD::SETOGE:
4141     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4142     case ISD::SETUGE: Swap = true; // Fallthrough
4143     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4144     case ISD::SETUGT: Swap = true; // Fallthrough
4145     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4146     case ISD::SETUEQ: Invert = true; // Fallthrough
4147     case ISD::SETONE:
4148       // Expand this to (OLT | OGT).
4149       TmpOp0 = Op0;
4150       TmpOp1 = Op1;
4151       Opc = ISD::OR;
4152       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4153       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4154       break;
4155     case ISD::SETUO: Invert = true; // Fallthrough
4156     case ISD::SETO:
4157       // Expand this to (OLT | OGE).
4158       TmpOp0 = Op0;
4159       TmpOp1 = Op1;
4160       Opc = ISD::OR;
4161       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4162       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4163       break;
4164     }
4165   } else {
4166     // Integer comparisons.
4167     switch (SetCCOpcode) {
4168     default: llvm_unreachable("Illegal integer comparison");
4169     case ISD::SETNE:  Invert = true;
4170     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4171     case ISD::SETLT:  Swap = true;
4172     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4173     case ISD::SETLE:  Swap = true;
4174     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4175     case ISD::SETULT: Swap = true;
4176     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4177     case ISD::SETULE: Swap = true;
4178     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4179     }
4180
4181     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4182     if (Opc == ARMISD::VCEQ) {
4183
4184       SDValue AndOp;
4185       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4186         AndOp = Op0;
4187       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4188         AndOp = Op1;
4189
4190       // Ignore bitconvert.
4191       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4192         AndOp = AndOp.getOperand(0);
4193
4194       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4195         Opc = ARMISD::VTST;
4196         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4197         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4198         Invert = !Invert;
4199       }
4200     }
4201   }
4202
4203   if (Swap)
4204     std::swap(Op0, Op1);
4205
4206   // If one of the operands is a constant vector zero, attempt to fold the
4207   // comparison to a specialized compare-against-zero form.
4208   SDValue SingleOp;
4209   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4210     SingleOp = Op0;
4211   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4212     if (Opc == ARMISD::VCGE)
4213       Opc = ARMISD::VCLEZ;
4214     else if (Opc == ARMISD::VCGT)
4215       Opc = ARMISD::VCLTZ;
4216     SingleOp = Op1;
4217   }
4218
4219   SDValue Result;
4220   if (SingleOp.getNode()) {
4221     switch (Opc) {
4222     case ARMISD::VCEQ:
4223       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4224     case ARMISD::VCGE:
4225       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4226     case ARMISD::VCLEZ:
4227       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4228     case ARMISD::VCGT:
4229       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4230     case ARMISD::VCLTZ:
4231       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4232     default:
4233       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4234     }
4235   } else {
4236      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4237   }
4238
4239   if (Invert)
4240     Result = DAG.getNOT(dl, Result, VT);
4241
4242   return Result;
4243 }
4244
4245 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4246 /// valid vector constant for a NEON instruction with a "modified immediate"
4247 /// operand (e.g., VMOV).  If so, return the encoded value.
4248 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4249                                  unsigned SplatBitSize, SelectionDAG &DAG,
4250                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4251   unsigned OpCmode, Imm;
4252
4253   // SplatBitSize is set to the smallest size that splats the vector, so a
4254   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4255   // immediate instructions others than VMOV do not support the 8-bit encoding
4256   // of a zero vector, and the default encoding of zero is supposed to be the
4257   // 32-bit version.
4258   if (SplatBits == 0)
4259     SplatBitSize = 32;
4260
4261   switch (SplatBitSize) {
4262   case 8:
4263     if (type != VMOVModImm)
4264       return SDValue();
4265     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4266     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4267     OpCmode = 0xe;
4268     Imm = SplatBits;
4269     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4270     break;
4271
4272   case 16:
4273     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4274     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4275     if ((SplatBits & ~0xff) == 0) {
4276       // Value = 0x00nn: Op=x, Cmode=100x.
4277       OpCmode = 0x8;
4278       Imm = SplatBits;
4279       break;
4280     }
4281     if ((SplatBits & ~0xff00) == 0) {
4282       // Value = 0xnn00: Op=x, Cmode=101x.
4283       OpCmode = 0xa;
4284       Imm = SplatBits >> 8;
4285       break;
4286     }
4287     return SDValue();
4288
4289   case 32:
4290     // NEON's 32-bit VMOV supports splat values where:
4291     // * only one byte is nonzero, or
4292     // * the least significant byte is 0xff and the second byte is nonzero, or
4293     // * the least significant 2 bytes are 0xff and the third is nonzero.
4294     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4295     if ((SplatBits & ~0xff) == 0) {
4296       // Value = 0x000000nn: Op=x, Cmode=000x.
4297       OpCmode = 0;
4298       Imm = SplatBits;
4299       break;
4300     }
4301     if ((SplatBits & ~0xff00) == 0) {
4302       // Value = 0x0000nn00: Op=x, Cmode=001x.
4303       OpCmode = 0x2;
4304       Imm = SplatBits >> 8;
4305       break;
4306     }
4307     if ((SplatBits & ~0xff0000) == 0) {
4308       // Value = 0x00nn0000: Op=x, Cmode=010x.
4309       OpCmode = 0x4;
4310       Imm = SplatBits >> 16;
4311       break;
4312     }
4313     if ((SplatBits & ~0xff000000) == 0) {
4314       // Value = 0xnn000000: Op=x, Cmode=011x.
4315       OpCmode = 0x6;
4316       Imm = SplatBits >> 24;
4317       break;
4318     }
4319
4320     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4321     if (type == OtherModImm) return SDValue();
4322
4323     if ((SplatBits & ~0xffff) == 0 &&
4324         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4325       // Value = 0x0000nnff: Op=x, Cmode=1100.
4326       OpCmode = 0xc;
4327       Imm = SplatBits >> 8;
4328       SplatBits |= 0xff;
4329       break;
4330     }
4331
4332     if ((SplatBits & ~0xffffff) == 0 &&
4333         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4334       // Value = 0x00nnffff: Op=x, Cmode=1101.
4335       OpCmode = 0xd;
4336       Imm = SplatBits >> 16;
4337       SplatBits |= 0xffff;
4338       break;
4339     }
4340
4341     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4342     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4343     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4344     // and fall through here to test for a valid 64-bit splat.  But, then the
4345     // caller would also need to check and handle the change in size.
4346     return SDValue();
4347
4348   case 64: {
4349     if (type != VMOVModImm)
4350       return SDValue();
4351     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4352     uint64_t BitMask = 0xff;
4353     uint64_t Val = 0;
4354     unsigned ImmMask = 1;
4355     Imm = 0;
4356     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4357       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4358         Val |= BitMask;
4359         Imm |= ImmMask;
4360       } else if ((SplatBits & BitMask) != 0) {
4361         return SDValue();
4362       }
4363       BitMask <<= 8;
4364       ImmMask <<= 1;
4365     }
4366     // Op=1, Cmode=1110.
4367     OpCmode = 0x1e;
4368     SplatBits = Val;
4369     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4370     break;
4371   }
4372
4373   default:
4374     llvm_unreachable("unexpected size for isNEONModifiedImm");
4375   }
4376
4377   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4378   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4379 }
4380
4381 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4382                                            const ARMSubtarget *ST) const {
4383   if (!ST->hasVFP3())
4384     return SDValue();
4385
4386   bool IsDouble = Op.getValueType() == MVT::f64;
4387   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4388
4389   // Try splatting with a VMOV.f32...
4390   APFloat FPVal = CFP->getValueAPF();
4391   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4392
4393   if (ImmVal != -1) {
4394     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4395       // We have code in place to select a valid ConstantFP already, no need to
4396       // do any mangling.
4397       return Op;
4398     }
4399
4400     // It's a float and we are trying to use NEON operations where
4401     // possible. Lower it to a splat followed by an extract.
4402     SDLoc DL(Op);
4403     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4404     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4405                                       NewVal);
4406     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4407                        DAG.getConstant(0, MVT::i32));
4408   }
4409
4410   // The rest of our options are NEON only, make sure that's allowed before
4411   // proceeding..
4412   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4413     return SDValue();
4414
4415   EVT VMovVT;
4416   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4417
4418   // It wouldn't really be worth bothering for doubles except for one very
4419   // important value, which does happen to match: 0.0. So make sure we don't do
4420   // anything stupid.
4421   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4422     return SDValue();
4423
4424   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4425   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4426                                      false, VMOVModImm);
4427   if (NewVal != SDValue()) {
4428     SDLoc DL(Op);
4429     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4430                                       NewVal);
4431     if (IsDouble)
4432       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4433
4434     // It's a float: cast and extract a vector element.
4435     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4436                                        VecConstant);
4437     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4438                        DAG.getConstant(0, MVT::i32));
4439   }
4440
4441   // Finally, try a VMVN.i32
4442   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4443                              false, VMVNModImm);
4444   if (NewVal != SDValue()) {
4445     SDLoc DL(Op);
4446     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4447
4448     if (IsDouble)
4449       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4450
4451     // It's a float: cast and extract a vector element.
4452     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4453                                        VecConstant);
4454     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4455                        DAG.getConstant(0, MVT::i32));
4456   }
4457
4458   return SDValue();
4459 }
4460
4461 // check if an VEXT instruction can handle the shuffle mask when the
4462 // vector sources of the shuffle are the same.
4463 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4464   unsigned NumElts = VT.getVectorNumElements();
4465
4466   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4467   if (M[0] < 0)
4468     return false;
4469
4470   Imm = M[0];
4471
4472   // If this is a VEXT shuffle, the immediate value is the index of the first
4473   // element.  The other shuffle indices must be the successive elements after
4474   // the first one.
4475   unsigned ExpectedElt = Imm;
4476   for (unsigned i = 1; i < NumElts; ++i) {
4477     // Increment the expected index.  If it wraps around, just follow it
4478     // back to index zero and keep going.
4479     ++ExpectedElt;
4480     if (ExpectedElt == NumElts)
4481       ExpectedElt = 0;
4482
4483     if (M[i] < 0) continue; // ignore UNDEF indices
4484     if (ExpectedElt != static_cast<unsigned>(M[i]))
4485       return false;
4486   }
4487
4488   return true;
4489 }
4490
4491
4492 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4493                        bool &ReverseVEXT, unsigned &Imm) {
4494   unsigned NumElts = VT.getVectorNumElements();
4495   ReverseVEXT = false;
4496
4497   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4498   if (M[0] < 0)
4499     return false;
4500
4501   Imm = M[0];
4502
4503   // If this is a VEXT shuffle, the immediate value is the index of the first
4504   // element.  The other shuffle indices must be the successive elements after
4505   // the first one.
4506   unsigned ExpectedElt = Imm;
4507   for (unsigned i = 1; i < NumElts; ++i) {
4508     // Increment the expected index.  If it wraps around, it may still be
4509     // a VEXT but the source vectors must be swapped.
4510     ExpectedElt += 1;
4511     if (ExpectedElt == NumElts * 2) {
4512       ExpectedElt = 0;
4513       ReverseVEXT = true;
4514     }
4515
4516     if (M[i] < 0) continue; // ignore UNDEF indices
4517     if (ExpectedElt != static_cast<unsigned>(M[i]))
4518       return false;
4519   }
4520
4521   // Adjust the index value if the source operands will be swapped.
4522   if (ReverseVEXT)
4523     Imm -= NumElts;
4524
4525   return true;
4526 }
4527
4528 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4529 /// instruction with the specified blocksize.  (The order of the elements
4530 /// within each block of the vector is reversed.)
4531 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4532   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4533          "Only possible block sizes for VREV are: 16, 32, 64");
4534
4535   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4536   if (EltSz == 64)
4537     return false;
4538
4539   unsigned NumElts = VT.getVectorNumElements();
4540   unsigned BlockElts = M[0] + 1;
4541   // If the first shuffle index is UNDEF, be optimistic.
4542   if (M[0] < 0)
4543     BlockElts = BlockSize / EltSz;
4544
4545   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4546     return false;
4547
4548   for (unsigned i = 0; i < NumElts; ++i) {
4549     if (M[i] < 0) continue; // ignore UNDEF indices
4550     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4551       return false;
4552   }
4553
4554   return true;
4555 }
4556
4557 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4558   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4559   // range, then 0 is placed into the resulting vector. So pretty much any mask
4560   // of 8 elements can work here.
4561   return VT == MVT::v8i8 && M.size() == 8;
4562 }
4563
4564 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4565   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4566   if (EltSz == 64)
4567     return false;
4568
4569   unsigned NumElts = VT.getVectorNumElements();
4570   WhichResult = (M[0] == 0 ? 0 : 1);
4571   for (unsigned i = 0; i < NumElts; i += 2) {
4572     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4573         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4574       return false;
4575   }
4576   return true;
4577 }
4578
4579 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4580 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4581 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4582 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4583   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4584   if (EltSz == 64)
4585     return false;
4586
4587   unsigned NumElts = VT.getVectorNumElements();
4588   WhichResult = (M[0] == 0 ? 0 : 1);
4589   for (unsigned i = 0; i < NumElts; i += 2) {
4590     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4591         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4592       return false;
4593   }
4594   return true;
4595 }
4596
4597 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4598   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4599   if (EltSz == 64)
4600     return false;
4601
4602   unsigned NumElts = VT.getVectorNumElements();
4603   WhichResult = (M[0] == 0 ? 0 : 1);
4604   for (unsigned i = 0; i != NumElts; ++i) {
4605     if (M[i] < 0) continue; // ignore UNDEF indices
4606     if ((unsigned) M[i] != 2 * i + WhichResult)
4607       return false;
4608   }
4609
4610   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4611   if (VT.is64BitVector() && EltSz == 32)
4612     return false;
4613
4614   return true;
4615 }
4616
4617 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4618 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4619 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4620 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4621   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4622   if (EltSz == 64)
4623     return false;
4624
4625   unsigned Half = VT.getVectorNumElements() / 2;
4626   WhichResult = (M[0] == 0 ? 0 : 1);
4627   for (unsigned j = 0; j != 2; ++j) {
4628     unsigned Idx = WhichResult;
4629     for (unsigned i = 0; i != Half; ++i) {
4630       int MIdx = M[i + j * Half];
4631       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4632         return false;
4633       Idx += 2;
4634     }
4635   }
4636
4637   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4638   if (VT.is64BitVector() && EltSz == 32)
4639     return false;
4640
4641   return true;
4642 }
4643
4644 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4645   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4646   if (EltSz == 64)
4647     return false;
4648
4649   unsigned NumElts = VT.getVectorNumElements();
4650   WhichResult = (M[0] == 0 ? 0 : 1);
4651   unsigned Idx = WhichResult * NumElts / 2;
4652   for (unsigned i = 0; i != NumElts; i += 2) {
4653     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4654         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4655       return false;
4656     Idx += 1;
4657   }
4658
4659   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4660   if (VT.is64BitVector() && EltSz == 32)
4661     return false;
4662
4663   return true;
4664 }
4665
4666 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4667 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4668 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4669 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4670   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4671   if (EltSz == 64)
4672     return false;
4673
4674   unsigned NumElts = VT.getVectorNumElements();
4675   WhichResult = (M[0] == 0 ? 0 : 1);
4676   unsigned Idx = WhichResult * NumElts / 2;
4677   for (unsigned i = 0; i != NumElts; i += 2) {
4678     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4679         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4680       return false;
4681     Idx += 1;
4682   }
4683
4684   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4685   if (VT.is64BitVector() && EltSz == 32)
4686     return false;
4687
4688   return true;
4689 }
4690
4691 /// \return true if this is a reverse operation on an vector.
4692 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4693   unsigned NumElts = VT.getVectorNumElements();
4694   // Make sure the mask has the right size.
4695   if (NumElts != M.size())
4696       return false;
4697
4698   // Look for <15, ..., 3, -1, 1, 0>.
4699   for (unsigned i = 0; i != NumElts; ++i)
4700     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4701       return false;
4702
4703   return true;
4704 }
4705
4706 // If N is an integer constant that can be moved into a register in one
4707 // instruction, return an SDValue of such a constant (will become a MOV
4708 // instruction).  Otherwise return null.
4709 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4710                                      const ARMSubtarget *ST, SDLoc dl) {
4711   uint64_t Val;
4712   if (!isa<ConstantSDNode>(N))
4713     return SDValue();
4714   Val = cast<ConstantSDNode>(N)->getZExtValue();
4715
4716   if (ST->isThumb1Only()) {
4717     if (Val <= 255 || ~Val <= 255)
4718       return DAG.getConstant(Val, MVT::i32);
4719   } else {
4720     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4721       return DAG.getConstant(Val, MVT::i32);
4722   }
4723   return SDValue();
4724 }
4725
4726 // If this is a case we can't handle, return null and let the default
4727 // expansion code take care of it.
4728 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4729                                              const ARMSubtarget *ST) const {
4730   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4731   SDLoc dl(Op);
4732   EVT VT = Op.getValueType();
4733
4734   APInt SplatBits, SplatUndef;
4735   unsigned SplatBitSize;
4736   bool HasAnyUndefs;
4737   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4738     if (SplatBitSize <= 64) {
4739       // Check if an immediate VMOV works.
4740       EVT VmovVT;
4741       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4742                                       SplatUndef.getZExtValue(), SplatBitSize,
4743                                       DAG, VmovVT, VT.is128BitVector(),
4744                                       VMOVModImm);
4745       if (Val.getNode()) {
4746         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4747         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4748       }
4749
4750       // Try an immediate VMVN.
4751       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4752       Val = isNEONModifiedImm(NegatedImm,
4753                                       SplatUndef.getZExtValue(), SplatBitSize,
4754                                       DAG, VmovVT, VT.is128BitVector(),
4755                                       VMVNModImm);
4756       if (Val.getNode()) {
4757         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4758         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4759       }
4760
4761       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4762       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4763         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4764         if (ImmVal != -1) {
4765           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4766           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4767         }
4768       }
4769     }
4770   }
4771
4772   // Scan through the operands to see if only one value is used.
4773   //
4774   // As an optimisation, even if more than one value is used it may be more
4775   // profitable to splat with one value then change some lanes.
4776   //
4777   // Heuristically we decide to do this if the vector has a "dominant" value,
4778   // defined as splatted to more than half of the lanes.
4779   unsigned NumElts = VT.getVectorNumElements();
4780   bool isOnlyLowElement = true;
4781   bool usesOnlyOneValue = true;
4782   bool hasDominantValue = false;
4783   bool isConstant = true;
4784
4785   // Map of the number of times a particular SDValue appears in the
4786   // element list.
4787   DenseMap<SDValue, unsigned> ValueCounts;
4788   SDValue Value;
4789   for (unsigned i = 0; i < NumElts; ++i) {
4790     SDValue V = Op.getOperand(i);
4791     if (V.getOpcode() == ISD::UNDEF)
4792       continue;
4793     if (i > 0)
4794       isOnlyLowElement = false;
4795     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4796       isConstant = false;
4797
4798     ValueCounts.insert(std::make_pair(V, 0));
4799     unsigned &Count = ValueCounts[V];
4800
4801     // Is this value dominant? (takes up more than half of the lanes)
4802     if (++Count > (NumElts / 2)) {
4803       hasDominantValue = true;
4804       Value = V;
4805     }
4806   }
4807   if (ValueCounts.size() != 1)
4808     usesOnlyOneValue = false;
4809   if (!Value.getNode() && ValueCounts.size() > 0)
4810     Value = ValueCounts.begin()->first;
4811
4812   if (ValueCounts.size() == 0)
4813     return DAG.getUNDEF(VT);
4814
4815   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4816   // Keep going if we are hitting this case.
4817   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4818     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4819
4820   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4821
4822   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4823   // i32 and try again.
4824   if (hasDominantValue && EltSize <= 32) {
4825     if (!isConstant) {
4826       SDValue N;
4827
4828       // If we are VDUPing a value that comes directly from a vector, that will
4829       // cause an unnecessary move to and from a GPR, where instead we could
4830       // just use VDUPLANE. We can only do this if the lane being extracted
4831       // is at a constant index, as the VDUP from lane instructions only have
4832       // constant-index forms.
4833       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4834           isa<ConstantSDNode>(Value->getOperand(1))) {
4835         // We need to create a new undef vector to use for the VDUPLANE if the
4836         // size of the vector from which we get the value is different than the
4837         // size of the vector that we need to create. We will insert the element
4838         // such that the register coalescer will remove unnecessary copies.
4839         if (VT != Value->getOperand(0).getValueType()) {
4840           ConstantSDNode *constIndex;
4841           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4842           assert(constIndex && "The index is not a constant!");
4843           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4844                              VT.getVectorNumElements();
4845           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4846                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4847                         Value, DAG.getConstant(index, MVT::i32)),
4848                            DAG.getConstant(index, MVT::i32));
4849         } else
4850           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4851                         Value->getOperand(0), Value->getOperand(1));
4852       } else
4853         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4854
4855       if (!usesOnlyOneValue) {
4856         // The dominant value was splatted as 'N', but we now have to insert
4857         // all differing elements.
4858         for (unsigned I = 0; I < NumElts; ++I) {
4859           if (Op.getOperand(I) == Value)
4860             continue;
4861           SmallVector<SDValue, 3> Ops;
4862           Ops.push_back(N);
4863           Ops.push_back(Op.getOperand(I));
4864           Ops.push_back(DAG.getConstant(I, MVT::i32));
4865           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4866         }
4867       }
4868       return N;
4869     }
4870     if (VT.getVectorElementType().isFloatingPoint()) {
4871       SmallVector<SDValue, 8> Ops;
4872       for (unsigned i = 0; i < NumElts; ++i)
4873         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4874                                   Op.getOperand(i)));
4875       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4876       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4877       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4878       if (Val.getNode())
4879         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4880     }
4881     if (usesOnlyOneValue) {
4882       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4883       if (isConstant && Val.getNode())
4884         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4885     }
4886   }
4887
4888   // If all elements are constants and the case above didn't get hit, fall back
4889   // to the default expansion, which will generate a load from the constant
4890   // pool.
4891   if (isConstant)
4892     return SDValue();
4893
4894   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4895   if (NumElts >= 4) {
4896     SDValue shuffle = ReconstructShuffle(Op, DAG);
4897     if (shuffle != SDValue())
4898       return shuffle;
4899   }
4900
4901   // Vectors with 32- or 64-bit elements can be built by directly assigning
4902   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4903   // will be legalized.
4904   if (EltSize >= 32) {
4905     // Do the expansion with floating-point types, since that is what the VFP
4906     // registers are defined to use, and since i64 is not legal.
4907     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4908     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4909     SmallVector<SDValue, 8> Ops;
4910     for (unsigned i = 0; i < NumElts; ++i)
4911       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4912     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4913     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4914   }
4915
4916   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4917   // know the default expansion would otherwise fall back on something even
4918   // worse. For a vector with one or two non-undef values, that's
4919   // scalar_to_vector for the elements followed by a shuffle (provided the
4920   // shuffle is valid for the target) and materialization element by element
4921   // on the stack followed by a load for everything else.
4922   if (!isConstant && !usesOnlyOneValue) {
4923     SDValue Vec = DAG.getUNDEF(VT);
4924     for (unsigned i = 0 ; i < NumElts; ++i) {
4925       SDValue V = Op.getOperand(i);
4926       if (V.getOpcode() == ISD::UNDEF)
4927         continue;
4928       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4929       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4930     }
4931     return Vec;
4932   }
4933
4934   return SDValue();
4935 }
4936
4937 // Gather data to see if the operation can be modelled as a
4938 // shuffle in combination with VEXTs.
4939 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4940                                               SelectionDAG &DAG) const {
4941   SDLoc dl(Op);
4942   EVT VT = Op.getValueType();
4943   unsigned NumElts = VT.getVectorNumElements();
4944
4945   SmallVector<SDValue, 2> SourceVecs;
4946   SmallVector<unsigned, 2> MinElts;
4947   SmallVector<unsigned, 2> MaxElts;
4948
4949   for (unsigned i = 0; i < NumElts; ++i) {
4950     SDValue V = Op.getOperand(i);
4951     if (V.getOpcode() == ISD::UNDEF)
4952       continue;
4953     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4954       // A shuffle can only come from building a vector from various
4955       // elements of other vectors.
4956       return SDValue();
4957     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4958                VT.getVectorElementType()) {
4959       // This code doesn't know how to handle shuffles where the vector
4960       // element types do not match (this happens because type legalization
4961       // promotes the return type of EXTRACT_VECTOR_ELT).
4962       // FIXME: It might be appropriate to extend this code to handle
4963       // mismatched types.
4964       return SDValue();
4965     }
4966
4967     // Record this extraction against the appropriate vector if possible...
4968     SDValue SourceVec = V.getOperand(0);
4969     // If the element number isn't a constant, we can't effectively
4970     // analyze what's going on.
4971     if (!isa<ConstantSDNode>(V.getOperand(1)))
4972       return SDValue();
4973     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4974     bool FoundSource = false;
4975     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4976       if (SourceVecs[j] == SourceVec) {
4977         if (MinElts[j] > EltNo)
4978           MinElts[j] = EltNo;
4979         if (MaxElts[j] < EltNo)
4980           MaxElts[j] = EltNo;
4981         FoundSource = true;
4982         break;
4983       }
4984     }
4985
4986     // Or record a new source if not...
4987     if (!FoundSource) {
4988       SourceVecs.push_back(SourceVec);
4989       MinElts.push_back(EltNo);
4990       MaxElts.push_back(EltNo);
4991     }
4992   }
4993
4994   // Currently only do something sane when at most two source vectors
4995   // involved.
4996   if (SourceVecs.size() > 2)
4997     return SDValue();
4998
4999   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5000   int VEXTOffsets[2] = {0, 0};
5001
5002   // This loop extracts the usage patterns of the source vectors
5003   // and prepares appropriate SDValues for a shuffle if possible.
5004   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5005     if (SourceVecs[i].getValueType() == VT) {
5006       // No VEXT necessary
5007       ShuffleSrcs[i] = SourceVecs[i];
5008       VEXTOffsets[i] = 0;
5009       continue;
5010     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5011       // It probably isn't worth padding out a smaller vector just to
5012       // break it down again in a shuffle.
5013       return SDValue();
5014     }
5015
5016     // Since only 64-bit and 128-bit vectors are legal on ARM and
5017     // we've eliminated the other cases...
5018     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5019            "unexpected vector sizes in ReconstructShuffle");
5020
5021     if (MaxElts[i] - MinElts[i] >= NumElts) {
5022       // Span too large for a VEXT to cope
5023       return SDValue();
5024     }
5025
5026     if (MinElts[i] >= NumElts) {
5027       // The extraction can just take the second half
5028       VEXTOffsets[i] = NumElts;
5029       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5030                                    SourceVecs[i],
5031                                    DAG.getIntPtrConstant(NumElts));
5032     } else if (MaxElts[i] < NumElts) {
5033       // The extraction can just take the first half
5034       VEXTOffsets[i] = 0;
5035       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5036                                    SourceVecs[i],
5037                                    DAG.getIntPtrConstant(0));
5038     } else {
5039       // An actual VEXT is needed
5040       VEXTOffsets[i] = MinElts[i];
5041       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5042                                      SourceVecs[i],
5043                                      DAG.getIntPtrConstant(0));
5044       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5045                                      SourceVecs[i],
5046                                      DAG.getIntPtrConstant(NumElts));
5047       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5048                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5049     }
5050   }
5051
5052   SmallVector<int, 8> Mask;
5053
5054   for (unsigned i = 0; i < NumElts; ++i) {
5055     SDValue Entry = Op.getOperand(i);
5056     if (Entry.getOpcode() == ISD::UNDEF) {
5057       Mask.push_back(-1);
5058       continue;
5059     }
5060
5061     SDValue ExtractVec = Entry.getOperand(0);
5062     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5063                                           .getOperand(1))->getSExtValue();
5064     if (ExtractVec == SourceVecs[0]) {
5065       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5066     } else {
5067       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5068     }
5069   }
5070
5071   // Final check before we try to produce nonsense...
5072   if (isShuffleMaskLegal(Mask, VT))
5073     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5074                                 &Mask[0]);
5075
5076   return SDValue();
5077 }
5078
5079 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5080 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5081 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5082 /// are assumed to be legal.
5083 bool
5084 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5085                                       EVT VT) const {
5086   if (VT.getVectorNumElements() == 4 &&
5087       (VT.is128BitVector() || VT.is64BitVector())) {
5088     unsigned PFIndexes[4];
5089     for (unsigned i = 0; i != 4; ++i) {
5090       if (M[i] < 0)
5091         PFIndexes[i] = 8;
5092       else
5093         PFIndexes[i] = M[i];
5094     }
5095
5096     // Compute the index in the perfect shuffle table.
5097     unsigned PFTableIndex =
5098       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5099     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5100     unsigned Cost = (PFEntry >> 30);
5101
5102     if (Cost <= 4)
5103       return true;
5104   }
5105
5106   bool ReverseVEXT;
5107   unsigned Imm, WhichResult;
5108
5109   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5110   return (EltSize >= 32 ||
5111           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5112           isVREVMask(M, VT, 64) ||
5113           isVREVMask(M, VT, 32) ||
5114           isVREVMask(M, VT, 16) ||
5115           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5116           isVTBLMask(M, VT) ||
5117           isVTRNMask(M, VT, WhichResult) ||
5118           isVUZPMask(M, VT, WhichResult) ||
5119           isVZIPMask(M, VT, WhichResult) ||
5120           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5121           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5122           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5123           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5124 }
5125
5126 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5127 /// the specified operations to build the shuffle.
5128 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5129                                       SDValue RHS, SelectionDAG &DAG,
5130                                       SDLoc dl) {
5131   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5132   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5133   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5134
5135   enum {
5136     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5137     OP_VREV,
5138     OP_VDUP0,
5139     OP_VDUP1,
5140     OP_VDUP2,
5141     OP_VDUP3,
5142     OP_VEXT1,
5143     OP_VEXT2,
5144     OP_VEXT3,
5145     OP_VUZPL, // VUZP, left result
5146     OP_VUZPR, // VUZP, right result
5147     OP_VZIPL, // VZIP, left result
5148     OP_VZIPR, // VZIP, right result
5149     OP_VTRNL, // VTRN, left result
5150     OP_VTRNR  // VTRN, right result
5151   };
5152
5153   if (OpNum == OP_COPY) {
5154     if (LHSID == (1*9+2)*9+3) return LHS;
5155     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5156     return RHS;
5157   }
5158
5159   SDValue OpLHS, OpRHS;
5160   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5161   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5162   EVT VT = OpLHS.getValueType();
5163
5164   switch (OpNum) {
5165   default: llvm_unreachable("Unknown shuffle opcode!");
5166   case OP_VREV:
5167     // VREV divides the vector in half and swaps within the half.
5168     if (VT.getVectorElementType() == MVT::i32 ||
5169         VT.getVectorElementType() == MVT::f32)
5170       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5171     // vrev <4 x i16> -> VREV32
5172     if (VT.getVectorElementType() == MVT::i16)
5173       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5174     // vrev <4 x i8> -> VREV16
5175     assert(VT.getVectorElementType() == MVT::i8);
5176     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5177   case OP_VDUP0:
5178   case OP_VDUP1:
5179   case OP_VDUP2:
5180   case OP_VDUP3:
5181     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5182                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5183   case OP_VEXT1:
5184   case OP_VEXT2:
5185   case OP_VEXT3:
5186     return DAG.getNode(ARMISD::VEXT, dl, VT,
5187                        OpLHS, OpRHS,
5188                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5189   case OP_VUZPL:
5190   case OP_VUZPR:
5191     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5192                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5193   case OP_VZIPL:
5194   case OP_VZIPR:
5195     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5196                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5197   case OP_VTRNL:
5198   case OP_VTRNR:
5199     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5200                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5201   }
5202 }
5203
5204 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5205                                        ArrayRef<int> ShuffleMask,
5206                                        SelectionDAG &DAG) {
5207   // Check to see if we can use the VTBL instruction.
5208   SDValue V1 = Op.getOperand(0);
5209   SDValue V2 = Op.getOperand(1);
5210   SDLoc DL(Op);
5211
5212   SmallVector<SDValue, 8> VTBLMask;
5213   for (ArrayRef<int>::iterator
5214          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5215     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5216
5217   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5218     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5219                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5220                                    &VTBLMask[0], 8));
5221
5222   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5223                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5224                                  &VTBLMask[0], 8));
5225 }
5226
5227 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5228                                                       SelectionDAG &DAG) {
5229   SDLoc DL(Op);
5230   SDValue OpLHS = Op.getOperand(0);
5231   EVT VT = OpLHS.getValueType();
5232
5233   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5234          "Expect an v8i16/v16i8 type");
5235   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5236   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5237   // extract the first 8 bytes into the top double word and the last 8 bytes
5238   // into the bottom double word. The v8i16 case is similar.
5239   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5240   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5241                      DAG.getConstant(ExtractNum, MVT::i32));
5242 }
5243
5244 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5245   SDValue V1 = Op.getOperand(0);
5246   SDValue V2 = Op.getOperand(1);
5247   SDLoc dl(Op);
5248   EVT VT = Op.getValueType();
5249   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5250
5251   // Convert shuffles that are directly supported on NEON to target-specific
5252   // DAG nodes, instead of keeping them as shuffles and matching them again
5253   // during code selection.  This is more efficient and avoids the possibility
5254   // of inconsistencies between legalization and selection.
5255   // FIXME: floating-point vectors should be canonicalized to integer vectors
5256   // of the same time so that they get CSEd properly.
5257   ArrayRef<int> ShuffleMask = SVN->getMask();
5258
5259   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5260   if (EltSize <= 32) {
5261     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5262       int Lane = SVN->getSplatIndex();
5263       // If this is undef splat, generate it via "just" vdup, if possible.
5264       if (Lane == -1) Lane = 0;
5265
5266       // Test if V1 is a SCALAR_TO_VECTOR.
5267       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5268         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5269       }
5270       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5271       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5272       // reaches it).
5273       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5274           !isa<ConstantSDNode>(V1.getOperand(0))) {
5275         bool IsScalarToVector = true;
5276         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5277           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5278             IsScalarToVector = false;
5279             break;
5280           }
5281         if (IsScalarToVector)
5282           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5283       }
5284       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5285                          DAG.getConstant(Lane, MVT::i32));
5286     }
5287
5288     bool ReverseVEXT;
5289     unsigned Imm;
5290     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5291       if (ReverseVEXT)
5292         std::swap(V1, V2);
5293       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5294                          DAG.getConstant(Imm, MVT::i32));
5295     }
5296
5297     if (isVREVMask(ShuffleMask, VT, 64))
5298       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5299     if (isVREVMask(ShuffleMask, VT, 32))
5300       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5301     if (isVREVMask(ShuffleMask, VT, 16))
5302       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5303
5304     if (V2->getOpcode() == ISD::UNDEF &&
5305         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5306       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5307                          DAG.getConstant(Imm, MVT::i32));
5308     }
5309
5310     // Check for Neon shuffles that modify both input vectors in place.
5311     // If both results are used, i.e., if there are two shuffles with the same
5312     // source operands and with masks corresponding to both results of one of
5313     // these operations, DAG memoization will ensure that a single node is
5314     // used for both shuffles.
5315     unsigned WhichResult;
5316     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5317       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5318                          V1, V2).getValue(WhichResult);
5319     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5320       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5321                          V1, V2).getValue(WhichResult);
5322     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5323       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5324                          V1, V2).getValue(WhichResult);
5325
5326     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5327       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5328                          V1, V1).getValue(WhichResult);
5329     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5330       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5331                          V1, V1).getValue(WhichResult);
5332     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5333       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5334                          V1, V1).getValue(WhichResult);
5335   }
5336
5337   // If the shuffle is not directly supported and it has 4 elements, use
5338   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5339   unsigned NumElts = VT.getVectorNumElements();
5340   if (NumElts == 4) {
5341     unsigned PFIndexes[4];
5342     for (unsigned i = 0; i != 4; ++i) {
5343       if (ShuffleMask[i] < 0)
5344         PFIndexes[i] = 8;
5345       else
5346         PFIndexes[i] = ShuffleMask[i];
5347     }
5348
5349     // Compute the index in the perfect shuffle table.
5350     unsigned PFTableIndex =
5351       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5352     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5353     unsigned Cost = (PFEntry >> 30);
5354
5355     if (Cost <= 4)
5356       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5357   }
5358
5359   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5360   if (EltSize >= 32) {
5361     // Do the expansion with floating-point types, since that is what the VFP
5362     // registers are defined to use, and since i64 is not legal.
5363     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5364     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5365     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5366     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5367     SmallVector<SDValue, 8> Ops;
5368     for (unsigned i = 0; i < NumElts; ++i) {
5369       if (ShuffleMask[i] < 0)
5370         Ops.push_back(DAG.getUNDEF(EltVT));
5371       else
5372         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5373                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5374                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5375                                                   MVT::i32)));
5376     }
5377     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5378     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5379   }
5380
5381   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5382     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5383
5384   if (VT == MVT::v8i8) {
5385     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5386     if (NewOp.getNode())
5387       return NewOp;
5388   }
5389
5390   return SDValue();
5391 }
5392
5393 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5394   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5395   SDValue Lane = Op.getOperand(2);
5396   if (!isa<ConstantSDNode>(Lane))
5397     return SDValue();
5398
5399   return Op;
5400 }
5401
5402 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5403   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5404   SDValue Lane = Op.getOperand(1);
5405   if (!isa<ConstantSDNode>(Lane))
5406     return SDValue();
5407
5408   SDValue Vec = Op.getOperand(0);
5409   if (Op.getValueType() == MVT::i32 &&
5410       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5411     SDLoc dl(Op);
5412     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5413   }
5414
5415   return Op;
5416 }
5417
5418 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5419   // The only time a CONCAT_VECTORS operation can have legal types is when
5420   // two 64-bit vectors are concatenated to a 128-bit vector.
5421   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5422          "unexpected CONCAT_VECTORS");
5423   SDLoc dl(Op);
5424   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5425   SDValue Op0 = Op.getOperand(0);
5426   SDValue Op1 = Op.getOperand(1);
5427   if (Op0.getOpcode() != ISD::UNDEF)
5428     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5429                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5430                       DAG.getIntPtrConstant(0));
5431   if (Op1.getOpcode() != ISD::UNDEF)
5432     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5433                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5434                       DAG.getIntPtrConstant(1));
5435   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5436 }
5437
5438 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5439 /// element has been zero/sign-extended, depending on the isSigned parameter,
5440 /// from an integer type half its size.
5441 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5442                                    bool isSigned) {
5443   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5444   EVT VT = N->getValueType(0);
5445   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5446     SDNode *BVN = N->getOperand(0).getNode();
5447     if (BVN->getValueType(0) != MVT::v4i32 ||
5448         BVN->getOpcode() != ISD::BUILD_VECTOR)
5449       return false;
5450     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5451     unsigned HiElt = 1 - LoElt;
5452     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5453     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5454     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5455     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5456     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5457       return false;
5458     if (isSigned) {
5459       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5460           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5461         return true;
5462     } else {
5463       if (Hi0->isNullValue() && Hi1->isNullValue())
5464         return true;
5465     }
5466     return false;
5467   }
5468
5469   if (N->getOpcode() != ISD::BUILD_VECTOR)
5470     return false;
5471
5472   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5473     SDNode *Elt = N->getOperand(i).getNode();
5474     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5475       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5476       unsigned HalfSize = EltSize / 2;
5477       if (isSigned) {
5478         if (!isIntN(HalfSize, C->getSExtValue()))
5479           return false;
5480       } else {
5481         if (!isUIntN(HalfSize, C->getZExtValue()))
5482           return false;
5483       }
5484       continue;
5485     }
5486     return false;
5487   }
5488
5489   return true;
5490 }
5491
5492 /// isSignExtended - Check if a node is a vector value that is sign-extended
5493 /// or a constant BUILD_VECTOR with sign-extended elements.
5494 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5495   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5496     return true;
5497   if (isExtendedBUILD_VECTOR(N, DAG, true))
5498     return true;
5499   return false;
5500 }
5501
5502 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5503 /// or a constant BUILD_VECTOR with zero-extended elements.
5504 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5505   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5506     return true;
5507   if (isExtendedBUILD_VECTOR(N, DAG, false))
5508     return true;
5509   return false;
5510 }
5511
5512 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5513   if (OrigVT.getSizeInBits() >= 64)
5514     return OrigVT;
5515
5516   assert(OrigVT.isSimple() && "Expecting a simple value type");
5517
5518   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5519   switch (OrigSimpleTy) {
5520   default: llvm_unreachable("Unexpected Vector Type");
5521   case MVT::v2i8:
5522   case MVT::v2i16:
5523      return MVT::v2i32;
5524   case MVT::v4i8:
5525     return  MVT::v4i16;
5526   }
5527 }
5528
5529 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5530 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5531 /// We insert the required extension here to get the vector to fill a D register.
5532 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5533                                             const EVT &OrigTy,
5534                                             const EVT &ExtTy,
5535                                             unsigned ExtOpcode) {
5536   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5537   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5538   // 64-bits we need to insert a new extension so that it will be 64-bits.
5539   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5540   if (OrigTy.getSizeInBits() >= 64)
5541     return N;
5542
5543   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5544   EVT NewVT = getExtensionTo64Bits(OrigTy);
5545
5546   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5547 }
5548
5549 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5550 /// does not do any sign/zero extension. If the original vector is less
5551 /// than 64 bits, an appropriate extension will be added after the load to
5552 /// reach a total size of 64 bits. We have to add the extension separately
5553 /// because ARM does not have a sign/zero extending load for vectors.
5554 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5555   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5556
5557   // The load already has the right type.
5558   if (ExtendedTy == LD->getMemoryVT())
5559     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5560                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5561                 LD->isNonTemporal(), LD->isInvariant(),
5562                 LD->getAlignment());
5563
5564   // We need to create a zextload/sextload. We cannot just create a load
5565   // followed by a zext/zext node because LowerMUL is also run during normal
5566   // operation legalization where we can't create illegal types.
5567   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5568                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5569                         LD->getMemoryVT(), LD->isVolatile(),
5570                         LD->isNonTemporal(), LD->getAlignment());
5571 }
5572
5573 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5574 /// extending load, or BUILD_VECTOR with extended elements, return the
5575 /// unextended value. The unextended vector should be 64 bits so that it can
5576 /// be used as an operand to a VMULL instruction. If the original vector size
5577 /// before extension is less than 64 bits we add a an extension to resize
5578 /// the vector to 64 bits.
5579 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5580   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5581     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5582                                         N->getOperand(0)->getValueType(0),
5583                                         N->getValueType(0),
5584                                         N->getOpcode());
5585
5586   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5587     return SkipLoadExtensionForVMULL(LD, DAG);
5588
5589   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5590   // have been legalized as a BITCAST from v4i32.
5591   if (N->getOpcode() == ISD::BITCAST) {
5592     SDNode *BVN = N->getOperand(0).getNode();
5593     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5594            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5595     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5596     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5597                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5598   }
5599   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5600   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5601   EVT VT = N->getValueType(0);
5602   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5603   unsigned NumElts = VT.getVectorNumElements();
5604   MVT TruncVT = MVT::getIntegerVT(EltSize);
5605   SmallVector<SDValue, 8> Ops;
5606   for (unsigned i = 0; i != NumElts; ++i) {
5607     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5608     const APInt &CInt = C->getAPIntValue();
5609     // Element types smaller than 32 bits are not legal, so use i32 elements.
5610     // The values are implicitly truncated so sext vs. zext doesn't matter.
5611     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5612   }
5613   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5614                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5615 }
5616
5617 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5618   unsigned Opcode = N->getOpcode();
5619   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5620     SDNode *N0 = N->getOperand(0).getNode();
5621     SDNode *N1 = N->getOperand(1).getNode();
5622     return N0->hasOneUse() && N1->hasOneUse() &&
5623       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5624   }
5625   return false;
5626 }
5627
5628 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5629   unsigned Opcode = N->getOpcode();
5630   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5631     SDNode *N0 = N->getOperand(0).getNode();
5632     SDNode *N1 = N->getOperand(1).getNode();
5633     return N0->hasOneUse() && N1->hasOneUse() &&
5634       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5635   }
5636   return false;
5637 }
5638
5639 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5640   // Multiplications are only custom-lowered for 128-bit vectors so that
5641   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5642   EVT VT = Op.getValueType();
5643   assert(VT.is128BitVector() && VT.isInteger() &&
5644          "unexpected type for custom-lowering ISD::MUL");
5645   SDNode *N0 = Op.getOperand(0).getNode();
5646   SDNode *N1 = Op.getOperand(1).getNode();
5647   unsigned NewOpc = 0;
5648   bool isMLA = false;
5649   bool isN0SExt = isSignExtended(N0, DAG);
5650   bool isN1SExt = isSignExtended(N1, DAG);
5651   if (isN0SExt && isN1SExt)
5652     NewOpc = ARMISD::VMULLs;
5653   else {
5654     bool isN0ZExt = isZeroExtended(N0, DAG);
5655     bool isN1ZExt = isZeroExtended(N1, DAG);
5656     if (isN0ZExt && isN1ZExt)
5657       NewOpc = ARMISD::VMULLu;
5658     else if (isN1SExt || isN1ZExt) {
5659       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5660       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5661       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5662         NewOpc = ARMISD::VMULLs;
5663         isMLA = true;
5664       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5665         NewOpc = ARMISD::VMULLu;
5666         isMLA = true;
5667       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5668         std::swap(N0, N1);
5669         NewOpc = ARMISD::VMULLu;
5670         isMLA = true;
5671       }
5672     }
5673
5674     if (!NewOpc) {
5675       if (VT == MVT::v2i64)
5676         // Fall through to expand this.  It is not legal.
5677         return SDValue();
5678       else
5679         // Other vector multiplications are legal.
5680         return Op;
5681     }
5682   }
5683
5684   // Legalize to a VMULL instruction.
5685   SDLoc DL(Op);
5686   SDValue Op0;
5687   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5688   if (!isMLA) {
5689     Op0 = SkipExtensionForVMULL(N0, DAG);
5690     assert(Op0.getValueType().is64BitVector() &&
5691            Op1.getValueType().is64BitVector() &&
5692            "unexpected types for extended operands to VMULL");
5693     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5694   }
5695
5696   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5697   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5698   //   vmull q0, d4, d6
5699   //   vmlal q0, d5, d6
5700   // is faster than
5701   //   vaddl q0, d4, d5
5702   //   vmovl q1, d6
5703   //   vmul  q0, q0, q1
5704   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5705   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5706   EVT Op1VT = Op1.getValueType();
5707   return DAG.getNode(N0->getOpcode(), DL, VT,
5708                      DAG.getNode(NewOpc, DL, VT,
5709                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5710                      DAG.getNode(NewOpc, DL, VT,
5711                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5712 }
5713
5714 static SDValue
5715 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5716   // Convert to float
5717   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5718   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5719   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5720   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5721   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5722   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5723   // Get reciprocal estimate.
5724   // float4 recip = vrecpeq_f32(yf);
5725   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5726                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5727   // Because char has a smaller range than uchar, we can actually get away
5728   // without any newton steps.  This requires that we use a weird bias
5729   // of 0xb000, however (again, this has been exhaustively tested).
5730   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5731   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5732   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5733   Y = DAG.getConstant(0xb000, MVT::i32);
5734   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5735   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5736   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5737   // Convert back to short.
5738   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5739   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5740   return X;
5741 }
5742
5743 static SDValue
5744 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5745   SDValue N2;
5746   // Convert to float.
5747   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5748   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5749   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5750   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5751   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5752   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5753
5754   // Use reciprocal estimate and one refinement step.
5755   // float4 recip = vrecpeq_f32(yf);
5756   // recip *= vrecpsq_f32(yf, recip);
5757   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5758                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5759   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5760                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5761                    N1, N2);
5762   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5763   // Because short has a smaller range than ushort, we can actually get away
5764   // with only a single newton step.  This requires that we use a weird bias
5765   // of 89, however (again, this has been exhaustively tested).
5766   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5767   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5768   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5769   N1 = DAG.getConstant(0x89, MVT::i32);
5770   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5771   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5772   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5773   // Convert back to integer and return.
5774   // return vmovn_s32(vcvt_s32_f32(result));
5775   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5776   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5777   return N0;
5778 }
5779
5780 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5781   EVT VT = Op.getValueType();
5782   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5783          "unexpected type for custom-lowering ISD::SDIV");
5784
5785   SDLoc dl(Op);
5786   SDValue N0 = Op.getOperand(0);
5787   SDValue N1 = Op.getOperand(1);
5788   SDValue N2, N3;
5789
5790   if (VT == MVT::v8i8) {
5791     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5792     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5793
5794     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5795                      DAG.getIntPtrConstant(4));
5796     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5797                      DAG.getIntPtrConstant(4));
5798     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5799                      DAG.getIntPtrConstant(0));
5800     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5801                      DAG.getIntPtrConstant(0));
5802
5803     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5804     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5805
5806     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5807     N0 = LowerCONCAT_VECTORS(N0, DAG);
5808
5809     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5810     return N0;
5811   }
5812   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5813 }
5814
5815 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5816   EVT VT = Op.getValueType();
5817   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5818          "unexpected type for custom-lowering ISD::UDIV");
5819
5820   SDLoc dl(Op);
5821   SDValue N0 = Op.getOperand(0);
5822   SDValue N1 = Op.getOperand(1);
5823   SDValue N2, N3;
5824
5825   if (VT == MVT::v8i8) {
5826     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5827     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5828
5829     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5830                      DAG.getIntPtrConstant(4));
5831     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5832                      DAG.getIntPtrConstant(4));
5833     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5834                      DAG.getIntPtrConstant(0));
5835     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5836                      DAG.getIntPtrConstant(0));
5837
5838     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5839     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5840
5841     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5842     N0 = LowerCONCAT_VECTORS(N0, DAG);
5843
5844     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5845                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5846                      N0);
5847     return N0;
5848   }
5849
5850   // v4i16 sdiv ... Convert to float.
5851   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5852   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5853   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5854   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5855   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5856   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5857
5858   // Use reciprocal estimate and two refinement steps.
5859   // float4 recip = vrecpeq_f32(yf);
5860   // recip *= vrecpsq_f32(yf, recip);
5861   // recip *= vrecpsq_f32(yf, recip);
5862   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5863                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5864   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5865                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5866                    BN1, N2);
5867   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5868   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5869                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5870                    BN1, N2);
5871   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5872   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5873   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5874   // and that it will never cause us to return an answer too large).
5875   // float4 result = as_float4(as_int4(xf*recip) + 2);
5876   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5877   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5878   N1 = DAG.getConstant(2, MVT::i32);
5879   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5880   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5881   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5882   // Convert back to integer and return.
5883   // return vmovn_u32(vcvt_s32_f32(result));
5884   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5885   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5886   return N0;
5887 }
5888
5889 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5890   EVT VT = Op.getNode()->getValueType(0);
5891   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5892
5893   unsigned Opc;
5894   bool ExtraOp = false;
5895   switch (Op.getOpcode()) {
5896   default: llvm_unreachable("Invalid code");
5897   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5898   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5899   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5900   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5901   }
5902
5903   if (!ExtraOp)
5904     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5905                        Op.getOperand(1));
5906   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5907                      Op.getOperand(1), Op.getOperand(2));
5908 }
5909
5910 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5911   // Monotonic load/store is legal for all targets
5912   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5913     return Op;
5914
5915   // Aquire/Release load/store is not legal for targets without a
5916   // dmb or equivalent available.
5917   return SDValue();
5918 }
5919
5920 static void
5921 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5922                     SelectionDAG &DAG, unsigned NewOp) {
5923   SDLoc dl(Node);
5924   assert (Node->getValueType(0) == MVT::i64 &&
5925           "Only know how to expand i64 atomics");
5926
5927   SmallVector<SDValue, 6> Ops;
5928   Ops.push_back(Node->getOperand(0)); // Chain
5929   Ops.push_back(Node->getOperand(1)); // Ptr
5930   // Low part of Val1
5931   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5932                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5933   // High part of Val1
5934   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5935                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5936   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5937     // High part of Val1
5938     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5939                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5940     // High part of Val2
5941     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5942                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5943   }
5944   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5945   SDValue Result =
5946     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5947                             cast<MemSDNode>(Node)->getMemOperand());
5948   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5949   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5950   Results.push_back(Result.getValue(2));
5951 }
5952
5953 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5954                                     SmallVectorImpl<SDValue> &Results,
5955                                     SelectionDAG &DAG,
5956                                     const ARMSubtarget *Subtarget) {
5957   SDLoc DL(N);
5958   SDValue Cycles32, OutChain;
5959
5960   if (Subtarget->hasPerfMon()) {
5961     // Under Power Management extensions, the cycle-count is:
5962     //    mrc p15, #0, <Rt>, c9, c13, #0
5963     SDValue Ops[] = { N->getOperand(0), // Chain
5964                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5965                       DAG.getConstant(15, MVT::i32),
5966                       DAG.getConstant(0, MVT::i32),
5967                       DAG.getConstant(9, MVT::i32),
5968                       DAG.getConstant(13, MVT::i32),
5969                       DAG.getConstant(0, MVT::i32)
5970     };
5971
5972     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5973                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5974                            array_lengthof(Ops));
5975     OutChain = Cycles32.getValue(1);
5976   } else {
5977     // Intrinsic is defined to return 0 on unsupported platforms. Technically
5978     // there are older ARM CPUs that have implementation-specific ways of
5979     // obtaining this information (FIXME!).
5980     Cycles32 = DAG.getConstant(0, MVT::i32);
5981     OutChain = DAG.getEntryNode();
5982   }
5983
5984
5985   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5986                                  Cycles32, DAG.getConstant(0, MVT::i32));
5987   Results.push_back(Cycles64);
5988   Results.push_back(OutChain);
5989 }
5990
5991 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5992   switch (Op.getOpcode()) {
5993   default: llvm_unreachable("Don't know how to custom lower this!");
5994   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5995   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5996   case ISD::GlobalAddress:
5997     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5998       LowerGlobalAddressELF(Op, DAG);
5999   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6000   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6001   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6002   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6003   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6004   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6005   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6006   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6007   case ISD::SINT_TO_FP:
6008   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6009   case ISD::FP_TO_SINT:
6010   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6011   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6012   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6013   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6014   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6015   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6016   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6017   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6018                                                                Subtarget);
6019   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6020   case ISD::SHL:
6021   case ISD::SRL:
6022   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6023   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6024   case ISD::SRL_PARTS:
6025   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6026   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6027   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6028   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6029   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6030   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6031   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6032   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6033   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6034   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6035   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6036   case ISD::MUL:           return LowerMUL(Op, DAG);
6037   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6038   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6039   case ISD::ADDC:
6040   case ISD::ADDE:
6041   case ISD::SUBC:
6042   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6043   case ISD::ATOMIC_LOAD:
6044   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6045   case ISD::SDIVREM:
6046   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6047   }
6048 }
6049
6050 /// ReplaceNodeResults - Replace the results of node with an illegal result
6051 /// type with new values built out of custom code.
6052 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6053                                            SmallVectorImpl<SDValue>&Results,
6054                                            SelectionDAG &DAG) const {
6055   SDValue Res;
6056   switch (N->getOpcode()) {
6057   default:
6058     llvm_unreachable("Don't know how to custom expand this!");
6059   case ISD::BITCAST:
6060     Res = ExpandBITCAST(N, DAG);
6061     break;
6062   case ISD::SIGN_EXTEND:
6063   case ISD::ZERO_EXTEND:
6064     Res = ExpandVectorExtension(N, DAG);
6065     break;
6066   case ISD::SRL:
6067   case ISD::SRA:
6068     Res = Expand64BitShift(N, DAG, Subtarget);
6069     break;
6070   case ISD::READCYCLECOUNTER:
6071     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6072     return;
6073   case ISD::ATOMIC_LOAD_ADD:
6074     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
6075     return;
6076   case ISD::ATOMIC_LOAD_AND:
6077     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
6078     return;
6079   case ISD::ATOMIC_LOAD_NAND:
6080     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
6081     return;
6082   case ISD::ATOMIC_LOAD_OR:
6083     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
6084     return;
6085   case ISD::ATOMIC_LOAD_SUB:
6086     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
6087     return;
6088   case ISD::ATOMIC_LOAD_XOR:
6089     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
6090     return;
6091   case ISD::ATOMIC_SWAP:
6092     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
6093     return;
6094   case ISD::ATOMIC_CMP_SWAP:
6095     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
6096     return;
6097   case ISD::ATOMIC_LOAD_MIN:
6098     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
6099     return;
6100   case ISD::ATOMIC_LOAD_UMIN:
6101     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
6102     return;
6103   case ISD::ATOMIC_LOAD_MAX:
6104     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
6105     return;
6106   case ISD::ATOMIC_LOAD_UMAX:
6107     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
6108     return;
6109   }
6110   if (Res.getNode())
6111     Results.push_back(Res);
6112 }
6113
6114 //===----------------------------------------------------------------------===//
6115 //                           ARM Scheduler Hooks
6116 //===----------------------------------------------------------------------===//
6117
6118 MachineBasicBlock *
6119 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6120                                      MachineBasicBlock *BB,
6121                                      unsigned Size) const {
6122   unsigned dest    = MI->getOperand(0).getReg();
6123   unsigned ptr     = MI->getOperand(1).getReg();
6124   unsigned oldval  = MI->getOperand(2).getReg();
6125   unsigned newval  = MI->getOperand(3).getReg();
6126   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6127   DebugLoc dl = MI->getDebugLoc();
6128   bool isThumb2 = Subtarget->isThumb2();
6129
6130   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6131   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6132     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6133     (const TargetRegisterClass*)&ARM::GPRRegClass);
6134
6135   if (isThumb2) {
6136     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6137     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6138     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6139   }
6140
6141   unsigned ldrOpc, strOpc;
6142   switch (Size) {
6143   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6144   case 1:
6145     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6146     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6147     break;
6148   case 2:
6149     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6150     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6151     break;
6152   case 4:
6153     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6154     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6155     break;
6156   }
6157
6158   MachineFunction *MF = BB->getParent();
6159   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6160   MachineFunction::iterator It = BB;
6161   ++It; // insert the new blocks after the current block
6162
6163   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6164   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6165   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6166   MF->insert(It, loop1MBB);
6167   MF->insert(It, loop2MBB);
6168   MF->insert(It, exitMBB);
6169
6170   // Transfer the remainder of BB and its successor edges to exitMBB.
6171   exitMBB->splice(exitMBB->begin(), BB,
6172                   llvm::next(MachineBasicBlock::iterator(MI)),
6173                   BB->end());
6174   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6175
6176   //  thisMBB:
6177   //   ...
6178   //   fallthrough --> loop1MBB
6179   BB->addSuccessor(loop1MBB);
6180
6181   // loop1MBB:
6182   //   ldrex dest, [ptr]
6183   //   cmp dest, oldval
6184   //   bne exitMBB
6185   BB = loop1MBB;
6186   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6187   if (ldrOpc == ARM::t2LDREX)
6188     MIB.addImm(0);
6189   AddDefaultPred(MIB);
6190   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6191                  .addReg(dest).addReg(oldval));
6192   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6193     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6194   BB->addSuccessor(loop2MBB);
6195   BB->addSuccessor(exitMBB);
6196
6197   // loop2MBB:
6198   //   strex scratch, newval, [ptr]
6199   //   cmp scratch, #0
6200   //   bne loop1MBB
6201   BB = loop2MBB;
6202   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6203   if (strOpc == ARM::t2STREX)
6204     MIB.addImm(0);
6205   AddDefaultPred(MIB);
6206   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6207                  .addReg(scratch).addImm(0));
6208   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6209     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6210   BB->addSuccessor(loop1MBB);
6211   BB->addSuccessor(exitMBB);
6212
6213   //  exitMBB:
6214   //   ...
6215   BB = exitMBB;
6216
6217   MI->eraseFromParent();   // The instruction is gone now.
6218
6219   return BB;
6220 }
6221
6222 MachineBasicBlock *
6223 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6224                                     unsigned Size, unsigned BinOpcode) const {
6225   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6226   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6227
6228   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6229   MachineFunction *MF = BB->getParent();
6230   MachineFunction::iterator It = BB;
6231   ++It;
6232
6233   unsigned dest = MI->getOperand(0).getReg();
6234   unsigned ptr = MI->getOperand(1).getReg();
6235   unsigned incr = MI->getOperand(2).getReg();
6236   DebugLoc dl = MI->getDebugLoc();
6237   bool isThumb2 = Subtarget->isThumb2();
6238
6239   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6240   if (isThumb2) {
6241     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6242     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6243   }
6244
6245   unsigned ldrOpc, strOpc;
6246   switch (Size) {
6247   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6248   case 1:
6249     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6250     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6251     break;
6252   case 2:
6253     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6254     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6255     break;
6256   case 4:
6257     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6258     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6259     break;
6260   }
6261
6262   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6263   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6264   MF->insert(It, loopMBB);
6265   MF->insert(It, exitMBB);
6266
6267   // Transfer the remainder of BB and its successor edges to exitMBB.
6268   exitMBB->splice(exitMBB->begin(), BB,
6269                   llvm::next(MachineBasicBlock::iterator(MI)),
6270                   BB->end());
6271   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6272
6273   const TargetRegisterClass *TRC = isThumb2 ?
6274     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6275     (const TargetRegisterClass*)&ARM::GPRRegClass;
6276   unsigned scratch = MRI.createVirtualRegister(TRC);
6277   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6278
6279   //  thisMBB:
6280   //   ...
6281   //   fallthrough --> loopMBB
6282   BB->addSuccessor(loopMBB);
6283
6284   //  loopMBB:
6285   //   ldrex dest, ptr
6286   //   <binop> scratch2, dest, incr
6287   //   strex scratch, scratch2, ptr
6288   //   cmp scratch, #0
6289   //   bne- loopMBB
6290   //   fallthrough --> exitMBB
6291   BB = loopMBB;
6292   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6293   if (ldrOpc == ARM::t2LDREX)
6294     MIB.addImm(0);
6295   AddDefaultPred(MIB);
6296   if (BinOpcode) {
6297     // operand order needs to go the other way for NAND
6298     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6299       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6300                      addReg(incr).addReg(dest)).addReg(0);
6301     else
6302       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6303                      addReg(dest).addReg(incr)).addReg(0);
6304   }
6305
6306   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6307   if (strOpc == ARM::t2STREX)
6308     MIB.addImm(0);
6309   AddDefaultPred(MIB);
6310   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6311                  .addReg(scratch).addImm(0));
6312   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6313     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6314
6315   BB->addSuccessor(loopMBB);
6316   BB->addSuccessor(exitMBB);
6317
6318   //  exitMBB:
6319   //   ...
6320   BB = exitMBB;
6321
6322   MI->eraseFromParent();   // The instruction is gone now.
6323
6324   return BB;
6325 }
6326
6327 MachineBasicBlock *
6328 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6329                                           MachineBasicBlock *BB,
6330                                           unsigned Size,
6331                                           bool signExtend,
6332                                           ARMCC::CondCodes Cond) const {
6333   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6334
6335   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6336   MachineFunction *MF = BB->getParent();
6337   MachineFunction::iterator It = BB;
6338   ++It;
6339
6340   unsigned dest = MI->getOperand(0).getReg();
6341   unsigned ptr = MI->getOperand(1).getReg();
6342   unsigned incr = MI->getOperand(2).getReg();
6343   unsigned oldval = dest;
6344   DebugLoc dl = MI->getDebugLoc();
6345   bool isThumb2 = Subtarget->isThumb2();
6346
6347   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6348   if (isThumb2) {
6349     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6350     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6351   }
6352
6353   unsigned ldrOpc, strOpc, extendOpc;
6354   switch (Size) {
6355   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6356   case 1:
6357     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6358     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6359     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6360     break;
6361   case 2:
6362     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6363     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6364     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6365     break;
6366   case 4:
6367     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6368     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6369     extendOpc = 0;
6370     break;
6371   }
6372
6373   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6374   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6375   MF->insert(It, loopMBB);
6376   MF->insert(It, exitMBB);
6377
6378   // Transfer the remainder of BB and its successor edges to exitMBB.
6379   exitMBB->splice(exitMBB->begin(), BB,
6380                   llvm::next(MachineBasicBlock::iterator(MI)),
6381                   BB->end());
6382   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6383
6384   const TargetRegisterClass *TRC = isThumb2 ?
6385     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6386     (const TargetRegisterClass*)&ARM::GPRRegClass;
6387   unsigned scratch = MRI.createVirtualRegister(TRC);
6388   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6389
6390   //  thisMBB:
6391   //   ...
6392   //   fallthrough --> loopMBB
6393   BB->addSuccessor(loopMBB);
6394
6395   //  loopMBB:
6396   //   ldrex dest, ptr
6397   //   (sign extend dest, if required)
6398   //   cmp dest, incr
6399   //   cmov.cond scratch2, incr, dest
6400   //   strex scratch, scratch2, ptr
6401   //   cmp scratch, #0
6402   //   bne- loopMBB
6403   //   fallthrough --> exitMBB
6404   BB = loopMBB;
6405   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6406   if (ldrOpc == ARM::t2LDREX)
6407     MIB.addImm(0);
6408   AddDefaultPred(MIB);
6409
6410   // Sign extend the value, if necessary.
6411   if (signExtend && extendOpc) {
6412     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6413     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6414                      .addReg(dest)
6415                      .addImm(0));
6416   }
6417
6418   // Build compare and cmov instructions.
6419   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6420                  .addReg(oldval).addReg(incr));
6421   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6422          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6423
6424   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6425   if (strOpc == ARM::t2STREX)
6426     MIB.addImm(0);
6427   AddDefaultPred(MIB);
6428   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6429                  .addReg(scratch).addImm(0));
6430   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6431     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6432
6433   BB->addSuccessor(loopMBB);
6434   BB->addSuccessor(exitMBB);
6435
6436   //  exitMBB:
6437   //   ...
6438   BB = exitMBB;
6439
6440   MI->eraseFromParent();   // The instruction is gone now.
6441
6442   return BB;
6443 }
6444
6445 MachineBasicBlock *
6446 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6447                                       unsigned Op1, unsigned Op2,
6448                                       bool NeedsCarry, bool IsCmpxchg,
6449                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6450   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6451   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6452
6453   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6454   MachineFunction *MF = BB->getParent();
6455   MachineFunction::iterator It = BB;
6456   ++It;
6457
6458   unsigned destlo = MI->getOperand(0).getReg();
6459   unsigned desthi = MI->getOperand(1).getReg();
6460   unsigned ptr = MI->getOperand(2).getReg();
6461   unsigned vallo = MI->getOperand(3).getReg();
6462   unsigned valhi = MI->getOperand(4).getReg();
6463   DebugLoc dl = MI->getDebugLoc();
6464   bool isThumb2 = Subtarget->isThumb2();
6465
6466   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6467   if (isThumb2) {
6468     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6469     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6470     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6471     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6472     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6473   }
6474
6475   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6476   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6477   if (IsCmpxchg || IsMinMax)
6478     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6479   if (IsCmpxchg)
6480     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6481   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6482
6483   MF->insert(It, loopMBB);
6484   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6485   if (IsCmpxchg) MF->insert(It, cont2BB);
6486   MF->insert(It, exitMBB);
6487
6488   // Transfer the remainder of BB and its successor edges to exitMBB.
6489   exitMBB->splice(exitMBB->begin(), BB,
6490                   llvm::next(MachineBasicBlock::iterator(MI)),
6491                   BB->end());
6492   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6493
6494   const TargetRegisterClass *TRC = isThumb2 ?
6495     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6496     (const TargetRegisterClass*)&ARM::GPRRegClass;
6497   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6498
6499   //  thisMBB:
6500   //   ...
6501   //   fallthrough --> loopMBB
6502   BB->addSuccessor(loopMBB);
6503
6504   //  loopMBB:
6505   //   ldrexd r2, r3, ptr
6506   //   <binopa> r0, r2, incr
6507   //   <binopb> r1, r3, incr
6508   //   strexd storesuccess, r0, r1, ptr
6509   //   cmp storesuccess, #0
6510   //   bne- loopMBB
6511   //   fallthrough --> exitMBB
6512   BB = loopMBB;
6513
6514   // Load
6515   if (isThumb2) {
6516     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6517                    .addReg(destlo, RegState::Define)
6518                    .addReg(desthi, RegState::Define)
6519                    .addReg(ptr));
6520   } else {
6521     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6522     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6523                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6524     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6525     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6526       .addReg(GPRPair0, 0, ARM::gsub_0);
6527     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6528       .addReg(GPRPair0, 0, ARM::gsub_1);
6529   }
6530
6531   unsigned StoreLo, StoreHi;
6532   if (IsCmpxchg) {
6533     // Add early exit
6534     for (unsigned i = 0; i < 2; i++) {
6535       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6536                                                          ARM::CMPrr))
6537                      .addReg(i == 0 ? destlo : desthi)
6538                      .addReg(i == 0 ? vallo : valhi));
6539       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6540         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6541       BB->addSuccessor(exitMBB);
6542       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6543       BB = (i == 0 ? contBB : cont2BB);
6544     }
6545
6546     // Copy to physregs for strexd
6547     StoreLo = MI->getOperand(5).getReg();
6548     StoreHi = MI->getOperand(6).getReg();
6549   } else if (Op1) {
6550     // Perform binary operation
6551     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6552     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6553                    .addReg(destlo).addReg(vallo))
6554         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6555     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6556     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6557                    .addReg(desthi).addReg(valhi))
6558         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6559
6560     StoreLo = tmpRegLo;
6561     StoreHi = tmpRegHi;
6562   } else {
6563     // Copy to physregs for strexd
6564     StoreLo = vallo;
6565     StoreHi = valhi;
6566   }
6567   if (IsMinMax) {
6568     // Compare and branch to exit block.
6569     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6570       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6571     BB->addSuccessor(exitMBB);
6572     BB->addSuccessor(contBB);
6573     BB = contBB;
6574     StoreLo = vallo;
6575     StoreHi = valhi;
6576   }
6577
6578   // Store
6579   if (isThumb2) {
6580     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6581     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6582     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6583                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6584   } else {
6585     // Marshal a pair...
6586     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6587     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6588     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6589     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6590     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6591       .addReg(UndefPair)
6592       .addReg(StoreLo)
6593       .addImm(ARM::gsub_0);
6594     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6595       .addReg(r1)
6596       .addReg(StoreHi)
6597       .addImm(ARM::gsub_1);
6598
6599     // ...and store it
6600     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6601                    .addReg(StorePair).addReg(ptr));
6602   }
6603   // Cmp+jump
6604   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6605                  .addReg(storesuccess).addImm(0));
6606   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6607     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6608
6609   BB->addSuccessor(loopMBB);
6610   BB->addSuccessor(exitMBB);
6611
6612   //  exitMBB:
6613   //   ...
6614   BB = exitMBB;
6615
6616   MI->eraseFromParent();   // The instruction is gone now.
6617
6618   return BB;
6619 }
6620
6621 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6622 /// registers the function context.
6623 void ARMTargetLowering::
6624 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6625                        MachineBasicBlock *DispatchBB, int FI) const {
6626   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6627   DebugLoc dl = MI->getDebugLoc();
6628   MachineFunction *MF = MBB->getParent();
6629   MachineRegisterInfo *MRI = &MF->getRegInfo();
6630   MachineConstantPool *MCP = MF->getConstantPool();
6631   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6632   const Function *F = MF->getFunction();
6633
6634   bool isThumb = Subtarget->isThumb();
6635   bool isThumb2 = Subtarget->isThumb2();
6636
6637   unsigned PCLabelId = AFI->createPICLabelUId();
6638   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6639   ARMConstantPoolValue *CPV =
6640     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6641   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6642
6643   const TargetRegisterClass *TRC = isThumb ?
6644     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6645     (const TargetRegisterClass*)&ARM::GPRRegClass;
6646
6647   // Grab constant pool and fixed stack memory operands.
6648   MachineMemOperand *CPMMO =
6649     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6650                              MachineMemOperand::MOLoad, 4, 4);
6651
6652   MachineMemOperand *FIMMOSt =
6653     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6654                              MachineMemOperand::MOStore, 4, 4);
6655
6656   // Load the address of the dispatch MBB into the jump buffer.
6657   if (isThumb2) {
6658     // Incoming value: jbuf
6659     //   ldr.n  r5, LCPI1_1
6660     //   orr    r5, r5, #1
6661     //   add    r5, pc
6662     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6663     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6664     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6665                    .addConstantPoolIndex(CPI)
6666                    .addMemOperand(CPMMO));
6667     // Set the low bit because of thumb mode.
6668     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6669     AddDefaultCC(
6670       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6671                      .addReg(NewVReg1, RegState::Kill)
6672                      .addImm(0x01)));
6673     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6674     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6675       .addReg(NewVReg2, RegState::Kill)
6676       .addImm(PCLabelId);
6677     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6678                    .addReg(NewVReg3, RegState::Kill)
6679                    .addFrameIndex(FI)
6680                    .addImm(36)  // &jbuf[1] :: pc
6681                    .addMemOperand(FIMMOSt));
6682   } else if (isThumb) {
6683     // Incoming value: jbuf
6684     //   ldr.n  r1, LCPI1_4
6685     //   add    r1, pc
6686     //   mov    r2, #1
6687     //   orrs   r1, r2
6688     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6689     //   str    r1, [r2]
6690     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6691     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6692                    .addConstantPoolIndex(CPI)
6693                    .addMemOperand(CPMMO));
6694     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6695     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6696       .addReg(NewVReg1, RegState::Kill)
6697       .addImm(PCLabelId);
6698     // Set the low bit because of thumb mode.
6699     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6700     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6701                    .addReg(ARM::CPSR, RegState::Define)
6702                    .addImm(1));
6703     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6704     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6705                    .addReg(ARM::CPSR, RegState::Define)
6706                    .addReg(NewVReg2, RegState::Kill)
6707                    .addReg(NewVReg3, RegState::Kill));
6708     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6709     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6710                    .addFrameIndex(FI)
6711                    .addImm(36)); // &jbuf[1] :: pc
6712     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6713                    .addReg(NewVReg4, RegState::Kill)
6714                    .addReg(NewVReg5, RegState::Kill)
6715                    .addImm(0)
6716                    .addMemOperand(FIMMOSt));
6717   } else {
6718     // Incoming value: jbuf
6719     //   ldr  r1, LCPI1_1
6720     //   add  r1, pc, r1
6721     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6722     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6723     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6724                    .addConstantPoolIndex(CPI)
6725                    .addImm(0)
6726                    .addMemOperand(CPMMO));
6727     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6728     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6729                    .addReg(NewVReg1, RegState::Kill)
6730                    .addImm(PCLabelId));
6731     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6732                    .addReg(NewVReg2, RegState::Kill)
6733                    .addFrameIndex(FI)
6734                    .addImm(36)  // &jbuf[1] :: pc
6735                    .addMemOperand(FIMMOSt));
6736   }
6737 }
6738
6739 MachineBasicBlock *ARMTargetLowering::
6740 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6741   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6742   DebugLoc dl = MI->getDebugLoc();
6743   MachineFunction *MF = MBB->getParent();
6744   MachineRegisterInfo *MRI = &MF->getRegInfo();
6745   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6746   MachineFrameInfo *MFI = MF->getFrameInfo();
6747   int FI = MFI->getFunctionContextIndex();
6748
6749   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6750     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6751     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6752
6753   // Get a mapping of the call site numbers to all of the landing pads they're
6754   // associated with.
6755   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6756   unsigned MaxCSNum = 0;
6757   MachineModuleInfo &MMI = MF->getMMI();
6758   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6759        ++BB) {
6760     if (!BB->isLandingPad()) continue;
6761
6762     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6763     // pad.
6764     for (MachineBasicBlock::iterator
6765            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6766       if (!II->isEHLabel()) continue;
6767
6768       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6769       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6770
6771       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6772       for (SmallVectorImpl<unsigned>::iterator
6773              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6774            CSI != CSE; ++CSI) {
6775         CallSiteNumToLPad[*CSI].push_back(BB);
6776         MaxCSNum = std::max(MaxCSNum, *CSI);
6777       }
6778       break;
6779     }
6780   }
6781
6782   // Get an ordered list of the machine basic blocks for the jump table.
6783   std::vector<MachineBasicBlock*> LPadList;
6784   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6785   LPadList.reserve(CallSiteNumToLPad.size());
6786   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6787     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6788     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6789            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6790       LPadList.push_back(*II);
6791       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6792     }
6793   }
6794
6795   assert(!LPadList.empty() &&
6796          "No landing pad destinations for the dispatch jump table!");
6797
6798   // Create the jump table and associated information.
6799   MachineJumpTableInfo *JTI =
6800     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6801   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6802   unsigned UId = AFI->createJumpTableUId();
6803   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6804
6805   // Create the MBBs for the dispatch code.
6806
6807   // Shove the dispatch's address into the return slot in the function context.
6808   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6809   DispatchBB->setIsLandingPad();
6810
6811   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6812   unsigned trap_opcode;
6813   if (Subtarget->isThumb())
6814     trap_opcode = ARM::tTRAP;
6815   else
6816     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6817
6818   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6819   DispatchBB->addSuccessor(TrapBB);
6820
6821   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6822   DispatchBB->addSuccessor(DispContBB);
6823
6824   // Insert and MBBs.
6825   MF->insert(MF->end(), DispatchBB);
6826   MF->insert(MF->end(), DispContBB);
6827   MF->insert(MF->end(), TrapBB);
6828
6829   // Insert code into the entry block that creates and registers the function
6830   // context.
6831   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6832
6833   MachineMemOperand *FIMMOLd =
6834     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6835                              MachineMemOperand::MOLoad |
6836                              MachineMemOperand::MOVolatile, 4, 4);
6837
6838   MachineInstrBuilder MIB;
6839   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6840
6841   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6842   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6843
6844   // Add a register mask with no preserved registers.  This results in all
6845   // registers being marked as clobbered.
6846   MIB.addRegMask(RI.getNoPreservedMask());
6847
6848   unsigned NumLPads = LPadList.size();
6849   if (Subtarget->isThumb2()) {
6850     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6851     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6852                    .addFrameIndex(FI)
6853                    .addImm(4)
6854                    .addMemOperand(FIMMOLd));
6855
6856     if (NumLPads < 256) {
6857       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6858                      .addReg(NewVReg1)
6859                      .addImm(LPadList.size()));
6860     } else {
6861       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6862       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6863                      .addImm(NumLPads & 0xFFFF));
6864
6865       unsigned VReg2 = VReg1;
6866       if ((NumLPads & 0xFFFF0000) != 0) {
6867         VReg2 = MRI->createVirtualRegister(TRC);
6868         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6869                        .addReg(VReg1)
6870                        .addImm(NumLPads >> 16));
6871       }
6872
6873       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6874                      .addReg(NewVReg1)
6875                      .addReg(VReg2));
6876     }
6877
6878     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6879       .addMBB(TrapBB)
6880       .addImm(ARMCC::HI)
6881       .addReg(ARM::CPSR);
6882
6883     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6884     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6885                    .addJumpTableIndex(MJTI)
6886                    .addImm(UId));
6887
6888     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6889     AddDefaultCC(
6890       AddDefaultPred(
6891         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6892         .addReg(NewVReg3, RegState::Kill)
6893         .addReg(NewVReg1)
6894         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6895
6896     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6897       .addReg(NewVReg4, RegState::Kill)
6898       .addReg(NewVReg1)
6899       .addJumpTableIndex(MJTI)
6900       .addImm(UId);
6901   } else if (Subtarget->isThumb()) {
6902     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6903     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6904                    .addFrameIndex(FI)
6905                    .addImm(1)
6906                    .addMemOperand(FIMMOLd));
6907
6908     if (NumLPads < 256) {
6909       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6910                      .addReg(NewVReg1)
6911                      .addImm(NumLPads));
6912     } else {
6913       MachineConstantPool *ConstantPool = MF->getConstantPool();
6914       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6915       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6916
6917       // MachineConstantPool wants an explicit alignment.
6918       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6919       if (Align == 0)
6920         Align = getDataLayout()->getTypeAllocSize(C->getType());
6921       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6922
6923       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6924       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6925                      .addReg(VReg1, RegState::Define)
6926                      .addConstantPoolIndex(Idx));
6927       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6928                      .addReg(NewVReg1)
6929                      .addReg(VReg1));
6930     }
6931
6932     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6933       .addMBB(TrapBB)
6934       .addImm(ARMCC::HI)
6935       .addReg(ARM::CPSR);
6936
6937     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6938     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6939                    .addReg(ARM::CPSR, RegState::Define)
6940                    .addReg(NewVReg1)
6941                    .addImm(2));
6942
6943     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6944     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6945                    .addJumpTableIndex(MJTI)
6946                    .addImm(UId));
6947
6948     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6949     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6950                    .addReg(ARM::CPSR, RegState::Define)
6951                    .addReg(NewVReg2, RegState::Kill)
6952                    .addReg(NewVReg3));
6953
6954     MachineMemOperand *JTMMOLd =
6955       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6956                                MachineMemOperand::MOLoad, 4, 4);
6957
6958     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6959     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6960                    .addReg(NewVReg4, RegState::Kill)
6961                    .addImm(0)
6962                    .addMemOperand(JTMMOLd));
6963
6964     unsigned NewVReg6 = NewVReg5;
6965     if (RelocM == Reloc::PIC_) {
6966       NewVReg6 = MRI->createVirtualRegister(TRC);
6967       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6968                      .addReg(ARM::CPSR, RegState::Define)
6969                      .addReg(NewVReg5, RegState::Kill)
6970                      .addReg(NewVReg3));
6971     }
6972
6973     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6974       .addReg(NewVReg6, RegState::Kill)
6975       .addJumpTableIndex(MJTI)
6976       .addImm(UId);
6977   } else {
6978     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6979     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6980                    .addFrameIndex(FI)
6981                    .addImm(4)
6982                    .addMemOperand(FIMMOLd));
6983
6984     if (NumLPads < 256) {
6985       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6986                      .addReg(NewVReg1)
6987                      .addImm(NumLPads));
6988     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6989       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6990       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6991                      .addImm(NumLPads & 0xFFFF));
6992
6993       unsigned VReg2 = VReg1;
6994       if ((NumLPads & 0xFFFF0000) != 0) {
6995         VReg2 = MRI->createVirtualRegister(TRC);
6996         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6997                        .addReg(VReg1)
6998                        .addImm(NumLPads >> 16));
6999       }
7000
7001       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7002                      .addReg(NewVReg1)
7003                      .addReg(VReg2));
7004     } else {
7005       MachineConstantPool *ConstantPool = MF->getConstantPool();
7006       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7007       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7008
7009       // MachineConstantPool wants an explicit alignment.
7010       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7011       if (Align == 0)
7012         Align = getDataLayout()->getTypeAllocSize(C->getType());
7013       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7014
7015       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7016       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7017                      .addReg(VReg1, RegState::Define)
7018                      .addConstantPoolIndex(Idx)
7019                      .addImm(0));
7020       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7021                      .addReg(NewVReg1)
7022                      .addReg(VReg1, RegState::Kill));
7023     }
7024
7025     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7026       .addMBB(TrapBB)
7027       .addImm(ARMCC::HI)
7028       .addReg(ARM::CPSR);
7029
7030     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7031     AddDefaultCC(
7032       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7033                      .addReg(NewVReg1)
7034                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7035     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7036     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7037                    .addJumpTableIndex(MJTI)
7038                    .addImm(UId));
7039
7040     MachineMemOperand *JTMMOLd =
7041       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7042                                MachineMemOperand::MOLoad, 4, 4);
7043     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7044     AddDefaultPred(
7045       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7046       .addReg(NewVReg3, RegState::Kill)
7047       .addReg(NewVReg4)
7048       .addImm(0)
7049       .addMemOperand(JTMMOLd));
7050
7051     if (RelocM == Reloc::PIC_) {
7052       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7053         .addReg(NewVReg5, RegState::Kill)
7054         .addReg(NewVReg4)
7055         .addJumpTableIndex(MJTI)
7056         .addImm(UId);
7057     } else {
7058       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7059         .addReg(NewVReg5, RegState::Kill)
7060         .addJumpTableIndex(MJTI)
7061         .addImm(UId);
7062     }
7063   }
7064
7065   // Add the jump table entries as successors to the MBB.
7066   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7067   for (std::vector<MachineBasicBlock*>::iterator
7068          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7069     MachineBasicBlock *CurMBB = *I;
7070     if (SeenMBBs.insert(CurMBB))
7071       DispContBB->addSuccessor(CurMBB);
7072   }
7073
7074   // N.B. the order the invoke BBs are processed in doesn't matter here.
7075   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7076   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7077   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7078          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7079     MachineBasicBlock *BB = *I;
7080
7081     // Remove the landing pad successor from the invoke block and replace it
7082     // with the new dispatch block.
7083     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7084                                                   BB->succ_end());
7085     while (!Successors.empty()) {
7086       MachineBasicBlock *SMBB = Successors.pop_back_val();
7087       if (SMBB->isLandingPad()) {
7088         BB->removeSuccessor(SMBB);
7089         MBBLPads.push_back(SMBB);
7090       }
7091     }
7092
7093     BB->addSuccessor(DispatchBB);
7094
7095     // Find the invoke call and mark all of the callee-saved registers as
7096     // 'implicit defined' so that they're spilled. This prevents code from
7097     // moving instructions to before the EH block, where they will never be
7098     // executed.
7099     for (MachineBasicBlock::reverse_iterator
7100            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7101       if (!II->isCall()) continue;
7102
7103       DenseMap<unsigned, bool> DefRegs;
7104       for (MachineInstr::mop_iterator
7105              OI = II->operands_begin(), OE = II->operands_end();
7106            OI != OE; ++OI) {
7107         if (!OI->isReg()) continue;
7108         DefRegs[OI->getReg()] = true;
7109       }
7110
7111       MachineInstrBuilder MIB(*MF, &*II);
7112
7113       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7114         unsigned Reg = SavedRegs[i];
7115         if (Subtarget->isThumb2() &&
7116             !ARM::tGPRRegClass.contains(Reg) &&
7117             !ARM::hGPRRegClass.contains(Reg))
7118           continue;
7119         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7120           continue;
7121         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7122           continue;
7123         if (!DefRegs[Reg])
7124           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7125       }
7126
7127       break;
7128     }
7129   }
7130
7131   // Mark all former landing pads as non-landing pads. The dispatch is the only
7132   // landing pad now.
7133   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7134          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7135     (*I)->setIsLandingPad(false);
7136
7137   // The instruction is gone now.
7138   MI->eraseFromParent();
7139
7140   return MBB;
7141 }
7142
7143 static
7144 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7145   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7146        E = MBB->succ_end(); I != E; ++I)
7147     if (*I != Succ)
7148       return *I;
7149   llvm_unreachable("Expecting a BB with two successors!");
7150 }
7151
7152 MachineBasicBlock *ARMTargetLowering::
7153 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
7154   // This pseudo instruction has 3 operands: dst, src, size
7155   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7156   // Otherwise, we will generate unrolled scalar copies.
7157   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7158   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7159   MachineFunction::iterator It = BB;
7160   ++It;
7161
7162   unsigned dest = MI->getOperand(0).getReg();
7163   unsigned src = MI->getOperand(1).getReg();
7164   unsigned SizeVal = MI->getOperand(2).getImm();
7165   unsigned Align = MI->getOperand(3).getImm();
7166   DebugLoc dl = MI->getDebugLoc();
7167
7168   bool isThumb2 = Subtarget->isThumb2();
7169   MachineFunction *MF = BB->getParent();
7170   MachineRegisterInfo &MRI = MF->getRegInfo();
7171   unsigned ldrOpc, strOpc, UnitSize = 0;
7172
7173   const TargetRegisterClass *TRC = isThumb2 ?
7174     (const TargetRegisterClass*)&ARM::tGPRRegClass :
7175     (const TargetRegisterClass*)&ARM::GPRRegClass;
7176   const TargetRegisterClass *TRC_Vec = 0;
7177
7178   if (Align & 1) {
7179     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7180     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7181     UnitSize = 1;
7182   } else if (Align & 2) {
7183     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
7184     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
7185     UnitSize = 2;
7186   } else {
7187     // Check whether we can use NEON instructions.
7188     if (!MF->getFunction()->getAttributes().
7189           hasAttribute(AttributeSet::FunctionIndex,
7190                        Attribute::NoImplicitFloat) &&
7191         Subtarget->hasNEON()) {
7192       if ((Align % 16 == 0) && SizeVal >= 16) {
7193         ldrOpc = ARM::VLD1q32wb_fixed;
7194         strOpc = ARM::VST1q32wb_fixed;
7195         UnitSize = 16;
7196         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
7197       }
7198       else if ((Align % 8 == 0) && SizeVal >= 8) {
7199         ldrOpc = ARM::VLD1d32wb_fixed;
7200         strOpc = ARM::VST1d32wb_fixed;
7201         UnitSize = 8;
7202         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7203       }
7204     }
7205     // Can't use NEON instructions.
7206     if (UnitSize == 0) {
7207       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7208       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7209       UnitSize = 4;
7210     }
7211   }
7212
7213   unsigned BytesLeft = SizeVal % UnitSize;
7214   unsigned LoopSize = SizeVal - BytesLeft;
7215
7216   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7217     // Use LDR and STR to copy.
7218     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7219     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7220     unsigned srcIn = src;
7221     unsigned destIn = dest;
7222     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7223       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7224       unsigned srcOut = MRI.createVirtualRegister(TRC);
7225       unsigned destOut = MRI.createVirtualRegister(TRC);
7226       if (UnitSize >= 8) {
7227         AddDefaultPred(BuildMI(*BB, MI, dl,
7228           TII->get(ldrOpc), scratch)
7229           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7230
7231         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7232           .addReg(destIn).addImm(0).addReg(scratch));
7233       } else if (isThumb2) {
7234         AddDefaultPred(BuildMI(*BB, MI, dl,
7235           TII->get(ldrOpc), scratch)
7236           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7237
7238         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7239           .addReg(scratch).addReg(destIn)
7240           .addImm(UnitSize));
7241       } else {
7242         AddDefaultPred(BuildMI(*BB, MI, dl,
7243           TII->get(ldrOpc), scratch)
7244           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7245           .addImm(UnitSize));
7246
7247         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7248           .addReg(scratch).addReg(destIn)
7249           .addReg(0).addImm(UnitSize));
7250       }
7251       srcIn = srcOut;
7252       destIn = destOut;
7253     }
7254
7255     // Handle the leftover bytes with LDRB and STRB.
7256     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7257     // [destOut] = STRB_POST(scratch, destIn, 1)
7258     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7259     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7260     for (unsigned i = 0; i < BytesLeft; i++) {
7261       unsigned scratch = MRI.createVirtualRegister(TRC);
7262       unsigned srcOut = MRI.createVirtualRegister(TRC);
7263       unsigned destOut = MRI.createVirtualRegister(TRC);
7264       if (isThumb2) {
7265         AddDefaultPred(BuildMI(*BB, MI, dl,
7266           TII->get(ldrOpc),scratch)
7267           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7268
7269         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7270           .addReg(scratch).addReg(destIn)
7271           .addReg(0).addImm(1));
7272       } else {
7273         AddDefaultPred(BuildMI(*BB, MI, dl,
7274           TII->get(ldrOpc),scratch)
7275           .addReg(srcOut, RegState::Define).addReg(srcIn)
7276           .addReg(0).addImm(1));
7277
7278         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7279           .addReg(scratch).addReg(destIn)
7280           .addReg(0).addImm(1));
7281       }
7282       srcIn = srcOut;
7283       destIn = destOut;
7284     }
7285     MI->eraseFromParent();   // The instruction is gone now.
7286     return BB;
7287   }
7288
7289   // Expand the pseudo op to a loop.
7290   // thisMBB:
7291   //   ...
7292   //   movw varEnd, # --> with thumb2
7293   //   movt varEnd, #
7294   //   ldrcp varEnd, idx --> without thumb2
7295   //   fallthrough --> loopMBB
7296   // loopMBB:
7297   //   PHI varPhi, varEnd, varLoop
7298   //   PHI srcPhi, src, srcLoop
7299   //   PHI destPhi, dst, destLoop
7300   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7301   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7302   //   subs varLoop, varPhi, #UnitSize
7303   //   bne loopMBB
7304   //   fallthrough --> exitMBB
7305   // exitMBB:
7306   //   epilogue to handle left-over bytes
7307   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7308   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7309   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7310   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7311   MF->insert(It, loopMBB);
7312   MF->insert(It, exitMBB);
7313
7314   // Transfer the remainder of BB and its successor edges to exitMBB.
7315   exitMBB->splice(exitMBB->begin(), BB,
7316                   llvm::next(MachineBasicBlock::iterator(MI)),
7317                   BB->end());
7318   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7319
7320   // Load an immediate to varEnd.
7321   unsigned varEnd = MRI.createVirtualRegister(TRC);
7322   if (isThumb2) {
7323     unsigned VReg1 = varEnd;
7324     if ((LoopSize & 0xFFFF0000) != 0)
7325       VReg1 = MRI.createVirtualRegister(TRC);
7326     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7327                    .addImm(LoopSize & 0xFFFF));
7328
7329     if ((LoopSize & 0xFFFF0000) != 0)
7330       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7331                      .addReg(VReg1)
7332                      .addImm(LoopSize >> 16));
7333   } else {
7334     MachineConstantPool *ConstantPool = MF->getConstantPool();
7335     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7336     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7337
7338     // MachineConstantPool wants an explicit alignment.
7339     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7340     if (Align == 0)
7341       Align = getDataLayout()->getTypeAllocSize(C->getType());
7342     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7343
7344     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7345                    .addReg(varEnd, RegState::Define)
7346                    .addConstantPoolIndex(Idx)
7347                    .addImm(0));
7348   }
7349   BB->addSuccessor(loopMBB);
7350
7351   // Generate the loop body:
7352   //   varPhi = PHI(varLoop, varEnd)
7353   //   srcPhi = PHI(srcLoop, src)
7354   //   destPhi = PHI(destLoop, dst)
7355   MachineBasicBlock *entryBB = BB;
7356   BB = loopMBB;
7357   unsigned varLoop = MRI.createVirtualRegister(TRC);
7358   unsigned varPhi = MRI.createVirtualRegister(TRC);
7359   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7360   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7361   unsigned destLoop = MRI.createVirtualRegister(TRC);
7362   unsigned destPhi = MRI.createVirtualRegister(TRC);
7363
7364   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7365     .addReg(varLoop).addMBB(loopMBB)
7366     .addReg(varEnd).addMBB(entryBB);
7367   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7368     .addReg(srcLoop).addMBB(loopMBB)
7369     .addReg(src).addMBB(entryBB);
7370   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7371     .addReg(destLoop).addMBB(loopMBB)
7372     .addReg(dest).addMBB(entryBB);
7373
7374   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7375   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7376   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7377   if (UnitSize >= 8) {
7378     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7379       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7380
7381     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7382       .addReg(destPhi).addImm(0).addReg(scratch));
7383   } else if (isThumb2) {
7384     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7385       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7386
7387     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7388       .addReg(scratch).addReg(destPhi)
7389       .addImm(UnitSize));
7390   } else {
7391     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7392       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7393       .addImm(UnitSize));
7394
7395     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7396       .addReg(scratch).addReg(destPhi)
7397       .addReg(0).addImm(UnitSize));
7398   }
7399
7400   // Decrement loop variable by UnitSize.
7401   MachineInstrBuilder MIB = BuildMI(BB, dl,
7402     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7403   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7404   MIB->getOperand(5).setReg(ARM::CPSR);
7405   MIB->getOperand(5).setIsDef(true);
7406
7407   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7408     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7409
7410   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7411   BB->addSuccessor(loopMBB);
7412   BB->addSuccessor(exitMBB);
7413
7414   // Add epilogue to handle BytesLeft.
7415   BB = exitMBB;
7416   MachineInstr *StartOfExit = exitMBB->begin();
7417   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7418   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7419
7420   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7421   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7422   unsigned srcIn = srcLoop;
7423   unsigned destIn = destLoop;
7424   for (unsigned i = 0; i < BytesLeft; i++) {
7425     unsigned scratch = MRI.createVirtualRegister(TRC);
7426     unsigned srcOut = MRI.createVirtualRegister(TRC);
7427     unsigned destOut = MRI.createVirtualRegister(TRC);
7428     if (isThumb2) {
7429       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7430         TII->get(ldrOpc),scratch)
7431         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7432
7433       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7434         .addReg(scratch).addReg(destIn)
7435         .addImm(1));
7436     } else {
7437       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7438         TII->get(ldrOpc),scratch)
7439         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7440
7441       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7442         .addReg(scratch).addReg(destIn)
7443         .addReg(0).addImm(1));
7444     }
7445     srcIn = srcOut;
7446     destIn = destOut;
7447   }
7448
7449   MI->eraseFromParent();   // The instruction is gone now.
7450   return BB;
7451 }
7452
7453 MachineBasicBlock *
7454 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7455                                                MachineBasicBlock *BB) const {
7456   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7457   DebugLoc dl = MI->getDebugLoc();
7458   bool isThumb2 = Subtarget->isThumb2();
7459   switch (MI->getOpcode()) {
7460   default: {
7461     MI->dump();
7462     llvm_unreachable("Unexpected instr type to insert");
7463   }
7464   // The Thumb2 pre-indexed stores have the same MI operands, they just
7465   // define them differently in the .td files from the isel patterns, so
7466   // they need pseudos.
7467   case ARM::t2STR_preidx:
7468     MI->setDesc(TII->get(ARM::t2STR_PRE));
7469     return BB;
7470   case ARM::t2STRB_preidx:
7471     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7472     return BB;
7473   case ARM::t2STRH_preidx:
7474     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7475     return BB;
7476
7477   case ARM::STRi_preidx:
7478   case ARM::STRBi_preidx: {
7479     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7480       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7481     // Decode the offset.
7482     unsigned Offset = MI->getOperand(4).getImm();
7483     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7484     Offset = ARM_AM::getAM2Offset(Offset);
7485     if (isSub)
7486       Offset = -Offset;
7487
7488     MachineMemOperand *MMO = *MI->memoperands_begin();
7489     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7490       .addOperand(MI->getOperand(0))  // Rn_wb
7491       .addOperand(MI->getOperand(1))  // Rt
7492       .addOperand(MI->getOperand(2))  // Rn
7493       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7494       .addOperand(MI->getOperand(5))  // pred
7495       .addOperand(MI->getOperand(6))
7496       .addMemOperand(MMO);
7497     MI->eraseFromParent();
7498     return BB;
7499   }
7500   case ARM::STRr_preidx:
7501   case ARM::STRBr_preidx:
7502   case ARM::STRH_preidx: {
7503     unsigned NewOpc;
7504     switch (MI->getOpcode()) {
7505     default: llvm_unreachable("unexpected opcode!");
7506     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7507     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7508     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7509     }
7510     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7511     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7512       MIB.addOperand(MI->getOperand(i));
7513     MI->eraseFromParent();
7514     return BB;
7515   }
7516   case ARM::ATOMIC_LOAD_ADD_I8:
7517      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7518   case ARM::ATOMIC_LOAD_ADD_I16:
7519      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7520   case ARM::ATOMIC_LOAD_ADD_I32:
7521      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7522
7523   case ARM::ATOMIC_LOAD_AND_I8:
7524      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7525   case ARM::ATOMIC_LOAD_AND_I16:
7526      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7527   case ARM::ATOMIC_LOAD_AND_I32:
7528      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7529
7530   case ARM::ATOMIC_LOAD_OR_I8:
7531      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7532   case ARM::ATOMIC_LOAD_OR_I16:
7533      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7534   case ARM::ATOMIC_LOAD_OR_I32:
7535      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7536
7537   case ARM::ATOMIC_LOAD_XOR_I8:
7538      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7539   case ARM::ATOMIC_LOAD_XOR_I16:
7540      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7541   case ARM::ATOMIC_LOAD_XOR_I32:
7542      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7543
7544   case ARM::ATOMIC_LOAD_NAND_I8:
7545      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7546   case ARM::ATOMIC_LOAD_NAND_I16:
7547      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7548   case ARM::ATOMIC_LOAD_NAND_I32:
7549      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7550
7551   case ARM::ATOMIC_LOAD_SUB_I8:
7552      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7553   case ARM::ATOMIC_LOAD_SUB_I16:
7554      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7555   case ARM::ATOMIC_LOAD_SUB_I32:
7556      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7557
7558   case ARM::ATOMIC_LOAD_MIN_I8:
7559      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7560   case ARM::ATOMIC_LOAD_MIN_I16:
7561      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7562   case ARM::ATOMIC_LOAD_MIN_I32:
7563      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7564
7565   case ARM::ATOMIC_LOAD_MAX_I8:
7566      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7567   case ARM::ATOMIC_LOAD_MAX_I16:
7568      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7569   case ARM::ATOMIC_LOAD_MAX_I32:
7570      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7571
7572   case ARM::ATOMIC_LOAD_UMIN_I8:
7573      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7574   case ARM::ATOMIC_LOAD_UMIN_I16:
7575      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7576   case ARM::ATOMIC_LOAD_UMIN_I32:
7577      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7578
7579   case ARM::ATOMIC_LOAD_UMAX_I8:
7580      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7581   case ARM::ATOMIC_LOAD_UMAX_I16:
7582      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7583   case ARM::ATOMIC_LOAD_UMAX_I32:
7584      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7585
7586   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7587   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7588   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7589
7590   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7591   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7592   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7593
7594
7595   case ARM::ATOMADD6432:
7596     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7597                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7598                               /*NeedsCarry*/ true);
7599   case ARM::ATOMSUB6432:
7600     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7601                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7602                               /*NeedsCarry*/ true);
7603   case ARM::ATOMOR6432:
7604     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7605                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7606   case ARM::ATOMXOR6432:
7607     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7608                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7609   case ARM::ATOMAND6432:
7610     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7611                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7612   case ARM::ATOMSWAP6432:
7613     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7614   case ARM::ATOMCMPXCHG6432:
7615     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7616                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7617                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7618   case ARM::ATOMMIN6432:
7619     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7620                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7621                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7622                               /*IsMinMax*/ true, ARMCC::LT);
7623   case ARM::ATOMMAX6432:
7624     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7625                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7626                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7627                               /*IsMinMax*/ true, ARMCC::GE);
7628   case ARM::ATOMUMIN6432:
7629     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7630                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7631                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7632                               /*IsMinMax*/ true, ARMCC::LO);
7633   case ARM::ATOMUMAX6432:
7634     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7635                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7636                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7637                               /*IsMinMax*/ true, ARMCC::HS);
7638
7639   case ARM::tMOVCCr_pseudo: {
7640     // To "insert" a SELECT_CC instruction, we actually have to insert the
7641     // diamond control-flow pattern.  The incoming instruction knows the
7642     // destination vreg to set, the condition code register to branch on, the
7643     // true/false values to select between, and a branch opcode to use.
7644     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7645     MachineFunction::iterator It = BB;
7646     ++It;
7647
7648     //  thisMBB:
7649     //  ...
7650     //   TrueVal = ...
7651     //   cmpTY ccX, r1, r2
7652     //   bCC copy1MBB
7653     //   fallthrough --> copy0MBB
7654     MachineBasicBlock *thisMBB  = BB;
7655     MachineFunction *F = BB->getParent();
7656     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7657     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7658     F->insert(It, copy0MBB);
7659     F->insert(It, sinkMBB);
7660
7661     // Transfer the remainder of BB and its successor edges to sinkMBB.
7662     sinkMBB->splice(sinkMBB->begin(), BB,
7663                     llvm::next(MachineBasicBlock::iterator(MI)),
7664                     BB->end());
7665     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7666
7667     BB->addSuccessor(copy0MBB);
7668     BB->addSuccessor(sinkMBB);
7669
7670     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7671       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7672
7673     //  copy0MBB:
7674     //   %FalseValue = ...
7675     //   # fallthrough to sinkMBB
7676     BB = copy0MBB;
7677
7678     // Update machine-CFG edges
7679     BB->addSuccessor(sinkMBB);
7680
7681     //  sinkMBB:
7682     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7683     //  ...
7684     BB = sinkMBB;
7685     BuildMI(*BB, BB->begin(), dl,
7686             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7687       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7688       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7689
7690     MI->eraseFromParent();   // The pseudo instruction is gone now.
7691     return BB;
7692   }
7693
7694   case ARM::BCCi64:
7695   case ARM::BCCZi64: {
7696     // If there is an unconditional branch to the other successor, remove it.
7697     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7698
7699     // Compare both parts that make up the double comparison separately for
7700     // equality.
7701     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7702
7703     unsigned LHS1 = MI->getOperand(1).getReg();
7704     unsigned LHS2 = MI->getOperand(2).getReg();
7705     if (RHSisZero) {
7706       AddDefaultPred(BuildMI(BB, dl,
7707                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7708                      .addReg(LHS1).addImm(0));
7709       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7710         .addReg(LHS2).addImm(0)
7711         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7712     } else {
7713       unsigned RHS1 = MI->getOperand(3).getReg();
7714       unsigned RHS2 = MI->getOperand(4).getReg();
7715       AddDefaultPred(BuildMI(BB, dl,
7716                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7717                      .addReg(LHS1).addReg(RHS1));
7718       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7719         .addReg(LHS2).addReg(RHS2)
7720         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7721     }
7722
7723     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7724     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7725     if (MI->getOperand(0).getImm() == ARMCC::NE)
7726       std::swap(destMBB, exitMBB);
7727
7728     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7729       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7730     if (isThumb2)
7731       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7732     else
7733       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7734
7735     MI->eraseFromParent();   // The pseudo instruction is gone now.
7736     return BB;
7737   }
7738
7739   case ARM::Int_eh_sjlj_setjmp:
7740   case ARM::Int_eh_sjlj_setjmp_nofp:
7741   case ARM::tInt_eh_sjlj_setjmp:
7742   case ARM::t2Int_eh_sjlj_setjmp:
7743   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7744     EmitSjLjDispatchBlock(MI, BB);
7745     return BB;
7746
7747   case ARM::ABS:
7748   case ARM::t2ABS: {
7749     // To insert an ABS instruction, we have to insert the
7750     // diamond control-flow pattern.  The incoming instruction knows the
7751     // source vreg to test against 0, the destination vreg to set,
7752     // the condition code register to branch on, the
7753     // true/false values to select between, and a branch opcode to use.
7754     // It transforms
7755     //     V1 = ABS V0
7756     // into
7757     //     V2 = MOVS V0
7758     //     BCC                      (branch to SinkBB if V0 >= 0)
7759     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7760     //     SinkBB: V1 = PHI(V2, V3)
7761     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7762     MachineFunction::iterator BBI = BB;
7763     ++BBI;
7764     MachineFunction *Fn = BB->getParent();
7765     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7766     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7767     Fn->insert(BBI, RSBBB);
7768     Fn->insert(BBI, SinkBB);
7769
7770     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7771     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7772     bool isThumb2 = Subtarget->isThumb2();
7773     MachineRegisterInfo &MRI = Fn->getRegInfo();
7774     // In Thumb mode S must not be specified if source register is the SP or
7775     // PC and if destination register is the SP, so restrict register class
7776     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7777       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7778       (const TargetRegisterClass*)&ARM::GPRRegClass);
7779
7780     // Transfer the remainder of BB and its successor edges to sinkMBB.
7781     SinkBB->splice(SinkBB->begin(), BB,
7782       llvm::next(MachineBasicBlock::iterator(MI)),
7783       BB->end());
7784     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7785
7786     BB->addSuccessor(RSBBB);
7787     BB->addSuccessor(SinkBB);
7788
7789     // fall through to SinkMBB
7790     RSBBB->addSuccessor(SinkBB);
7791
7792     // insert a cmp at the end of BB
7793     AddDefaultPred(BuildMI(BB, dl,
7794                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7795                    .addReg(ABSSrcReg).addImm(0));
7796
7797     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7798     BuildMI(BB, dl,
7799       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7800       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7801
7802     // insert rsbri in RSBBB
7803     // Note: BCC and rsbri will be converted into predicated rsbmi
7804     // by if-conversion pass
7805     BuildMI(*RSBBB, RSBBB->begin(), dl,
7806       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7807       .addReg(ABSSrcReg, RegState::Kill)
7808       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7809
7810     // insert PHI in SinkBB,
7811     // reuse ABSDstReg to not change uses of ABS instruction
7812     BuildMI(*SinkBB, SinkBB->begin(), dl,
7813       TII->get(ARM::PHI), ABSDstReg)
7814       .addReg(NewRsbDstReg).addMBB(RSBBB)
7815       .addReg(ABSSrcReg).addMBB(BB);
7816
7817     // remove ABS instruction
7818     MI->eraseFromParent();
7819
7820     // return last added BB
7821     return SinkBB;
7822   }
7823   case ARM::COPY_STRUCT_BYVAL_I32:
7824     ++NumLoopByVals;
7825     return EmitStructByval(MI, BB);
7826   }
7827 }
7828
7829 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7830                                                       SDNode *Node) const {
7831   if (!MI->hasPostISelHook()) {
7832     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7833            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7834     return;
7835   }
7836
7837   const MCInstrDesc *MCID = &MI->getDesc();
7838   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7839   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7840   // operand is still set to noreg. If needed, set the optional operand's
7841   // register to CPSR, and remove the redundant implicit def.
7842   //
7843   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7844
7845   // Rename pseudo opcodes.
7846   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7847   if (NewOpc) {
7848     const ARMBaseInstrInfo *TII =
7849       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7850     MCID = &TII->get(NewOpc);
7851
7852     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7853            "converted opcode should be the same except for cc_out");
7854
7855     MI->setDesc(*MCID);
7856
7857     // Add the optional cc_out operand
7858     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7859   }
7860   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7861
7862   // Any ARM instruction that sets the 's' bit should specify an optional
7863   // "cc_out" operand in the last operand position.
7864   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7865     assert(!NewOpc && "Optional cc_out operand required");
7866     return;
7867   }
7868   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7869   // since we already have an optional CPSR def.
7870   bool definesCPSR = false;
7871   bool deadCPSR = false;
7872   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7873        i != e; ++i) {
7874     const MachineOperand &MO = MI->getOperand(i);
7875     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7876       definesCPSR = true;
7877       if (MO.isDead())
7878         deadCPSR = true;
7879       MI->RemoveOperand(i);
7880       break;
7881     }
7882   }
7883   if (!definesCPSR) {
7884     assert(!NewOpc && "Optional cc_out operand required");
7885     return;
7886   }
7887   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7888   if (deadCPSR) {
7889     assert(!MI->getOperand(ccOutIdx).getReg() &&
7890            "expect uninitialized optional cc_out operand");
7891     return;
7892   }
7893
7894   // If this instruction was defined with an optional CPSR def and its dag node
7895   // had a live implicit CPSR def, then activate the optional CPSR def.
7896   MachineOperand &MO = MI->getOperand(ccOutIdx);
7897   MO.setReg(ARM::CPSR);
7898   MO.setIsDef(true);
7899 }
7900
7901 //===----------------------------------------------------------------------===//
7902 //                           ARM Optimization Hooks
7903 //===----------------------------------------------------------------------===//
7904
7905 // Helper function that checks if N is a null or all ones constant.
7906 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7907   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7908   if (!C)
7909     return false;
7910   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7911 }
7912
7913 // Return true if N is conditionally 0 or all ones.
7914 // Detects these expressions where cc is an i1 value:
7915 //
7916 //   (select cc 0, y)   [AllOnes=0]
7917 //   (select cc y, 0)   [AllOnes=0]
7918 //   (zext cc)          [AllOnes=0]
7919 //   (sext cc)          [AllOnes=0/1]
7920 //   (select cc -1, y)  [AllOnes=1]
7921 //   (select cc y, -1)  [AllOnes=1]
7922 //
7923 // Invert is set when N is the null/all ones constant when CC is false.
7924 // OtherOp is set to the alternative value of N.
7925 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7926                                        SDValue &CC, bool &Invert,
7927                                        SDValue &OtherOp,
7928                                        SelectionDAG &DAG) {
7929   switch (N->getOpcode()) {
7930   default: return false;
7931   case ISD::SELECT: {
7932     CC = N->getOperand(0);
7933     SDValue N1 = N->getOperand(1);
7934     SDValue N2 = N->getOperand(2);
7935     if (isZeroOrAllOnes(N1, AllOnes)) {
7936       Invert = false;
7937       OtherOp = N2;
7938       return true;
7939     }
7940     if (isZeroOrAllOnes(N2, AllOnes)) {
7941       Invert = true;
7942       OtherOp = N1;
7943       return true;
7944     }
7945     return false;
7946   }
7947   case ISD::ZERO_EXTEND:
7948     // (zext cc) can never be the all ones value.
7949     if (AllOnes)
7950       return false;
7951     // Fall through.
7952   case ISD::SIGN_EXTEND: {
7953     EVT VT = N->getValueType(0);
7954     CC = N->getOperand(0);
7955     if (CC.getValueType() != MVT::i1)
7956       return false;
7957     Invert = !AllOnes;
7958     if (AllOnes)
7959       // When looking for an AllOnes constant, N is an sext, and the 'other'
7960       // value is 0.
7961       OtherOp = DAG.getConstant(0, VT);
7962     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7963       // When looking for a 0 constant, N can be zext or sext.
7964       OtherOp = DAG.getConstant(1, VT);
7965     else
7966       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7967     return true;
7968   }
7969   }
7970 }
7971
7972 // Combine a constant select operand into its use:
7973 //
7974 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7975 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7976 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7977 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7978 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7979 //
7980 // The transform is rejected if the select doesn't have a constant operand that
7981 // is null, or all ones when AllOnes is set.
7982 //
7983 // Also recognize sext/zext from i1:
7984 //
7985 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7986 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7987 //
7988 // These transformations eventually create predicated instructions.
7989 //
7990 // @param N       The node to transform.
7991 // @param Slct    The N operand that is a select.
7992 // @param OtherOp The other N operand (x above).
7993 // @param DCI     Context.
7994 // @param AllOnes Require the select constant to be all ones instead of null.
7995 // @returns The new node, or SDValue() on failure.
7996 static
7997 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7998                             TargetLowering::DAGCombinerInfo &DCI,
7999                             bool AllOnes = false) {
8000   SelectionDAG &DAG = DCI.DAG;
8001   EVT VT = N->getValueType(0);
8002   SDValue NonConstantVal;
8003   SDValue CCOp;
8004   bool SwapSelectOps;
8005   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8006                                   NonConstantVal, DAG))
8007     return SDValue();
8008
8009   // Slct is now know to be the desired identity constant when CC is true.
8010   SDValue TrueVal = OtherOp;
8011   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8012                                  OtherOp, NonConstantVal);
8013   // Unless SwapSelectOps says CC should be false.
8014   if (SwapSelectOps)
8015     std::swap(TrueVal, FalseVal);
8016
8017   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8018                      CCOp, TrueVal, FalseVal);
8019 }
8020
8021 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8022 static
8023 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8024                                        TargetLowering::DAGCombinerInfo &DCI) {
8025   SDValue N0 = N->getOperand(0);
8026   SDValue N1 = N->getOperand(1);
8027   if (N0.getNode()->hasOneUse()) {
8028     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8029     if (Result.getNode())
8030       return Result;
8031   }
8032   if (N1.getNode()->hasOneUse()) {
8033     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8034     if (Result.getNode())
8035       return Result;
8036   }
8037   return SDValue();
8038 }
8039
8040 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8041 // (only after legalization).
8042 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8043                                  TargetLowering::DAGCombinerInfo &DCI,
8044                                  const ARMSubtarget *Subtarget) {
8045
8046   // Only perform optimization if after legalize, and if NEON is available. We
8047   // also expected both operands to be BUILD_VECTORs.
8048   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8049       || N0.getOpcode() != ISD::BUILD_VECTOR
8050       || N1.getOpcode() != ISD::BUILD_VECTOR)
8051     return SDValue();
8052
8053   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8054   EVT VT = N->getValueType(0);
8055   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8056     return SDValue();
8057
8058   // Check that the vector operands are of the right form.
8059   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8060   // operands, where N is the size of the formed vector.
8061   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8062   // index such that we have a pair wise add pattern.
8063
8064   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8065   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8066     return SDValue();
8067   SDValue Vec = N0->getOperand(0)->getOperand(0);
8068   SDNode *V = Vec.getNode();
8069   unsigned nextIndex = 0;
8070
8071   // For each operands to the ADD which are BUILD_VECTORs,
8072   // check to see if each of their operands are an EXTRACT_VECTOR with
8073   // the same vector and appropriate index.
8074   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8075     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8076         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8077
8078       SDValue ExtVec0 = N0->getOperand(i);
8079       SDValue ExtVec1 = N1->getOperand(i);
8080
8081       // First operand is the vector, verify its the same.
8082       if (V != ExtVec0->getOperand(0).getNode() ||
8083           V != ExtVec1->getOperand(0).getNode())
8084         return SDValue();
8085
8086       // Second is the constant, verify its correct.
8087       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8088       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8089
8090       // For the constant, we want to see all the even or all the odd.
8091       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8092           || C1->getZExtValue() != nextIndex+1)
8093         return SDValue();
8094
8095       // Increment index.
8096       nextIndex+=2;
8097     } else
8098       return SDValue();
8099   }
8100
8101   // Create VPADDL node.
8102   SelectionDAG &DAG = DCI.DAG;
8103   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8104
8105   // Build operand list.
8106   SmallVector<SDValue, 8> Ops;
8107   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8108                                 TLI.getPointerTy()));
8109
8110   // Input is the vector.
8111   Ops.push_back(Vec);
8112
8113   // Get widened type and narrowed type.
8114   MVT widenType;
8115   unsigned numElem = VT.getVectorNumElements();
8116   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8117     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8118     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8119     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8120     default:
8121       llvm_unreachable("Invalid vector element type for padd optimization.");
8122   }
8123
8124   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8125                             widenType, &Ops[0], Ops.size());
8126   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8127 }
8128
8129 static SDValue findMUL_LOHI(SDValue V) {
8130   if (V->getOpcode() == ISD::UMUL_LOHI ||
8131       V->getOpcode() == ISD::SMUL_LOHI)
8132     return V;
8133   return SDValue();
8134 }
8135
8136 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8137                                      TargetLowering::DAGCombinerInfo &DCI,
8138                                      const ARMSubtarget *Subtarget) {
8139
8140   if (Subtarget->isThumb1Only()) return SDValue();
8141
8142   // Only perform the checks after legalize when the pattern is available.
8143   if (DCI.isBeforeLegalize()) return SDValue();
8144
8145   // Look for multiply add opportunities.
8146   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8147   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8148   // a glue link from the first add to the second add.
8149   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8150   // a S/UMLAL instruction.
8151   //          loAdd   UMUL_LOHI
8152   //            \    / :lo    \ :hi
8153   //             \  /          \          [no multiline comment]
8154   //              ADDC         |  hiAdd
8155   //                 \ :glue  /  /
8156   //                  \      /  /
8157   //                    ADDE
8158   //
8159   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8160   SDValue AddcOp0 = AddcNode->getOperand(0);
8161   SDValue AddcOp1 = AddcNode->getOperand(1);
8162
8163   // Check if the two operands are from the same mul_lohi node.
8164   if (AddcOp0.getNode() == AddcOp1.getNode())
8165     return SDValue();
8166
8167   assert(AddcNode->getNumValues() == 2 &&
8168          AddcNode->getValueType(0) == MVT::i32 &&
8169          "Expect ADDC with two result values. First: i32");
8170
8171   // Check that we have a glued ADDC node.
8172   if (AddcNode->getValueType(1) != MVT::Glue)
8173     return SDValue();
8174
8175   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8176   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8177       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8178       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8179       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8180     return SDValue();
8181
8182   // Look for the glued ADDE.
8183   SDNode* AddeNode = AddcNode->getGluedUser();
8184   if (AddeNode == NULL)
8185     return SDValue();
8186
8187   // Make sure it is really an ADDE.
8188   if (AddeNode->getOpcode() != ISD::ADDE)
8189     return SDValue();
8190
8191   assert(AddeNode->getNumOperands() == 3 &&
8192          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8193          "ADDE node has the wrong inputs");
8194
8195   // Check for the triangle shape.
8196   SDValue AddeOp0 = AddeNode->getOperand(0);
8197   SDValue AddeOp1 = AddeNode->getOperand(1);
8198
8199   // Make sure that the ADDE operands are not coming from the same node.
8200   if (AddeOp0.getNode() == AddeOp1.getNode())
8201     return SDValue();
8202
8203   // Find the MUL_LOHI node walking up ADDE's operands.
8204   bool IsLeftOperandMUL = false;
8205   SDValue MULOp = findMUL_LOHI(AddeOp0);
8206   if (MULOp == SDValue())
8207    MULOp = findMUL_LOHI(AddeOp1);
8208   else
8209     IsLeftOperandMUL = true;
8210   if (MULOp == SDValue())
8211      return SDValue();
8212
8213   // Figure out the right opcode.
8214   unsigned Opc = MULOp->getOpcode();
8215   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8216
8217   // Figure out the high and low input values to the MLAL node.
8218   SDValue* HiMul = &MULOp;
8219   SDValue* HiAdd = NULL;
8220   SDValue* LoMul = NULL;
8221   SDValue* LowAdd = NULL;
8222
8223   if (IsLeftOperandMUL)
8224     HiAdd = &AddeOp1;
8225   else
8226     HiAdd = &AddeOp0;
8227
8228
8229   if (AddcOp0->getOpcode() == Opc) {
8230     LoMul = &AddcOp0;
8231     LowAdd = &AddcOp1;
8232   }
8233   if (AddcOp1->getOpcode() == Opc) {
8234     LoMul = &AddcOp1;
8235     LowAdd = &AddcOp0;
8236   }
8237
8238   if (LoMul == NULL)
8239     return SDValue();
8240
8241   if (LoMul->getNode() != HiMul->getNode())
8242     return SDValue();
8243
8244   // Create the merged node.
8245   SelectionDAG &DAG = DCI.DAG;
8246
8247   // Build operand list.
8248   SmallVector<SDValue, 8> Ops;
8249   Ops.push_back(LoMul->getOperand(0));
8250   Ops.push_back(LoMul->getOperand(1));
8251   Ops.push_back(*LowAdd);
8252   Ops.push_back(*HiAdd);
8253
8254   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8255                                  DAG.getVTList(MVT::i32, MVT::i32),
8256                                  &Ops[0], Ops.size());
8257
8258   // Replace the ADDs' nodes uses by the MLA node's values.
8259   SDValue HiMLALResult(MLALNode.getNode(), 1);
8260   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8261
8262   SDValue LoMLALResult(MLALNode.getNode(), 0);
8263   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8264
8265   // Return original node to notify the driver to stop replacing.
8266   SDValue resNode(AddcNode, 0);
8267   return resNode;
8268 }
8269
8270 /// PerformADDCCombine - Target-specific dag combine transform from
8271 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8272 static SDValue PerformADDCCombine(SDNode *N,
8273                                  TargetLowering::DAGCombinerInfo &DCI,
8274                                  const ARMSubtarget *Subtarget) {
8275
8276   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8277
8278 }
8279
8280 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8281 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8282 /// called with the default operands, and if that fails, with commuted
8283 /// operands.
8284 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8285                                           TargetLowering::DAGCombinerInfo &DCI,
8286                                           const ARMSubtarget *Subtarget){
8287
8288   // Attempt to create vpaddl for this add.
8289   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8290   if (Result.getNode())
8291     return Result;
8292
8293   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8294   if (N0.getNode()->hasOneUse()) {
8295     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8296     if (Result.getNode()) return Result;
8297   }
8298   return SDValue();
8299 }
8300
8301 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8302 ///
8303 static SDValue PerformADDCombine(SDNode *N,
8304                                  TargetLowering::DAGCombinerInfo &DCI,
8305                                  const ARMSubtarget *Subtarget) {
8306   SDValue N0 = N->getOperand(0);
8307   SDValue N1 = N->getOperand(1);
8308
8309   // First try with the default operand order.
8310   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8311   if (Result.getNode())
8312     return Result;
8313
8314   // If that didn't work, try again with the operands commuted.
8315   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8316 }
8317
8318 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8319 ///
8320 static SDValue PerformSUBCombine(SDNode *N,
8321                                  TargetLowering::DAGCombinerInfo &DCI) {
8322   SDValue N0 = N->getOperand(0);
8323   SDValue N1 = N->getOperand(1);
8324
8325   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8326   if (N1.getNode()->hasOneUse()) {
8327     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8328     if (Result.getNode()) return Result;
8329   }
8330
8331   return SDValue();
8332 }
8333
8334 /// PerformVMULCombine
8335 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8336 /// special multiplier accumulator forwarding.
8337 ///   vmul d3, d0, d2
8338 ///   vmla d3, d1, d2
8339 /// is faster than
8340 ///   vadd d3, d0, d1
8341 ///   vmul d3, d3, d2
8342 static SDValue PerformVMULCombine(SDNode *N,
8343                                   TargetLowering::DAGCombinerInfo &DCI,
8344                                   const ARMSubtarget *Subtarget) {
8345   if (!Subtarget->hasVMLxForwarding())
8346     return SDValue();
8347
8348   SelectionDAG &DAG = DCI.DAG;
8349   SDValue N0 = N->getOperand(0);
8350   SDValue N1 = N->getOperand(1);
8351   unsigned Opcode = N0.getOpcode();
8352   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8353       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8354     Opcode = N1.getOpcode();
8355     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8356         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8357       return SDValue();
8358     std::swap(N0, N1);
8359   }
8360
8361   EVT VT = N->getValueType(0);
8362   SDLoc DL(N);
8363   SDValue N00 = N0->getOperand(0);
8364   SDValue N01 = N0->getOperand(1);
8365   return DAG.getNode(Opcode, DL, VT,
8366                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8367                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8368 }
8369
8370 static SDValue PerformMULCombine(SDNode *N,
8371                                  TargetLowering::DAGCombinerInfo &DCI,
8372                                  const ARMSubtarget *Subtarget) {
8373   SelectionDAG &DAG = DCI.DAG;
8374
8375   if (Subtarget->isThumb1Only())
8376     return SDValue();
8377
8378   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8379     return SDValue();
8380
8381   EVT VT = N->getValueType(0);
8382   if (VT.is64BitVector() || VT.is128BitVector())
8383     return PerformVMULCombine(N, DCI, Subtarget);
8384   if (VT != MVT::i32)
8385     return SDValue();
8386
8387   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8388   if (!C)
8389     return SDValue();
8390
8391   int64_t MulAmt = C->getSExtValue();
8392   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8393
8394   ShiftAmt = ShiftAmt & (32 - 1);
8395   SDValue V = N->getOperand(0);
8396   SDLoc DL(N);
8397
8398   SDValue Res;
8399   MulAmt >>= ShiftAmt;
8400
8401   if (MulAmt >= 0) {
8402     if (isPowerOf2_32(MulAmt - 1)) {
8403       // (mul x, 2^N + 1) => (add (shl x, N), x)
8404       Res = DAG.getNode(ISD::ADD, DL, VT,
8405                         V,
8406                         DAG.getNode(ISD::SHL, DL, VT,
8407                                     V,
8408                                     DAG.getConstant(Log2_32(MulAmt - 1),
8409                                                     MVT::i32)));
8410     } else if (isPowerOf2_32(MulAmt + 1)) {
8411       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8412       Res = DAG.getNode(ISD::SUB, DL, VT,
8413                         DAG.getNode(ISD::SHL, DL, VT,
8414                                     V,
8415                                     DAG.getConstant(Log2_32(MulAmt + 1),
8416                                                     MVT::i32)),
8417                         V);
8418     } else
8419       return SDValue();
8420   } else {
8421     uint64_t MulAmtAbs = -MulAmt;
8422     if (isPowerOf2_32(MulAmtAbs + 1)) {
8423       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8424       Res = DAG.getNode(ISD::SUB, DL, VT,
8425                         V,
8426                         DAG.getNode(ISD::SHL, DL, VT,
8427                                     V,
8428                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8429                                                     MVT::i32)));
8430     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8431       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8432       Res = DAG.getNode(ISD::ADD, DL, VT,
8433                         V,
8434                         DAG.getNode(ISD::SHL, DL, VT,
8435                                     V,
8436                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8437                                                     MVT::i32)));
8438       Res = DAG.getNode(ISD::SUB, DL, VT,
8439                         DAG.getConstant(0, MVT::i32),Res);
8440
8441     } else
8442       return SDValue();
8443   }
8444
8445   if (ShiftAmt != 0)
8446     Res = DAG.getNode(ISD::SHL, DL, VT,
8447                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8448
8449   // Do not add new nodes to DAG combiner worklist.
8450   DCI.CombineTo(N, Res, false);
8451   return SDValue();
8452 }
8453
8454 static SDValue PerformANDCombine(SDNode *N,
8455                                  TargetLowering::DAGCombinerInfo &DCI,
8456                                  const ARMSubtarget *Subtarget) {
8457
8458   // Attempt to use immediate-form VBIC
8459   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8460   SDLoc dl(N);
8461   EVT VT = N->getValueType(0);
8462   SelectionDAG &DAG = DCI.DAG;
8463
8464   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8465     return SDValue();
8466
8467   APInt SplatBits, SplatUndef;
8468   unsigned SplatBitSize;
8469   bool HasAnyUndefs;
8470   if (BVN &&
8471       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8472     if (SplatBitSize <= 64) {
8473       EVT VbicVT;
8474       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8475                                       SplatUndef.getZExtValue(), SplatBitSize,
8476                                       DAG, VbicVT, VT.is128BitVector(),
8477                                       OtherModImm);
8478       if (Val.getNode()) {
8479         SDValue Input =
8480           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8481         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8482         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8483       }
8484     }
8485   }
8486
8487   if (!Subtarget->isThumb1Only()) {
8488     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8489     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8490     if (Result.getNode())
8491       return Result;
8492   }
8493
8494   return SDValue();
8495 }
8496
8497 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8498 static SDValue PerformORCombine(SDNode *N,
8499                                 TargetLowering::DAGCombinerInfo &DCI,
8500                                 const ARMSubtarget *Subtarget) {
8501   // Attempt to use immediate-form VORR
8502   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8503   SDLoc dl(N);
8504   EVT VT = N->getValueType(0);
8505   SelectionDAG &DAG = DCI.DAG;
8506
8507   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8508     return SDValue();
8509
8510   APInt SplatBits, SplatUndef;
8511   unsigned SplatBitSize;
8512   bool HasAnyUndefs;
8513   if (BVN && Subtarget->hasNEON() &&
8514       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8515     if (SplatBitSize <= 64) {
8516       EVT VorrVT;
8517       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8518                                       SplatUndef.getZExtValue(), SplatBitSize,
8519                                       DAG, VorrVT, VT.is128BitVector(),
8520                                       OtherModImm);
8521       if (Val.getNode()) {
8522         SDValue Input =
8523           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8524         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8525         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8526       }
8527     }
8528   }
8529
8530   if (!Subtarget->isThumb1Only()) {
8531     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8532     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8533     if (Result.getNode())
8534       return Result;
8535   }
8536
8537   // The code below optimizes (or (and X, Y), Z).
8538   // The AND operand needs to have a single user to make these optimizations
8539   // profitable.
8540   SDValue N0 = N->getOperand(0);
8541   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8542     return SDValue();
8543   SDValue N1 = N->getOperand(1);
8544
8545   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8546   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8547       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8548     APInt SplatUndef;
8549     unsigned SplatBitSize;
8550     bool HasAnyUndefs;
8551
8552     APInt SplatBits0, SplatBits1;
8553     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8554     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8555     // Ensure that the second operand of both ands are constants
8556     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8557                                       HasAnyUndefs) && !HasAnyUndefs) {
8558         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8559                                           HasAnyUndefs) && !HasAnyUndefs) {
8560             // Ensure that the bit width of the constants are the same and that
8561             // the splat arguments are logical inverses as per the pattern we
8562             // are trying to simplify.
8563             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8564                 SplatBits0 == ~SplatBits1) {
8565                 // Canonicalize the vector type to make instruction selection
8566                 // simpler.
8567                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8568                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8569                                              N0->getOperand(1),
8570                                              N0->getOperand(0),
8571                                              N1->getOperand(0));
8572                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8573             }
8574         }
8575     }
8576   }
8577
8578   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8579   // reasonable.
8580
8581   // BFI is only available on V6T2+
8582   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8583     return SDValue();
8584
8585   SDLoc DL(N);
8586   // 1) or (and A, mask), val => ARMbfi A, val, mask
8587   //      iff (val & mask) == val
8588   //
8589   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8590   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8591   //          && mask == ~mask2
8592   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8593   //          && ~mask == mask2
8594   //  (i.e., copy a bitfield value into another bitfield of the same width)
8595
8596   if (VT != MVT::i32)
8597     return SDValue();
8598
8599   SDValue N00 = N0.getOperand(0);
8600
8601   // The value and the mask need to be constants so we can verify this is
8602   // actually a bitfield set. If the mask is 0xffff, we can do better
8603   // via a movt instruction, so don't use BFI in that case.
8604   SDValue MaskOp = N0.getOperand(1);
8605   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8606   if (!MaskC)
8607     return SDValue();
8608   unsigned Mask = MaskC->getZExtValue();
8609   if (Mask == 0xffff)
8610     return SDValue();
8611   SDValue Res;
8612   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8613   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8614   if (N1C) {
8615     unsigned Val = N1C->getZExtValue();
8616     if ((Val & ~Mask) != Val)
8617       return SDValue();
8618
8619     if (ARM::isBitFieldInvertedMask(Mask)) {
8620       Val >>= countTrailingZeros(~Mask);
8621
8622       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8623                         DAG.getConstant(Val, MVT::i32),
8624                         DAG.getConstant(Mask, MVT::i32));
8625
8626       // Do not add new nodes to DAG combiner worklist.
8627       DCI.CombineTo(N, Res, false);
8628       return SDValue();
8629     }
8630   } else if (N1.getOpcode() == ISD::AND) {
8631     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8632     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8633     if (!N11C)
8634       return SDValue();
8635     unsigned Mask2 = N11C->getZExtValue();
8636
8637     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8638     // as is to match.
8639     if (ARM::isBitFieldInvertedMask(Mask) &&
8640         (Mask == ~Mask2)) {
8641       // The pack halfword instruction works better for masks that fit it,
8642       // so use that when it's available.
8643       if (Subtarget->hasT2ExtractPack() &&
8644           (Mask == 0xffff || Mask == 0xffff0000))
8645         return SDValue();
8646       // 2a
8647       unsigned amt = countTrailingZeros(Mask2);
8648       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8649                         DAG.getConstant(amt, MVT::i32));
8650       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8651                         DAG.getConstant(Mask, MVT::i32));
8652       // Do not add new nodes to DAG combiner worklist.
8653       DCI.CombineTo(N, Res, false);
8654       return SDValue();
8655     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8656                (~Mask == Mask2)) {
8657       // The pack halfword instruction works better for masks that fit it,
8658       // so use that when it's available.
8659       if (Subtarget->hasT2ExtractPack() &&
8660           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8661         return SDValue();
8662       // 2b
8663       unsigned lsb = countTrailingZeros(Mask);
8664       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8665                         DAG.getConstant(lsb, MVT::i32));
8666       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8667                         DAG.getConstant(Mask2, MVT::i32));
8668       // Do not add new nodes to DAG combiner worklist.
8669       DCI.CombineTo(N, Res, false);
8670       return SDValue();
8671     }
8672   }
8673
8674   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8675       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8676       ARM::isBitFieldInvertedMask(~Mask)) {
8677     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8678     // where lsb(mask) == #shamt and masked bits of B are known zero.
8679     SDValue ShAmt = N00.getOperand(1);
8680     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8681     unsigned LSB = countTrailingZeros(Mask);
8682     if (ShAmtC != LSB)
8683       return SDValue();
8684
8685     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8686                       DAG.getConstant(~Mask, MVT::i32));
8687
8688     // Do not add new nodes to DAG combiner worklist.
8689     DCI.CombineTo(N, Res, false);
8690   }
8691
8692   return SDValue();
8693 }
8694
8695 static SDValue PerformXORCombine(SDNode *N,
8696                                  TargetLowering::DAGCombinerInfo &DCI,
8697                                  const ARMSubtarget *Subtarget) {
8698   EVT VT = N->getValueType(0);
8699   SelectionDAG &DAG = DCI.DAG;
8700
8701   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8702     return SDValue();
8703
8704   if (!Subtarget->isThumb1Only()) {
8705     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8706     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8707     if (Result.getNode())
8708       return Result;
8709   }
8710
8711   return SDValue();
8712 }
8713
8714 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8715 /// the bits being cleared by the AND are not demanded by the BFI.
8716 static SDValue PerformBFICombine(SDNode *N,
8717                                  TargetLowering::DAGCombinerInfo &DCI) {
8718   SDValue N1 = N->getOperand(1);
8719   if (N1.getOpcode() == ISD::AND) {
8720     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8721     if (!N11C)
8722       return SDValue();
8723     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8724     unsigned LSB = countTrailingZeros(~InvMask);
8725     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8726     unsigned Mask = (1 << Width)-1;
8727     unsigned Mask2 = N11C->getZExtValue();
8728     if ((Mask & (~Mask2)) == 0)
8729       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8730                              N->getOperand(0), N1.getOperand(0),
8731                              N->getOperand(2));
8732   }
8733   return SDValue();
8734 }
8735
8736 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8737 /// ARMISD::VMOVRRD.
8738 static SDValue PerformVMOVRRDCombine(SDNode *N,
8739                                      TargetLowering::DAGCombinerInfo &DCI) {
8740   // vmovrrd(vmovdrr x, y) -> x,y
8741   SDValue InDouble = N->getOperand(0);
8742   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8743     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8744
8745   // vmovrrd(load f64) -> (load i32), (load i32)
8746   SDNode *InNode = InDouble.getNode();
8747   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8748       InNode->getValueType(0) == MVT::f64 &&
8749       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8750       !cast<LoadSDNode>(InNode)->isVolatile()) {
8751     // TODO: Should this be done for non-FrameIndex operands?
8752     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8753
8754     SelectionDAG &DAG = DCI.DAG;
8755     SDLoc DL(LD);
8756     SDValue BasePtr = LD->getBasePtr();
8757     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8758                                  LD->getPointerInfo(), LD->isVolatile(),
8759                                  LD->isNonTemporal(), LD->isInvariant(),
8760                                  LD->getAlignment());
8761
8762     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8763                                     DAG.getConstant(4, MVT::i32));
8764     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8765                                  LD->getPointerInfo(), LD->isVolatile(),
8766                                  LD->isNonTemporal(), LD->isInvariant(),
8767                                  std::min(4U, LD->getAlignment() / 2));
8768
8769     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8770     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8771     DCI.RemoveFromWorklist(LD);
8772     DAG.DeleteNode(LD);
8773     return Result;
8774   }
8775
8776   return SDValue();
8777 }
8778
8779 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8780 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8781 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8782   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8783   SDValue Op0 = N->getOperand(0);
8784   SDValue Op1 = N->getOperand(1);
8785   if (Op0.getOpcode() == ISD::BITCAST)
8786     Op0 = Op0.getOperand(0);
8787   if (Op1.getOpcode() == ISD::BITCAST)
8788     Op1 = Op1.getOperand(0);
8789   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8790       Op0.getNode() == Op1.getNode() &&
8791       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8792     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8793                        N->getValueType(0), Op0.getOperand(0));
8794   return SDValue();
8795 }
8796
8797 /// PerformSTORECombine - Target-specific dag combine xforms for
8798 /// ISD::STORE.
8799 static SDValue PerformSTORECombine(SDNode *N,
8800                                    TargetLowering::DAGCombinerInfo &DCI) {
8801   StoreSDNode *St = cast<StoreSDNode>(N);
8802   if (St->isVolatile())
8803     return SDValue();
8804
8805   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8806   // pack all of the elements in one place.  Next, store to memory in fewer
8807   // chunks.
8808   SDValue StVal = St->getValue();
8809   EVT VT = StVal.getValueType();
8810   if (St->isTruncatingStore() && VT.isVector()) {
8811     SelectionDAG &DAG = DCI.DAG;
8812     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8813     EVT StVT = St->getMemoryVT();
8814     unsigned NumElems = VT.getVectorNumElements();
8815     assert(StVT != VT && "Cannot truncate to the same type");
8816     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8817     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8818
8819     // From, To sizes and ElemCount must be pow of two
8820     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8821
8822     // We are going to use the original vector elt for storing.
8823     // Accumulated smaller vector elements must be a multiple of the store size.
8824     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8825
8826     unsigned SizeRatio  = FromEltSz / ToEltSz;
8827     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8828
8829     // Create a type on which we perform the shuffle.
8830     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8831                                      NumElems*SizeRatio);
8832     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8833
8834     SDLoc DL(St);
8835     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8836     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8837     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8838
8839     // Can't shuffle using an illegal type.
8840     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8841
8842     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8843                                 DAG.getUNDEF(WideVec.getValueType()),
8844                                 ShuffleVec.data());
8845     // At this point all of the data is stored at the bottom of the
8846     // register. We now need to save it to mem.
8847
8848     // Find the largest store unit
8849     MVT StoreType = MVT::i8;
8850     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8851          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8852       MVT Tp = (MVT::SimpleValueType)tp;
8853       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8854         StoreType = Tp;
8855     }
8856     // Didn't find a legal store type.
8857     if (!TLI.isTypeLegal(StoreType))
8858       return SDValue();
8859
8860     // Bitcast the original vector into a vector of store-size units
8861     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8862             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8863     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8864     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8865     SmallVector<SDValue, 8> Chains;
8866     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8867                                         TLI.getPointerTy());
8868     SDValue BasePtr = St->getBasePtr();
8869
8870     // Perform one or more big stores into memory.
8871     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8872     for (unsigned I = 0; I < E; I++) {
8873       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8874                                    StoreType, ShuffWide,
8875                                    DAG.getIntPtrConstant(I));
8876       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8877                                 St->getPointerInfo(), St->isVolatile(),
8878                                 St->isNonTemporal(), St->getAlignment());
8879       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8880                             Increment);
8881       Chains.push_back(Ch);
8882     }
8883     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8884                        Chains.size());
8885   }
8886
8887   if (!ISD::isNormalStore(St))
8888     return SDValue();
8889
8890   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8891   // ARM stores of arguments in the same cache line.
8892   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8893       StVal.getNode()->hasOneUse()) {
8894     SelectionDAG  &DAG = DCI.DAG;
8895     SDLoc DL(St);
8896     SDValue BasePtr = St->getBasePtr();
8897     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8898                                   StVal.getNode()->getOperand(0), BasePtr,
8899                                   St->getPointerInfo(), St->isVolatile(),
8900                                   St->isNonTemporal(), St->getAlignment());
8901
8902     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8903                                     DAG.getConstant(4, MVT::i32));
8904     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8905                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8906                         St->isNonTemporal(),
8907                         std::min(4U, St->getAlignment() / 2));
8908   }
8909
8910   if (StVal.getValueType() != MVT::i64 ||
8911       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8912     return SDValue();
8913
8914   // Bitcast an i64 store extracted from a vector to f64.
8915   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8916   SelectionDAG &DAG = DCI.DAG;
8917   SDLoc dl(StVal);
8918   SDValue IntVec = StVal.getOperand(0);
8919   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8920                                  IntVec.getValueType().getVectorNumElements());
8921   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8922   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8923                                Vec, StVal.getOperand(1));
8924   dl = SDLoc(N);
8925   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8926   // Make the DAGCombiner fold the bitcasts.
8927   DCI.AddToWorklist(Vec.getNode());
8928   DCI.AddToWorklist(ExtElt.getNode());
8929   DCI.AddToWorklist(V.getNode());
8930   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8931                       St->getPointerInfo(), St->isVolatile(),
8932                       St->isNonTemporal(), St->getAlignment(),
8933                       St->getTBAAInfo());
8934 }
8935
8936 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8937 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8938 /// i64 vector to have f64 elements, since the value can then be loaded
8939 /// directly into a VFP register.
8940 static bool hasNormalLoadOperand(SDNode *N) {
8941   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8942   for (unsigned i = 0; i < NumElts; ++i) {
8943     SDNode *Elt = N->getOperand(i).getNode();
8944     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8945       return true;
8946   }
8947   return false;
8948 }
8949
8950 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8951 /// ISD::BUILD_VECTOR.
8952 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8953                                           TargetLowering::DAGCombinerInfo &DCI){
8954   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8955   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8956   // into a pair of GPRs, which is fine when the value is used as a scalar,
8957   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8958   SelectionDAG &DAG = DCI.DAG;
8959   if (N->getNumOperands() == 2) {
8960     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8961     if (RV.getNode())
8962       return RV;
8963   }
8964
8965   // Load i64 elements as f64 values so that type legalization does not split
8966   // them up into i32 values.
8967   EVT VT = N->getValueType(0);
8968   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8969     return SDValue();
8970   SDLoc dl(N);
8971   SmallVector<SDValue, 8> Ops;
8972   unsigned NumElts = VT.getVectorNumElements();
8973   for (unsigned i = 0; i < NumElts; ++i) {
8974     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8975     Ops.push_back(V);
8976     // Make the DAGCombiner fold the bitcast.
8977     DCI.AddToWorklist(V.getNode());
8978   }
8979   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8980   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8981   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8982 }
8983
8984 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8985 static SDValue
8986 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8987   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8988   // At that time, we may have inserted bitcasts from integer to float.
8989   // If these bitcasts have survived DAGCombine, change the lowering of this
8990   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8991   // force to use floating point types.
8992
8993   // Make sure we can change the type of the vector.
8994   // This is possible iff:
8995   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8996   //    1.1. Vector is used only once.
8997   //    1.2. Use is a bit convert to an integer type.
8998   // 2. The size of its operands are 32-bits (64-bits are not legal).
8999   EVT VT = N->getValueType(0);
9000   EVT EltVT = VT.getVectorElementType();
9001
9002   // Check 1.1. and 2.
9003   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9004     return SDValue();
9005
9006   // By construction, the input type must be float.
9007   assert(EltVT == MVT::f32 && "Unexpected type!");
9008
9009   // Check 1.2.
9010   SDNode *Use = *N->use_begin();
9011   if (Use->getOpcode() != ISD::BITCAST ||
9012       Use->getValueType(0).isFloatingPoint())
9013     return SDValue();
9014
9015   // Check profitability.
9016   // Model is, if more than half of the relevant operands are bitcast from
9017   // i32, turn the build_vector into a sequence of insert_vector_elt.
9018   // Relevant operands are everything that is not statically
9019   // (i.e., at compile time) bitcasted.
9020   unsigned NumOfBitCastedElts = 0;
9021   unsigned NumElts = VT.getVectorNumElements();
9022   unsigned NumOfRelevantElts = NumElts;
9023   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9024     SDValue Elt = N->getOperand(Idx);
9025     if (Elt->getOpcode() == ISD::BITCAST) {
9026       // Assume only bit cast to i32 will go away.
9027       if (Elt->getOperand(0).getValueType() == MVT::i32)
9028         ++NumOfBitCastedElts;
9029     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9030       // Constants are statically casted, thus do not count them as
9031       // relevant operands.
9032       --NumOfRelevantElts;
9033   }
9034
9035   // Check if more than half of the elements require a non-free bitcast.
9036   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9037     return SDValue();
9038
9039   SelectionDAG &DAG = DCI.DAG;
9040   // Create the new vector type.
9041   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9042   // Check if the type is legal.
9043   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9044   if (!TLI.isTypeLegal(VecVT))
9045     return SDValue();
9046
9047   // Combine:
9048   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9049   // => BITCAST INSERT_VECTOR_ELT
9050   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9051   //                      (BITCAST EN), N.
9052   SDValue Vec = DAG.getUNDEF(VecVT);
9053   SDLoc dl(N);
9054   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9055     SDValue V = N->getOperand(Idx);
9056     if (V.getOpcode() == ISD::UNDEF)
9057       continue;
9058     if (V.getOpcode() == ISD::BITCAST &&
9059         V->getOperand(0).getValueType() == MVT::i32)
9060       // Fold obvious case.
9061       V = V.getOperand(0);
9062     else {
9063       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9064       // Make the DAGCombiner fold the bitcasts.
9065       DCI.AddToWorklist(V.getNode());
9066     }
9067     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9068     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9069   }
9070   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9071   // Make the DAGCombiner fold the bitcasts.
9072   DCI.AddToWorklist(Vec.getNode());
9073   return Vec;
9074 }
9075
9076 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9077 /// ISD::INSERT_VECTOR_ELT.
9078 static SDValue PerformInsertEltCombine(SDNode *N,
9079                                        TargetLowering::DAGCombinerInfo &DCI) {
9080   // Bitcast an i64 load inserted into a vector to f64.
9081   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9082   EVT VT = N->getValueType(0);
9083   SDNode *Elt = N->getOperand(1).getNode();
9084   if (VT.getVectorElementType() != MVT::i64 ||
9085       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9086     return SDValue();
9087
9088   SelectionDAG &DAG = DCI.DAG;
9089   SDLoc dl(N);
9090   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9091                                  VT.getVectorNumElements());
9092   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9093   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9094   // Make the DAGCombiner fold the bitcasts.
9095   DCI.AddToWorklist(Vec.getNode());
9096   DCI.AddToWorklist(V.getNode());
9097   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9098                                Vec, V, N->getOperand(2));
9099   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9100 }
9101
9102 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9103 /// ISD::VECTOR_SHUFFLE.
9104 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9105   // The LLVM shufflevector instruction does not require the shuffle mask
9106   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9107   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9108   // operands do not match the mask length, they are extended by concatenating
9109   // them with undef vectors.  That is probably the right thing for other
9110   // targets, but for NEON it is better to concatenate two double-register
9111   // size vector operands into a single quad-register size vector.  Do that
9112   // transformation here:
9113   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9114   //   shuffle(concat(v1, v2), undef)
9115   SDValue Op0 = N->getOperand(0);
9116   SDValue Op1 = N->getOperand(1);
9117   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9118       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9119       Op0.getNumOperands() != 2 ||
9120       Op1.getNumOperands() != 2)
9121     return SDValue();
9122   SDValue Concat0Op1 = Op0.getOperand(1);
9123   SDValue Concat1Op1 = Op1.getOperand(1);
9124   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9125       Concat1Op1.getOpcode() != ISD::UNDEF)
9126     return SDValue();
9127   // Skip the transformation if any of the types are illegal.
9128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9129   EVT VT = N->getValueType(0);
9130   if (!TLI.isTypeLegal(VT) ||
9131       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9132       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9133     return SDValue();
9134
9135   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9136                                   Op0.getOperand(0), Op1.getOperand(0));
9137   // Translate the shuffle mask.
9138   SmallVector<int, 16> NewMask;
9139   unsigned NumElts = VT.getVectorNumElements();
9140   unsigned HalfElts = NumElts/2;
9141   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9142   for (unsigned n = 0; n < NumElts; ++n) {
9143     int MaskElt = SVN->getMaskElt(n);
9144     int NewElt = -1;
9145     if (MaskElt < (int)HalfElts)
9146       NewElt = MaskElt;
9147     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9148       NewElt = HalfElts + MaskElt - NumElts;
9149     NewMask.push_back(NewElt);
9150   }
9151   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9152                               DAG.getUNDEF(VT), NewMask.data());
9153 }
9154
9155 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9156 /// NEON load/store intrinsics to merge base address updates.
9157 static SDValue CombineBaseUpdate(SDNode *N,
9158                                  TargetLowering::DAGCombinerInfo &DCI) {
9159   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9160     return SDValue();
9161
9162   SelectionDAG &DAG = DCI.DAG;
9163   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9164                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9165   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9166   SDValue Addr = N->getOperand(AddrOpIdx);
9167
9168   // Search for a use of the address operand that is an increment.
9169   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9170          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9171     SDNode *User = *UI;
9172     if (User->getOpcode() != ISD::ADD ||
9173         UI.getUse().getResNo() != Addr.getResNo())
9174       continue;
9175
9176     // Check that the add is independent of the load/store.  Otherwise, folding
9177     // it would create a cycle.
9178     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9179       continue;
9180
9181     // Find the new opcode for the updating load/store.
9182     bool isLoad = true;
9183     bool isLaneOp = false;
9184     unsigned NewOpc = 0;
9185     unsigned NumVecs = 0;
9186     if (isIntrinsic) {
9187       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9188       switch (IntNo) {
9189       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9190       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9191         NumVecs = 1; break;
9192       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9193         NumVecs = 2; break;
9194       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9195         NumVecs = 3; break;
9196       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9197         NumVecs = 4; break;
9198       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9199         NumVecs = 2; isLaneOp = true; break;
9200       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9201         NumVecs = 3; isLaneOp = true; break;
9202       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9203         NumVecs = 4; isLaneOp = true; break;
9204       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9205         NumVecs = 1; isLoad = false; break;
9206       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9207         NumVecs = 2; isLoad = false; break;
9208       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9209         NumVecs = 3; isLoad = false; break;
9210       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9211         NumVecs = 4; isLoad = false; break;
9212       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9213         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9214       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9215         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9216       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9217         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9218       }
9219     } else {
9220       isLaneOp = true;
9221       switch (N->getOpcode()) {
9222       default: llvm_unreachable("unexpected opcode for Neon base update");
9223       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9224       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9225       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9226       }
9227     }
9228
9229     // Find the size of memory referenced by the load/store.
9230     EVT VecTy;
9231     if (isLoad)
9232       VecTy = N->getValueType(0);
9233     else
9234       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9235     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9236     if (isLaneOp)
9237       NumBytes /= VecTy.getVectorNumElements();
9238
9239     // If the increment is a constant, it must match the memory ref size.
9240     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9241     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9242       uint64_t IncVal = CInc->getZExtValue();
9243       if (IncVal != NumBytes)
9244         continue;
9245     } else if (NumBytes >= 3 * 16) {
9246       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9247       // separate instructions that make it harder to use a non-constant update.
9248       continue;
9249     }
9250
9251     // Create the new updating load/store node.
9252     EVT Tys[6];
9253     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9254     unsigned n;
9255     for (n = 0; n < NumResultVecs; ++n)
9256       Tys[n] = VecTy;
9257     Tys[n++] = MVT::i32;
9258     Tys[n] = MVT::Other;
9259     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9260     SmallVector<SDValue, 8> Ops;
9261     Ops.push_back(N->getOperand(0)); // incoming chain
9262     Ops.push_back(N->getOperand(AddrOpIdx));
9263     Ops.push_back(Inc);
9264     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9265       Ops.push_back(N->getOperand(i));
9266     }
9267     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9268     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9269                                            Ops.data(), Ops.size(),
9270                                            MemInt->getMemoryVT(),
9271                                            MemInt->getMemOperand());
9272
9273     // Update the uses.
9274     std::vector<SDValue> NewResults;
9275     for (unsigned i = 0; i < NumResultVecs; ++i) {
9276       NewResults.push_back(SDValue(UpdN.getNode(), i));
9277     }
9278     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9279     DCI.CombineTo(N, NewResults);
9280     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9281
9282     break;
9283   }
9284   return SDValue();
9285 }
9286
9287 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9288 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9289 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9290 /// return true.
9291 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9292   SelectionDAG &DAG = DCI.DAG;
9293   EVT VT = N->getValueType(0);
9294   // vldN-dup instructions only support 64-bit vectors for N > 1.
9295   if (!VT.is64BitVector())
9296     return false;
9297
9298   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9299   SDNode *VLD = N->getOperand(0).getNode();
9300   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9301     return false;
9302   unsigned NumVecs = 0;
9303   unsigned NewOpc = 0;
9304   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9305   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9306     NumVecs = 2;
9307     NewOpc = ARMISD::VLD2DUP;
9308   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9309     NumVecs = 3;
9310     NewOpc = ARMISD::VLD3DUP;
9311   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9312     NumVecs = 4;
9313     NewOpc = ARMISD::VLD4DUP;
9314   } else {
9315     return false;
9316   }
9317
9318   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9319   // numbers match the load.
9320   unsigned VLDLaneNo =
9321     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9322   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9323        UI != UE; ++UI) {
9324     // Ignore uses of the chain result.
9325     if (UI.getUse().getResNo() == NumVecs)
9326       continue;
9327     SDNode *User = *UI;
9328     if (User->getOpcode() != ARMISD::VDUPLANE ||
9329         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9330       return false;
9331   }
9332
9333   // Create the vldN-dup node.
9334   EVT Tys[5];
9335   unsigned n;
9336   for (n = 0; n < NumVecs; ++n)
9337     Tys[n] = VT;
9338   Tys[n] = MVT::Other;
9339   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9340   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9341   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9342   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9343                                            Ops, 2, VLDMemInt->getMemoryVT(),
9344                                            VLDMemInt->getMemOperand());
9345
9346   // Update the uses.
9347   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9348        UI != UE; ++UI) {
9349     unsigned ResNo = UI.getUse().getResNo();
9350     // Ignore uses of the chain result.
9351     if (ResNo == NumVecs)
9352       continue;
9353     SDNode *User = *UI;
9354     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9355   }
9356
9357   // Now the vldN-lane intrinsic is dead except for its chain result.
9358   // Update uses of the chain.
9359   std::vector<SDValue> VLDDupResults;
9360   for (unsigned n = 0; n < NumVecs; ++n)
9361     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9362   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9363   DCI.CombineTo(VLD, VLDDupResults);
9364
9365   return true;
9366 }
9367
9368 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9369 /// ARMISD::VDUPLANE.
9370 static SDValue PerformVDUPLANECombine(SDNode *N,
9371                                       TargetLowering::DAGCombinerInfo &DCI) {
9372   SDValue Op = N->getOperand(0);
9373
9374   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9375   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9376   if (CombineVLDDUP(N, DCI))
9377     return SDValue(N, 0);
9378
9379   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9380   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9381   while (Op.getOpcode() == ISD::BITCAST)
9382     Op = Op.getOperand(0);
9383   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9384     return SDValue();
9385
9386   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9387   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9388   // The canonical VMOV for a zero vector uses a 32-bit element size.
9389   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9390   unsigned EltBits;
9391   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9392     EltSize = 8;
9393   EVT VT = N->getValueType(0);
9394   if (EltSize > VT.getVectorElementType().getSizeInBits())
9395     return SDValue();
9396
9397   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9398 }
9399
9400 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9401 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9402 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9403 {
9404   integerPart cN;
9405   integerPart c0 = 0;
9406   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9407        I != E; I++) {
9408     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9409     if (!C)
9410       return false;
9411
9412     bool isExact;
9413     APFloat APF = C->getValueAPF();
9414     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9415         != APFloat::opOK || !isExact)
9416       return false;
9417
9418     c0 = (I == 0) ? cN : c0;
9419     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9420       return false;
9421   }
9422   C = c0;
9423   return true;
9424 }
9425
9426 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9427 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9428 /// when the VMUL has a constant operand that is a power of 2.
9429 ///
9430 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9431 ///  vmul.f32        d16, d17, d16
9432 ///  vcvt.s32.f32    d16, d16
9433 /// becomes:
9434 ///  vcvt.s32.f32    d16, d16, #3
9435 static SDValue PerformVCVTCombine(SDNode *N,
9436                                   TargetLowering::DAGCombinerInfo &DCI,
9437                                   const ARMSubtarget *Subtarget) {
9438   SelectionDAG &DAG = DCI.DAG;
9439   SDValue Op = N->getOperand(0);
9440
9441   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9442       Op.getOpcode() != ISD::FMUL)
9443     return SDValue();
9444
9445   uint64_t C;
9446   SDValue N0 = Op->getOperand(0);
9447   SDValue ConstVec = Op->getOperand(1);
9448   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9449
9450   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9451       !isConstVecPow2(ConstVec, isSigned, C))
9452     return SDValue();
9453
9454   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9455   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9456   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9457     // These instructions only exist converting from f32 to i32. We can handle
9458     // smaller integers by generating an extra truncate, but larger ones would
9459     // be lossy.
9460     return SDValue();
9461   }
9462
9463   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9464     Intrinsic::arm_neon_vcvtfp2fxu;
9465   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9466   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9467                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9468                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9469                                  DAG.getConstant(Log2_64(C), MVT::i32));
9470
9471   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9472     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9473
9474   return FixConv;
9475 }
9476
9477 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9478 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9479 /// when the VDIV has a constant operand that is a power of 2.
9480 ///
9481 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9482 ///  vcvt.f32.s32    d16, d16
9483 ///  vdiv.f32        d16, d17, d16
9484 /// becomes:
9485 ///  vcvt.f32.s32    d16, d16, #3
9486 static SDValue PerformVDIVCombine(SDNode *N,
9487                                   TargetLowering::DAGCombinerInfo &DCI,
9488                                   const ARMSubtarget *Subtarget) {
9489   SelectionDAG &DAG = DCI.DAG;
9490   SDValue Op = N->getOperand(0);
9491   unsigned OpOpcode = Op.getNode()->getOpcode();
9492
9493   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9494       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9495     return SDValue();
9496
9497   uint64_t C;
9498   SDValue ConstVec = N->getOperand(1);
9499   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9500
9501   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9502       !isConstVecPow2(ConstVec, isSigned, C))
9503     return SDValue();
9504
9505   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9506   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9507   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9508     // These instructions only exist converting from i32 to f32. We can handle
9509     // smaller integers by generating an extra extend, but larger ones would
9510     // be lossy.
9511     return SDValue();
9512   }
9513
9514   SDValue ConvInput = Op.getOperand(0);
9515   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9516   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9517     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9518                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9519                             ConvInput);
9520
9521   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9522     Intrinsic::arm_neon_vcvtfxu2fp;
9523   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9524                      Op.getValueType(),
9525                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9526                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9527 }
9528
9529 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9530 /// operand of a vector shift operation, where all the elements of the
9531 /// build_vector must have the same constant integer value.
9532 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9533   // Ignore bit_converts.
9534   while (Op.getOpcode() == ISD::BITCAST)
9535     Op = Op.getOperand(0);
9536   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9537   APInt SplatBits, SplatUndef;
9538   unsigned SplatBitSize;
9539   bool HasAnyUndefs;
9540   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9541                                       HasAnyUndefs, ElementBits) ||
9542       SplatBitSize > ElementBits)
9543     return false;
9544   Cnt = SplatBits.getSExtValue();
9545   return true;
9546 }
9547
9548 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9549 /// operand of a vector shift left operation.  That value must be in the range:
9550 ///   0 <= Value < ElementBits for a left shift; or
9551 ///   0 <= Value <= ElementBits for a long left shift.
9552 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9553   assert(VT.isVector() && "vector shift count is not a vector type");
9554   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9555   if (! getVShiftImm(Op, ElementBits, Cnt))
9556     return false;
9557   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9558 }
9559
9560 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9561 /// operand of a vector shift right operation.  For a shift opcode, the value
9562 /// is positive, but for an intrinsic the value count must be negative. The
9563 /// absolute value must be in the range:
9564 ///   1 <= |Value| <= ElementBits for a right shift; or
9565 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9566 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9567                          int64_t &Cnt) {
9568   assert(VT.isVector() && "vector shift count is not a vector type");
9569   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9570   if (! getVShiftImm(Op, ElementBits, Cnt))
9571     return false;
9572   if (isIntrinsic)
9573     Cnt = -Cnt;
9574   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9575 }
9576
9577 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9578 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9579   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9580   switch (IntNo) {
9581   default:
9582     // Don't do anything for most intrinsics.
9583     break;
9584
9585   // Vector shifts: check for immediate versions and lower them.
9586   // Note: This is done during DAG combining instead of DAG legalizing because
9587   // the build_vectors for 64-bit vector element shift counts are generally
9588   // not legal, and it is hard to see their values after they get legalized to
9589   // loads from a constant pool.
9590   case Intrinsic::arm_neon_vshifts:
9591   case Intrinsic::arm_neon_vshiftu:
9592   case Intrinsic::arm_neon_vshiftls:
9593   case Intrinsic::arm_neon_vshiftlu:
9594   case Intrinsic::arm_neon_vshiftn:
9595   case Intrinsic::arm_neon_vrshifts:
9596   case Intrinsic::arm_neon_vrshiftu:
9597   case Intrinsic::arm_neon_vrshiftn:
9598   case Intrinsic::arm_neon_vqshifts:
9599   case Intrinsic::arm_neon_vqshiftu:
9600   case Intrinsic::arm_neon_vqshiftsu:
9601   case Intrinsic::arm_neon_vqshiftns:
9602   case Intrinsic::arm_neon_vqshiftnu:
9603   case Intrinsic::arm_neon_vqshiftnsu:
9604   case Intrinsic::arm_neon_vqrshiftns:
9605   case Intrinsic::arm_neon_vqrshiftnu:
9606   case Intrinsic::arm_neon_vqrshiftnsu: {
9607     EVT VT = N->getOperand(1).getValueType();
9608     int64_t Cnt;
9609     unsigned VShiftOpc = 0;
9610
9611     switch (IntNo) {
9612     case Intrinsic::arm_neon_vshifts:
9613     case Intrinsic::arm_neon_vshiftu:
9614       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9615         VShiftOpc = ARMISD::VSHL;
9616         break;
9617       }
9618       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9619         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9620                      ARMISD::VSHRs : ARMISD::VSHRu);
9621         break;
9622       }
9623       return SDValue();
9624
9625     case Intrinsic::arm_neon_vshiftls:
9626     case Intrinsic::arm_neon_vshiftlu:
9627       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9628         break;
9629       llvm_unreachable("invalid shift count for vshll intrinsic");
9630
9631     case Intrinsic::arm_neon_vrshifts:
9632     case Intrinsic::arm_neon_vrshiftu:
9633       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9634         break;
9635       return SDValue();
9636
9637     case Intrinsic::arm_neon_vqshifts:
9638     case Intrinsic::arm_neon_vqshiftu:
9639       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9640         break;
9641       return SDValue();
9642
9643     case Intrinsic::arm_neon_vqshiftsu:
9644       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9645         break;
9646       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9647
9648     case Intrinsic::arm_neon_vshiftn:
9649     case Intrinsic::arm_neon_vrshiftn:
9650     case Intrinsic::arm_neon_vqshiftns:
9651     case Intrinsic::arm_neon_vqshiftnu:
9652     case Intrinsic::arm_neon_vqshiftnsu:
9653     case Intrinsic::arm_neon_vqrshiftns:
9654     case Intrinsic::arm_neon_vqrshiftnu:
9655     case Intrinsic::arm_neon_vqrshiftnsu:
9656       // Narrowing shifts require an immediate right shift.
9657       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9658         break;
9659       llvm_unreachable("invalid shift count for narrowing vector shift "
9660                        "intrinsic");
9661
9662     default:
9663       llvm_unreachable("unhandled vector shift");
9664     }
9665
9666     switch (IntNo) {
9667     case Intrinsic::arm_neon_vshifts:
9668     case Intrinsic::arm_neon_vshiftu:
9669       // Opcode already set above.
9670       break;
9671     case Intrinsic::arm_neon_vshiftls:
9672     case Intrinsic::arm_neon_vshiftlu:
9673       if (Cnt == VT.getVectorElementType().getSizeInBits())
9674         VShiftOpc = ARMISD::VSHLLi;
9675       else
9676         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9677                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9678       break;
9679     case Intrinsic::arm_neon_vshiftn:
9680       VShiftOpc = ARMISD::VSHRN; break;
9681     case Intrinsic::arm_neon_vrshifts:
9682       VShiftOpc = ARMISD::VRSHRs; break;
9683     case Intrinsic::arm_neon_vrshiftu:
9684       VShiftOpc = ARMISD::VRSHRu; break;
9685     case Intrinsic::arm_neon_vrshiftn:
9686       VShiftOpc = ARMISD::VRSHRN; break;
9687     case Intrinsic::arm_neon_vqshifts:
9688       VShiftOpc = ARMISD::VQSHLs; break;
9689     case Intrinsic::arm_neon_vqshiftu:
9690       VShiftOpc = ARMISD::VQSHLu; break;
9691     case Intrinsic::arm_neon_vqshiftsu:
9692       VShiftOpc = ARMISD::VQSHLsu; break;
9693     case Intrinsic::arm_neon_vqshiftns:
9694       VShiftOpc = ARMISD::VQSHRNs; break;
9695     case Intrinsic::arm_neon_vqshiftnu:
9696       VShiftOpc = ARMISD::VQSHRNu; break;
9697     case Intrinsic::arm_neon_vqshiftnsu:
9698       VShiftOpc = ARMISD::VQSHRNsu; break;
9699     case Intrinsic::arm_neon_vqrshiftns:
9700       VShiftOpc = ARMISD::VQRSHRNs; break;
9701     case Intrinsic::arm_neon_vqrshiftnu:
9702       VShiftOpc = ARMISD::VQRSHRNu; break;
9703     case Intrinsic::arm_neon_vqrshiftnsu:
9704       VShiftOpc = ARMISD::VQRSHRNsu; break;
9705     }
9706
9707     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9708                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9709   }
9710
9711   case Intrinsic::arm_neon_vshiftins: {
9712     EVT VT = N->getOperand(1).getValueType();
9713     int64_t Cnt;
9714     unsigned VShiftOpc = 0;
9715
9716     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9717       VShiftOpc = ARMISD::VSLI;
9718     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9719       VShiftOpc = ARMISD::VSRI;
9720     else {
9721       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9722     }
9723
9724     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9725                        N->getOperand(1), N->getOperand(2),
9726                        DAG.getConstant(Cnt, MVT::i32));
9727   }
9728
9729   case Intrinsic::arm_neon_vqrshifts:
9730   case Intrinsic::arm_neon_vqrshiftu:
9731     // No immediate versions of these to check for.
9732     break;
9733   }
9734
9735   return SDValue();
9736 }
9737
9738 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9739 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9740 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9741 /// vector element shift counts are generally not legal, and it is hard to see
9742 /// their values after they get legalized to loads from a constant pool.
9743 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9744                                    const ARMSubtarget *ST) {
9745   EVT VT = N->getValueType(0);
9746   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9747     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9748     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9749     SDValue N1 = N->getOperand(1);
9750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9751       SDValue N0 = N->getOperand(0);
9752       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9753           DAG.MaskedValueIsZero(N0.getOperand(0),
9754                                 APInt::getHighBitsSet(32, 16)))
9755         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9756     }
9757   }
9758
9759   // Nothing to be done for scalar shifts.
9760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9761   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9762     return SDValue();
9763
9764   assert(ST->hasNEON() && "unexpected vector shift");
9765   int64_t Cnt;
9766
9767   switch (N->getOpcode()) {
9768   default: llvm_unreachable("unexpected shift opcode");
9769
9770   case ISD::SHL:
9771     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9772       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9773                          DAG.getConstant(Cnt, MVT::i32));
9774     break;
9775
9776   case ISD::SRA:
9777   case ISD::SRL:
9778     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9779       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9780                             ARMISD::VSHRs : ARMISD::VSHRu);
9781       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9782                          DAG.getConstant(Cnt, MVT::i32));
9783     }
9784   }
9785   return SDValue();
9786 }
9787
9788 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9789 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9790 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9791                                     const ARMSubtarget *ST) {
9792   SDValue N0 = N->getOperand(0);
9793
9794   // Check for sign- and zero-extensions of vector extract operations of 8-
9795   // and 16-bit vector elements.  NEON supports these directly.  They are
9796   // handled during DAG combining because type legalization will promote them
9797   // to 32-bit types and it is messy to recognize the operations after that.
9798   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9799     SDValue Vec = N0.getOperand(0);
9800     SDValue Lane = N0.getOperand(1);
9801     EVT VT = N->getValueType(0);
9802     EVT EltVT = N0.getValueType();
9803     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9804
9805     if (VT == MVT::i32 &&
9806         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9807         TLI.isTypeLegal(Vec.getValueType()) &&
9808         isa<ConstantSDNode>(Lane)) {
9809
9810       unsigned Opc = 0;
9811       switch (N->getOpcode()) {
9812       default: llvm_unreachable("unexpected opcode");
9813       case ISD::SIGN_EXTEND:
9814         Opc = ARMISD::VGETLANEs;
9815         break;
9816       case ISD::ZERO_EXTEND:
9817       case ISD::ANY_EXTEND:
9818         Opc = ARMISD::VGETLANEu;
9819         break;
9820       }
9821       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9822     }
9823   }
9824
9825   return SDValue();
9826 }
9827
9828 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9829 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9830 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9831                                        const ARMSubtarget *ST) {
9832   // If the target supports NEON, try to use vmax/vmin instructions for f32
9833   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9834   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9835   // a NaN; only do the transformation when it matches that behavior.
9836
9837   // For now only do this when using NEON for FP operations; if using VFP, it
9838   // is not obvious that the benefit outweighs the cost of switching to the
9839   // NEON pipeline.
9840   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9841       N->getValueType(0) != MVT::f32)
9842     return SDValue();
9843
9844   SDValue CondLHS = N->getOperand(0);
9845   SDValue CondRHS = N->getOperand(1);
9846   SDValue LHS = N->getOperand(2);
9847   SDValue RHS = N->getOperand(3);
9848   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9849
9850   unsigned Opcode = 0;
9851   bool IsReversed;
9852   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9853     IsReversed = false; // x CC y ? x : y
9854   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9855     IsReversed = true ; // x CC y ? y : x
9856   } else {
9857     return SDValue();
9858   }
9859
9860   bool IsUnordered;
9861   switch (CC) {
9862   default: break;
9863   case ISD::SETOLT:
9864   case ISD::SETOLE:
9865   case ISD::SETLT:
9866   case ISD::SETLE:
9867   case ISD::SETULT:
9868   case ISD::SETULE:
9869     // If LHS is NaN, an ordered comparison will be false and the result will
9870     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9871     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9872     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9873     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9874       break;
9875     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9876     // will return -0, so vmin can only be used for unsafe math or if one of
9877     // the operands is known to be nonzero.
9878     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9879         !DAG.getTarget().Options.UnsafeFPMath &&
9880         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9881       break;
9882     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9883     break;
9884
9885   case ISD::SETOGT:
9886   case ISD::SETOGE:
9887   case ISD::SETGT:
9888   case ISD::SETGE:
9889   case ISD::SETUGT:
9890   case ISD::SETUGE:
9891     // If LHS is NaN, an ordered comparison will be false and the result will
9892     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9893     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9894     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9895     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9896       break;
9897     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9898     // will return +0, so vmax can only be used for unsafe math or if one of
9899     // the operands is known to be nonzero.
9900     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9901         !DAG.getTarget().Options.UnsafeFPMath &&
9902         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9903       break;
9904     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9905     break;
9906   }
9907
9908   if (!Opcode)
9909     return SDValue();
9910   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9911 }
9912
9913 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9914 SDValue
9915 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9916   SDValue Cmp = N->getOperand(4);
9917   if (Cmp.getOpcode() != ARMISD::CMPZ)
9918     // Only looking at EQ and NE cases.
9919     return SDValue();
9920
9921   EVT VT = N->getValueType(0);
9922   SDLoc dl(N);
9923   SDValue LHS = Cmp.getOperand(0);
9924   SDValue RHS = Cmp.getOperand(1);
9925   SDValue FalseVal = N->getOperand(0);
9926   SDValue TrueVal = N->getOperand(1);
9927   SDValue ARMcc = N->getOperand(2);
9928   ARMCC::CondCodes CC =
9929     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9930
9931   // Simplify
9932   //   mov     r1, r0
9933   //   cmp     r1, x
9934   //   mov     r0, y
9935   //   moveq   r0, x
9936   // to
9937   //   cmp     r0, x
9938   //   movne   r0, y
9939   //
9940   //   mov     r1, r0
9941   //   cmp     r1, x
9942   //   mov     r0, x
9943   //   movne   r0, y
9944   // to
9945   //   cmp     r0, x
9946   //   movne   r0, y
9947   /// FIXME: Turn this into a target neutral optimization?
9948   SDValue Res;
9949   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9950     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9951                       N->getOperand(3), Cmp);
9952   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9953     SDValue ARMcc;
9954     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9955     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9956                       N->getOperand(3), NewCmp);
9957   }
9958
9959   if (Res.getNode()) {
9960     APInt KnownZero, KnownOne;
9961     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9962     // Capture demanded bits information that would be otherwise lost.
9963     if (KnownZero == 0xfffffffe)
9964       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9965                         DAG.getValueType(MVT::i1));
9966     else if (KnownZero == 0xffffff00)
9967       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9968                         DAG.getValueType(MVT::i8));
9969     else if (KnownZero == 0xffff0000)
9970       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9971                         DAG.getValueType(MVT::i16));
9972   }
9973
9974   return Res;
9975 }
9976
9977 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9978                                              DAGCombinerInfo &DCI) const {
9979   switch (N->getOpcode()) {
9980   default: break;
9981   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9982   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9983   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9984   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9985   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9986   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9987   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9988   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9989   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9990   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9991   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9992   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9993   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9994   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9995   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9996   case ISD::FP_TO_SINT:
9997   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9998   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9999   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10000   case ISD::SHL:
10001   case ISD::SRA:
10002   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10003   case ISD::SIGN_EXTEND:
10004   case ISD::ZERO_EXTEND:
10005   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10006   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10007   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10008   case ARMISD::VLD2DUP:
10009   case ARMISD::VLD3DUP:
10010   case ARMISD::VLD4DUP:
10011     return CombineBaseUpdate(N, DCI);
10012   case ARMISD::BUILD_VECTOR:
10013     return PerformARMBUILD_VECTORCombine(N, DCI);
10014   case ISD::INTRINSIC_VOID:
10015   case ISD::INTRINSIC_W_CHAIN:
10016     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10017     case Intrinsic::arm_neon_vld1:
10018     case Intrinsic::arm_neon_vld2:
10019     case Intrinsic::arm_neon_vld3:
10020     case Intrinsic::arm_neon_vld4:
10021     case Intrinsic::arm_neon_vld2lane:
10022     case Intrinsic::arm_neon_vld3lane:
10023     case Intrinsic::arm_neon_vld4lane:
10024     case Intrinsic::arm_neon_vst1:
10025     case Intrinsic::arm_neon_vst2:
10026     case Intrinsic::arm_neon_vst3:
10027     case Intrinsic::arm_neon_vst4:
10028     case Intrinsic::arm_neon_vst2lane:
10029     case Intrinsic::arm_neon_vst3lane:
10030     case Intrinsic::arm_neon_vst4lane:
10031       return CombineBaseUpdate(N, DCI);
10032     default: break;
10033     }
10034     break;
10035   }
10036   return SDValue();
10037 }
10038
10039 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10040                                                           EVT VT) const {
10041   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10042 }
10043
10044 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10045   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10046   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10047
10048   switch (VT.getSimpleVT().SimpleTy) {
10049   default:
10050     return false;
10051   case MVT::i8:
10052   case MVT::i16:
10053   case MVT::i32: {
10054     // Unaligned access can use (for example) LRDB, LRDH, LDR
10055     if (AllowsUnaligned) {
10056       if (Fast)
10057         *Fast = Subtarget->hasV7Ops();
10058       return true;
10059     }
10060     return false;
10061   }
10062   case MVT::f64:
10063   case MVT::v2f64: {
10064     // For any little-endian targets with neon, we can support unaligned ld/st
10065     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10066     // A big-endian target may also explictly support unaligned accesses
10067     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10068       if (Fast)
10069         *Fast = true;
10070       return true;
10071     }
10072     return false;
10073   }
10074   }
10075 }
10076
10077 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10078                        unsigned AlignCheck) {
10079   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10080           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10081 }
10082
10083 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10084                                            unsigned DstAlign, unsigned SrcAlign,
10085                                            bool IsMemset, bool ZeroMemset,
10086                                            bool MemcpyStrSrc,
10087                                            MachineFunction &MF) const {
10088   const Function *F = MF.getFunction();
10089
10090   // See if we can use NEON instructions for this...
10091   if ((!IsMemset || ZeroMemset) &&
10092       Subtarget->hasNEON() &&
10093       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10094                                        Attribute::NoImplicitFloat)) {
10095     bool Fast;
10096     if (Size >= 16 &&
10097         (memOpAlign(SrcAlign, DstAlign, 16) ||
10098          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10099       return MVT::v2f64;
10100     } else if (Size >= 8 &&
10101                (memOpAlign(SrcAlign, DstAlign, 8) ||
10102                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10103       return MVT::f64;
10104     }
10105   }
10106
10107   // Lowering to i32/i16 if the size permits.
10108   if (Size >= 4)
10109     return MVT::i32;
10110   else if (Size >= 2)
10111     return MVT::i16;
10112
10113   // Let the target-independent logic figure it out.
10114   return MVT::Other;
10115 }
10116
10117 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10118   if (Val.getOpcode() != ISD::LOAD)
10119     return false;
10120
10121   EVT VT1 = Val.getValueType();
10122   if (!VT1.isSimple() || !VT1.isInteger() ||
10123       !VT2.isSimple() || !VT2.isInteger())
10124     return false;
10125
10126   switch (VT1.getSimpleVT().SimpleTy) {
10127   default: break;
10128   case MVT::i1:
10129   case MVT::i8:
10130   case MVT::i16:
10131     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10132     return true;
10133   }
10134
10135   return false;
10136 }
10137
10138 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10139   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10140     return false;
10141
10142   if (!isTypeLegal(EVT::getEVT(Ty1)))
10143     return false;
10144
10145   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10146
10147   // Assuming the caller doesn't have a zeroext or signext return parameter,
10148   // truncation all the way down to i1 is valid.
10149   return true;
10150 }
10151
10152
10153 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10154   if (V < 0)
10155     return false;
10156
10157   unsigned Scale = 1;
10158   switch (VT.getSimpleVT().SimpleTy) {
10159   default: return false;
10160   case MVT::i1:
10161   case MVT::i8:
10162     // Scale == 1;
10163     break;
10164   case MVT::i16:
10165     // Scale == 2;
10166     Scale = 2;
10167     break;
10168   case MVT::i32:
10169     // Scale == 4;
10170     Scale = 4;
10171     break;
10172   }
10173
10174   if ((V & (Scale - 1)) != 0)
10175     return false;
10176   V /= Scale;
10177   return V == (V & ((1LL << 5) - 1));
10178 }
10179
10180 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10181                                       const ARMSubtarget *Subtarget) {
10182   bool isNeg = false;
10183   if (V < 0) {
10184     isNeg = true;
10185     V = - V;
10186   }
10187
10188   switch (VT.getSimpleVT().SimpleTy) {
10189   default: return false;
10190   case MVT::i1:
10191   case MVT::i8:
10192   case MVT::i16:
10193   case MVT::i32:
10194     // + imm12 or - imm8
10195     if (isNeg)
10196       return V == (V & ((1LL << 8) - 1));
10197     return V == (V & ((1LL << 12) - 1));
10198   case MVT::f32:
10199   case MVT::f64:
10200     // Same as ARM mode. FIXME: NEON?
10201     if (!Subtarget->hasVFP2())
10202       return false;
10203     if ((V & 3) != 0)
10204       return false;
10205     V >>= 2;
10206     return V == (V & ((1LL << 8) - 1));
10207   }
10208 }
10209
10210 /// isLegalAddressImmediate - Return true if the integer value can be used
10211 /// as the offset of the target addressing mode for load / store of the
10212 /// given type.
10213 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10214                                     const ARMSubtarget *Subtarget) {
10215   if (V == 0)
10216     return true;
10217
10218   if (!VT.isSimple())
10219     return false;
10220
10221   if (Subtarget->isThumb1Only())
10222     return isLegalT1AddressImmediate(V, VT);
10223   else if (Subtarget->isThumb2())
10224     return isLegalT2AddressImmediate(V, VT, Subtarget);
10225
10226   // ARM mode.
10227   if (V < 0)
10228     V = - V;
10229   switch (VT.getSimpleVT().SimpleTy) {
10230   default: return false;
10231   case MVT::i1:
10232   case MVT::i8:
10233   case MVT::i32:
10234     // +- imm12
10235     return V == (V & ((1LL << 12) - 1));
10236   case MVT::i16:
10237     // +- imm8
10238     return V == (V & ((1LL << 8) - 1));
10239   case MVT::f32:
10240   case MVT::f64:
10241     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10242       return false;
10243     if ((V & 3) != 0)
10244       return false;
10245     V >>= 2;
10246     return V == (V & ((1LL << 8) - 1));
10247   }
10248 }
10249
10250 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10251                                                       EVT VT) const {
10252   int Scale = AM.Scale;
10253   if (Scale < 0)
10254     return false;
10255
10256   switch (VT.getSimpleVT().SimpleTy) {
10257   default: return false;
10258   case MVT::i1:
10259   case MVT::i8:
10260   case MVT::i16:
10261   case MVT::i32:
10262     if (Scale == 1)
10263       return true;
10264     // r + r << imm
10265     Scale = Scale & ~1;
10266     return Scale == 2 || Scale == 4 || Scale == 8;
10267   case MVT::i64:
10268     // r + r
10269     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10270       return true;
10271     return false;
10272   case MVT::isVoid:
10273     // Note, we allow "void" uses (basically, uses that aren't loads or
10274     // stores), because arm allows folding a scale into many arithmetic
10275     // operations.  This should be made more precise and revisited later.
10276
10277     // Allow r << imm, but the imm has to be a multiple of two.
10278     if (Scale & 1) return false;
10279     return isPowerOf2_32(Scale);
10280   }
10281 }
10282
10283 /// isLegalAddressingMode - Return true if the addressing mode represented
10284 /// by AM is legal for this target, for a load/store of the specified type.
10285 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10286                                               Type *Ty) const {
10287   EVT VT = getValueType(Ty, true);
10288   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10289     return false;
10290
10291   // Can never fold addr of global into load/store.
10292   if (AM.BaseGV)
10293     return false;
10294
10295   switch (AM.Scale) {
10296   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10297     break;
10298   case 1:
10299     if (Subtarget->isThumb1Only())
10300       return false;
10301     // FALL THROUGH.
10302   default:
10303     // ARM doesn't support any R+R*scale+imm addr modes.
10304     if (AM.BaseOffs)
10305       return false;
10306
10307     if (!VT.isSimple())
10308       return false;
10309
10310     if (Subtarget->isThumb2())
10311       return isLegalT2ScaledAddressingMode(AM, VT);
10312
10313     int Scale = AM.Scale;
10314     switch (VT.getSimpleVT().SimpleTy) {
10315     default: return false;
10316     case MVT::i1:
10317     case MVT::i8:
10318     case MVT::i32:
10319       if (Scale < 0) Scale = -Scale;
10320       if (Scale == 1)
10321         return true;
10322       // r + r << imm
10323       return isPowerOf2_32(Scale & ~1);
10324     case MVT::i16:
10325     case MVT::i64:
10326       // r + r
10327       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10328         return true;
10329       return false;
10330
10331     case MVT::isVoid:
10332       // Note, we allow "void" uses (basically, uses that aren't loads or
10333       // stores), because arm allows folding a scale into many arithmetic
10334       // operations.  This should be made more precise and revisited later.
10335
10336       // Allow r << imm, but the imm has to be a multiple of two.
10337       if (Scale & 1) return false;
10338       return isPowerOf2_32(Scale);
10339     }
10340   }
10341   return true;
10342 }
10343
10344 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10345 /// icmp immediate, that is the target has icmp instructions which can compare
10346 /// a register against the immediate without having to materialize the
10347 /// immediate into a register.
10348 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10349   // Thumb2 and ARM modes can use cmn for negative immediates.
10350   if (!Subtarget->isThumb())
10351     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10352   if (Subtarget->isThumb2())
10353     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10354   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10355   return Imm >= 0 && Imm <= 255;
10356 }
10357
10358 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10359 /// *or sub* immediate, that is the target has add or sub instructions which can
10360 /// add a register with the immediate without having to materialize the
10361 /// immediate into a register.
10362 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10363   // Same encoding for add/sub, just flip the sign.
10364   int64_t AbsImm = llvm::abs64(Imm);
10365   if (!Subtarget->isThumb())
10366     return ARM_AM::getSOImmVal(AbsImm) != -1;
10367   if (Subtarget->isThumb2())
10368     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10369   // Thumb1 only has 8-bit unsigned immediate.
10370   return AbsImm >= 0 && AbsImm <= 255;
10371 }
10372
10373 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10374                                       bool isSEXTLoad, SDValue &Base,
10375                                       SDValue &Offset, bool &isInc,
10376                                       SelectionDAG &DAG) {
10377   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10378     return false;
10379
10380   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10381     // AddressingMode 3
10382     Base = Ptr->getOperand(0);
10383     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10384       int RHSC = (int)RHS->getZExtValue();
10385       if (RHSC < 0 && RHSC > -256) {
10386         assert(Ptr->getOpcode() == ISD::ADD);
10387         isInc = false;
10388         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10389         return true;
10390       }
10391     }
10392     isInc = (Ptr->getOpcode() == ISD::ADD);
10393     Offset = Ptr->getOperand(1);
10394     return true;
10395   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10396     // AddressingMode 2
10397     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10398       int RHSC = (int)RHS->getZExtValue();
10399       if (RHSC < 0 && RHSC > -0x1000) {
10400         assert(Ptr->getOpcode() == ISD::ADD);
10401         isInc = false;
10402         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10403         Base = Ptr->getOperand(0);
10404         return true;
10405       }
10406     }
10407
10408     if (Ptr->getOpcode() == ISD::ADD) {
10409       isInc = true;
10410       ARM_AM::ShiftOpc ShOpcVal=
10411         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10412       if (ShOpcVal != ARM_AM::no_shift) {
10413         Base = Ptr->getOperand(1);
10414         Offset = Ptr->getOperand(0);
10415       } else {
10416         Base = Ptr->getOperand(0);
10417         Offset = Ptr->getOperand(1);
10418       }
10419       return true;
10420     }
10421
10422     isInc = (Ptr->getOpcode() == ISD::ADD);
10423     Base = Ptr->getOperand(0);
10424     Offset = Ptr->getOperand(1);
10425     return true;
10426   }
10427
10428   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10429   return false;
10430 }
10431
10432 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10433                                      bool isSEXTLoad, SDValue &Base,
10434                                      SDValue &Offset, bool &isInc,
10435                                      SelectionDAG &DAG) {
10436   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10437     return false;
10438
10439   Base = Ptr->getOperand(0);
10440   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10441     int RHSC = (int)RHS->getZExtValue();
10442     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10443       assert(Ptr->getOpcode() == ISD::ADD);
10444       isInc = false;
10445       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10446       return true;
10447     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10448       isInc = Ptr->getOpcode() == ISD::ADD;
10449       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10450       return true;
10451     }
10452   }
10453
10454   return false;
10455 }
10456
10457 /// getPreIndexedAddressParts - returns true by value, base pointer and
10458 /// offset pointer and addressing mode by reference if the node's address
10459 /// can be legally represented as pre-indexed load / store address.
10460 bool
10461 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10462                                              SDValue &Offset,
10463                                              ISD::MemIndexedMode &AM,
10464                                              SelectionDAG &DAG) const {
10465   if (Subtarget->isThumb1Only())
10466     return false;
10467
10468   EVT VT;
10469   SDValue Ptr;
10470   bool isSEXTLoad = false;
10471   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10472     Ptr = LD->getBasePtr();
10473     VT  = LD->getMemoryVT();
10474     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10475   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10476     Ptr = ST->getBasePtr();
10477     VT  = ST->getMemoryVT();
10478   } else
10479     return false;
10480
10481   bool isInc;
10482   bool isLegal = false;
10483   if (Subtarget->isThumb2())
10484     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10485                                        Offset, isInc, DAG);
10486   else
10487     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10488                                         Offset, isInc, DAG);
10489   if (!isLegal)
10490     return false;
10491
10492   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10493   return true;
10494 }
10495
10496 /// getPostIndexedAddressParts - returns true by value, base pointer and
10497 /// offset pointer and addressing mode by reference if this node can be
10498 /// combined with a load / store to form a post-indexed load / store.
10499 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10500                                                    SDValue &Base,
10501                                                    SDValue &Offset,
10502                                                    ISD::MemIndexedMode &AM,
10503                                                    SelectionDAG &DAG) const {
10504   if (Subtarget->isThumb1Only())
10505     return false;
10506
10507   EVT VT;
10508   SDValue Ptr;
10509   bool isSEXTLoad = false;
10510   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10511     VT  = LD->getMemoryVT();
10512     Ptr = LD->getBasePtr();
10513     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10514   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10515     VT  = ST->getMemoryVT();
10516     Ptr = ST->getBasePtr();
10517   } else
10518     return false;
10519
10520   bool isInc;
10521   bool isLegal = false;
10522   if (Subtarget->isThumb2())
10523     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10524                                        isInc, DAG);
10525   else
10526     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10527                                         isInc, DAG);
10528   if (!isLegal)
10529     return false;
10530
10531   if (Ptr != Base) {
10532     // Swap base ptr and offset to catch more post-index load / store when
10533     // it's legal. In Thumb2 mode, offset must be an immediate.
10534     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10535         !Subtarget->isThumb2())
10536       std::swap(Base, Offset);
10537
10538     // Post-indexed load / store update the base pointer.
10539     if (Ptr != Base)
10540       return false;
10541   }
10542
10543   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10544   return true;
10545 }
10546
10547 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10548                                                        APInt &KnownZero,
10549                                                        APInt &KnownOne,
10550                                                        const SelectionDAG &DAG,
10551                                                        unsigned Depth) const {
10552   unsigned BitWidth = KnownOne.getBitWidth();
10553   KnownZero = KnownOne = APInt(BitWidth, 0);
10554   switch (Op.getOpcode()) {
10555   default: break;
10556   case ARMISD::ADDC:
10557   case ARMISD::ADDE:
10558   case ARMISD::SUBC:
10559   case ARMISD::SUBE:
10560     // These nodes' second result is a boolean
10561     if (Op.getResNo() == 0)
10562       break;
10563     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10564     break;
10565   case ARMISD::CMOV: {
10566     // Bits are known zero/one if known on the LHS and RHS.
10567     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10568     if (KnownZero == 0 && KnownOne == 0) return;
10569
10570     APInt KnownZeroRHS, KnownOneRHS;
10571     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10572     KnownZero &= KnownZeroRHS;
10573     KnownOne  &= KnownOneRHS;
10574     return;
10575   }
10576   }
10577 }
10578
10579 //===----------------------------------------------------------------------===//
10580 //                           ARM Inline Assembly Support
10581 //===----------------------------------------------------------------------===//
10582
10583 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10584   // Looking for "rev" which is V6+.
10585   if (!Subtarget->hasV6Ops())
10586     return false;
10587
10588   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10589   std::string AsmStr = IA->getAsmString();
10590   SmallVector<StringRef, 4> AsmPieces;
10591   SplitString(AsmStr, AsmPieces, ";\n");
10592
10593   switch (AsmPieces.size()) {
10594   default: return false;
10595   case 1:
10596     AsmStr = AsmPieces[0];
10597     AsmPieces.clear();
10598     SplitString(AsmStr, AsmPieces, " \t,");
10599
10600     // rev $0, $1
10601     if (AsmPieces.size() == 3 &&
10602         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10603         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10604       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10605       if (Ty && Ty->getBitWidth() == 32)
10606         return IntrinsicLowering::LowerToByteSwap(CI);
10607     }
10608     break;
10609   }
10610
10611   return false;
10612 }
10613
10614 /// getConstraintType - Given a constraint letter, return the type of
10615 /// constraint it is for this target.
10616 ARMTargetLowering::ConstraintType
10617 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10618   if (Constraint.size() == 1) {
10619     switch (Constraint[0]) {
10620     default:  break;
10621     case 'l': return C_RegisterClass;
10622     case 'w': return C_RegisterClass;
10623     case 'h': return C_RegisterClass;
10624     case 'x': return C_RegisterClass;
10625     case 't': return C_RegisterClass;
10626     case 'j': return C_Other; // Constant for movw.
10627       // An address with a single base register. Due to the way we
10628       // currently handle addresses it is the same as an 'r' memory constraint.
10629     case 'Q': return C_Memory;
10630     }
10631   } else if (Constraint.size() == 2) {
10632     switch (Constraint[0]) {
10633     default: break;
10634     // All 'U+' constraints are addresses.
10635     case 'U': return C_Memory;
10636     }
10637   }
10638   return TargetLowering::getConstraintType(Constraint);
10639 }
10640
10641 /// Examine constraint type and operand type and determine a weight value.
10642 /// This object must already have been set up with the operand type
10643 /// and the current alternative constraint selected.
10644 TargetLowering::ConstraintWeight
10645 ARMTargetLowering::getSingleConstraintMatchWeight(
10646     AsmOperandInfo &info, const char *constraint) const {
10647   ConstraintWeight weight = CW_Invalid;
10648   Value *CallOperandVal = info.CallOperandVal;
10649     // If we don't have a value, we can't do a match,
10650     // but allow it at the lowest weight.
10651   if (CallOperandVal == NULL)
10652     return CW_Default;
10653   Type *type = CallOperandVal->getType();
10654   // Look at the constraint type.
10655   switch (*constraint) {
10656   default:
10657     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10658     break;
10659   case 'l':
10660     if (type->isIntegerTy()) {
10661       if (Subtarget->isThumb())
10662         weight = CW_SpecificReg;
10663       else
10664         weight = CW_Register;
10665     }
10666     break;
10667   case 'w':
10668     if (type->isFloatingPointTy())
10669       weight = CW_Register;
10670     break;
10671   }
10672   return weight;
10673 }
10674
10675 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10676 RCPair
10677 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10678                                                 MVT VT) const {
10679   if (Constraint.size() == 1) {
10680     // GCC ARM Constraint Letters
10681     switch (Constraint[0]) {
10682     case 'l': // Low regs or general regs.
10683       if (Subtarget->isThumb())
10684         return RCPair(0U, &ARM::tGPRRegClass);
10685       return RCPair(0U, &ARM::GPRRegClass);
10686     case 'h': // High regs or no regs.
10687       if (Subtarget->isThumb())
10688         return RCPair(0U, &ARM::hGPRRegClass);
10689       break;
10690     case 'r':
10691       return RCPair(0U, &ARM::GPRRegClass);
10692     case 'w':
10693       if (VT == MVT::f32)
10694         return RCPair(0U, &ARM::SPRRegClass);
10695       if (VT.getSizeInBits() == 64)
10696         return RCPair(0U, &ARM::DPRRegClass);
10697       if (VT.getSizeInBits() == 128)
10698         return RCPair(0U, &ARM::QPRRegClass);
10699       break;
10700     case 'x':
10701       if (VT == MVT::f32)
10702         return RCPair(0U, &ARM::SPR_8RegClass);
10703       if (VT.getSizeInBits() == 64)
10704         return RCPair(0U, &ARM::DPR_8RegClass);
10705       if (VT.getSizeInBits() == 128)
10706         return RCPair(0U, &ARM::QPR_8RegClass);
10707       break;
10708     case 't':
10709       if (VT == MVT::f32)
10710         return RCPair(0U, &ARM::SPRRegClass);
10711       break;
10712     }
10713   }
10714   if (StringRef("{cc}").equals_lower(Constraint))
10715     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10716
10717   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10718 }
10719
10720 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10721 /// vector.  If it is invalid, don't add anything to Ops.
10722 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10723                                                      std::string &Constraint,
10724                                                      std::vector<SDValue>&Ops,
10725                                                      SelectionDAG &DAG) const {
10726   SDValue Result(0, 0);
10727
10728   // Currently only support length 1 constraints.
10729   if (Constraint.length() != 1) return;
10730
10731   char ConstraintLetter = Constraint[0];
10732   switch (ConstraintLetter) {
10733   default: break;
10734   case 'j':
10735   case 'I': case 'J': case 'K': case 'L':
10736   case 'M': case 'N': case 'O':
10737     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10738     if (!C)
10739       return;
10740
10741     int64_t CVal64 = C->getSExtValue();
10742     int CVal = (int) CVal64;
10743     // None of these constraints allow values larger than 32 bits.  Check
10744     // that the value fits in an int.
10745     if (CVal != CVal64)
10746       return;
10747
10748     switch (ConstraintLetter) {
10749       case 'j':
10750         // Constant suitable for movw, must be between 0 and
10751         // 65535.
10752         if (Subtarget->hasV6T2Ops())
10753           if (CVal >= 0 && CVal <= 65535)
10754             break;
10755         return;
10756       case 'I':
10757         if (Subtarget->isThumb1Only()) {
10758           // This must be a constant between 0 and 255, for ADD
10759           // immediates.
10760           if (CVal >= 0 && CVal <= 255)
10761             break;
10762         } else if (Subtarget->isThumb2()) {
10763           // A constant that can be used as an immediate value in a
10764           // data-processing instruction.
10765           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10766             break;
10767         } else {
10768           // A constant that can be used as an immediate value in a
10769           // data-processing instruction.
10770           if (ARM_AM::getSOImmVal(CVal) != -1)
10771             break;
10772         }
10773         return;
10774
10775       case 'J':
10776         if (Subtarget->isThumb()) {  // FIXME thumb2
10777           // This must be a constant between -255 and -1, for negated ADD
10778           // immediates. This can be used in GCC with an "n" modifier that
10779           // prints the negated value, for use with SUB instructions. It is
10780           // not useful otherwise but is implemented for compatibility.
10781           if (CVal >= -255 && CVal <= -1)
10782             break;
10783         } else {
10784           // This must be a constant between -4095 and 4095. It is not clear
10785           // what this constraint is intended for. Implemented for
10786           // compatibility with GCC.
10787           if (CVal >= -4095 && CVal <= 4095)
10788             break;
10789         }
10790         return;
10791
10792       case 'K':
10793         if (Subtarget->isThumb1Only()) {
10794           // A 32-bit value where only one byte has a nonzero value. Exclude
10795           // zero to match GCC. This constraint is used by GCC internally for
10796           // constants that can be loaded with a move/shift combination.
10797           // It is not useful otherwise but is implemented for compatibility.
10798           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10799             break;
10800         } else if (Subtarget->isThumb2()) {
10801           // A constant whose bitwise inverse can be used as an immediate
10802           // value in a data-processing instruction. This can be used in GCC
10803           // with a "B" modifier that prints the inverted value, for use with
10804           // BIC and MVN instructions. It is not useful otherwise but is
10805           // implemented for compatibility.
10806           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10807             break;
10808         } else {
10809           // A constant whose bitwise inverse can be used as an immediate
10810           // value in a data-processing instruction. This can be used in GCC
10811           // with a "B" modifier that prints the inverted value, for use with
10812           // BIC and MVN instructions. It is not useful otherwise but is
10813           // implemented for compatibility.
10814           if (ARM_AM::getSOImmVal(~CVal) != -1)
10815             break;
10816         }
10817         return;
10818
10819       case 'L':
10820         if (Subtarget->isThumb1Only()) {
10821           // This must be a constant between -7 and 7,
10822           // for 3-operand ADD/SUB immediate instructions.
10823           if (CVal >= -7 && CVal < 7)
10824             break;
10825         } else if (Subtarget->isThumb2()) {
10826           // A constant whose negation can be used as an immediate value in a
10827           // data-processing instruction. This can be used in GCC with an "n"
10828           // modifier that prints the negated value, for use with SUB
10829           // instructions. It is not useful otherwise but is implemented for
10830           // compatibility.
10831           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10832             break;
10833         } else {
10834           // A constant whose negation can be used as an immediate value in a
10835           // data-processing instruction. This can be used in GCC with an "n"
10836           // modifier that prints the negated value, for use with SUB
10837           // instructions. It is not useful otherwise but is implemented for
10838           // compatibility.
10839           if (ARM_AM::getSOImmVal(-CVal) != -1)
10840             break;
10841         }
10842         return;
10843
10844       case 'M':
10845         if (Subtarget->isThumb()) { // FIXME thumb2
10846           // This must be a multiple of 4 between 0 and 1020, for
10847           // ADD sp + immediate.
10848           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10849             break;
10850         } else {
10851           // A power of two or a constant between 0 and 32.  This is used in
10852           // GCC for the shift amount on shifted register operands, but it is
10853           // useful in general for any shift amounts.
10854           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10855             break;
10856         }
10857         return;
10858
10859       case 'N':
10860         if (Subtarget->isThumb()) {  // FIXME thumb2
10861           // This must be a constant between 0 and 31, for shift amounts.
10862           if (CVal >= 0 && CVal <= 31)
10863             break;
10864         }
10865         return;
10866
10867       case 'O':
10868         if (Subtarget->isThumb()) {  // FIXME thumb2
10869           // This must be a multiple of 4 between -508 and 508, for
10870           // ADD/SUB sp = sp + immediate.
10871           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10872             break;
10873         }
10874         return;
10875     }
10876     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10877     break;
10878   }
10879
10880   if (Result.getNode()) {
10881     Ops.push_back(Result);
10882     return;
10883   }
10884   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10885 }
10886
10887 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10888   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10889   unsigned Opcode = Op->getOpcode();
10890   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10891       "Invalid opcode for Div/Rem lowering");
10892   bool isSigned = (Opcode == ISD::SDIVREM);
10893   EVT VT = Op->getValueType(0);
10894   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10895
10896   RTLIB::Libcall LC;
10897   switch (VT.getSimpleVT().SimpleTy) {
10898   default: llvm_unreachable("Unexpected request for libcall!");
10899   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10900   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10901   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10902   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10903   }
10904
10905   SDValue InChain = DAG.getEntryNode();
10906
10907   TargetLowering::ArgListTy Args;
10908   TargetLowering::ArgListEntry Entry;
10909   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10910     EVT ArgVT = Op->getOperand(i).getValueType();
10911     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10912     Entry.Node = Op->getOperand(i);
10913     Entry.Ty = ArgTy;
10914     Entry.isSExt = isSigned;
10915     Entry.isZExt = !isSigned;
10916     Args.push_back(Entry);
10917   }
10918
10919   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10920                                          getPointerTy());
10921
10922   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10923
10924   SDLoc dl(Op);
10925   TargetLowering::
10926   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10927                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10928                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10929                     Callee, Args, DAG, dl);
10930   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10931
10932   return CallInfo.first;
10933 }
10934
10935 bool
10936 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10937   // The ARM target isn't yet aware of offsets.
10938   return false;
10939 }
10940
10941 bool ARM::isBitFieldInvertedMask(unsigned v) {
10942   if (v == 0xffffffff)
10943     return false;
10944
10945   // there can be 1's on either or both "outsides", all the "inside"
10946   // bits must be 0's
10947   unsigned TO = CountTrailingOnes_32(v);
10948   unsigned LO = CountLeadingOnes_32(v);
10949   v = (v >> TO) << TO;
10950   v = (v << LO) >> LO;
10951   return v == 0;
10952 }
10953
10954 /// isFPImmLegal - Returns true if the target can instruction select the
10955 /// specified FP immediate natively. If false, the legalizer will
10956 /// materialize the FP immediate as a load from a constant pool.
10957 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10958   if (!Subtarget->hasVFP3())
10959     return false;
10960   if (VT == MVT::f32)
10961     return ARM_AM::getFP32Imm(Imm) != -1;
10962   if (VT == MVT::f64)
10963     return ARM_AM::getFP64Imm(Imm) != -1;
10964   return false;
10965 }
10966
10967 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10968 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10969 /// specified in the intrinsic calls.
10970 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10971                                            const CallInst &I,
10972                                            unsigned Intrinsic) const {
10973   switch (Intrinsic) {
10974   case Intrinsic::arm_neon_vld1:
10975   case Intrinsic::arm_neon_vld2:
10976   case Intrinsic::arm_neon_vld3:
10977   case Intrinsic::arm_neon_vld4:
10978   case Intrinsic::arm_neon_vld2lane:
10979   case Intrinsic::arm_neon_vld3lane:
10980   case Intrinsic::arm_neon_vld4lane: {
10981     Info.opc = ISD::INTRINSIC_W_CHAIN;
10982     // Conservatively set memVT to the entire set of vectors loaded.
10983     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10984     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10985     Info.ptrVal = I.getArgOperand(0);
10986     Info.offset = 0;
10987     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10988     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10989     Info.vol = false; // volatile loads with NEON intrinsics not supported
10990     Info.readMem = true;
10991     Info.writeMem = false;
10992     return true;
10993   }
10994   case Intrinsic::arm_neon_vst1:
10995   case Intrinsic::arm_neon_vst2:
10996   case Intrinsic::arm_neon_vst3:
10997   case Intrinsic::arm_neon_vst4:
10998   case Intrinsic::arm_neon_vst2lane:
10999   case Intrinsic::arm_neon_vst3lane:
11000   case Intrinsic::arm_neon_vst4lane: {
11001     Info.opc = ISD::INTRINSIC_VOID;
11002     // Conservatively set memVT to the entire set of vectors stored.
11003     unsigned NumElts = 0;
11004     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11005       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11006       if (!ArgTy->isVectorTy())
11007         break;
11008       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11009     }
11010     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11011     Info.ptrVal = I.getArgOperand(0);
11012     Info.offset = 0;
11013     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11014     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11015     Info.vol = false; // volatile stores with NEON intrinsics not supported
11016     Info.readMem = false;
11017     Info.writeMem = true;
11018     return true;
11019   }
11020   case Intrinsic::arm_ldrex: {
11021     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11022     Info.opc = ISD::INTRINSIC_W_CHAIN;
11023     Info.memVT = MVT::getVT(PtrTy->getElementType());
11024     Info.ptrVal = I.getArgOperand(0);
11025     Info.offset = 0;
11026     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11027     Info.vol = true;
11028     Info.readMem = true;
11029     Info.writeMem = false;
11030     return true;
11031   }
11032   case Intrinsic::arm_strex: {
11033     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11034     Info.opc = ISD::INTRINSIC_W_CHAIN;
11035     Info.memVT = MVT::getVT(PtrTy->getElementType());
11036     Info.ptrVal = I.getArgOperand(1);
11037     Info.offset = 0;
11038     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11039     Info.vol = true;
11040     Info.readMem = false;
11041     Info.writeMem = true;
11042     return true;
11043   }
11044   case Intrinsic::arm_strexd: {
11045     Info.opc = ISD::INTRINSIC_W_CHAIN;
11046     Info.memVT = MVT::i64;
11047     Info.ptrVal = I.getArgOperand(2);
11048     Info.offset = 0;
11049     Info.align = 8;
11050     Info.vol = true;
11051     Info.readMem = false;
11052     Info.writeMem = true;
11053     return true;
11054   }
11055   case Intrinsic::arm_ldrexd: {
11056     Info.opc = ISD::INTRINSIC_W_CHAIN;
11057     Info.memVT = MVT::i64;
11058     Info.ptrVal = I.getArgOperand(0);
11059     Info.offset = 0;
11060     Info.align = 8;
11061     Info.vol = true;
11062     Info.readMem = true;
11063     Info.writeMem = false;
11064     return true;
11065   }
11066   default:
11067     break;
11068   }
11069
11070   return false;
11071 }