For ARM backend, fixed "byval" attribute support.
[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, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(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
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
508
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Mark v2f32 intrinsics.
526     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
541
542     // Neon does not support some operations on v1i64 and v2i64 types.
543     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544     // Custom handling for some quad-vector types to detect VMULL.
545     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548     // Custom handling for some vector types to avoid expensive expansions
549     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556     // a destination type that is wider than the source, and nor does
557     // it have a FP_TO_[SU]INT instruction with a narrower destination than
558     // source.
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
563
564     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
565     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
566
567     // Custom expand long extensions to vectors.
568     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
569     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
571     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
575     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
576
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585     // NEON only has FMA instructions as of VFP4.
586     if (!Subtarget->hasVFP4()) {
587       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
589     }
590
591     setTargetDAGCombine(ISD::INTRINSIC_VOID);
592     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594     setTargetDAGCombine(ISD::SHL);
595     setTargetDAGCombine(ISD::SRL);
596     setTargetDAGCombine(ISD::SRA);
597     setTargetDAGCombine(ISD::SIGN_EXTEND);
598     setTargetDAGCombine(ISD::ZERO_EXTEND);
599     setTargetDAGCombine(ISD::ANY_EXTEND);
600     setTargetDAGCombine(ISD::SELECT_CC);
601     setTargetDAGCombine(ISD::BUILD_VECTOR);
602     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604     setTargetDAGCombine(ISD::STORE);
605     setTargetDAGCombine(ISD::FP_TO_SINT);
606     setTargetDAGCombine(ISD::FP_TO_UINT);
607     setTargetDAGCombine(ISD::FDIV);
608
609     // It is legal to extload from v4i8 to v4i16 or v4i32.
610     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611                   MVT::v4i16, MVT::v2i16,
612                   MVT::v2i32};
613     for (unsigned i = 0; i < 6; ++i) {
614       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
617     }
618   }
619
620   // ARM and Thumb2 support UMLAL/SMLAL.
621   if (!Subtarget->isThumb1Only())
622     setTargetDAGCombine(ISD::ADDC);
623
624
625   computeRegisterProperties();
626
627   // ARM does not have f32 extending load.
628   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
629
630   // ARM does not have i1 sign extending load.
631   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
632
633   // ARM supports all 4 flavors of integer indexed load / store.
634   if (!Subtarget->isThumb1Only()) {
635     for (unsigned im = (unsigned)ISD::PRE_INC;
636          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637       setIndexedLoadAction(im,  MVT::i1,  Legal);
638       setIndexedLoadAction(im,  MVT::i8,  Legal);
639       setIndexedLoadAction(im,  MVT::i16, Legal);
640       setIndexedLoadAction(im,  MVT::i32, Legal);
641       setIndexedStoreAction(im, MVT::i1,  Legal);
642       setIndexedStoreAction(im, MVT::i8,  Legal);
643       setIndexedStoreAction(im, MVT::i16, Legal);
644       setIndexedStoreAction(im, MVT::i32, Legal);
645     }
646   }
647
648   // i64 operation support.
649   setOperationAction(ISD::MUL,     MVT::i64, Expand);
650   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
651   if (Subtarget->isThumb1Only()) {
652     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
654   }
655   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657     setOperationAction(ISD::MULHS, MVT::i32, Expand);
658
659   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL,       MVT::i64, Custom);
663   setOperationAction(ISD::SRA,       MVT::i64, Custom);
664
665   if (!Subtarget->isThumb1Only()) {
666     // FIXME: We should do this for Thumb1 as well.
667     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
668     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
669     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
671   }
672
673   // ARM does not have ROTL.
674   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
675   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
676   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
679
680   // These just redirect to CTTZ and CTLZ on ARM.
681   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
682   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
683
684   // Only ARMv6 has BSWAP.
685   if (!Subtarget->hasV6Ops())
686     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
687
688   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
689       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
690     // These are expanded into libcalls if the cpu doesn't have HW divider.
691     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
692     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
693   }
694   setOperationAction(ISD::SREM,  MVT::i32, Expand);
695   setOperationAction(ISD::UREM,  MVT::i32, Expand);
696   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
697   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
698
699   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
700   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
701   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
702   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
703   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
704
705   setOperationAction(ISD::TRAP, MVT::Other, Legal);
706
707   // Use the default implementation.
708   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
709   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
710   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
711   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
712   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
713   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
714
715   if (!Subtarget->isTargetDarwin()) {
716     // Non-Darwin platforms may return values in these registers via the
717     // personality function.
718     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
719     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
720     setExceptionPointerRegister(ARM::R0);
721     setExceptionSelectorRegister(ARM::R1);
722   }
723
724   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
725   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
726   // the default expansion.
727   // FIXME: This should be checking for v6k, not just v6.
728   if (Subtarget->hasDataBarrier() ||
729       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
730     // membarrier needs custom lowering; the rest are legal and handled
731     // normally.
732     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
733     // Custom lowering for 64-bit ops
734     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
735     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
736     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
737     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
738     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
739     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
740     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
741     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
742     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
743     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
744     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
745     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
746     setInsertFencesForAtomic(true);
747   } else {
748     // Set them all for expansion, which will force libcalls.
749     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
750     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
751     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
752     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
755     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
756     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
757     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
758     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
759     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
762     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
763     // Unordered/Monotonic case.
764     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
765     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
766   }
767
768   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
769
770   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
771   if (!Subtarget->hasV6Ops()) {
772     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
773     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
774   }
775   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
776
777   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
778       !Subtarget->isThumb1Only()) {
779     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
780     // iff target supports vfp2.
781     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
782     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
783   }
784
785   // We want to custom lower some of our intrinsics.
786   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
787   if (Subtarget->isTargetDarwin()) {
788     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
789     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
790     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
791   }
792
793   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
794   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
795   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
796   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
797   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
798   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
799   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
800   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
801   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
802
803   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
804   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
805   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
806   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
807   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
808
809   // We don't support sin/cos/fmod/copysign/pow
810   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
811   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
812   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
813   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
814   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
815   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
816   setOperationAction(ISD::FREM,      MVT::f64, Expand);
817   setOperationAction(ISD::FREM,      MVT::f32, Expand);
818   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
819       !Subtarget->isThumb1Only()) {
820     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
821     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
822   }
823   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
824   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
825
826   if (!Subtarget->hasVFP4()) {
827     setOperationAction(ISD::FMA, MVT::f64, Expand);
828     setOperationAction(ISD::FMA, MVT::f32, Expand);
829   }
830
831   // Various VFP goodness
832   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
833     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
834     if (Subtarget->hasVFP2()) {
835       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
836       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
837       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
838       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
839     }
840     // Special handling for half-precision FP.
841     if (!Subtarget->hasFP16()) {
842       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
843       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
844     }
845   }
846
847   // We have target-specific dag combine patterns for the following nodes:
848   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
849   setTargetDAGCombine(ISD::ADD);
850   setTargetDAGCombine(ISD::SUB);
851   setTargetDAGCombine(ISD::MUL);
852   setTargetDAGCombine(ISD::AND);
853   setTargetDAGCombine(ISD::OR);
854   setTargetDAGCombine(ISD::XOR);
855
856   if (Subtarget->hasV6Ops())
857     setTargetDAGCombine(ISD::SRL);
858
859   setStackPointerRegisterToSaveRestore(ARM::SP);
860
861   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862       !Subtarget->hasVFP2())
863     setSchedulingPreference(Sched::RegPressure);
864   else
865     setSchedulingPreference(Sched::Hybrid);
866
867   //// temporary - rewrite interface to use type
868   MaxStoresPerMemset = 8;
869   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874
875   // On ARM arguments smaller than 4 bytes are extended, so all arguments
876   // are at least 4 bytes aligned.
877   setMinStackArgumentAlignment(4);
878
879   // Prefer likely predicted branches to selects on out-of-order cores.
880   PredictableSelectIsExpensive = Subtarget->isLikeA9();
881
882   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
883 }
884
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
894 // and extractions.
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897   const TargetRegisterClass *RRC = 0;
898   uint8_t Cost = 1;
899   switch (VT.SimpleTy) {
900   default:
901     return TargetLowering::findRepresentativeClass(VT);
902   // Use DPR as representative register class for all floating point
903   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904   // the cost is 1 for both f32 and f64.
905   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907     RRC = &ARM::DPRRegClass;
908     // When NEON is used for SP, only half of the register file is available
909     // because operations that define both SP and DP results will be constrained
910     // to the VFP2 class (D0-D15). We currently model this constraint prior to
911     // coalescing by double-counting the SP regs. See the FIXME above.
912     if (Subtarget->useNEONForSinglePrecisionFP())
913       Cost = 2;
914     break;
915   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916   case MVT::v4f32: case MVT::v2f64:
917     RRC = &ARM::DPRRegClass;
918     Cost = 2;
919     break;
920   case MVT::v4i64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 4;
923     break;
924   case MVT::v8i64:
925     RRC = &ARM::DPRRegClass;
926     Cost = 8;
927     break;
928   }
929   return std::make_pair(RRC, Cost);
930 }
931
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
933   switch (Opcode) {
934   default: return 0;
935   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
936   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
937   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
938   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
939   case ARMISD::CALL:          return "ARMISD::CALL";
940   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
941   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
942   case ARMISD::tCALL:         return "ARMISD::tCALL";
943   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
944   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
945   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
946   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
947   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
948   case ARMISD::CMP:           return "ARMISD::CMP";
949   case ARMISD::CMN:           return "ARMISD::CMN";
950   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
951   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
952   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
953   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
954   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
955
956   case ARMISD::CMOV:          return "ARMISD::CMOV";
957
958   case ARMISD::RBIT:          return "ARMISD::RBIT";
959
960   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
961   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
962   case ARMISD::SITOF:         return "ARMISD::SITOF";
963   case ARMISD::UITOF:         return "ARMISD::UITOF";
964
965   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
966   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
967   case ARMISD::RRX:           return "ARMISD::RRX";
968
969   case ARMISD::ADDC:          return "ARMISD::ADDC";
970   case ARMISD::ADDE:          return "ARMISD::ADDE";
971   case ARMISD::SUBC:          return "ARMISD::SUBC";
972   case ARMISD::SUBE:          return "ARMISD::SUBE";
973
974   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
975   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
976
977   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
979
980   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
981
982   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
983
984   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
985
986   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
987   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
988
989   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
990
991   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
992   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
993   case ARMISD::VCGE:          return "ARMISD::VCGE";
994   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
995   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
996   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
997   case ARMISD::VCGT:          return "ARMISD::VCGT";
998   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
999   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1000   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1001   case ARMISD::VTST:          return "ARMISD::VTST";
1002
1003   case ARMISD::VSHL:          return "ARMISD::VSHL";
1004   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1005   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1006   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1007   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1008   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1009   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1010   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1011   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1012   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1013   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1014   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1015   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1016   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1017   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1018   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1019   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1020   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1021   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1022   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1023   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1024   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1025   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1026   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1027   case ARMISD::VDUP:          return "ARMISD::VDUP";
1028   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1029   case ARMISD::VEXT:          return "ARMISD::VEXT";
1030   case ARMISD::VREV64:        return "ARMISD::VREV64";
1031   case ARMISD::VREV32:        return "ARMISD::VREV32";
1032   case ARMISD::VREV16:        return "ARMISD::VREV16";
1033   case ARMISD::VZIP:          return "ARMISD::VZIP";
1034   case ARMISD::VUZP:          return "ARMISD::VUZP";
1035   case ARMISD::VTRN:          return "ARMISD::VTRN";
1036   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1037   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1038   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1039   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1040   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1041   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1042   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1043   case ARMISD::FMAX:          return "ARMISD::FMAX";
1044   case ARMISD::FMIN:          return "ARMISD::FMIN";
1045   case ARMISD::BFI:           return "ARMISD::BFI";
1046   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1047   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1048   case ARMISD::VBSL:          return "ARMISD::VBSL";
1049   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1050   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1051   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1052   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1053   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1054   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1055   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1056   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1057   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1058   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1059   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1060   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1061   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1062   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1063   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1064   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1065   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1066   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1067   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1068   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1069   }
1070 }
1071
1072 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1073   if (!VT.isVector()) return getPointerTy();
1074   return VT.changeVectorElementTypeToInteger();
1075 }
1076
1077 /// getRegClassFor - Return the register class that should be used for the
1078 /// specified value type.
1079 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1080   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1081   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1082   // load / store 4 to 8 consecutive D registers.
1083   if (Subtarget->hasNEON()) {
1084     if (VT == MVT::v4i64)
1085       return &ARM::QQPRRegClass;
1086     if (VT == MVT::v8i64)
1087       return &ARM::QQQQPRRegClass;
1088   }
1089   return TargetLowering::getRegClassFor(VT);
1090 }
1091
1092 // Create a fast isel object.
1093 FastISel *
1094 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1095                                   const TargetLibraryInfo *libInfo) const {
1096   return ARM::createFastISel(funcInfo, libInfo);
1097 }
1098
1099 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1100 /// be used for loads / stores from the global.
1101 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1102   return (Subtarget->isThumb1Only() ? 127 : 4095);
1103 }
1104
1105 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1106   unsigned NumVals = N->getNumValues();
1107   if (!NumVals)
1108     return Sched::RegPressure;
1109
1110   for (unsigned i = 0; i != NumVals; ++i) {
1111     EVT VT = N->getValueType(i);
1112     if (VT == MVT::Glue || VT == MVT::Other)
1113       continue;
1114     if (VT.isFloatingPoint() || VT.isVector())
1115       return Sched::ILP;
1116   }
1117
1118   if (!N->isMachineOpcode())
1119     return Sched::RegPressure;
1120
1121   // Load are scheduled for latency even if there instruction itinerary
1122   // is not available.
1123   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1124   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1125
1126   if (MCID.getNumDefs() == 0)
1127     return Sched::RegPressure;
1128   if (!Itins->isEmpty() &&
1129       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1130     return Sched::ILP;
1131
1132   return Sched::RegPressure;
1133 }
1134
1135 //===----------------------------------------------------------------------===//
1136 // Lowering Code
1137 //===----------------------------------------------------------------------===//
1138
1139 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1140 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1141   switch (CC) {
1142   default: llvm_unreachable("Unknown condition code!");
1143   case ISD::SETNE:  return ARMCC::NE;
1144   case ISD::SETEQ:  return ARMCC::EQ;
1145   case ISD::SETGT:  return ARMCC::GT;
1146   case ISD::SETGE:  return ARMCC::GE;
1147   case ISD::SETLT:  return ARMCC::LT;
1148   case ISD::SETLE:  return ARMCC::LE;
1149   case ISD::SETUGT: return ARMCC::HI;
1150   case ISD::SETUGE: return ARMCC::HS;
1151   case ISD::SETULT: return ARMCC::LO;
1152   case ISD::SETULE: return ARMCC::LS;
1153   }
1154 }
1155
1156 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1157 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1158                         ARMCC::CondCodes &CondCode2) {
1159   CondCode2 = ARMCC::AL;
1160   switch (CC) {
1161   default: llvm_unreachable("Unknown FP condition!");
1162   case ISD::SETEQ:
1163   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1164   case ISD::SETGT:
1165   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1166   case ISD::SETGE:
1167   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1168   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1169   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1170   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1171   case ISD::SETO:   CondCode = ARMCC::VC; break;
1172   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1173   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1174   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1175   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1176   case ISD::SETLT:
1177   case ISD::SETULT: CondCode = ARMCC::LT; break;
1178   case ISD::SETLE:
1179   case ISD::SETULE: CondCode = ARMCC::LE; break;
1180   case ISD::SETNE:
1181   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1182   }
1183 }
1184
1185 //===----------------------------------------------------------------------===//
1186 //                      Calling Convention Implementation
1187 //===----------------------------------------------------------------------===//
1188
1189 #include "ARMGenCallingConv.inc"
1190
1191 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1192 /// given CallingConvention value.
1193 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1194                                                  bool Return,
1195                                                  bool isVarArg) const {
1196   switch (CC) {
1197   default:
1198     llvm_unreachable("Unsupported calling convention");
1199   case CallingConv::Fast:
1200     if (Subtarget->hasVFP2() && !isVarArg) {
1201       if (!Subtarget->isAAPCS_ABI())
1202         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1203       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1204       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1205     }
1206     // Fallthrough
1207   case CallingConv::C: {
1208     // Use target triple & subtarget features to do actual dispatch.
1209     if (!Subtarget->isAAPCS_ABI())
1210       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1211     else if (Subtarget->hasVFP2() &&
1212              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1213              !isVarArg)
1214       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1215     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1216   }
1217   case CallingConv::ARM_AAPCS_VFP:
1218     if (!isVarArg)
1219       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1220     // Fallthrough
1221   case CallingConv::ARM_AAPCS:
1222     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1223   case CallingConv::ARM_APCS:
1224     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1225   case CallingConv::GHC:
1226     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1227   }
1228 }
1229
1230 /// LowerCallResult - Lower the result values of a call into the
1231 /// appropriate copies out of appropriate physical registers.
1232 SDValue
1233 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1234                                    CallingConv::ID CallConv, bool isVarArg,
1235                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1236                                    DebugLoc dl, SelectionDAG &DAG,
1237                                    SmallVectorImpl<SDValue> &InVals,
1238                                    bool isThisReturn, SDValue ThisVal) const {
1239
1240   // Assign locations to each value returned by this call.
1241   SmallVector<CCValAssign, 16> RVLocs;
1242   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1243                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1244   CCInfo.AnalyzeCallResult(Ins,
1245                            CCAssignFnForNode(CallConv, /* Return*/ true,
1246                                              isVarArg));
1247
1248   // Copy all of the result registers out of their specified physreg.
1249   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1250     CCValAssign VA = RVLocs[i];
1251
1252     // Pass 'this' value directly from the argument to return value, to avoid
1253     // reg unit interference
1254     if (i == 0 && isThisReturn) {
1255       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1256              "unexpected return calling convention register assignment");
1257       InVals.push_back(ThisVal);
1258       continue;
1259     }
1260
1261     SDValue Val;
1262     if (VA.needsCustom()) {
1263       // Handle f64 or half of a v2f64.
1264       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1265                                       InFlag);
1266       Chain = Lo.getValue(1);
1267       InFlag = Lo.getValue(2);
1268       VA = RVLocs[++i]; // skip ahead to next loc
1269       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1270                                       InFlag);
1271       Chain = Hi.getValue(1);
1272       InFlag = Hi.getValue(2);
1273       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1274
1275       if (VA.getLocVT() == MVT::v2f64) {
1276         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1277         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1278                           DAG.getConstant(0, MVT::i32));
1279
1280         VA = RVLocs[++i]; // skip ahead to next loc
1281         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1282         Chain = Lo.getValue(1);
1283         InFlag = Lo.getValue(2);
1284         VA = RVLocs[++i]; // skip ahead to next loc
1285         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1286         Chain = Hi.getValue(1);
1287         InFlag = Hi.getValue(2);
1288         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1289         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1290                           DAG.getConstant(1, MVT::i32));
1291       }
1292     } else {
1293       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1294                                InFlag);
1295       Chain = Val.getValue(1);
1296       InFlag = Val.getValue(2);
1297     }
1298
1299     switch (VA.getLocInfo()) {
1300     default: llvm_unreachable("Unknown loc info!");
1301     case CCValAssign::Full: break;
1302     case CCValAssign::BCvt:
1303       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1304       break;
1305     }
1306
1307     InVals.push_back(Val);
1308   }
1309
1310   return Chain;
1311 }
1312
1313 /// LowerMemOpCallTo - Store the argument to the stack.
1314 SDValue
1315 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1316                                     SDValue StackPtr, SDValue Arg,
1317                                     DebugLoc dl, SelectionDAG &DAG,
1318                                     const CCValAssign &VA,
1319                                     ISD::ArgFlagsTy Flags) const {
1320   unsigned LocMemOffset = VA.getLocMemOffset();
1321   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1322   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1323   return DAG.getStore(Chain, dl, Arg, PtrOff,
1324                       MachinePointerInfo::getStack(LocMemOffset),
1325                       false, false, 0);
1326 }
1327
1328 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1329                                          SDValue Chain, SDValue &Arg,
1330                                          RegsToPassVector &RegsToPass,
1331                                          CCValAssign &VA, CCValAssign &NextVA,
1332                                          SDValue &StackPtr,
1333                                          SmallVector<SDValue, 8> &MemOpChains,
1334                                          ISD::ArgFlagsTy Flags) const {
1335
1336   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1337                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1338   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1339
1340   if (NextVA.isRegLoc())
1341     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1342   else {
1343     assert(NextVA.isMemLoc());
1344     if (StackPtr.getNode() == 0)
1345       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1346
1347     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1348                                            dl, DAG, NextVA,
1349                                            Flags));
1350   }
1351 }
1352
1353 /// LowerCall - Lowering a call into a callseq_start <-
1354 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1355 /// nodes.
1356 SDValue
1357 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1358                              SmallVectorImpl<SDValue> &InVals) const {
1359   SelectionDAG &DAG                     = CLI.DAG;
1360   DebugLoc &dl                          = CLI.DL;
1361   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1362   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1363   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1364   SDValue Chain                         = CLI.Chain;
1365   SDValue Callee                        = CLI.Callee;
1366   bool &isTailCall                      = CLI.IsTailCall;
1367   CallingConv::ID CallConv              = CLI.CallConv;
1368   bool doesNotRet                       = CLI.DoesNotReturn;
1369   bool isVarArg                         = CLI.IsVarArg;
1370
1371   MachineFunction &MF = DAG.getMachineFunction();
1372   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1373   bool isThisReturn   = false;
1374   bool isSibCall      = false;
1375   // Disable tail calls if they're not supported.
1376   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1377     isTailCall = false;
1378   if (isTailCall) {
1379     // Check if it's really possible to do a tail call.
1380     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1381                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1382                                                    Outs, OutVals, Ins, DAG);
1383     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1384     // detected sibcalls.
1385     if (isTailCall) {
1386       ++NumTailCalls;
1387       isSibCall = true;
1388     }
1389   }
1390
1391   // Analyze operands of the call, assigning locations to each operand.
1392   SmallVector<CCValAssign, 16> ArgLocs;
1393   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1394                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1395   CCInfo.AnalyzeCallOperands(Outs,
1396                              CCAssignFnForNode(CallConv, /* Return*/ false,
1397                                                isVarArg));
1398
1399   // Get a count of how many bytes are to be pushed on the stack.
1400   unsigned NumBytes = CCInfo.getNextStackOffset();
1401
1402   // For tail calls, memory operands are available in our caller's stack.
1403   if (isSibCall)
1404     NumBytes = 0;
1405
1406   // Adjust the stack pointer for the new arguments...
1407   // These operations are automatically eliminated by the prolog/epilog pass
1408   if (!isSibCall)
1409     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1410
1411   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1412
1413   RegsToPassVector RegsToPass;
1414   SmallVector<SDValue, 8> MemOpChains;
1415
1416   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1417   // of tail call optimization, arguments are handled later.
1418   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1419        i != e;
1420        ++i, ++realArgIdx) {
1421     CCValAssign &VA = ArgLocs[i];
1422     SDValue Arg = OutVals[realArgIdx];
1423     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1424     bool isByVal = Flags.isByVal();
1425
1426     // Promote the value if needed.
1427     switch (VA.getLocInfo()) {
1428     default: llvm_unreachable("Unknown loc info!");
1429     case CCValAssign::Full: break;
1430     case CCValAssign::SExt:
1431       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1432       break;
1433     case CCValAssign::ZExt:
1434       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1435       break;
1436     case CCValAssign::AExt:
1437       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1438       break;
1439     case CCValAssign::BCvt:
1440       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1441       break;
1442     }
1443
1444     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1445     if (VA.needsCustom()) {
1446       if (VA.getLocVT() == MVT::v2f64) {
1447         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1448                                   DAG.getConstant(0, MVT::i32));
1449         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1450                                   DAG.getConstant(1, MVT::i32));
1451
1452         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1453                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1454
1455         VA = ArgLocs[++i]; // skip ahead to next loc
1456         if (VA.isRegLoc()) {
1457           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1458                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1459         } else {
1460           assert(VA.isMemLoc());
1461
1462           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1463                                                  dl, DAG, VA, Flags));
1464         }
1465       } else {
1466         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1467                          StackPtr, MemOpChains, Flags);
1468       }
1469     } else if (VA.isRegLoc()) {
1470       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1471         assert(VA.getLocVT() == MVT::i32 &&
1472                "unexpected calling convention register assignment");
1473         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1474                "unexpected use of 'returned'");
1475         isThisReturn = true;
1476       }
1477       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1478     } else if (isByVal) {
1479       assert(VA.isMemLoc());
1480       unsigned offset = 0;
1481
1482       // True if this byval aggregate will be split between registers
1483       // and memory.
1484       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1485       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1486
1487       if (CurByValIdx < ByValArgsCount) {
1488
1489         unsigned RegBegin, RegEnd;
1490         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1491
1492         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1493         unsigned int i, j;
1494         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1495           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1496           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1497           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1498                                      MachinePointerInfo(),
1499                                      false, false, false, 0);
1500           MemOpChains.push_back(Load.getValue(1));
1501           RegsToPass.push_back(std::make_pair(j, Load));
1502         }
1503
1504         // If parameter size outsides register area, "offset" value
1505         // helps us to calculate stack slot for remained part properly.
1506         offset = RegEnd - RegBegin;
1507
1508         CCInfo.nextInRegsParam();
1509       }
1510
1511       if (Flags.getByValSize() > 4*offset) {
1512         unsigned LocMemOffset = VA.getLocMemOffset();
1513         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1514         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1515                                   StkPtrOff);
1516         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1517         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1518         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1519                                            MVT::i32);
1520         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1521
1522         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1523         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1524         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1525                                           Ops, array_lengthof(Ops)));
1526       }
1527     } else if (!isSibCall) {
1528       assert(VA.isMemLoc());
1529
1530       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1531                                              dl, DAG, VA, Flags));
1532     }
1533   }
1534
1535   if (!MemOpChains.empty())
1536     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1537                         &MemOpChains[0], MemOpChains.size());
1538
1539   // Build a sequence of copy-to-reg nodes chained together with token chain
1540   // and flag operands which copy the outgoing args into the appropriate regs.
1541   SDValue InFlag;
1542   // Tail call byval lowering might overwrite argument registers so in case of
1543   // tail call optimization the copies to registers are lowered later.
1544   if (!isTailCall)
1545     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1546       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1547                                RegsToPass[i].second, InFlag);
1548       InFlag = Chain.getValue(1);
1549     }
1550
1551   // For tail calls lower the arguments to the 'real' stack slot.
1552   if (isTailCall) {
1553     // Force all the incoming stack arguments to be loaded from the stack
1554     // before any new outgoing arguments are stored to the stack, because the
1555     // outgoing stack slots may alias the incoming argument stack slots, and
1556     // the alias isn't otherwise explicit. This is slightly more conservative
1557     // than necessary, because it means that each store effectively depends
1558     // on every argument instead of just those arguments it would clobber.
1559
1560     // Do not flag preceding copytoreg stuff together with the following stuff.
1561     InFlag = SDValue();
1562     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1563       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1564                                RegsToPass[i].second, InFlag);
1565       InFlag = Chain.getValue(1);
1566     }
1567     InFlag = SDValue();
1568   }
1569
1570   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1571   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1572   // node so that legalize doesn't hack it.
1573   bool isDirect = false;
1574   bool isARMFunc = false;
1575   bool isLocalARMFunc = false;
1576   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1577
1578   if (EnableARMLongCalls) {
1579     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1580             && "long-calls with non-static relocation model!");
1581     // Handle a global address or an external symbol. If it's not one of
1582     // those, the target's already in a register, so we don't need to do
1583     // anything extra.
1584     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1585       const GlobalValue *GV = G->getGlobal();
1586       // Create a constant pool entry for the callee address
1587       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1588       ARMConstantPoolValue *CPV =
1589         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1590
1591       // Get the address of the callee into a register
1592       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1593       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1594       Callee = DAG.getLoad(getPointerTy(), dl,
1595                            DAG.getEntryNode(), CPAddr,
1596                            MachinePointerInfo::getConstantPool(),
1597                            false, false, false, 0);
1598     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1599       const char *Sym = S->getSymbol();
1600
1601       // Create a constant pool entry for the callee address
1602       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1603       ARMConstantPoolValue *CPV =
1604         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1605                                       ARMPCLabelIndex, 0);
1606       // Get the address of the callee into a register
1607       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1608       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1609       Callee = DAG.getLoad(getPointerTy(), dl,
1610                            DAG.getEntryNode(), CPAddr,
1611                            MachinePointerInfo::getConstantPool(),
1612                            false, false, false, 0);
1613     }
1614   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1615     const GlobalValue *GV = G->getGlobal();
1616     isDirect = true;
1617     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1618     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1619                    getTargetMachine().getRelocationModel() != Reloc::Static;
1620     isARMFunc = !Subtarget->isThumb() || isStub;
1621     // ARM call to a local ARM function is predicable.
1622     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1623     // tBX takes a register source operand.
1624     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1625       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1626       ARMConstantPoolValue *CPV =
1627         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1628       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1629       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1630       Callee = DAG.getLoad(getPointerTy(), dl,
1631                            DAG.getEntryNode(), CPAddr,
1632                            MachinePointerInfo::getConstantPool(),
1633                            false, false, false, 0);
1634       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1635       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1636                            getPointerTy(), Callee, PICLabel);
1637     } else {
1638       // On ELF targets for PIC code, direct calls should go through the PLT
1639       unsigned OpFlags = 0;
1640       if (Subtarget->isTargetELF() &&
1641           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1642         OpFlags = ARMII::MO_PLT;
1643       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1644     }
1645   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1646     isDirect = true;
1647     bool isStub = Subtarget->isTargetDarwin() &&
1648                   getTargetMachine().getRelocationModel() != Reloc::Static;
1649     isARMFunc = !Subtarget->isThumb() || isStub;
1650     // tBX takes a register source operand.
1651     const char *Sym = S->getSymbol();
1652     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1653       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1654       ARMConstantPoolValue *CPV =
1655         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1656                                       ARMPCLabelIndex, 4);
1657       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1658       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1659       Callee = DAG.getLoad(getPointerTy(), dl,
1660                            DAG.getEntryNode(), CPAddr,
1661                            MachinePointerInfo::getConstantPool(),
1662                            false, false, false, 0);
1663       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1664       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1665                            getPointerTy(), Callee, PICLabel);
1666     } else {
1667       unsigned OpFlags = 0;
1668       // On ELF targets for PIC code, direct calls should go through the PLT
1669       if (Subtarget->isTargetELF() &&
1670                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1671         OpFlags = ARMII::MO_PLT;
1672       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1673     }
1674   }
1675
1676   // FIXME: handle tail calls differently.
1677   unsigned CallOpc;
1678   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1679     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1680   if (Subtarget->isThumb()) {
1681     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1682       CallOpc = ARMISD::CALL_NOLINK;
1683     else
1684       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1685   } else {
1686     if (!isDirect && !Subtarget->hasV5TOps())
1687       CallOpc = ARMISD::CALL_NOLINK;
1688     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1689                // Emit regular call when code size is the priority
1690                !HasMinSizeAttr)
1691       // "mov lr, pc; b _foo" to avoid confusing the RSP
1692       CallOpc = ARMISD::CALL_NOLINK;
1693     else
1694       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1695   }
1696
1697   std::vector<SDValue> Ops;
1698   Ops.push_back(Chain);
1699   Ops.push_back(Callee);
1700
1701   // Add argument registers to the end of the list so that they are known live
1702   // into the call.
1703   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1704     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1705                                   RegsToPass[i].second.getValueType()));
1706
1707   // Add a register mask operand representing the call-preserved registers.
1708   const uint32_t *Mask;
1709   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1710   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1711   if (isThisReturn)
1712     // For 'this' returns, use the R0-preserving mask
1713     Mask = ARI->getThisReturnPreservedMask(CallConv);
1714   else
1715     Mask = ARI->getCallPreservedMask(CallConv);
1716
1717   assert(Mask && "Missing call preserved mask for calling convention");
1718   Ops.push_back(DAG.getRegisterMask(Mask));
1719
1720   if (InFlag.getNode())
1721     Ops.push_back(InFlag);
1722
1723   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1724   if (isTailCall)
1725     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1726
1727   // Returns a chain and a flag for retval copy to use.
1728   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1729   InFlag = Chain.getValue(1);
1730
1731   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1732                              DAG.getIntPtrConstant(0, true), InFlag);
1733   if (!Ins.empty())
1734     InFlag = Chain.getValue(1);
1735
1736   // Handle result values, copying them out of physregs into vregs that we
1737   // return.
1738   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1739                          InVals, isThisReturn,
1740                          isThisReturn ? OutVals[0] : SDValue());
1741 }
1742
1743 /// HandleByVal - Every parameter *after* a byval parameter is passed
1744 /// on the stack.  Remember the next parameter register to allocate,
1745 /// and then confiscate the rest of the parameter registers to insure
1746 /// this.
1747 void
1748 ARMTargetLowering::HandleByVal(
1749     CCState *State, unsigned &size, unsigned Align) const {
1750   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1751   assert((State->getCallOrPrologue() == Prologue ||
1752           State->getCallOrPrologue() == Call) &&
1753          "unhandled ParmContext");
1754
1755   // For in-prologue parameters handling, we also introduce stack offset
1756   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1757   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1758   // NSAA should be evaluted (NSAA means "next stacked argument address").
1759   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1760   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1761   unsigned NSAAOffset = State->getNextStackOffset();
1762   if (State->getCallOrPrologue() != Call) {
1763     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1764       unsigned RB, RE;
1765       State->getInRegsParamInfo(i, RB, RE);
1766       assert(NSAAOffset >= (RE-RB)*4 &&
1767              "Stack offset for byval regs doesn't introduced anymore?");
1768       NSAAOffset -= (RE-RB)*4;
1769     }
1770   }
1771   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1772     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1773       unsigned AlignInRegs = Align / 4;
1774       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1775       for (unsigned i = 0; i < Waste; ++i)
1776         reg = State->AllocateReg(GPRArgRegs, 4);
1777     }
1778     if (reg != 0) {
1779       unsigned excess = 4 * (ARM::R4 - reg);
1780
1781       // Special case when NSAA != SP and parameter size greater than size of
1782       // all remained GPR regs. In that case we can't split parameter, we must
1783       // send it to stack. We also must set NCRN to R4, so waste all
1784       // remained registers.
1785       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1786         while (State->AllocateReg(GPRArgRegs, 4))
1787           ;
1788         return;
1789       }
1790
1791       // First register for byval parameter is the first register that wasn't
1792       // allocated before this method call, so it would be "reg".
1793       // If parameter is small enough to be saved in range [reg, r4), then
1794       // the end (first after last) register would be reg + param-size-in-regs,
1795       // else parameter would be splitted between registers and stack,
1796       // end register would be r4 in this case.
1797       unsigned ByValRegBegin = reg;
1798       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : ARM::R4;
1799       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1800       // Note, first register is allocated in the beginning of function already,
1801       // allocate remained amount of registers we need.
1802       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1803         State->AllocateReg(GPRArgRegs, 4);
1804       // At a call site, a byval parameter that is split between
1805       // registers and memory needs its size truncated here.  In a
1806       // function prologue, such byval parameters are reassembled in
1807       // memory, and are not truncated.
1808       if (State->getCallOrPrologue() == Call) {
1809         // Make remained size equal to 0 in case, when
1810         // the whole structure may be stored into registers.
1811         if (size < excess)
1812           size = 0;
1813         else
1814           size -= excess;
1815       }
1816     }
1817   }
1818 }
1819
1820 /// MatchingStackOffset - Return true if the given stack call argument is
1821 /// already available in the same position (relatively) of the caller's
1822 /// incoming argument stack.
1823 static
1824 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1825                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1826                          const TargetInstrInfo *TII) {
1827   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1828   int FI = INT_MAX;
1829   if (Arg.getOpcode() == ISD::CopyFromReg) {
1830     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1831     if (!TargetRegisterInfo::isVirtualRegister(VR))
1832       return false;
1833     MachineInstr *Def = MRI->getVRegDef(VR);
1834     if (!Def)
1835       return false;
1836     if (!Flags.isByVal()) {
1837       if (!TII->isLoadFromStackSlot(Def, FI))
1838         return false;
1839     } else {
1840       return false;
1841     }
1842   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1843     if (Flags.isByVal())
1844       // ByVal argument is passed in as a pointer but it's now being
1845       // dereferenced. e.g.
1846       // define @foo(%struct.X* %A) {
1847       //   tail call @bar(%struct.X* byval %A)
1848       // }
1849       return false;
1850     SDValue Ptr = Ld->getBasePtr();
1851     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1852     if (!FINode)
1853       return false;
1854     FI = FINode->getIndex();
1855   } else
1856     return false;
1857
1858   assert(FI != INT_MAX);
1859   if (!MFI->isFixedObjectIndex(FI))
1860     return false;
1861   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1862 }
1863
1864 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1865 /// for tail call optimization. Targets which want to do tail call
1866 /// optimization should implement this function.
1867 bool
1868 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1869                                                      CallingConv::ID CalleeCC,
1870                                                      bool isVarArg,
1871                                                      bool isCalleeStructRet,
1872                                                      bool isCallerStructRet,
1873                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1874                                     const SmallVectorImpl<SDValue> &OutVals,
1875                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1876                                                      SelectionDAG& DAG) const {
1877   const Function *CallerF = DAG.getMachineFunction().getFunction();
1878   CallingConv::ID CallerCC = CallerF->getCallingConv();
1879   bool CCMatch = CallerCC == CalleeCC;
1880
1881   // Look for obvious safe cases to perform tail call optimization that do not
1882   // require ABI changes. This is what gcc calls sibcall.
1883
1884   // Do not sibcall optimize vararg calls unless the call site is not passing
1885   // any arguments.
1886   if (isVarArg && !Outs.empty())
1887     return false;
1888
1889   // Also avoid sibcall optimization if either caller or callee uses struct
1890   // return semantics.
1891   if (isCalleeStructRet || isCallerStructRet)
1892     return false;
1893
1894   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1895   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1896   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1897   // support in the assembler and linker to be used. This would need to be
1898   // fixed to fully support tail calls in Thumb1.
1899   //
1900   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1901   // LR.  This means if we need to reload LR, it takes an extra instructions,
1902   // which outweighs the value of the tail call; but here we don't know yet
1903   // whether LR is going to be used.  Probably the right approach is to
1904   // generate the tail call here and turn it back into CALL/RET in
1905   // emitEpilogue if LR is used.
1906
1907   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1908   // but we need to make sure there are enough registers; the only valid
1909   // registers are the 4 used for parameters.  We don't currently do this
1910   // case.
1911   if (Subtarget->isThumb1Only())
1912     return false;
1913
1914   // If the calling conventions do not match, then we'd better make sure the
1915   // results are returned in the same way as what the caller expects.
1916   if (!CCMatch) {
1917     SmallVector<CCValAssign, 16> RVLocs1;
1918     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1919                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1920     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1921
1922     SmallVector<CCValAssign, 16> RVLocs2;
1923     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1924                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1925     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1926
1927     if (RVLocs1.size() != RVLocs2.size())
1928       return false;
1929     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1930       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1931         return false;
1932       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1933         return false;
1934       if (RVLocs1[i].isRegLoc()) {
1935         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1936           return false;
1937       } else {
1938         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1939           return false;
1940       }
1941     }
1942   }
1943
1944   // If Caller's vararg or byval argument has been split between registers and
1945   // stack, do not perform tail call, since part of the argument is in caller's
1946   // local frame.
1947   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1948                                       getInfo<ARMFunctionInfo>();
1949   if (AFI_Caller->getArgRegsSaveSize())
1950     return false;
1951
1952   // If the callee takes no arguments then go on to check the results of the
1953   // call.
1954   if (!Outs.empty()) {
1955     // Check if stack adjustment is needed. For now, do not do this if any
1956     // argument is passed on the stack.
1957     SmallVector<CCValAssign, 16> ArgLocs;
1958     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1959                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1960     CCInfo.AnalyzeCallOperands(Outs,
1961                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1962     if (CCInfo.getNextStackOffset()) {
1963       MachineFunction &MF = DAG.getMachineFunction();
1964
1965       // Check if the arguments are already laid out in the right way as
1966       // the caller's fixed stack objects.
1967       MachineFrameInfo *MFI = MF.getFrameInfo();
1968       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1969       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1970       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1971            i != e;
1972            ++i, ++realArgIdx) {
1973         CCValAssign &VA = ArgLocs[i];
1974         EVT RegVT = VA.getLocVT();
1975         SDValue Arg = OutVals[realArgIdx];
1976         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1977         if (VA.getLocInfo() == CCValAssign::Indirect)
1978           return false;
1979         if (VA.needsCustom()) {
1980           // f64 and vector types are split into multiple registers or
1981           // register/stack-slot combinations.  The types will not match
1982           // the registers; give up on memory f64 refs until we figure
1983           // out what to do about this.
1984           if (!VA.isRegLoc())
1985             return false;
1986           if (!ArgLocs[++i].isRegLoc())
1987             return false;
1988           if (RegVT == MVT::v2f64) {
1989             if (!ArgLocs[++i].isRegLoc())
1990               return false;
1991             if (!ArgLocs[++i].isRegLoc())
1992               return false;
1993           }
1994         } else if (!VA.isRegLoc()) {
1995           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1996                                    MFI, MRI, TII))
1997             return false;
1998         }
1999       }
2000     }
2001   }
2002
2003   return true;
2004 }
2005
2006 bool
2007 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2008                                   MachineFunction &MF, bool isVarArg,
2009                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2010                                   LLVMContext &Context) const {
2011   SmallVector<CCValAssign, 16> RVLocs;
2012   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2013   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2014                                                     isVarArg));
2015 }
2016
2017 SDValue
2018 ARMTargetLowering::LowerReturn(SDValue Chain,
2019                                CallingConv::ID CallConv, bool isVarArg,
2020                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2021                                const SmallVectorImpl<SDValue> &OutVals,
2022                                DebugLoc dl, SelectionDAG &DAG) const {
2023
2024   // CCValAssign - represent the assignment of the return value to a location.
2025   SmallVector<CCValAssign, 16> RVLocs;
2026
2027   // CCState - Info about the registers and stack slots.
2028   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2029                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2030
2031   // Analyze outgoing return values.
2032   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2033                                                isVarArg));
2034
2035   SDValue Flag;
2036   SmallVector<SDValue, 4> RetOps;
2037   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2038
2039   // Copy the result values into the output registers.
2040   for (unsigned i = 0, realRVLocIdx = 0;
2041        i != RVLocs.size();
2042        ++i, ++realRVLocIdx) {
2043     CCValAssign &VA = RVLocs[i];
2044     assert(VA.isRegLoc() && "Can only return in registers!");
2045
2046     SDValue Arg = OutVals[realRVLocIdx];
2047
2048     switch (VA.getLocInfo()) {
2049     default: llvm_unreachable("Unknown loc info!");
2050     case CCValAssign::Full: break;
2051     case CCValAssign::BCvt:
2052       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2053       break;
2054     }
2055
2056     if (VA.needsCustom()) {
2057       if (VA.getLocVT() == MVT::v2f64) {
2058         // Extract the first half and return it in two registers.
2059         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2060                                    DAG.getConstant(0, MVT::i32));
2061         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2062                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2063
2064         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2065         Flag = Chain.getValue(1);
2066         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2067         VA = RVLocs[++i]; // skip ahead to next loc
2068         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2069                                  HalfGPRs.getValue(1), Flag);
2070         Flag = Chain.getValue(1);
2071         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2072         VA = RVLocs[++i]; // skip ahead to next loc
2073
2074         // Extract the 2nd half and fall through to handle it as an f64 value.
2075         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2076                           DAG.getConstant(1, MVT::i32));
2077       }
2078       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2079       // available.
2080       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2081                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2082       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2083       Flag = Chain.getValue(1);
2084       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2085       VA = RVLocs[++i]; // skip ahead to next loc
2086       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2087                                Flag);
2088     } else
2089       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2090
2091     // Guarantee that all emitted copies are
2092     // stuck together, avoiding something bad.
2093     Flag = Chain.getValue(1);
2094     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2095   }
2096
2097   // Update chain and glue.
2098   RetOps[0] = Chain;
2099   if (Flag.getNode())
2100     RetOps.push_back(Flag);
2101
2102   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2103                      RetOps.data(), RetOps.size());
2104 }
2105
2106 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2107   if (N->getNumValues() != 1)
2108     return false;
2109   if (!N->hasNUsesOfValue(1, 0))
2110     return false;
2111
2112   SDValue TCChain = Chain;
2113   SDNode *Copy = *N->use_begin();
2114   if (Copy->getOpcode() == ISD::CopyToReg) {
2115     // If the copy has a glue operand, we conservatively assume it isn't safe to
2116     // perform a tail call.
2117     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2118       return false;
2119     TCChain = Copy->getOperand(0);
2120   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2121     SDNode *VMov = Copy;
2122     // f64 returned in a pair of GPRs.
2123     SmallPtrSet<SDNode*, 2> Copies;
2124     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2125          UI != UE; ++UI) {
2126       if (UI->getOpcode() != ISD::CopyToReg)
2127         return false;
2128       Copies.insert(*UI);
2129     }
2130     if (Copies.size() > 2)
2131       return false;
2132
2133     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2134          UI != UE; ++UI) {
2135       SDValue UseChain = UI->getOperand(0);
2136       if (Copies.count(UseChain.getNode()))
2137         // Second CopyToReg
2138         Copy = *UI;
2139       else
2140         // First CopyToReg
2141         TCChain = UseChain;
2142     }
2143   } else if (Copy->getOpcode() == ISD::BITCAST) {
2144     // f32 returned in a single GPR.
2145     if (!Copy->hasOneUse())
2146       return false;
2147     Copy = *Copy->use_begin();
2148     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2149       return false;
2150     Chain = Copy->getOperand(0);
2151   } else {
2152     return false;
2153   }
2154
2155   bool HasRet = false;
2156   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2157        UI != UE; ++UI) {
2158     if (UI->getOpcode() != ARMISD::RET_FLAG)
2159       return false;
2160     HasRet = true;
2161   }
2162
2163   if (!HasRet)
2164     return false;
2165
2166   Chain = TCChain;
2167   return true;
2168 }
2169
2170 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2171   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2172     return false;
2173
2174   if (!CI->isTailCall())
2175     return false;
2176
2177   return !Subtarget->isThumb1Only();
2178 }
2179
2180 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2181 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2182 // one of the above mentioned nodes. It has to be wrapped because otherwise
2183 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2184 // be used to form addressing mode. These wrapped nodes will be selected
2185 // into MOVi.
2186 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2187   EVT PtrVT = Op.getValueType();
2188   // FIXME there is no actual debug info here
2189   DebugLoc dl = Op.getDebugLoc();
2190   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2191   SDValue Res;
2192   if (CP->isMachineConstantPoolEntry())
2193     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2194                                     CP->getAlignment());
2195   else
2196     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2197                                     CP->getAlignment());
2198   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2199 }
2200
2201 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2202   return MachineJumpTableInfo::EK_Inline;
2203 }
2204
2205 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2206                                              SelectionDAG &DAG) const {
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2209   unsigned ARMPCLabelIndex = 0;
2210   DebugLoc DL = Op.getDebugLoc();
2211   EVT PtrVT = getPointerTy();
2212   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2213   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2214   SDValue CPAddr;
2215   if (RelocM == Reloc::Static) {
2216     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2217   } else {
2218     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2219     ARMPCLabelIndex = AFI->createPICLabelUId();
2220     ARMConstantPoolValue *CPV =
2221       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2222                                       ARMCP::CPBlockAddress, PCAdj);
2223     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2224   }
2225   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2226   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2227                                MachinePointerInfo::getConstantPool(),
2228                                false, false, false, 0);
2229   if (RelocM == Reloc::Static)
2230     return Result;
2231   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2232   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2233 }
2234
2235 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2236 SDValue
2237 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2238                                                  SelectionDAG &DAG) const {
2239   DebugLoc dl = GA->getDebugLoc();
2240   EVT PtrVT = getPointerTy();
2241   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2242   MachineFunction &MF = DAG.getMachineFunction();
2243   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2244   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2245   ARMConstantPoolValue *CPV =
2246     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2247                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2248   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2249   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2250   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2251                          MachinePointerInfo::getConstantPool(),
2252                          false, false, false, 0);
2253   SDValue Chain = Argument.getValue(1);
2254
2255   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2256   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2257
2258   // call __tls_get_addr.
2259   ArgListTy Args;
2260   ArgListEntry Entry;
2261   Entry.Node = Argument;
2262   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2263   Args.push_back(Entry);
2264   // FIXME: is there useful debug info available here?
2265   TargetLowering::CallLoweringInfo CLI(Chain,
2266                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2267                 false, false, false, false,
2268                 0, CallingConv::C, /*isTailCall=*/false,
2269                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2270                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2271   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2272   return CallResult.first;
2273 }
2274
2275 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2276 // "local exec" model.
2277 SDValue
2278 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2279                                         SelectionDAG &DAG,
2280                                         TLSModel::Model model) const {
2281   const GlobalValue *GV = GA->getGlobal();
2282   DebugLoc dl = GA->getDebugLoc();
2283   SDValue Offset;
2284   SDValue Chain = DAG.getEntryNode();
2285   EVT PtrVT = getPointerTy();
2286   // Get the Thread Pointer
2287   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2288
2289   if (model == TLSModel::InitialExec) {
2290     MachineFunction &MF = DAG.getMachineFunction();
2291     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2292     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2293     // Initial exec model.
2294     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2295     ARMConstantPoolValue *CPV =
2296       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2297                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2298                                       true);
2299     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2300     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2301     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2302                          MachinePointerInfo::getConstantPool(),
2303                          false, false, false, 0);
2304     Chain = Offset.getValue(1);
2305
2306     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2307     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2308
2309     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2310                          MachinePointerInfo::getConstantPool(),
2311                          false, false, false, 0);
2312   } else {
2313     // local exec model
2314     assert(model == TLSModel::LocalExec);
2315     ARMConstantPoolValue *CPV =
2316       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2317     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2318     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2319     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2320                          MachinePointerInfo::getConstantPool(),
2321                          false, false, false, 0);
2322   }
2323
2324   // The address of the thread local variable is the add of the thread
2325   // pointer with the offset of the variable.
2326   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2327 }
2328
2329 SDValue
2330 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2331   // TODO: implement the "local dynamic" model
2332   assert(Subtarget->isTargetELF() &&
2333          "TLS not implemented for non-ELF targets");
2334   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2335
2336   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2337
2338   switch (model) {
2339     case TLSModel::GeneralDynamic:
2340     case TLSModel::LocalDynamic:
2341       return LowerToTLSGeneralDynamicModel(GA, DAG);
2342     case TLSModel::InitialExec:
2343     case TLSModel::LocalExec:
2344       return LowerToTLSExecModels(GA, DAG, model);
2345   }
2346   llvm_unreachable("bogus TLS model");
2347 }
2348
2349 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2350                                                  SelectionDAG &DAG) const {
2351   EVT PtrVT = getPointerTy();
2352   DebugLoc dl = Op.getDebugLoc();
2353   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2354   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2355     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2356     ARMConstantPoolValue *CPV =
2357       ARMConstantPoolConstant::Create(GV,
2358                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2359     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2361     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2362                                  CPAddr,
2363                                  MachinePointerInfo::getConstantPool(),
2364                                  false, false, false, 0);
2365     SDValue Chain = Result.getValue(1);
2366     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2367     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2368     if (!UseGOTOFF)
2369       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2370                            MachinePointerInfo::getGOT(),
2371                            false, false, false, 0);
2372     return Result;
2373   }
2374
2375   // If we have T2 ops, we can materialize the address directly via movt/movw
2376   // pair. This is always cheaper.
2377   if (Subtarget->useMovt()) {
2378     ++NumMovwMovt;
2379     // FIXME: Once remat is capable of dealing with instructions with register
2380     // operands, expand this into two nodes.
2381     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2382                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2383   } else {
2384     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2385     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2386     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2387                        MachinePointerInfo::getConstantPool(),
2388                        false, false, false, 0);
2389   }
2390 }
2391
2392 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2393                                                     SelectionDAG &DAG) const {
2394   EVT PtrVT = getPointerTy();
2395   DebugLoc dl = Op.getDebugLoc();
2396   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2397   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2398
2399   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2400   // update ARMFastISel::ARMMaterializeGV.
2401   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2402     ++NumMovwMovt;
2403     // FIXME: Once remat is capable of dealing with instructions with register
2404     // operands, expand this into two nodes.
2405     if (RelocM == Reloc::Static)
2406       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2407                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2408
2409     unsigned Wrapper = (RelocM == Reloc::PIC_)
2410       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2411     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2412                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2413     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2414       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2415                            MachinePointerInfo::getGOT(),
2416                            false, false, false, 0);
2417     return Result;
2418   }
2419
2420   unsigned ARMPCLabelIndex = 0;
2421   SDValue CPAddr;
2422   if (RelocM == Reloc::Static) {
2423     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2424   } else {
2425     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2426     ARMPCLabelIndex = AFI->createPICLabelUId();
2427     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2428     ARMConstantPoolValue *CPV =
2429       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2430                                       PCAdj);
2431     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2432   }
2433   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2434
2435   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2436                                MachinePointerInfo::getConstantPool(),
2437                                false, false, false, 0);
2438   SDValue Chain = Result.getValue(1);
2439
2440   if (RelocM == Reloc::PIC_) {
2441     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2442     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2443   }
2444
2445   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2446     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2447                          false, false, false, 0);
2448
2449   return Result;
2450 }
2451
2452 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2453                                                     SelectionDAG &DAG) const {
2454   assert(Subtarget->isTargetELF() &&
2455          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2456   MachineFunction &MF = DAG.getMachineFunction();
2457   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2458   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2459   EVT PtrVT = getPointerTy();
2460   DebugLoc dl = Op.getDebugLoc();
2461   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2462   ARMConstantPoolValue *CPV =
2463     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2464                                   ARMPCLabelIndex, PCAdj);
2465   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2466   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2467   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2468                                MachinePointerInfo::getConstantPool(),
2469                                false, false, false, 0);
2470   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2471   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2472 }
2473
2474 SDValue
2475 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2476   DebugLoc dl = Op.getDebugLoc();
2477   SDValue Val = DAG.getConstant(0, MVT::i32);
2478   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2479                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2480                      Op.getOperand(1), Val);
2481 }
2482
2483 SDValue
2484 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2485   DebugLoc dl = Op.getDebugLoc();
2486   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2487                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2488 }
2489
2490 SDValue
2491 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2492                                           const ARMSubtarget *Subtarget) const {
2493   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2494   DebugLoc dl = Op.getDebugLoc();
2495   switch (IntNo) {
2496   default: return SDValue();    // Don't custom lower most intrinsics.
2497   case Intrinsic::arm_thread_pointer: {
2498     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2499     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2500   }
2501   case Intrinsic::eh_sjlj_lsda: {
2502     MachineFunction &MF = DAG.getMachineFunction();
2503     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2504     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2505     EVT PtrVT = getPointerTy();
2506     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2507     SDValue CPAddr;
2508     unsigned PCAdj = (RelocM != Reloc::PIC_)
2509       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2510     ARMConstantPoolValue *CPV =
2511       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2512                                       ARMCP::CPLSDA, PCAdj);
2513     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2514     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2515     SDValue Result =
2516       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517                   MachinePointerInfo::getConstantPool(),
2518                   false, false, false, 0);
2519
2520     if (RelocM == Reloc::PIC_) {
2521       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2522       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2523     }
2524     return Result;
2525   }
2526   case Intrinsic::arm_neon_vmulls:
2527   case Intrinsic::arm_neon_vmullu: {
2528     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2529       ? ARMISD::VMULLs : ARMISD::VMULLu;
2530     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2531                        Op.getOperand(1), Op.getOperand(2));
2532   }
2533   }
2534 }
2535
2536 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2537                                  const ARMSubtarget *Subtarget) {
2538   // FIXME: handle "fence singlethread" more efficiently.
2539   DebugLoc dl = Op.getDebugLoc();
2540   if (!Subtarget->hasDataBarrier()) {
2541     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2542     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2543     // here.
2544     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2545            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2546     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2547                        DAG.getConstant(0, MVT::i32));
2548   }
2549
2550   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2551                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2552 }
2553
2554 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2555                              const ARMSubtarget *Subtarget) {
2556   // ARM pre v5TE and Thumb1 does not have preload instructions.
2557   if (!(Subtarget->isThumb2() ||
2558         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2559     // Just preserve the chain.
2560     return Op.getOperand(0);
2561
2562   DebugLoc dl = Op.getDebugLoc();
2563   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2564   if (!isRead &&
2565       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2566     // ARMv7 with MP extension has PLDW.
2567     return Op.getOperand(0);
2568
2569   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2570   if (Subtarget->isThumb()) {
2571     // Invert the bits.
2572     isRead = ~isRead & 1;
2573     isData = ~isData & 1;
2574   }
2575
2576   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2577                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2578                      DAG.getConstant(isData, MVT::i32));
2579 }
2580
2581 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2582   MachineFunction &MF = DAG.getMachineFunction();
2583   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2584
2585   // vastart just stores the address of the VarArgsFrameIndex slot into the
2586   // memory location argument.
2587   DebugLoc dl = Op.getDebugLoc();
2588   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2589   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2590   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2591   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2592                       MachinePointerInfo(SV), false, false, 0);
2593 }
2594
2595 SDValue
2596 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2597                                         SDValue &Root, SelectionDAG &DAG,
2598                                         DebugLoc dl) const {
2599   MachineFunction &MF = DAG.getMachineFunction();
2600   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601
2602   const TargetRegisterClass *RC;
2603   if (AFI->isThumb1OnlyFunction())
2604     RC = &ARM::tGPRRegClass;
2605   else
2606     RC = &ARM::GPRRegClass;
2607
2608   // Transform the arguments stored in physical registers into virtual ones.
2609   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2610   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2611
2612   SDValue ArgValue2;
2613   if (NextVA.isMemLoc()) {
2614     MachineFrameInfo *MFI = MF.getFrameInfo();
2615     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2616
2617     // Create load node to retrieve arguments from the stack.
2618     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2619     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2620                             MachinePointerInfo::getFixedStack(FI),
2621                             false, false, false, 0);
2622   } else {
2623     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2624     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2625   }
2626
2627   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2628 }
2629
2630 void
2631 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2632                                   unsigned InRegsParamRecordIdx,
2633                                   unsigned &ArgRegsSize,
2634                                   unsigned &ArgRegsSaveSize)
2635   const {
2636   unsigned NumGPRs;
2637   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2638     unsigned RBegin, REnd;
2639     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2640     NumGPRs = REnd - RBegin;
2641   } else {
2642     unsigned int firstUnalloced;
2643     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2644                                                 sizeof(GPRArgRegs) /
2645                                                 sizeof(GPRArgRegs[0]));
2646     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2647   }
2648
2649   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2650   ArgRegsSize = NumGPRs * 4;
2651   ArgRegsSaveSize = (ArgRegsSize + Align - 1) & ~(Align - 1);
2652 }
2653
2654 // The remaining GPRs hold either the beginning of variable-argument
2655 // data, or the beginning of an aggregate passed by value (usually
2656 // byval).  Either way, we allocate stack slots adjacent to the data
2657 // provided by our caller, and store the unallocated registers there.
2658 // If this is a variadic function, the va_list pointer will begin with
2659 // these values; otherwise, this reassembles a (byval) structure that
2660 // was split between registers and memory.
2661 // Return: The frame index registers were stored into.
2662 int
2663 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2664                                   DebugLoc dl, SDValue &Chain,
2665                                   const Value *OrigArg,
2666                                   unsigned InRegsParamRecordIdx,
2667                                   unsigned OffsetFromOrigArg,
2668                                   unsigned ArgOffset,
2669                                   bool ForceMutable) const {
2670
2671   // Currently, two use-cases possible:
2672   // Case #1. Non var-args function, and we meet first byval parameter.
2673   //          Setup first unallocated register as first byval register;
2674   //          eat all remained registers
2675   //          (these two actions are performed by HandleByVal method).
2676   //          Then, here, we initialize stack frame with
2677   //          "store-reg" instructions.
2678   // Case #2. Var-args function, that doesn't contain byval parameters.
2679   //          The same: eat all remained unallocated registers,
2680   //          initialize stack frame.
2681
2682   MachineFunction &MF = DAG.getMachineFunction();
2683   MachineFrameInfo *MFI = MF.getFrameInfo();
2684   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2685   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2686   unsigned RBegin, REnd;
2687   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2688     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2689     firstRegToSaveIndex = RBegin - ARM::R0;
2690     lastRegToSaveIndex = REnd - ARM::R0;
2691   } else {
2692     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2693       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2694     lastRegToSaveIndex = 4;
2695   }
2696
2697   unsigned ArgRegsSize, ArgRegsSaveSize;
2698   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgRegsSize, ArgRegsSaveSize);
2699
2700   // Store any by-val regs to their spots on the stack so that they may be
2701   // loaded by deferencing the result of formal parameter pointer or va_next.
2702   // Note: once stack area for byval/varargs registers
2703   // was initialized, it can't be initialized again.
2704   if (ArgRegsSaveSize) {
2705
2706     int FrameIndex = MFI->CreateFixedObject(
2707                       ArgRegsSaveSize,
2708                       ArgOffset + ArgRegsSaveSize - ArgRegsSize,
2709                       false);
2710     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2711
2712     SmallVector<SDValue, 4> MemOps;
2713     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2714          ++firstRegToSaveIndex, ++i) {
2715       const TargetRegisterClass *RC;
2716       if (AFI->isThumb1OnlyFunction())
2717         RC = &ARM::tGPRRegClass;
2718       else
2719         RC = &ARM::GPRRegClass;
2720
2721       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2722       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2723       SDValue Store =
2724         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2725                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2726                      false, false, 0);
2727       MemOps.push_back(Store);
2728       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2729                         DAG.getConstant(4, getPointerTy()));
2730     }
2731
2732     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2733
2734     if (!MemOps.empty())
2735       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2736                           &MemOps[0], MemOps.size());
2737     return FrameIndex;
2738   } else
2739     // This will point to the next argument passed via stack.
2740     return MFI->CreateFixedObject(4, ArgOffset, !ForceMutable);
2741 }
2742
2743 // Setup stack frame, the va_list pointer will start from.
2744 void
2745 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2746                                         DebugLoc dl, SDValue &Chain,
2747                                         unsigned ArgOffset,
2748                                         bool ForceMutable) const {
2749   MachineFunction &MF = DAG.getMachineFunction();
2750   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2751
2752   // Try to store any remaining integer argument regs
2753   // to their spots on the stack so that they may be loaded by deferencing
2754   // the result of va_next.
2755   // If there is no regs to be stored, just point address after last
2756   // argument passed via stack.
2757   int FrameIndex =
2758     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2759                    0, ArgOffset, ForceMutable);
2760
2761   AFI->setVarArgsFrameIndex(FrameIndex);
2762 }
2763
2764 SDValue
2765 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2766                                         CallingConv::ID CallConv, bool isVarArg,
2767                                         const SmallVectorImpl<ISD::InputArg>
2768                                           &Ins,
2769                                         DebugLoc dl, SelectionDAG &DAG,
2770                                         SmallVectorImpl<SDValue> &InVals)
2771                                           const {
2772   MachineFunction &MF = DAG.getMachineFunction();
2773   MachineFrameInfo *MFI = MF.getFrameInfo();
2774
2775   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2776
2777   // Assign locations to all of the incoming arguments.
2778   SmallVector<CCValAssign, 16> ArgLocs;
2779   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2780                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2781   CCInfo.AnalyzeFormalArguments(Ins,
2782                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2783                                                   isVarArg));
2784
2785   SmallVector<SDValue, 16> ArgValues;
2786   int lastInsIndex = -1;
2787   SDValue ArgValue;
2788   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2789   unsigned CurArgIdx = 0;
2790
2791   // Initially ArgRegsSaveSize is zero.
2792   // Then we increase this value each time we meet byval parameter.
2793   // We also increase this value in case of varargs function.
2794   AFI->setArgRegsSaveSize(0);
2795
2796   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2797     CCValAssign &VA = ArgLocs[i];
2798     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2799     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2800     // Arguments stored in registers.
2801     if (VA.isRegLoc()) {
2802       EVT RegVT = VA.getLocVT();
2803
2804       if (VA.needsCustom()) {
2805         // f64 and vector types are split up into multiple registers or
2806         // combinations of registers and stack slots.
2807         if (VA.getLocVT() == MVT::v2f64) {
2808           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2809                                                    Chain, DAG, dl);
2810           VA = ArgLocs[++i]; // skip ahead to next loc
2811           SDValue ArgValue2;
2812           if (VA.isMemLoc()) {
2813             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2814             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2815             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2816                                     MachinePointerInfo::getFixedStack(FI),
2817                                     false, false, false, 0);
2818           } else {
2819             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2820                                              Chain, DAG, dl);
2821           }
2822           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2823           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2824                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2825           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2826                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2827         } else
2828           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2829
2830       } else {
2831         const TargetRegisterClass *RC;
2832
2833         if (RegVT == MVT::f32)
2834           RC = &ARM::SPRRegClass;
2835         else if (RegVT == MVT::f64)
2836           RC = &ARM::DPRRegClass;
2837         else if (RegVT == MVT::v2f64)
2838           RC = &ARM::QPRRegClass;
2839         else if (RegVT == MVT::i32)
2840           RC = AFI->isThumb1OnlyFunction() ?
2841             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2842             (const TargetRegisterClass*)&ARM::GPRRegClass;
2843         else
2844           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2845
2846         // Transform the arguments in physical registers into virtual ones.
2847         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2848         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2849       }
2850
2851       // If this is an 8 or 16-bit value, it is really passed promoted
2852       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2853       // truncate to the right size.
2854       switch (VA.getLocInfo()) {
2855       default: llvm_unreachable("Unknown loc info!");
2856       case CCValAssign::Full: break;
2857       case CCValAssign::BCvt:
2858         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2859         break;
2860       case CCValAssign::SExt:
2861         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2862                                DAG.getValueType(VA.getValVT()));
2863         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2864         break;
2865       case CCValAssign::ZExt:
2866         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2867                                DAG.getValueType(VA.getValVT()));
2868         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2869         break;
2870       }
2871
2872       InVals.push_back(ArgValue);
2873
2874     } else { // VA.isRegLoc()
2875
2876       // sanity check
2877       assert(VA.isMemLoc());
2878       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2879
2880       int index = ArgLocs[i].getValNo();
2881
2882       // Some Ins[] entries become multiple ArgLoc[] entries.
2883       // Process them only once.
2884       if (index != lastInsIndex)
2885         {
2886           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2887           // FIXME: For now, all byval parameter objects are marked mutable.
2888           // This can be changed with more analysis.
2889           // In case of tail call optimization mark all arguments mutable.
2890           // Since they could be overwritten by lowering of arguments in case of
2891           // a tail call.
2892           if (Flags.isByVal()) {
2893             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2894             int FrameIndex = StoreByValRegs(
2895                 CCInfo, DAG, dl, Chain, CurOrigArg,
2896                 CurByValIndex,
2897                 Ins[VA.getValNo()].PartOffset,
2898                 VA.getLocMemOffset(),
2899                 true /*force mutable frames*/);
2900             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2901             CCInfo.nextInRegsParam();
2902           } else {
2903             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2904                                             VA.getLocMemOffset(), true);
2905
2906             // Create load nodes to retrieve arguments from the stack.
2907             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2908             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2909                                          MachinePointerInfo::getFixedStack(FI),
2910                                          false, false, false, 0));
2911           }
2912           lastInsIndex = index;
2913         }
2914     }
2915   }
2916
2917   // varargs
2918   if (isVarArg)
2919     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2920                          CCInfo.getNextStackOffset());
2921
2922   return Chain;
2923 }
2924
2925 /// isFloatingPointZero - Return true if this is +0.0.
2926 static bool isFloatingPointZero(SDValue Op) {
2927   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2928     return CFP->getValueAPF().isPosZero();
2929   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2930     // Maybe this has already been legalized into the constant pool?
2931     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2932       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2933       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2934         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2935           return CFP->getValueAPF().isPosZero();
2936     }
2937   }
2938   return false;
2939 }
2940
2941 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2942 /// the given operands.
2943 SDValue
2944 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2945                              SDValue &ARMcc, SelectionDAG &DAG,
2946                              DebugLoc dl) const {
2947   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2948     unsigned C = RHSC->getZExtValue();
2949     if (!isLegalICmpImmediate(C)) {
2950       // Constant does not fit, try adjusting it by one?
2951       switch (CC) {
2952       default: break;
2953       case ISD::SETLT:
2954       case ISD::SETGE:
2955         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2956           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2957           RHS = DAG.getConstant(C-1, MVT::i32);
2958         }
2959         break;
2960       case ISD::SETULT:
2961       case ISD::SETUGE:
2962         if (C != 0 && isLegalICmpImmediate(C-1)) {
2963           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2964           RHS = DAG.getConstant(C-1, MVT::i32);
2965         }
2966         break;
2967       case ISD::SETLE:
2968       case ISD::SETGT:
2969         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2970           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2971           RHS = DAG.getConstant(C+1, MVT::i32);
2972         }
2973         break;
2974       case ISD::SETULE:
2975       case ISD::SETUGT:
2976         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2977           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2978           RHS = DAG.getConstant(C+1, MVT::i32);
2979         }
2980         break;
2981       }
2982     }
2983   }
2984
2985   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2986   ARMISD::NodeType CompareType;
2987   switch (CondCode) {
2988   default:
2989     CompareType = ARMISD::CMP;
2990     break;
2991   case ARMCC::EQ:
2992   case ARMCC::NE:
2993     // Uses only Z Flag
2994     CompareType = ARMISD::CMPZ;
2995     break;
2996   }
2997   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2998   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2999 }
3000
3001 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3002 SDValue
3003 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3004                              DebugLoc dl) const {
3005   SDValue Cmp;
3006   if (!isFloatingPointZero(RHS))
3007     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3008   else
3009     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3010   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3011 }
3012
3013 /// duplicateCmp - Glue values can have only one use, so this function
3014 /// duplicates a comparison node.
3015 SDValue
3016 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3017   unsigned Opc = Cmp.getOpcode();
3018   DebugLoc DL = Cmp.getDebugLoc();
3019   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3020     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3021
3022   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3023   Cmp = Cmp.getOperand(0);
3024   Opc = Cmp.getOpcode();
3025   if (Opc == ARMISD::CMPFP)
3026     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3027   else {
3028     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3029     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3030   }
3031   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3032 }
3033
3034 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3035   SDValue Cond = Op.getOperand(0);
3036   SDValue SelectTrue = Op.getOperand(1);
3037   SDValue SelectFalse = Op.getOperand(2);
3038   DebugLoc dl = Op.getDebugLoc();
3039
3040   // Convert:
3041   //
3042   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3043   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3044   //
3045   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3046     const ConstantSDNode *CMOVTrue =
3047       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3048     const ConstantSDNode *CMOVFalse =
3049       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3050
3051     if (CMOVTrue && CMOVFalse) {
3052       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3053       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3054
3055       SDValue True;
3056       SDValue False;
3057       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3058         True = SelectTrue;
3059         False = SelectFalse;
3060       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3061         True = SelectFalse;
3062         False = SelectTrue;
3063       }
3064
3065       if (True.getNode() && False.getNode()) {
3066         EVT VT = Op.getValueType();
3067         SDValue ARMcc = Cond.getOperand(2);
3068         SDValue CCR = Cond.getOperand(3);
3069         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3070         assert(True.getValueType() == VT);
3071         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3072       }
3073     }
3074   }
3075
3076   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3077   // undefined bits before doing a full-word comparison with zero.
3078   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3079                      DAG.getConstant(1, Cond.getValueType()));
3080
3081   return DAG.getSelectCC(dl, Cond,
3082                          DAG.getConstant(0, Cond.getValueType()),
3083                          SelectTrue, SelectFalse, ISD::SETNE);
3084 }
3085
3086 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3087   EVT VT = Op.getValueType();
3088   SDValue LHS = Op.getOperand(0);
3089   SDValue RHS = Op.getOperand(1);
3090   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3091   SDValue TrueVal = Op.getOperand(2);
3092   SDValue FalseVal = Op.getOperand(3);
3093   DebugLoc dl = Op.getDebugLoc();
3094
3095   if (LHS.getValueType() == MVT::i32) {
3096     SDValue ARMcc;
3097     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3098     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3099     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3100   }
3101
3102   ARMCC::CondCodes CondCode, CondCode2;
3103   FPCCToARMCC(CC, CondCode, CondCode2);
3104
3105   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3106   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3107   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3108   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3109                                ARMcc, CCR, Cmp);
3110   if (CondCode2 != ARMCC::AL) {
3111     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3112     // FIXME: Needs another CMP because flag can have but one use.
3113     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3114     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3115                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3116   }
3117   return Result;
3118 }
3119
3120 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3121 /// to morph to an integer compare sequence.
3122 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3123                            const ARMSubtarget *Subtarget) {
3124   SDNode *N = Op.getNode();
3125   if (!N->hasOneUse())
3126     // Otherwise it requires moving the value from fp to integer registers.
3127     return false;
3128   if (!N->getNumValues())
3129     return false;
3130   EVT VT = Op.getValueType();
3131   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3132     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3133     // vmrs are very slow, e.g. cortex-a8.
3134     return false;
3135
3136   if (isFloatingPointZero(Op)) {
3137     SeenZero = true;
3138     return true;
3139   }
3140   return ISD::isNormalLoad(N);
3141 }
3142
3143 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3144   if (isFloatingPointZero(Op))
3145     return DAG.getConstant(0, MVT::i32);
3146
3147   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3148     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3149                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3150                        Ld->isVolatile(), Ld->isNonTemporal(),
3151                        Ld->isInvariant(), Ld->getAlignment());
3152
3153   llvm_unreachable("Unknown VFP cmp argument!");
3154 }
3155
3156 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3157                            SDValue &RetVal1, SDValue &RetVal2) {
3158   if (isFloatingPointZero(Op)) {
3159     RetVal1 = DAG.getConstant(0, MVT::i32);
3160     RetVal2 = DAG.getConstant(0, MVT::i32);
3161     return;
3162   }
3163
3164   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3165     SDValue Ptr = Ld->getBasePtr();
3166     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3167                           Ld->getChain(), Ptr,
3168                           Ld->getPointerInfo(),
3169                           Ld->isVolatile(), Ld->isNonTemporal(),
3170                           Ld->isInvariant(), Ld->getAlignment());
3171
3172     EVT PtrType = Ptr.getValueType();
3173     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3174     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3175                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3176     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3177                           Ld->getChain(), NewPtr,
3178                           Ld->getPointerInfo().getWithOffset(4),
3179                           Ld->isVolatile(), Ld->isNonTemporal(),
3180                           Ld->isInvariant(), NewAlign);
3181     return;
3182   }
3183
3184   llvm_unreachable("Unknown VFP cmp argument!");
3185 }
3186
3187 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3188 /// f32 and even f64 comparisons to integer ones.
3189 SDValue
3190 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3191   SDValue Chain = Op.getOperand(0);
3192   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3193   SDValue LHS = Op.getOperand(2);
3194   SDValue RHS = Op.getOperand(3);
3195   SDValue Dest = Op.getOperand(4);
3196   DebugLoc dl = Op.getDebugLoc();
3197
3198   bool LHSSeenZero = false;
3199   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3200   bool RHSSeenZero = false;
3201   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3202   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3203     // If unsafe fp math optimization is enabled and there are no other uses of
3204     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3205     // to an integer comparison.
3206     if (CC == ISD::SETOEQ)
3207       CC = ISD::SETEQ;
3208     else if (CC == ISD::SETUNE)
3209       CC = ISD::SETNE;
3210
3211     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3212     SDValue ARMcc;
3213     if (LHS.getValueType() == MVT::f32) {
3214       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3215                         bitcastf32Toi32(LHS, DAG), Mask);
3216       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3217                         bitcastf32Toi32(RHS, DAG), Mask);
3218       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3219       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3220       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3221                          Chain, Dest, ARMcc, CCR, Cmp);
3222     }
3223
3224     SDValue LHS1, LHS2;
3225     SDValue RHS1, RHS2;
3226     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3227     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3228     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3229     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3230     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3231     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3232     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3233     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3234     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3235   }
3236
3237   return SDValue();
3238 }
3239
3240 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3241   SDValue Chain = Op.getOperand(0);
3242   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3243   SDValue LHS = Op.getOperand(2);
3244   SDValue RHS = Op.getOperand(3);
3245   SDValue Dest = Op.getOperand(4);
3246   DebugLoc dl = Op.getDebugLoc();
3247
3248   if (LHS.getValueType() == MVT::i32) {
3249     SDValue ARMcc;
3250     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3251     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3252     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3253                        Chain, Dest, ARMcc, CCR, Cmp);
3254   }
3255
3256   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3257
3258   if (getTargetMachine().Options.UnsafeFPMath &&
3259       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3260        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3261     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3262     if (Result.getNode())
3263       return Result;
3264   }
3265
3266   ARMCC::CondCodes CondCode, CondCode2;
3267   FPCCToARMCC(CC, CondCode, CondCode2);
3268
3269   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3270   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3271   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3272   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3273   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3274   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3275   if (CondCode2 != ARMCC::AL) {
3276     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3277     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3278     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3279   }
3280   return Res;
3281 }
3282
3283 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3284   SDValue Chain = Op.getOperand(0);
3285   SDValue Table = Op.getOperand(1);
3286   SDValue Index = Op.getOperand(2);
3287   DebugLoc dl = Op.getDebugLoc();
3288
3289   EVT PTy = getPointerTy();
3290   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3291   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3292   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3293   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3294   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3295   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3296   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3297   if (Subtarget->isThumb2()) {
3298     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3299     // which does another jump to the destination. This also makes it easier
3300     // to translate it to TBB / TBH later.
3301     // FIXME: This might not work if the function is extremely large.
3302     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3303                        Addr, Op.getOperand(2), JTI, UId);
3304   }
3305   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3306     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3307                        MachinePointerInfo::getJumpTable(),
3308                        false, false, false, 0);
3309     Chain = Addr.getValue(1);
3310     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3311     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3312   } else {
3313     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3314                        MachinePointerInfo::getJumpTable(),
3315                        false, false, false, 0);
3316     Chain = Addr.getValue(1);
3317     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3318   }
3319 }
3320
3321 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3322   EVT VT = Op.getValueType();
3323   DebugLoc dl = Op.getDebugLoc();
3324
3325   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3326     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3327       return Op;
3328     return DAG.UnrollVectorOp(Op.getNode());
3329   }
3330
3331   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3332          "Invalid type for custom lowering!");
3333   if (VT != MVT::v4i16)
3334     return DAG.UnrollVectorOp(Op.getNode());
3335
3336   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3337   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3338 }
3339
3340 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3341   EVT VT = Op.getValueType();
3342   if (VT.isVector())
3343     return LowerVectorFP_TO_INT(Op, DAG);
3344
3345   DebugLoc dl = Op.getDebugLoc();
3346   unsigned Opc;
3347
3348   switch (Op.getOpcode()) {
3349   default: llvm_unreachable("Invalid opcode!");
3350   case ISD::FP_TO_SINT:
3351     Opc = ARMISD::FTOSI;
3352     break;
3353   case ISD::FP_TO_UINT:
3354     Opc = ARMISD::FTOUI;
3355     break;
3356   }
3357   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3358   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3359 }
3360
3361 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3362   EVT VT = Op.getValueType();
3363   DebugLoc dl = Op.getDebugLoc();
3364
3365   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3366     if (VT.getVectorElementType() == MVT::f32)
3367       return Op;
3368     return DAG.UnrollVectorOp(Op.getNode());
3369   }
3370
3371   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3372          "Invalid type for custom lowering!");
3373   if (VT != MVT::v4f32)
3374     return DAG.UnrollVectorOp(Op.getNode());
3375
3376   unsigned CastOpc;
3377   unsigned Opc;
3378   switch (Op.getOpcode()) {
3379   default: llvm_unreachable("Invalid opcode!");
3380   case ISD::SINT_TO_FP:
3381     CastOpc = ISD::SIGN_EXTEND;
3382     Opc = ISD::SINT_TO_FP;
3383     break;
3384   case ISD::UINT_TO_FP:
3385     CastOpc = ISD::ZERO_EXTEND;
3386     Opc = ISD::UINT_TO_FP;
3387     break;
3388   }
3389
3390   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3391   return DAG.getNode(Opc, dl, VT, Op);
3392 }
3393
3394 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3395   EVT VT = Op.getValueType();
3396   if (VT.isVector())
3397     return LowerVectorINT_TO_FP(Op, DAG);
3398
3399   DebugLoc dl = Op.getDebugLoc();
3400   unsigned Opc;
3401
3402   switch (Op.getOpcode()) {
3403   default: llvm_unreachable("Invalid opcode!");
3404   case ISD::SINT_TO_FP:
3405     Opc = ARMISD::SITOF;
3406     break;
3407   case ISD::UINT_TO_FP:
3408     Opc = ARMISD::UITOF;
3409     break;
3410   }
3411
3412   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3413   return DAG.getNode(Opc, dl, VT, Op);
3414 }
3415
3416 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3417   // Implement fcopysign with a fabs and a conditional fneg.
3418   SDValue Tmp0 = Op.getOperand(0);
3419   SDValue Tmp1 = Op.getOperand(1);
3420   DebugLoc dl = Op.getDebugLoc();
3421   EVT VT = Op.getValueType();
3422   EVT SrcVT = Tmp1.getValueType();
3423   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3424     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3425   bool UseNEON = !InGPR && Subtarget->hasNEON();
3426
3427   if (UseNEON) {
3428     // Use VBSL to copy the sign bit.
3429     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3430     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3431                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3432     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3433     if (VT == MVT::f64)
3434       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3435                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3436                          DAG.getConstant(32, MVT::i32));
3437     else /*if (VT == MVT::f32)*/
3438       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3439     if (SrcVT == MVT::f32) {
3440       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3441       if (VT == MVT::f64)
3442         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3443                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3444                            DAG.getConstant(32, MVT::i32));
3445     } else if (VT == MVT::f32)
3446       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3447                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3448                          DAG.getConstant(32, MVT::i32));
3449     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3450     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3451
3452     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3453                                             MVT::i32);
3454     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3455     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3456                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3457
3458     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3459                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3460                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3461     if (VT == MVT::f32) {
3462       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3463       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3464                         DAG.getConstant(0, MVT::i32));
3465     } else {
3466       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3467     }
3468
3469     return Res;
3470   }
3471
3472   // Bitcast operand 1 to i32.
3473   if (SrcVT == MVT::f64)
3474     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3475                        &Tmp1, 1).getValue(1);
3476   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3477
3478   // Or in the signbit with integer operations.
3479   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3480   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3481   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3482   if (VT == MVT::f32) {
3483     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3484                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3485     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3486                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3487   }
3488
3489   // f64: Or the high part with signbit and then combine two parts.
3490   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3491                      &Tmp0, 1);
3492   SDValue Lo = Tmp0.getValue(0);
3493   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3494   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3495   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3496 }
3497
3498 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3499   MachineFunction &MF = DAG.getMachineFunction();
3500   MachineFrameInfo *MFI = MF.getFrameInfo();
3501   MFI->setReturnAddressIsTaken(true);
3502
3503   EVT VT = Op.getValueType();
3504   DebugLoc dl = Op.getDebugLoc();
3505   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3506   if (Depth) {
3507     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3508     SDValue Offset = DAG.getConstant(4, MVT::i32);
3509     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3510                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3511                        MachinePointerInfo(), false, false, false, 0);
3512   }
3513
3514   // Return LR, which contains the return address. Mark it an implicit live-in.
3515   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3516   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3517 }
3518
3519 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3520   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3521   MFI->setFrameAddressIsTaken(true);
3522
3523   EVT VT = Op.getValueType();
3524   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3525   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3526   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3527     ? ARM::R7 : ARM::R11;
3528   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3529   while (Depth--)
3530     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3531                             MachinePointerInfo(),
3532                             false, false, false, 0);
3533   return FrameAddr;
3534 }
3535
3536 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3537 /// and size(DestVec) > 128-bits.
3538 /// This is achieved by doing the one extension from the SrcVec, splitting the
3539 /// result, extending these parts, and then concatenating these into the
3540 /// destination.
3541 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3542   SDValue Op = N->getOperand(0);
3543   EVT SrcVT = Op.getValueType();
3544   EVT DestVT = N->getValueType(0);
3545
3546   assert(DestVT.getSizeInBits() > 128 &&
3547          "Custom sext/zext expansion needs >128-bit vector.");
3548   // If this is a normal length extension, use the default expansion.
3549   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3550       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3551     return SDValue();
3552
3553   DebugLoc dl = N->getDebugLoc();
3554   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3555   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3556   unsigned NumElts = SrcVT.getVectorNumElements();
3557   LLVMContext &Ctx = *DAG.getContext();
3558   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3559
3560   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3561                                NumElts);
3562   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3563                                  NumElts/2);
3564   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3565                                NumElts/2);
3566
3567   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3568   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3569                         DAG.getIntPtrConstant(0));
3570   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3571                         DAG.getIntPtrConstant(NumElts/2));
3572   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3573   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3574   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3575 }
3576
3577 /// ExpandBITCAST - If the target supports VFP, this function is called to
3578 /// expand a bit convert where either the source or destination type is i64 to
3579 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3580 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3581 /// vectors), since the legalizer won't know what to do with that.
3582 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3584   DebugLoc dl = N->getDebugLoc();
3585   SDValue Op = N->getOperand(0);
3586
3587   // This function is only supposed to be called for i64 types, either as the
3588   // source or destination of the bit convert.
3589   EVT SrcVT = Op.getValueType();
3590   EVT DstVT = N->getValueType(0);
3591   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3592          "ExpandBITCAST called for non-i64 type");
3593
3594   // Turn i64->f64 into VMOVDRR.
3595   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3596     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3597                              DAG.getConstant(0, MVT::i32));
3598     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3599                              DAG.getConstant(1, MVT::i32));
3600     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3601                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3602   }
3603
3604   // Turn f64->i64 into VMOVRRD.
3605   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3606     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3607                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3608     // Merge the pieces into a single i64 value.
3609     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3610   }
3611
3612   return SDValue();
3613 }
3614
3615 /// getZeroVector - Returns a vector of specified type with all zero elements.
3616 /// Zero vectors are used to represent vector negation and in those cases
3617 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3618 /// not support i64 elements, so sometimes the zero vectors will need to be
3619 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3620 /// zero vector.
3621 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3622   assert(VT.isVector() && "Expected a vector type");
3623   // The canonical modified immediate encoding of a zero vector is....0!
3624   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3625   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3626   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3627   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3628 }
3629
3630 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3631 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3632 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3633                                                 SelectionDAG &DAG) const {
3634   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3635   EVT VT = Op.getValueType();
3636   unsigned VTBits = VT.getSizeInBits();
3637   DebugLoc dl = Op.getDebugLoc();
3638   SDValue ShOpLo = Op.getOperand(0);
3639   SDValue ShOpHi = Op.getOperand(1);
3640   SDValue ShAmt  = Op.getOperand(2);
3641   SDValue ARMcc;
3642   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3643
3644   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3645
3646   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3647                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3648   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3649   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3650                                    DAG.getConstant(VTBits, MVT::i32));
3651   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3652   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3653   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3654
3655   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3656   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3657                           ARMcc, DAG, dl);
3658   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3659   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3660                            CCR, Cmp);
3661
3662   SDValue Ops[2] = { Lo, Hi };
3663   return DAG.getMergeValues(Ops, 2, dl);
3664 }
3665
3666 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3667 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3668 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3669                                                SelectionDAG &DAG) const {
3670   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3671   EVT VT = Op.getValueType();
3672   unsigned VTBits = VT.getSizeInBits();
3673   DebugLoc dl = Op.getDebugLoc();
3674   SDValue ShOpLo = Op.getOperand(0);
3675   SDValue ShOpHi = Op.getOperand(1);
3676   SDValue ShAmt  = Op.getOperand(2);
3677   SDValue ARMcc;
3678
3679   assert(Op.getOpcode() == ISD::SHL_PARTS);
3680   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3681                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3682   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3683   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3684                                    DAG.getConstant(VTBits, MVT::i32));
3685   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3686   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3687
3688   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3689   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3690   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3691                           ARMcc, DAG, dl);
3692   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3693   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3694                            CCR, Cmp);
3695
3696   SDValue Ops[2] = { Lo, Hi };
3697   return DAG.getMergeValues(Ops, 2, dl);
3698 }
3699
3700 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3701                                             SelectionDAG &DAG) const {
3702   // The rounding mode is in bits 23:22 of the FPSCR.
3703   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3704   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3705   // so that the shift + and get folded into a bitfield extract.
3706   DebugLoc dl = Op.getDebugLoc();
3707   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3708                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3709                                               MVT::i32));
3710   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3711                                   DAG.getConstant(1U << 22, MVT::i32));
3712   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3713                               DAG.getConstant(22, MVT::i32));
3714   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3715                      DAG.getConstant(3, MVT::i32));
3716 }
3717
3718 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3719                          const ARMSubtarget *ST) {
3720   EVT VT = N->getValueType(0);
3721   DebugLoc dl = N->getDebugLoc();
3722
3723   if (!ST->hasV6T2Ops())
3724     return SDValue();
3725
3726   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3727   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3728 }
3729
3730 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3731 /// for each 16-bit element from operand, repeated.  The basic idea is to
3732 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3733 ///
3734 /// Trace for v4i16:
3735 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3736 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3737 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3738 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3739 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3740 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3741 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3742 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3743 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3744   EVT VT = N->getValueType(0);
3745   DebugLoc DL = N->getDebugLoc();
3746
3747   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3748   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3749   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3750   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3751   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3752   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3753 }
3754
3755 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3756 /// bit-count for each 16-bit element from the operand.  We need slightly
3757 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3758 /// 64/128-bit registers.
3759 ///
3760 /// Trace for v4i16:
3761 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3762 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3763 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3764 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3765 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3766   EVT VT = N->getValueType(0);
3767   DebugLoc DL = N->getDebugLoc();
3768
3769   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3770   if (VT.is64BitVector()) {
3771     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3772     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3773                        DAG.getIntPtrConstant(0));
3774   } else {
3775     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3776                                     BitCounts, DAG.getIntPtrConstant(0));
3777     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3778   }
3779 }
3780
3781 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3782 /// bit-count for each 32-bit element from the operand.  The idea here is
3783 /// to split the vector into 16-bit elements, leverage the 16-bit count
3784 /// routine, and then combine the results.
3785 ///
3786 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3787 /// input    = [v0    v1    ] (vi: 32-bit elements)
3788 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3789 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3790 /// vrev: N0 = [k1 k0 k3 k2 ]
3791 ///            [k0 k1 k2 k3 ]
3792 ///       N1 =+[k1 k0 k3 k2 ]
3793 ///            [k0 k2 k1 k3 ]
3794 ///       N2 =+[k1 k3 k0 k2 ]
3795 ///            [k0    k2    k1    k3    ]
3796 /// Extended =+[k1    k3    k0    k2    ]
3797 ///            [k0    k2    ]
3798 /// Extracted=+[k1    k3    ]
3799 ///
3800 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3801   EVT VT = N->getValueType(0);
3802   DebugLoc DL = N->getDebugLoc();
3803
3804   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3805
3806   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3807   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3808   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3809   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3810   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3811
3812   if (VT.is64BitVector()) {
3813     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3814     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3815                        DAG.getIntPtrConstant(0));
3816   } else {
3817     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3818                                     DAG.getIntPtrConstant(0));
3819     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3820   }
3821 }
3822
3823 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3824                           const ARMSubtarget *ST) {
3825   EVT VT = N->getValueType(0);
3826
3827   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3828   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3829           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3830          "Unexpected type for custom ctpop lowering");
3831
3832   if (VT.getVectorElementType() == MVT::i32)
3833     return lowerCTPOP32BitElements(N, DAG);
3834   else
3835     return lowerCTPOP16BitElements(N, DAG);
3836 }
3837
3838 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3839                           const ARMSubtarget *ST) {
3840   EVT VT = N->getValueType(0);
3841   DebugLoc dl = N->getDebugLoc();
3842
3843   if (!VT.isVector())
3844     return SDValue();
3845
3846   // Lower vector shifts on NEON to use VSHL.
3847   assert(ST->hasNEON() && "unexpected vector shift");
3848
3849   // Left shifts translate directly to the vshiftu intrinsic.
3850   if (N->getOpcode() == ISD::SHL)
3851     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3852                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3853                        N->getOperand(0), N->getOperand(1));
3854
3855   assert((N->getOpcode() == ISD::SRA ||
3856           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3857
3858   // NEON uses the same intrinsics for both left and right shifts.  For
3859   // right shifts, the shift amounts are negative, so negate the vector of
3860   // shift amounts.
3861   EVT ShiftVT = N->getOperand(1).getValueType();
3862   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3863                                      getZeroVector(ShiftVT, DAG, dl),
3864                                      N->getOperand(1));
3865   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3866                              Intrinsic::arm_neon_vshifts :
3867                              Intrinsic::arm_neon_vshiftu);
3868   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3869                      DAG.getConstant(vshiftInt, MVT::i32),
3870                      N->getOperand(0), NegatedCount);
3871 }
3872
3873 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3874                                 const ARMSubtarget *ST) {
3875   EVT VT = N->getValueType(0);
3876   DebugLoc dl = N->getDebugLoc();
3877
3878   // We can get here for a node like i32 = ISD::SHL i32, i64
3879   if (VT != MVT::i64)
3880     return SDValue();
3881
3882   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3883          "Unknown shift to lower!");
3884
3885   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3886   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3887       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3888     return SDValue();
3889
3890   // If we are in thumb mode, we don't have RRX.
3891   if (ST->isThumb1Only()) return SDValue();
3892
3893   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3894   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3895                            DAG.getConstant(0, MVT::i32));
3896   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3897                            DAG.getConstant(1, MVT::i32));
3898
3899   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3900   // captures the result into a carry flag.
3901   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3902   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3903
3904   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3905   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3906
3907   // Merge the pieces into a single i64 value.
3908  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3909 }
3910
3911 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3912   SDValue TmpOp0, TmpOp1;
3913   bool Invert = false;
3914   bool Swap = false;
3915   unsigned Opc = 0;
3916
3917   SDValue Op0 = Op.getOperand(0);
3918   SDValue Op1 = Op.getOperand(1);
3919   SDValue CC = Op.getOperand(2);
3920   EVT VT = Op.getValueType();
3921   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3922   DebugLoc dl = Op.getDebugLoc();
3923
3924   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3925     switch (SetCCOpcode) {
3926     default: llvm_unreachable("Illegal FP comparison");
3927     case ISD::SETUNE:
3928     case ISD::SETNE:  Invert = true; // Fallthrough
3929     case ISD::SETOEQ:
3930     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3931     case ISD::SETOLT:
3932     case ISD::SETLT: Swap = true; // Fallthrough
3933     case ISD::SETOGT:
3934     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3935     case ISD::SETOLE:
3936     case ISD::SETLE:  Swap = true; // Fallthrough
3937     case ISD::SETOGE:
3938     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3939     case ISD::SETUGE: Swap = true; // Fallthrough
3940     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3941     case ISD::SETUGT: Swap = true; // Fallthrough
3942     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3943     case ISD::SETUEQ: Invert = true; // Fallthrough
3944     case ISD::SETONE:
3945       // Expand this to (OLT | OGT).
3946       TmpOp0 = Op0;
3947       TmpOp1 = Op1;
3948       Opc = ISD::OR;
3949       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3950       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3951       break;
3952     case ISD::SETUO: Invert = true; // Fallthrough
3953     case ISD::SETO:
3954       // Expand this to (OLT | OGE).
3955       TmpOp0 = Op0;
3956       TmpOp1 = Op1;
3957       Opc = ISD::OR;
3958       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3959       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3960       break;
3961     }
3962   } else {
3963     // Integer comparisons.
3964     switch (SetCCOpcode) {
3965     default: llvm_unreachable("Illegal integer comparison");
3966     case ISD::SETNE:  Invert = true;
3967     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3968     case ISD::SETLT:  Swap = true;
3969     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3970     case ISD::SETLE:  Swap = true;
3971     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3972     case ISD::SETULT: Swap = true;
3973     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3974     case ISD::SETULE: Swap = true;
3975     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3976     }
3977
3978     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3979     if (Opc == ARMISD::VCEQ) {
3980
3981       SDValue AndOp;
3982       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3983         AndOp = Op0;
3984       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3985         AndOp = Op1;
3986
3987       // Ignore bitconvert.
3988       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3989         AndOp = AndOp.getOperand(0);
3990
3991       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3992         Opc = ARMISD::VTST;
3993         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3994         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3995         Invert = !Invert;
3996       }
3997     }
3998   }
3999
4000   if (Swap)
4001     std::swap(Op0, Op1);
4002
4003   // If one of the operands is a constant vector zero, attempt to fold the
4004   // comparison to a specialized compare-against-zero form.
4005   SDValue SingleOp;
4006   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4007     SingleOp = Op0;
4008   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4009     if (Opc == ARMISD::VCGE)
4010       Opc = ARMISD::VCLEZ;
4011     else if (Opc == ARMISD::VCGT)
4012       Opc = ARMISD::VCLTZ;
4013     SingleOp = Op1;
4014   }
4015
4016   SDValue Result;
4017   if (SingleOp.getNode()) {
4018     switch (Opc) {
4019     case ARMISD::VCEQ:
4020       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4021     case ARMISD::VCGE:
4022       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4023     case ARMISD::VCLEZ:
4024       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4025     case ARMISD::VCGT:
4026       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4027     case ARMISD::VCLTZ:
4028       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4029     default:
4030       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4031     }
4032   } else {
4033      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4034   }
4035
4036   if (Invert)
4037     Result = DAG.getNOT(dl, Result, VT);
4038
4039   return Result;
4040 }
4041
4042 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4043 /// valid vector constant for a NEON instruction with a "modified immediate"
4044 /// operand (e.g., VMOV).  If so, return the encoded value.
4045 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4046                                  unsigned SplatBitSize, SelectionDAG &DAG,
4047                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4048   unsigned OpCmode, Imm;
4049
4050   // SplatBitSize is set to the smallest size that splats the vector, so a
4051   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4052   // immediate instructions others than VMOV do not support the 8-bit encoding
4053   // of a zero vector, and the default encoding of zero is supposed to be the
4054   // 32-bit version.
4055   if (SplatBits == 0)
4056     SplatBitSize = 32;
4057
4058   switch (SplatBitSize) {
4059   case 8:
4060     if (type != VMOVModImm)
4061       return SDValue();
4062     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4063     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4064     OpCmode = 0xe;
4065     Imm = SplatBits;
4066     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4067     break;
4068
4069   case 16:
4070     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4071     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4072     if ((SplatBits & ~0xff) == 0) {
4073       // Value = 0x00nn: Op=x, Cmode=100x.
4074       OpCmode = 0x8;
4075       Imm = SplatBits;
4076       break;
4077     }
4078     if ((SplatBits & ~0xff00) == 0) {
4079       // Value = 0xnn00: Op=x, Cmode=101x.
4080       OpCmode = 0xa;
4081       Imm = SplatBits >> 8;
4082       break;
4083     }
4084     return SDValue();
4085
4086   case 32:
4087     // NEON's 32-bit VMOV supports splat values where:
4088     // * only one byte is nonzero, or
4089     // * the least significant byte is 0xff and the second byte is nonzero, or
4090     // * the least significant 2 bytes are 0xff and the third is nonzero.
4091     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4092     if ((SplatBits & ~0xff) == 0) {
4093       // Value = 0x000000nn: Op=x, Cmode=000x.
4094       OpCmode = 0;
4095       Imm = SplatBits;
4096       break;
4097     }
4098     if ((SplatBits & ~0xff00) == 0) {
4099       // Value = 0x0000nn00: Op=x, Cmode=001x.
4100       OpCmode = 0x2;
4101       Imm = SplatBits >> 8;
4102       break;
4103     }
4104     if ((SplatBits & ~0xff0000) == 0) {
4105       // Value = 0x00nn0000: Op=x, Cmode=010x.
4106       OpCmode = 0x4;
4107       Imm = SplatBits >> 16;
4108       break;
4109     }
4110     if ((SplatBits & ~0xff000000) == 0) {
4111       // Value = 0xnn000000: Op=x, Cmode=011x.
4112       OpCmode = 0x6;
4113       Imm = SplatBits >> 24;
4114       break;
4115     }
4116
4117     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4118     if (type == OtherModImm) return SDValue();
4119
4120     if ((SplatBits & ~0xffff) == 0 &&
4121         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4122       // Value = 0x0000nnff: Op=x, Cmode=1100.
4123       OpCmode = 0xc;
4124       Imm = SplatBits >> 8;
4125       SplatBits |= 0xff;
4126       break;
4127     }
4128
4129     if ((SplatBits & ~0xffffff) == 0 &&
4130         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4131       // Value = 0x00nnffff: Op=x, Cmode=1101.
4132       OpCmode = 0xd;
4133       Imm = SplatBits >> 16;
4134       SplatBits |= 0xffff;
4135       break;
4136     }
4137
4138     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4139     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4140     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4141     // and fall through here to test for a valid 64-bit splat.  But, then the
4142     // caller would also need to check and handle the change in size.
4143     return SDValue();
4144
4145   case 64: {
4146     if (type != VMOVModImm)
4147       return SDValue();
4148     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4149     uint64_t BitMask = 0xff;
4150     uint64_t Val = 0;
4151     unsigned ImmMask = 1;
4152     Imm = 0;
4153     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4154       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4155         Val |= BitMask;
4156         Imm |= ImmMask;
4157       } else if ((SplatBits & BitMask) != 0) {
4158         return SDValue();
4159       }
4160       BitMask <<= 8;
4161       ImmMask <<= 1;
4162     }
4163     // Op=1, Cmode=1110.
4164     OpCmode = 0x1e;
4165     SplatBits = Val;
4166     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4167     break;
4168   }
4169
4170   default:
4171     llvm_unreachable("unexpected size for isNEONModifiedImm");
4172   }
4173
4174   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4175   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4176 }
4177
4178 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4179                                            const ARMSubtarget *ST) const {
4180   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4181     return SDValue();
4182
4183   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4184   assert(Op.getValueType() == MVT::f32 &&
4185          "ConstantFP custom lowering should only occur for f32.");
4186
4187   // Try splatting with a VMOV.f32...
4188   APFloat FPVal = CFP->getValueAPF();
4189   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4190   if (ImmVal != -1) {
4191     DebugLoc DL = Op.getDebugLoc();
4192     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4193     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4194                                       NewVal);
4195     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4196                        DAG.getConstant(0, MVT::i32));
4197   }
4198
4199   // If that fails, try a VMOV.i32
4200   EVT VMovVT;
4201   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4202   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4203                                      VMOVModImm);
4204   if (NewVal != SDValue()) {
4205     DebugLoc DL = Op.getDebugLoc();
4206     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4207                                       NewVal);
4208     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4209                                        VecConstant);
4210     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4211                        DAG.getConstant(0, MVT::i32));
4212   }
4213
4214   // Finally, try a VMVN.i32
4215   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4216                              VMVNModImm);
4217   if (NewVal != SDValue()) {
4218     DebugLoc DL = Op.getDebugLoc();
4219     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4220     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4221                                        VecConstant);
4222     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4223                        DAG.getConstant(0, MVT::i32));
4224   }
4225
4226   return SDValue();
4227 }
4228
4229 // check if an VEXT instruction can handle the shuffle mask when the
4230 // vector sources of the shuffle are the same.
4231 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4232   unsigned NumElts = VT.getVectorNumElements();
4233
4234   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4235   if (M[0] < 0)
4236     return false;
4237
4238   Imm = M[0];
4239
4240   // If this is a VEXT shuffle, the immediate value is the index of the first
4241   // element.  The other shuffle indices must be the successive elements after
4242   // the first one.
4243   unsigned ExpectedElt = Imm;
4244   for (unsigned i = 1; i < NumElts; ++i) {
4245     // Increment the expected index.  If it wraps around, just follow it
4246     // back to index zero and keep going.
4247     ++ExpectedElt;
4248     if (ExpectedElt == NumElts)
4249       ExpectedElt = 0;
4250
4251     if (M[i] < 0) continue; // ignore UNDEF indices
4252     if (ExpectedElt != static_cast<unsigned>(M[i]))
4253       return false;
4254   }
4255
4256   return true;
4257 }
4258
4259
4260 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4261                        bool &ReverseVEXT, unsigned &Imm) {
4262   unsigned NumElts = VT.getVectorNumElements();
4263   ReverseVEXT = false;
4264
4265   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4266   if (M[0] < 0)
4267     return false;
4268
4269   Imm = M[0];
4270
4271   // If this is a VEXT shuffle, the immediate value is the index of the first
4272   // element.  The other shuffle indices must be the successive elements after
4273   // the first one.
4274   unsigned ExpectedElt = Imm;
4275   for (unsigned i = 1; i < NumElts; ++i) {
4276     // Increment the expected index.  If it wraps around, it may still be
4277     // a VEXT but the source vectors must be swapped.
4278     ExpectedElt += 1;
4279     if (ExpectedElt == NumElts * 2) {
4280       ExpectedElt = 0;
4281       ReverseVEXT = true;
4282     }
4283
4284     if (M[i] < 0) continue; // ignore UNDEF indices
4285     if (ExpectedElt != static_cast<unsigned>(M[i]))
4286       return false;
4287   }
4288
4289   // Adjust the index value if the source operands will be swapped.
4290   if (ReverseVEXT)
4291     Imm -= NumElts;
4292
4293   return true;
4294 }
4295
4296 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4297 /// instruction with the specified blocksize.  (The order of the elements
4298 /// within each block of the vector is reversed.)
4299 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4300   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4301          "Only possible block sizes for VREV are: 16, 32, 64");
4302
4303   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4304   if (EltSz == 64)
4305     return false;
4306
4307   unsigned NumElts = VT.getVectorNumElements();
4308   unsigned BlockElts = M[0] + 1;
4309   // If the first shuffle index is UNDEF, be optimistic.
4310   if (M[0] < 0)
4311     BlockElts = BlockSize / EltSz;
4312
4313   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4314     return false;
4315
4316   for (unsigned i = 0; i < NumElts; ++i) {
4317     if (M[i] < 0) continue; // ignore UNDEF indices
4318     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4319       return false;
4320   }
4321
4322   return true;
4323 }
4324
4325 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4326   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4327   // range, then 0 is placed into the resulting vector. So pretty much any mask
4328   // of 8 elements can work here.
4329   return VT == MVT::v8i8 && M.size() == 8;
4330 }
4331
4332 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4333   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4334   if (EltSz == 64)
4335     return false;
4336
4337   unsigned NumElts = VT.getVectorNumElements();
4338   WhichResult = (M[0] == 0 ? 0 : 1);
4339   for (unsigned i = 0; i < NumElts; i += 2) {
4340     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4341         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4342       return false;
4343   }
4344   return true;
4345 }
4346
4347 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4348 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4349 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4350 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4351   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4352   if (EltSz == 64)
4353     return false;
4354
4355   unsigned NumElts = VT.getVectorNumElements();
4356   WhichResult = (M[0] == 0 ? 0 : 1);
4357   for (unsigned i = 0; i < NumElts; i += 2) {
4358     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4359         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4360       return false;
4361   }
4362   return true;
4363 }
4364
4365 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4366   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4367   if (EltSz == 64)
4368     return false;
4369
4370   unsigned NumElts = VT.getVectorNumElements();
4371   WhichResult = (M[0] == 0 ? 0 : 1);
4372   for (unsigned i = 0; i != NumElts; ++i) {
4373     if (M[i] < 0) continue; // ignore UNDEF indices
4374     if ((unsigned) M[i] != 2 * i + WhichResult)
4375       return false;
4376   }
4377
4378   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4379   if (VT.is64BitVector() && EltSz == 32)
4380     return false;
4381
4382   return true;
4383 }
4384
4385 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4386 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4387 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4388 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4389   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4390   if (EltSz == 64)
4391     return false;
4392
4393   unsigned Half = VT.getVectorNumElements() / 2;
4394   WhichResult = (M[0] == 0 ? 0 : 1);
4395   for (unsigned j = 0; j != 2; ++j) {
4396     unsigned Idx = WhichResult;
4397     for (unsigned i = 0; i != Half; ++i) {
4398       int MIdx = M[i + j * Half];
4399       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4400         return false;
4401       Idx += 2;
4402     }
4403   }
4404
4405   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4406   if (VT.is64BitVector() && EltSz == 32)
4407     return false;
4408
4409   return true;
4410 }
4411
4412 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4413   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4414   if (EltSz == 64)
4415     return false;
4416
4417   unsigned NumElts = VT.getVectorNumElements();
4418   WhichResult = (M[0] == 0 ? 0 : 1);
4419   unsigned Idx = WhichResult * NumElts / 2;
4420   for (unsigned i = 0; i != NumElts; i += 2) {
4421     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4422         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4423       return false;
4424     Idx += 1;
4425   }
4426
4427   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4428   if (VT.is64BitVector() && EltSz == 32)
4429     return false;
4430
4431   return true;
4432 }
4433
4434 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4435 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4436 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4437 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4438   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4439   if (EltSz == 64)
4440     return false;
4441
4442   unsigned NumElts = VT.getVectorNumElements();
4443   WhichResult = (M[0] == 0 ? 0 : 1);
4444   unsigned Idx = WhichResult * NumElts / 2;
4445   for (unsigned i = 0; i != NumElts; i += 2) {
4446     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4447         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4448       return false;
4449     Idx += 1;
4450   }
4451
4452   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4453   if (VT.is64BitVector() && EltSz == 32)
4454     return false;
4455
4456   return true;
4457 }
4458
4459 /// \return true if this is a reverse operation on an vector.
4460 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4461   unsigned NumElts = VT.getVectorNumElements();
4462   // Make sure the mask has the right size.
4463   if (NumElts != M.size())
4464       return false;
4465
4466   // Look for <15, ..., 3, -1, 1, 0>.
4467   for (unsigned i = 0; i != NumElts; ++i)
4468     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4469       return false;
4470
4471   return true;
4472 }
4473
4474 // If N is an integer constant that can be moved into a register in one
4475 // instruction, return an SDValue of such a constant (will become a MOV
4476 // instruction).  Otherwise return null.
4477 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4478                                      const ARMSubtarget *ST, DebugLoc dl) {
4479   uint64_t Val;
4480   if (!isa<ConstantSDNode>(N))
4481     return SDValue();
4482   Val = cast<ConstantSDNode>(N)->getZExtValue();
4483
4484   if (ST->isThumb1Only()) {
4485     if (Val <= 255 || ~Val <= 255)
4486       return DAG.getConstant(Val, MVT::i32);
4487   } else {
4488     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4489       return DAG.getConstant(Val, MVT::i32);
4490   }
4491   return SDValue();
4492 }
4493
4494 // If this is a case we can't handle, return null and let the default
4495 // expansion code take care of it.
4496 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4497                                              const ARMSubtarget *ST) const {
4498   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4499   DebugLoc dl = Op.getDebugLoc();
4500   EVT VT = Op.getValueType();
4501
4502   APInt SplatBits, SplatUndef;
4503   unsigned SplatBitSize;
4504   bool HasAnyUndefs;
4505   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4506     if (SplatBitSize <= 64) {
4507       // Check if an immediate VMOV works.
4508       EVT VmovVT;
4509       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4510                                       SplatUndef.getZExtValue(), SplatBitSize,
4511                                       DAG, VmovVT, VT.is128BitVector(),
4512                                       VMOVModImm);
4513       if (Val.getNode()) {
4514         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4515         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4516       }
4517
4518       // Try an immediate VMVN.
4519       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4520       Val = isNEONModifiedImm(NegatedImm,
4521                                       SplatUndef.getZExtValue(), SplatBitSize,
4522                                       DAG, VmovVT, VT.is128BitVector(),
4523                                       VMVNModImm);
4524       if (Val.getNode()) {
4525         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4526         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4527       }
4528
4529       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4530       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4531         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4532         if (ImmVal != -1) {
4533           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4534           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4535         }
4536       }
4537     }
4538   }
4539
4540   // Scan through the operands to see if only one value is used.
4541   //
4542   // As an optimisation, even if more than one value is used it may be more
4543   // profitable to splat with one value then change some lanes.
4544   //
4545   // Heuristically we decide to do this if the vector has a "dominant" value,
4546   // defined as splatted to more than half of the lanes.
4547   unsigned NumElts = VT.getVectorNumElements();
4548   bool isOnlyLowElement = true;
4549   bool usesOnlyOneValue = true;
4550   bool hasDominantValue = false;
4551   bool isConstant = true;
4552
4553   // Map of the number of times a particular SDValue appears in the
4554   // element list.
4555   DenseMap<SDValue, unsigned> ValueCounts;
4556   SDValue Value;
4557   for (unsigned i = 0; i < NumElts; ++i) {
4558     SDValue V = Op.getOperand(i);
4559     if (V.getOpcode() == ISD::UNDEF)
4560       continue;
4561     if (i > 0)
4562       isOnlyLowElement = false;
4563     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4564       isConstant = false;
4565
4566     ValueCounts.insert(std::make_pair(V, 0));
4567     unsigned &Count = ValueCounts[V];
4568
4569     // Is this value dominant? (takes up more than half of the lanes)
4570     if (++Count > (NumElts / 2)) {
4571       hasDominantValue = true;
4572       Value = V;
4573     }
4574   }
4575   if (ValueCounts.size() != 1)
4576     usesOnlyOneValue = false;
4577   if (!Value.getNode() && ValueCounts.size() > 0)
4578     Value = ValueCounts.begin()->first;
4579
4580   if (ValueCounts.size() == 0)
4581     return DAG.getUNDEF(VT);
4582
4583   if (isOnlyLowElement)
4584     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4585
4586   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4587
4588   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4589   // i32 and try again.
4590   if (hasDominantValue && EltSize <= 32) {
4591     if (!isConstant) {
4592       SDValue N;
4593
4594       // If we are VDUPing a value that comes directly from a vector, that will
4595       // cause an unnecessary move to and from a GPR, where instead we could
4596       // just use VDUPLANE. We can only do this if the lane being extracted
4597       // is at a constant index, as the VDUP from lane instructions only have
4598       // constant-index forms.
4599       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4600           isa<ConstantSDNode>(Value->getOperand(1))) {
4601         // We need to create a new undef vector to use for the VDUPLANE if the
4602         // size of the vector from which we get the value is different than the
4603         // size of the vector that we need to create. We will insert the element
4604         // such that the register coalescer will remove unnecessary copies.
4605         if (VT != Value->getOperand(0).getValueType()) {
4606           ConstantSDNode *constIndex;
4607           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4608           assert(constIndex && "The index is not a constant!");
4609           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4610                              VT.getVectorNumElements();
4611           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4612                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4613                         Value, DAG.getConstant(index, MVT::i32)),
4614                            DAG.getConstant(index, MVT::i32));
4615         } else
4616           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4617                         Value->getOperand(0), Value->getOperand(1));
4618       } else
4619         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4620
4621       if (!usesOnlyOneValue) {
4622         // The dominant value was splatted as 'N', but we now have to insert
4623         // all differing elements.
4624         for (unsigned I = 0; I < NumElts; ++I) {
4625           if (Op.getOperand(I) == Value)
4626             continue;
4627           SmallVector<SDValue, 3> Ops;
4628           Ops.push_back(N);
4629           Ops.push_back(Op.getOperand(I));
4630           Ops.push_back(DAG.getConstant(I, MVT::i32));
4631           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4632         }
4633       }
4634       return N;
4635     }
4636     if (VT.getVectorElementType().isFloatingPoint()) {
4637       SmallVector<SDValue, 8> Ops;
4638       for (unsigned i = 0; i < NumElts; ++i)
4639         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4640                                   Op.getOperand(i)));
4641       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4642       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4643       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4644       if (Val.getNode())
4645         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4646     }
4647     if (usesOnlyOneValue) {
4648       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4649       if (isConstant && Val.getNode())
4650         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4651     }
4652   }
4653
4654   // If all elements are constants and the case above didn't get hit, fall back
4655   // to the default expansion, which will generate a load from the constant
4656   // pool.
4657   if (isConstant)
4658     return SDValue();
4659
4660   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4661   if (NumElts >= 4) {
4662     SDValue shuffle = ReconstructShuffle(Op, DAG);
4663     if (shuffle != SDValue())
4664       return shuffle;
4665   }
4666
4667   // Vectors with 32- or 64-bit elements can be built by directly assigning
4668   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4669   // will be legalized.
4670   if (EltSize >= 32) {
4671     // Do the expansion with floating-point types, since that is what the VFP
4672     // registers are defined to use, and since i64 is not legal.
4673     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4674     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4675     SmallVector<SDValue, 8> Ops;
4676     for (unsigned i = 0; i < NumElts; ++i)
4677       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4678     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4679     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4680   }
4681
4682   return SDValue();
4683 }
4684
4685 // Gather data to see if the operation can be modelled as a
4686 // shuffle in combination with VEXTs.
4687 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4688                                               SelectionDAG &DAG) const {
4689   DebugLoc dl = Op.getDebugLoc();
4690   EVT VT = Op.getValueType();
4691   unsigned NumElts = VT.getVectorNumElements();
4692
4693   SmallVector<SDValue, 2> SourceVecs;
4694   SmallVector<unsigned, 2> MinElts;
4695   SmallVector<unsigned, 2> MaxElts;
4696
4697   for (unsigned i = 0; i < NumElts; ++i) {
4698     SDValue V = Op.getOperand(i);
4699     if (V.getOpcode() == ISD::UNDEF)
4700       continue;
4701     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4702       // A shuffle can only come from building a vector from various
4703       // elements of other vectors.
4704       return SDValue();
4705     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4706                VT.getVectorElementType()) {
4707       // This code doesn't know how to handle shuffles where the vector
4708       // element types do not match (this happens because type legalization
4709       // promotes the return type of EXTRACT_VECTOR_ELT).
4710       // FIXME: It might be appropriate to extend this code to handle
4711       // mismatched types.
4712       return SDValue();
4713     }
4714
4715     // Record this extraction against the appropriate vector if possible...
4716     SDValue SourceVec = V.getOperand(0);
4717     // If the element number isn't a constant, we can't effectively
4718     // analyze what's going on.
4719     if (!isa<ConstantSDNode>(V.getOperand(1)))
4720       return SDValue();
4721     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4722     bool FoundSource = false;
4723     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4724       if (SourceVecs[j] == SourceVec) {
4725         if (MinElts[j] > EltNo)
4726           MinElts[j] = EltNo;
4727         if (MaxElts[j] < EltNo)
4728           MaxElts[j] = EltNo;
4729         FoundSource = true;
4730         break;
4731       }
4732     }
4733
4734     // Or record a new source if not...
4735     if (!FoundSource) {
4736       SourceVecs.push_back(SourceVec);
4737       MinElts.push_back(EltNo);
4738       MaxElts.push_back(EltNo);
4739     }
4740   }
4741
4742   // Currently only do something sane when at most two source vectors
4743   // involved.
4744   if (SourceVecs.size() > 2)
4745     return SDValue();
4746
4747   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4748   int VEXTOffsets[2] = {0, 0};
4749
4750   // This loop extracts the usage patterns of the source vectors
4751   // and prepares appropriate SDValues for a shuffle if possible.
4752   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4753     if (SourceVecs[i].getValueType() == VT) {
4754       // No VEXT necessary
4755       ShuffleSrcs[i] = SourceVecs[i];
4756       VEXTOffsets[i] = 0;
4757       continue;
4758     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4759       // It probably isn't worth padding out a smaller vector just to
4760       // break it down again in a shuffle.
4761       return SDValue();
4762     }
4763
4764     // Since only 64-bit and 128-bit vectors are legal on ARM and
4765     // we've eliminated the other cases...
4766     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4767            "unexpected vector sizes in ReconstructShuffle");
4768
4769     if (MaxElts[i] - MinElts[i] >= NumElts) {
4770       // Span too large for a VEXT to cope
4771       return SDValue();
4772     }
4773
4774     if (MinElts[i] >= NumElts) {
4775       // The extraction can just take the second half
4776       VEXTOffsets[i] = NumElts;
4777       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4778                                    SourceVecs[i],
4779                                    DAG.getIntPtrConstant(NumElts));
4780     } else if (MaxElts[i] < NumElts) {
4781       // The extraction can just take the first half
4782       VEXTOffsets[i] = 0;
4783       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4784                                    SourceVecs[i],
4785                                    DAG.getIntPtrConstant(0));
4786     } else {
4787       // An actual VEXT is needed
4788       VEXTOffsets[i] = MinElts[i];
4789       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4790                                      SourceVecs[i],
4791                                      DAG.getIntPtrConstant(0));
4792       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4793                                      SourceVecs[i],
4794                                      DAG.getIntPtrConstant(NumElts));
4795       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4796                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4797     }
4798   }
4799
4800   SmallVector<int, 8> Mask;
4801
4802   for (unsigned i = 0; i < NumElts; ++i) {
4803     SDValue Entry = Op.getOperand(i);
4804     if (Entry.getOpcode() == ISD::UNDEF) {
4805       Mask.push_back(-1);
4806       continue;
4807     }
4808
4809     SDValue ExtractVec = Entry.getOperand(0);
4810     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4811                                           .getOperand(1))->getSExtValue();
4812     if (ExtractVec == SourceVecs[0]) {
4813       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4814     } else {
4815       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4816     }
4817   }
4818
4819   // Final check before we try to produce nonsense...
4820   if (isShuffleMaskLegal(Mask, VT))
4821     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4822                                 &Mask[0]);
4823
4824   return SDValue();
4825 }
4826
4827 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4828 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4829 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4830 /// are assumed to be legal.
4831 bool
4832 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4833                                       EVT VT) const {
4834   if (VT.getVectorNumElements() == 4 &&
4835       (VT.is128BitVector() || VT.is64BitVector())) {
4836     unsigned PFIndexes[4];
4837     for (unsigned i = 0; i != 4; ++i) {
4838       if (M[i] < 0)
4839         PFIndexes[i] = 8;
4840       else
4841         PFIndexes[i] = M[i];
4842     }
4843
4844     // Compute the index in the perfect shuffle table.
4845     unsigned PFTableIndex =
4846       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4847     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4848     unsigned Cost = (PFEntry >> 30);
4849
4850     if (Cost <= 4)
4851       return true;
4852   }
4853
4854   bool ReverseVEXT;
4855   unsigned Imm, WhichResult;
4856
4857   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4858   return (EltSize >= 32 ||
4859           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4860           isVREVMask(M, VT, 64) ||
4861           isVREVMask(M, VT, 32) ||
4862           isVREVMask(M, VT, 16) ||
4863           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4864           isVTBLMask(M, VT) ||
4865           isVTRNMask(M, VT, WhichResult) ||
4866           isVUZPMask(M, VT, WhichResult) ||
4867           isVZIPMask(M, VT, WhichResult) ||
4868           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4869           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4870           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4871           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4872 }
4873
4874 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4875 /// the specified operations to build the shuffle.
4876 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4877                                       SDValue RHS, SelectionDAG &DAG,
4878                                       DebugLoc dl) {
4879   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4880   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4881   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4882
4883   enum {
4884     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4885     OP_VREV,
4886     OP_VDUP0,
4887     OP_VDUP1,
4888     OP_VDUP2,
4889     OP_VDUP3,
4890     OP_VEXT1,
4891     OP_VEXT2,
4892     OP_VEXT3,
4893     OP_VUZPL, // VUZP, left result
4894     OP_VUZPR, // VUZP, right result
4895     OP_VZIPL, // VZIP, left result
4896     OP_VZIPR, // VZIP, right result
4897     OP_VTRNL, // VTRN, left result
4898     OP_VTRNR  // VTRN, right result
4899   };
4900
4901   if (OpNum == OP_COPY) {
4902     if (LHSID == (1*9+2)*9+3) return LHS;
4903     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4904     return RHS;
4905   }
4906
4907   SDValue OpLHS, OpRHS;
4908   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4909   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4910   EVT VT = OpLHS.getValueType();
4911
4912   switch (OpNum) {
4913   default: llvm_unreachable("Unknown shuffle opcode!");
4914   case OP_VREV:
4915     // VREV divides the vector in half and swaps within the half.
4916     if (VT.getVectorElementType() == MVT::i32 ||
4917         VT.getVectorElementType() == MVT::f32)
4918       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4919     // vrev <4 x i16> -> VREV32
4920     if (VT.getVectorElementType() == MVT::i16)
4921       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4922     // vrev <4 x i8> -> VREV16
4923     assert(VT.getVectorElementType() == MVT::i8);
4924     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4925   case OP_VDUP0:
4926   case OP_VDUP1:
4927   case OP_VDUP2:
4928   case OP_VDUP3:
4929     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4930                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4931   case OP_VEXT1:
4932   case OP_VEXT2:
4933   case OP_VEXT3:
4934     return DAG.getNode(ARMISD::VEXT, dl, VT,
4935                        OpLHS, OpRHS,
4936                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4937   case OP_VUZPL:
4938   case OP_VUZPR:
4939     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4940                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4941   case OP_VZIPL:
4942   case OP_VZIPR:
4943     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4944                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4945   case OP_VTRNL:
4946   case OP_VTRNR:
4947     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4948                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4949   }
4950 }
4951
4952 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4953                                        ArrayRef<int> ShuffleMask,
4954                                        SelectionDAG &DAG) {
4955   // Check to see if we can use the VTBL instruction.
4956   SDValue V1 = Op.getOperand(0);
4957   SDValue V2 = Op.getOperand(1);
4958   DebugLoc DL = Op.getDebugLoc();
4959
4960   SmallVector<SDValue, 8> VTBLMask;
4961   for (ArrayRef<int>::iterator
4962          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4963     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4964
4965   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4966     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4967                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4968                                    &VTBLMask[0], 8));
4969
4970   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4971                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4972                                  &VTBLMask[0], 8));
4973 }
4974
4975 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4976                                                       SelectionDAG &DAG) {
4977   DebugLoc DL = Op.getDebugLoc();
4978   SDValue OpLHS = Op.getOperand(0);
4979   EVT VT = OpLHS.getValueType();
4980
4981   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4982          "Expect an v8i16/v16i8 type");
4983   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4984   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4985   // extract the first 8 bytes into the top double word and the last 8 bytes
4986   // into the bottom double word. The v8i16 case is similar.
4987   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4988   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4989                      DAG.getConstant(ExtractNum, MVT::i32));
4990 }
4991
4992 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4993   SDValue V1 = Op.getOperand(0);
4994   SDValue V2 = Op.getOperand(1);
4995   DebugLoc dl = Op.getDebugLoc();
4996   EVT VT = Op.getValueType();
4997   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4998
4999   // Convert shuffles that are directly supported on NEON to target-specific
5000   // DAG nodes, instead of keeping them as shuffles and matching them again
5001   // during code selection.  This is more efficient and avoids the possibility
5002   // of inconsistencies between legalization and selection.
5003   // FIXME: floating-point vectors should be canonicalized to integer vectors
5004   // of the same time so that they get CSEd properly.
5005   ArrayRef<int> ShuffleMask = SVN->getMask();
5006
5007   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5008   if (EltSize <= 32) {
5009     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5010       int Lane = SVN->getSplatIndex();
5011       // If this is undef splat, generate it via "just" vdup, if possible.
5012       if (Lane == -1) Lane = 0;
5013
5014       // Test if V1 is a SCALAR_TO_VECTOR.
5015       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5016         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5017       }
5018       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5019       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5020       // reaches it).
5021       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5022           !isa<ConstantSDNode>(V1.getOperand(0))) {
5023         bool IsScalarToVector = true;
5024         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5025           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5026             IsScalarToVector = false;
5027             break;
5028           }
5029         if (IsScalarToVector)
5030           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5031       }
5032       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5033                          DAG.getConstant(Lane, MVT::i32));
5034     }
5035
5036     bool ReverseVEXT;
5037     unsigned Imm;
5038     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5039       if (ReverseVEXT)
5040         std::swap(V1, V2);
5041       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5042                          DAG.getConstant(Imm, MVT::i32));
5043     }
5044
5045     if (isVREVMask(ShuffleMask, VT, 64))
5046       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5047     if (isVREVMask(ShuffleMask, VT, 32))
5048       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5049     if (isVREVMask(ShuffleMask, VT, 16))
5050       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5051
5052     if (V2->getOpcode() == ISD::UNDEF &&
5053         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5054       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5055                          DAG.getConstant(Imm, MVT::i32));
5056     }
5057
5058     // Check for Neon shuffles that modify both input vectors in place.
5059     // If both results are used, i.e., if there are two shuffles with the same
5060     // source operands and with masks corresponding to both results of one of
5061     // these operations, DAG memoization will ensure that a single node is
5062     // used for both shuffles.
5063     unsigned WhichResult;
5064     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5065       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5066                          V1, V2).getValue(WhichResult);
5067     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5068       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5069                          V1, V2).getValue(WhichResult);
5070     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5071       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5072                          V1, V2).getValue(WhichResult);
5073
5074     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5075       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5076                          V1, V1).getValue(WhichResult);
5077     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5078       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5079                          V1, V1).getValue(WhichResult);
5080     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5081       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5082                          V1, V1).getValue(WhichResult);
5083   }
5084
5085   // If the shuffle is not directly supported and it has 4 elements, use
5086   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5087   unsigned NumElts = VT.getVectorNumElements();
5088   if (NumElts == 4) {
5089     unsigned PFIndexes[4];
5090     for (unsigned i = 0; i != 4; ++i) {
5091       if (ShuffleMask[i] < 0)
5092         PFIndexes[i] = 8;
5093       else
5094         PFIndexes[i] = ShuffleMask[i];
5095     }
5096
5097     // Compute the index in the perfect shuffle table.
5098     unsigned PFTableIndex =
5099       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5100     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5101     unsigned Cost = (PFEntry >> 30);
5102
5103     if (Cost <= 4)
5104       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5105   }
5106
5107   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5108   if (EltSize >= 32) {
5109     // Do the expansion with floating-point types, since that is what the VFP
5110     // registers are defined to use, and since i64 is not legal.
5111     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5112     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5113     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5114     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5115     SmallVector<SDValue, 8> Ops;
5116     for (unsigned i = 0; i < NumElts; ++i) {
5117       if (ShuffleMask[i] < 0)
5118         Ops.push_back(DAG.getUNDEF(EltVT));
5119       else
5120         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5121                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5122                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5123                                                   MVT::i32)));
5124     }
5125     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5126     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5127   }
5128
5129   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5130     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5131
5132   if (VT == MVT::v8i8) {
5133     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5134     if (NewOp.getNode())
5135       return NewOp;
5136   }
5137
5138   return SDValue();
5139 }
5140
5141 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5142   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5143   SDValue Lane = Op.getOperand(2);
5144   if (!isa<ConstantSDNode>(Lane))
5145     return SDValue();
5146
5147   return Op;
5148 }
5149
5150 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5151   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5152   SDValue Lane = Op.getOperand(1);
5153   if (!isa<ConstantSDNode>(Lane))
5154     return SDValue();
5155
5156   SDValue Vec = Op.getOperand(0);
5157   if (Op.getValueType() == MVT::i32 &&
5158       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5159     DebugLoc dl = Op.getDebugLoc();
5160     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5161   }
5162
5163   return Op;
5164 }
5165
5166 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5167   // The only time a CONCAT_VECTORS operation can have legal types is when
5168   // two 64-bit vectors are concatenated to a 128-bit vector.
5169   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5170          "unexpected CONCAT_VECTORS");
5171   DebugLoc dl = Op.getDebugLoc();
5172   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5173   SDValue Op0 = Op.getOperand(0);
5174   SDValue Op1 = Op.getOperand(1);
5175   if (Op0.getOpcode() != ISD::UNDEF)
5176     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5177                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5178                       DAG.getIntPtrConstant(0));
5179   if (Op1.getOpcode() != ISD::UNDEF)
5180     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5181                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5182                       DAG.getIntPtrConstant(1));
5183   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5184 }
5185
5186 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5187 /// element has been zero/sign-extended, depending on the isSigned parameter,
5188 /// from an integer type half its size.
5189 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5190                                    bool isSigned) {
5191   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5192   EVT VT = N->getValueType(0);
5193   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5194     SDNode *BVN = N->getOperand(0).getNode();
5195     if (BVN->getValueType(0) != MVT::v4i32 ||
5196         BVN->getOpcode() != ISD::BUILD_VECTOR)
5197       return false;
5198     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5199     unsigned HiElt = 1 - LoElt;
5200     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5201     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5202     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5203     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5204     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5205       return false;
5206     if (isSigned) {
5207       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5208           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5209         return true;
5210     } else {
5211       if (Hi0->isNullValue() && Hi1->isNullValue())
5212         return true;
5213     }
5214     return false;
5215   }
5216
5217   if (N->getOpcode() != ISD::BUILD_VECTOR)
5218     return false;
5219
5220   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5221     SDNode *Elt = N->getOperand(i).getNode();
5222     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5223       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5224       unsigned HalfSize = EltSize / 2;
5225       if (isSigned) {
5226         if (!isIntN(HalfSize, C->getSExtValue()))
5227           return false;
5228       } else {
5229         if (!isUIntN(HalfSize, C->getZExtValue()))
5230           return false;
5231       }
5232       continue;
5233     }
5234     return false;
5235   }
5236
5237   return true;
5238 }
5239
5240 /// isSignExtended - Check if a node is a vector value that is sign-extended
5241 /// or a constant BUILD_VECTOR with sign-extended elements.
5242 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5243   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5244     return true;
5245   if (isExtendedBUILD_VECTOR(N, DAG, true))
5246     return true;
5247   return false;
5248 }
5249
5250 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5251 /// or a constant BUILD_VECTOR with zero-extended elements.
5252 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5253   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5254     return true;
5255   if (isExtendedBUILD_VECTOR(N, DAG, false))
5256     return true;
5257   return false;
5258 }
5259
5260 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5261 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5262 /// We insert the required extension here to get the vector to fill a D register.
5263 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5264                                             const EVT &OrigTy,
5265                                             const EVT &ExtTy,
5266                                             unsigned ExtOpcode) {
5267   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5268   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5269   // 64-bits we need to insert a new extension so that it will be 64-bits.
5270   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5271   if (OrigTy.getSizeInBits() >= 64)
5272     return N;
5273
5274   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5275   MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5276   EVT NewVT;
5277   switch (OrigSimpleTy) {
5278   default: llvm_unreachable("Unexpected Orig Vector Type");
5279   case MVT::v2i8:
5280   case MVT::v2i16:
5281     NewVT = MVT::v2i32;
5282     break;
5283   case MVT::v4i8:
5284     NewVT = MVT::v4i16;
5285     break;
5286   }
5287   return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5288 }
5289
5290 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5291 /// does not do any sign/zero extension. If the original vector is less
5292 /// than 64 bits, an appropriate extension will be added after the load to
5293 /// reach a total size of 64 bits. We have to add the extension separately
5294 /// because ARM does not have a sign/zero extending load for vectors.
5295 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5296   SDValue NonExtendingLoad =
5297     DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5298                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5299                 LD->isNonTemporal(), LD->isInvariant(),
5300                 LD->getAlignment());
5301   unsigned ExtOp = 0;
5302   switch (LD->getExtensionType()) {
5303   default: llvm_unreachable("Unexpected LoadExtType");
5304   case ISD::EXTLOAD:
5305   case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5306   case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5307   }
5308   MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5309   MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5310   return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5311                                       MemType, ExtType, ExtOp);
5312 }
5313
5314 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5315 /// extending load, or BUILD_VECTOR with extended elements, return the
5316 /// unextended value. The unextended vector should be 64 bits so that it can
5317 /// be used as an operand to a VMULL instruction. If the original vector size
5318 /// before extension is less than 64 bits we add a an extension to resize
5319 /// the vector to 64 bits.
5320 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5321   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5322     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5323                                         N->getOperand(0)->getValueType(0),
5324                                         N->getValueType(0),
5325                                         N->getOpcode());
5326
5327   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5328     return SkipLoadExtensionForVMULL(LD, DAG);
5329
5330   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5331   // have been legalized as a BITCAST from v4i32.
5332   if (N->getOpcode() == ISD::BITCAST) {
5333     SDNode *BVN = N->getOperand(0).getNode();
5334     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5335            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5336     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5337     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5338                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5339   }
5340   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5341   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5342   EVT VT = N->getValueType(0);
5343   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5344   unsigned NumElts = VT.getVectorNumElements();
5345   MVT TruncVT = MVT::getIntegerVT(EltSize);
5346   SmallVector<SDValue, 8> Ops;
5347   for (unsigned i = 0; i != NumElts; ++i) {
5348     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5349     const APInt &CInt = C->getAPIntValue();
5350     // Element types smaller than 32 bits are not legal, so use i32 elements.
5351     // The values are implicitly truncated so sext vs. zext doesn't matter.
5352     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5353   }
5354   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5355                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5356 }
5357
5358 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5359   unsigned Opcode = N->getOpcode();
5360   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5361     SDNode *N0 = N->getOperand(0).getNode();
5362     SDNode *N1 = N->getOperand(1).getNode();
5363     return N0->hasOneUse() && N1->hasOneUse() &&
5364       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5365   }
5366   return false;
5367 }
5368
5369 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5370   unsigned Opcode = N->getOpcode();
5371   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5372     SDNode *N0 = N->getOperand(0).getNode();
5373     SDNode *N1 = N->getOperand(1).getNode();
5374     return N0->hasOneUse() && N1->hasOneUse() &&
5375       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5376   }
5377   return false;
5378 }
5379
5380 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5381   // Multiplications are only custom-lowered for 128-bit vectors so that
5382   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5383   EVT VT = Op.getValueType();
5384   assert(VT.is128BitVector() && VT.isInteger() &&
5385          "unexpected type for custom-lowering ISD::MUL");
5386   SDNode *N0 = Op.getOperand(0).getNode();
5387   SDNode *N1 = Op.getOperand(1).getNode();
5388   unsigned NewOpc = 0;
5389   bool isMLA = false;
5390   bool isN0SExt = isSignExtended(N0, DAG);
5391   bool isN1SExt = isSignExtended(N1, DAG);
5392   if (isN0SExt && isN1SExt)
5393     NewOpc = ARMISD::VMULLs;
5394   else {
5395     bool isN0ZExt = isZeroExtended(N0, DAG);
5396     bool isN1ZExt = isZeroExtended(N1, DAG);
5397     if (isN0ZExt && isN1ZExt)
5398       NewOpc = ARMISD::VMULLu;
5399     else if (isN1SExt || isN1ZExt) {
5400       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5401       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5402       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5403         NewOpc = ARMISD::VMULLs;
5404         isMLA = true;
5405       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5406         NewOpc = ARMISD::VMULLu;
5407         isMLA = true;
5408       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5409         std::swap(N0, N1);
5410         NewOpc = ARMISD::VMULLu;
5411         isMLA = true;
5412       }
5413     }
5414
5415     if (!NewOpc) {
5416       if (VT == MVT::v2i64)
5417         // Fall through to expand this.  It is not legal.
5418         return SDValue();
5419       else
5420         // Other vector multiplications are legal.
5421         return Op;
5422     }
5423   }
5424
5425   // Legalize to a VMULL instruction.
5426   DebugLoc DL = Op.getDebugLoc();
5427   SDValue Op0;
5428   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5429   if (!isMLA) {
5430     Op0 = SkipExtensionForVMULL(N0, DAG);
5431     assert(Op0.getValueType().is64BitVector() &&
5432            Op1.getValueType().is64BitVector() &&
5433            "unexpected types for extended operands to VMULL");
5434     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5435   }
5436
5437   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5438   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5439   //   vmull q0, d4, d6
5440   //   vmlal q0, d5, d6
5441   // is faster than
5442   //   vaddl q0, d4, d5
5443   //   vmovl q1, d6
5444   //   vmul  q0, q0, q1
5445   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5446   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5447   EVT Op1VT = Op1.getValueType();
5448   return DAG.getNode(N0->getOpcode(), DL, VT,
5449                      DAG.getNode(NewOpc, DL, VT,
5450                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5451                      DAG.getNode(NewOpc, DL, VT,
5452                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5453 }
5454
5455 static SDValue
5456 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5457   // Convert to float
5458   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5459   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5460   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5461   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5462   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5463   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5464   // Get reciprocal estimate.
5465   // float4 recip = vrecpeq_f32(yf);
5466   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5467                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5468   // Because char has a smaller range than uchar, we can actually get away
5469   // without any newton steps.  This requires that we use a weird bias
5470   // of 0xb000, however (again, this has been exhaustively tested).
5471   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5472   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5473   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5474   Y = DAG.getConstant(0xb000, MVT::i32);
5475   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5476   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5477   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5478   // Convert back to short.
5479   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5480   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5481   return X;
5482 }
5483
5484 static SDValue
5485 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5486   SDValue N2;
5487   // Convert to float.
5488   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5489   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5490   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5491   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5492   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5493   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5494
5495   // Use reciprocal estimate and one refinement step.
5496   // float4 recip = vrecpeq_f32(yf);
5497   // recip *= vrecpsq_f32(yf, recip);
5498   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5499                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5500   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5501                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5502                    N1, N2);
5503   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5504   // Because short has a smaller range than ushort, we can actually get away
5505   // with only a single newton step.  This requires that we use a weird bias
5506   // of 89, however (again, this has been exhaustively tested).
5507   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5508   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5509   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5510   N1 = DAG.getConstant(0x89, MVT::i32);
5511   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5512   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5513   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5514   // Convert back to integer and return.
5515   // return vmovn_s32(vcvt_s32_f32(result));
5516   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5517   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5518   return N0;
5519 }
5520
5521 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5522   EVT VT = Op.getValueType();
5523   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5524          "unexpected type for custom-lowering ISD::SDIV");
5525
5526   DebugLoc dl = Op.getDebugLoc();
5527   SDValue N0 = Op.getOperand(0);
5528   SDValue N1 = Op.getOperand(1);
5529   SDValue N2, N3;
5530
5531   if (VT == MVT::v8i8) {
5532     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5533     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5534
5535     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5536                      DAG.getIntPtrConstant(4));
5537     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5538                      DAG.getIntPtrConstant(4));
5539     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5540                      DAG.getIntPtrConstant(0));
5541     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5542                      DAG.getIntPtrConstant(0));
5543
5544     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5545     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5546
5547     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5548     N0 = LowerCONCAT_VECTORS(N0, DAG);
5549
5550     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5551     return N0;
5552   }
5553   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5554 }
5555
5556 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5557   EVT VT = Op.getValueType();
5558   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5559          "unexpected type for custom-lowering ISD::UDIV");
5560
5561   DebugLoc dl = Op.getDebugLoc();
5562   SDValue N0 = Op.getOperand(0);
5563   SDValue N1 = Op.getOperand(1);
5564   SDValue N2, N3;
5565
5566   if (VT == MVT::v8i8) {
5567     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5568     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5569
5570     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5571                      DAG.getIntPtrConstant(4));
5572     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5573                      DAG.getIntPtrConstant(4));
5574     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5575                      DAG.getIntPtrConstant(0));
5576     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5577                      DAG.getIntPtrConstant(0));
5578
5579     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5580     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5581
5582     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5583     N0 = LowerCONCAT_VECTORS(N0, DAG);
5584
5585     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5586                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5587                      N0);
5588     return N0;
5589   }
5590
5591   // v4i16 sdiv ... Convert to float.
5592   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5593   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5594   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5595   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5596   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5597   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5598
5599   // Use reciprocal estimate and two refinement steps.
5600   // float4 recip = vrecpeq_f32(yf);
5601   // recip *= vrecpsq_f32(yf, recip);
5602   // recip *= vrecpsq_f32(yf, recip);
5603   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5604                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5605   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5606                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5607                    BN1, N2);
5608   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5609   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5610                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5611                    BN1, N2);
5612   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5613   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5614   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5615   // and that it will never cause us to return an answer too large).
5616   // float4 result = as_float4(as_int4(xf*recip) + 2);
5617   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5618   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5619   N1 = DAG.getConstant(2, MVT::i32);
5620   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5621   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5622   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5623   // Convert back to integer and return.
5624   // return vmovn_u32(vcvt_s32_f32(result));
5625   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5626   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5627   return N0;
5628 }
5629
5630 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5631   EVT VT = Op.getNode()->getValueType(0);
5632   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5633
5634   unsigned Opc;
5635   bool ExtraOp = false;
5636   switch (Op.getOpcode()) {
5637   default: llvm_unreachable("Invalid code");
5638   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5639   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5640   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5641   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5642   }
5643
5644   if (!ExtraOp)
5645     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5646                        Op.getOperand(1));
5647   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5648                      Op.getOperand(1), Op.getOperand(2));
5649 }
5650
5651 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5652   // Monotonic load/store is legal for all targets
5653   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5654     return Op;
5655
5656   // Aquire/Release load/store is not legal for targets without a
5657   // dmb or equivalent available.
5658   return SDValue();
5659 }
5660
5661
5662 static void
5663 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5664                     SelectionDAG &DAG, unsigned NewOp) {
5665   DebugLoc dl = Node->getDebugLoc();
5666   assert (Node->getValueType(0) == MVT::i64 &&
5667           "Only know how to expand i64 atomics");
5668
5669   SmallVector<SDValue, 6> Ops;
5670   Ops.push_back(Node->getOperand(0)); // Chain
5671   Ops.push_back(Node->getOperand(1)); // Ptr
5672   // Low part of Val1
5673   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5674                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5675   // High part of Val1
5676   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5677                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5678   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5679     // High part of Val1
5680     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5681                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5682     // High part of Val2
5683     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5684                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5685   }
5686   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5687   SDValue Result =
5688     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5689                             cast<MemSDNode>(Node)->getMemOperand());
5690   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5691   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5692   Results.push_back(Result.getValue(2));
5693 }
5694
5695 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5696   switch (Op.getOpcode()) {
5697   default: llvm_unreachable("Don't know how to custom lower this!");
5698   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5699   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5700   case ISD::GlobalAddress:
5701     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5702       LowerGlobalAddressELF(Op, DAG);
5703   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5704   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5705   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5706   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5707   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5708   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5709   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5710   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5711   case ISD::SINT_TO_FP:
5712   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5713   case ISD::FP_TO_SINT:
5714   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5715   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5716   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5717   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5718   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5719   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5720   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5721   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5722                                                                Subtarget);
5723   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5724   case ISD::SHL:
5725   case ISD::SRL:
5726   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5727   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5728   case ISD::SRL_PARTS:
5729   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5730   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5731   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5732   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5733   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5734   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5735   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5736   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5737   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5738   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5739   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5740   case ISD::MUL:           return LowerMUL(Op, DAG);
5741   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5742   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5743   case ISD::ADDC:
5744   case ISD::ADDE:
5745   case ISD::SUBC:
5746   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5747   case ISD::ATOMIC_LOAD:
5748   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5749   }
5750 }
5751
5752 /// ReplaceNodeResults - Replace the results of node with an illegal result
5753 /// type with new values built out of custom code.
5754 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5755                                            SmallVectorImpl<SDValue>&Results,
5756                                            SelectionDAG &DAG) const {
5757   SDValue Res;
5758   switch (N->getOpcode()) {
5759   default:
5760     llvm_unreachable("Don't know how to custom expand this!");
5761   case ISD::BITCAST:
5762     Res = ExpandBITCAST(N, DAG);
5763     break;
5764   case ISD::SIGN_EXTEND:
5765   case ISD::ZERO_EXTEND:
5766     Res = ExpandVectorExtension(N, DAG);
5767     break;
5768   case ISD::SRL:
5769   case ISD::SRA:
5770     Res = Expand64BitShift(N, DAG, Subtarget);
5771     break;
5772   case ISD::ATOMIC_LOAD_ADD:
5773     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5774     return;
5775   case ISD::ATOMIC_LOAD_AND:
5776     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5777     return;
5778   case ISD::ATOMIC_LOAD_NAND:
5779     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5780     return;
5781   case ISD::ATOMIC_LOAD_OR:
5782     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5783     return;
5784   case ISD::ATOMIC_LOAD_SUB:
5785     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5786     return;
5787   case ISD::ATOMIC_LOAD_XOR:
5788     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5789     return;
5790   case ISD::ATOMIC_SWAP:
5791     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5792     return;
5793   case ISD::ATOMIC_CMP_SWAP:
5794     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5795     return;
5796   case ISD::ATOMIC_LOAD_MIN:
5797     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5798     return;
5799   case ISD::ATOMIC_LOAD_UMIN:
5800     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5801     return;
5802   case ISD::ATOMIC_LOAD_MAX:
5803     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5804     return;
5805   case ISD::ATOMIC_LOAD_UMAX:
5806     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5807     return;
5808   }
5809   if (Res.getNode())
5810     Results.push_back(Res);
5811 }
5812
5813 //===----------------------------------------------------------------------===//
5814 //                           ARM Scheduler Hooks
5815 //===----------------------------------------------------------------------===//
5816
5817 MachineBasicBlock *
5818 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5819                                      MachineBasicBlock *BB,
5820                                      unsigned Size) const {
5821   unsigned dest    = MI->getOperand(0).getReg();
5822   unsigned ptr     = MI->getOperand(1).getReg();
5823   unsigned oldval  = MI->getOperand(2).getReg();
5824   unsigned newval  = MI->getOperand(3).getReg();
5825   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5826   DebugLoc dl = MI->getDebugLoc();
5827   bool isThumb2 = Subtarget->isThumb2();
5828
5829   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5830   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5831     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5832     (const TargetRegisterClass*)&ARM::GPRRegClass);
5833
5834   if (isThumb2) {
5835     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5836     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5837     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5838   }
5839
5840   unsigned ldrOpc, strOpc;
5841   switch (Size) {
5842   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5843   case 1:
5844     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5845     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5846     break;
5847   case 2:
5848     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5849     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5850     break;
5851   case 4:
5852     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5853     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5854     break;
5855   }
5856
5857   MachineFunction *MF = BB->getParent();
5858   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5859   MachineFunction::iterator It = BB;
5860   ++It; // insert the new blocks after the current block
5861
5862   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5863   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5864   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5865   MF->insert(It, loop1MBB);
5866   MF->insert(It, loop2MBB);
5867   MF->insert(It, exitMBB);
5868
5869   // Transfer the remainder of BB and its successor edges to exitMBB.
5870   exitMBB->splice(exitMBB->begin(), BB,
5871                   llvm::next(MachineBasicBlock::iterator(MI)),
5872                   BB->end());
5873   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5874
5875   //  thisMBB:
5876   //   ...
5877   //   fallthrough --> loop1MBB
5878   BB->addSuccessor(loop1MBB);
5879
5880   // loop1MBB:
5881   //   ldrex dest, [ptr]
5882   //   cmp dest, oldval
5883   //   bne exitMBB
5884   BB = loop1MBB;
5885   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5886   if (ldrOpc == ARM::t2LDREX)
5887     MIB.addImm(0);
5888   AddDefaultPred(MIB);
5889   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5890                  .addReg(dest).addReg(oldval));
5891   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5892     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5893   BB->addSuccessor(loop2MBB);
5894   BB->addSuccessor(exitMBB);
5895
5896   // loop2MBB:
5897   //   strex scratch, newval, [ptr]
5898   //   cmp scratch, #0
5899   //   bne loop1MBB
5900   BB = loop2MBB;
5901   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5902   if (strOpc == ARM::t2STREX)
5903     MIB.addImm(0);
5904   AddDefaultPred(MIB);
5905   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5906                  .addReg(scratch).addImm(0));
5907   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5908     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5909   BB->addSuccessor(loop1MBB);
5910   BB->addSuccessor(exitMBB);
5911
5912   //  exitMBB:
5913   //   ...
5914   BB = exitMBB;
5915
5916   MI->eraseFromParent();   // The instruction is gone now.
5917
5918   return BB;
5919 }
5920
5921 MachineBasicBlock *
5922 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5923                                     unsigned Size, unsigned BinOpcode) const {
5924   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5925   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5926
5927   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5928   MachineFunction *MF = BB->getParent();
5929   MachineFunction::iterator It = BB;
5930   ++It;
5931
5932   unsigned dest = MI->getOperand(0).getReg();
5933   unsigned ptr = MI->getOperand(1).getReg();
5934   unsigned incr = MI->getOperand(2).getReg();
5935   DebugLoc dl = MI->getDebugLoc();
5936   bool isThumb2 = Subtarget->isThumb2();
5937
5938   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5939   if (isThumb2) {
5940     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5941     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5942   }
5943
5944   unsigned ldrOpc, strOpc;
5945   switch (Size) {
5946   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5947   case 1:
5948     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5949     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5950     break;
5951   case 2:
5952     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5953     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5954     break;
5955   case 4:
5956     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5957     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5958     break;
5959   }
5960
5961   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5962   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5963   MF->insert(It, loopMBB);
5964   MF->insert(It, exitMBB);
5965
5966   // Transfer the remainder of BB and its successor edges to exitMBB.
5967   exitMBB->splice(exitMBB->begin(), BB,
5968                   llvm::next(MachineBasicBlock::iterator(MI)),
5969                   BB->end());
5970   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5971
5972   const TargetRegisterClass *TRC = isThumb2 ?
5973     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5974     (const TargetRegisterClass*)&ARM::GPRRegClass;
5975   unsigned scratch = MRI.createVirtualRegister(TRC);
5976   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5977
5978   //  thisMBB:
5979   //   ...
5980   //   fallthrough --> loopMBB
5981   BB->addSuccessor(loopMBB);
5982
5983   //  loopMBB:
5984   //   ldrex dest, ptr
5985   //   <binop> scratch2, dest, incr
5986   //   strex scratch, scratch2, ptr
5987   //   cmp scratch, #0
5988   //   bne- loopMBB
5989   //   fallthrough --> exitMBB
5990   BB = loopMBB;
5991   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5992   if (ldrOpc == ARM::t2LDREX)
5993     MIB.addImm(0);
5994   AddDefaultPred(MIB);
5995   if (BinOpcode) {
5996     // operand order needs to go the other way for NAND
5997     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5998       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5999                      addReg(incr).addReg(dest)).addReg(0);
6000     else
6001       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6002                      addReg(dest).addReg(incr)).addReg(0);
6003   }
6004
6005   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6006   if (strOpc == ARM::t2STREX)
6007     MIB.addImm(0);
6008   AddDefaultPred(MIB);
6009   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6010                  .addReg(scratch).addImm(0));
6011   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6012     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6013
6014   BB->addSuccessor(loopMBB);
6015   BB->addSuccessor(exitMBB);
6016
6017   //  exitMBB:
6018   //   ...
6019   BB = exitMBB;
6020
6021   MI->eraseFromParent();   // The instruction is gone now.
6022
6023   return BB;
6024 }
6025
6026 MachineBasicBlock *
6027 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6028                                           MachineBasicBlock *BB,
6029                                           unsigned Size,
6030                                           bool signExtend,
6031                                           ARMCC::CondCodes Cond) const {
6032   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6033
6034   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6035   MachineFunction *MF = BB->getParent();
6036   MachineFunction::iterator It = BB;
6037   ++It;
6038
6039   unsigned dest = MI->getOperand(0).getReg();
6040   unsigned ptr = MI->getOperand(1).getReg();
6041   unsigned incr = MI->getOperand(2).getReg();
6042   unsigned oldval = dest;
6043   DebugLoc dl = MI->getDebugLoc();
6044   bool isThumb2 = Subtarget->isThumb2();
6045
6046   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6047   if (isThumb2) {
6048     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6049     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6050   }
6051
6052   unsigned ldrOpc, strOpc, extendOpc;
6053   switch (Size) {
6054   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6055   case 1:
6056     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6057     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6058     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6059     break;
6060   case 2:
6061     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6062     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6063     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6064     break;
6065   case 4:
6066     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6067     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6068     extendOpc = 0;
6069     break;
6070   }
6071
6072   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6073   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6074   MF->insert(It, loopMBB);
6075   MF->insert(It, exitMBB);
6076
6077   // Transfer the remainder of BB and its successor edges to exitMBB.
6078   exitMBB->splice(exitMBB->begin(), BB,
6079                   llvm::next(MachineBasicBlock::iterator(MI)),
6080                   BB->end());
6081   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6082
6083   const TargetRegisterClass *TRC = isThumb2 ?
6084     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6085     (const TargetRegisterClass*)&ARM::GPRRegClass;
6086   unsigned scratch = MRI.createVirtualRegister(TRC);
6087   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6088
6089   //  thisMBB:
6090   //   ...
6091   //   fallthrough --> loopMBB
6092   BB->addSuccessor(loopMBB);
6093
6094   //  loopMBB:
6095   //   ldrex dest, ptr
6096   //   (sign extend dest, if required)
6097   //   cmp dest, incr
6098   //   cmov.cond scratch2, incr, dest
6099   //   strex scratch, scratch2, ptr
6100   //   cmp scratch, #0
6101   //   bne- loopMBB
6102   //   fallthrough --> exitMBB
6103   BB = loopMBB;
6104   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6105   if (ldrOpc == ARM::t2LDREX)
6106     MIB.addImm(0);
6107   AddDefaultPred(MIB);
6108
6109   // Sign extend the value, if necessary.
6110   if (signExtend && extendOpc) {
6111     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6112     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6113                      .addReg(dest)
6114                      .addImm(0));
6115   }
6116
6117   // Build compare and cmov instructions.
6118   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6119                  .addReg(oldval).addReg(incr));
6120   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6121          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6122
6123   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6124   if (strOpc == ARM::t2STREX)
6125     MIB.addImm(0);
6126   AddDefaultPred(MIB);
6127   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6128                  .addReg(scratch).addImm(0));
6129   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6130     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6131
6132   BB->addSuccessor(loopMBB);
6133   BB->addSuccessor(exitMBB);
6134
6135   //  exitMBB:
6136   //   ...
6137   BB = exitMBB;
6138
6139   MI->eraseFromParent();   // The instruction is gone now.
6140
6141   return BB;
6142 }
6143
6144 MachineBasicBlock *
6145 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6146                                       unsigned Op1, unsigned Op2,
6147                                       bool NeedsCarry, bool IsCmpxchg,
6148                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6149   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6150   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6151
6152   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6153   MachineFunction *MF = BB->getParent();
6154   MachineFunction::iterator It = BB;
6155   ++It;
6156
6157   unsigned destlo = MI->getOperand(0).getReg();
6158   unsigned desthi = MI->getOperand(1).getReg();
6159   unsigned ptr = MI->getOperand(2).getReg();
6160   unsigned vallo = MI->getOperand(3).getReg();
6161   unsigned valhi = MI->getOperand(4).getReg();
6162   DebugLoc dl = MI->getDebugLoc();
6163   bool isThumb2 = Subtarget->isThumb2();
6164
6165   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6166   if (isThumb2) {
6167     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6168     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6169     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6170   }
6171
6172   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6173   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6174   if (IsCmpxchg || IsMinMax)
6175     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6176   if (IsCmpxchg)
6177     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6178   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6179
6180   MF->insert(It, loopMBB);
6181   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6182   if (IsCmpxchg) MF->insert(It, cont2BB);
6183   MF->insert(It, exitMBB);
6184
6185   // Transfer the remainder of BB and its successor edges to exitMBB.
6186   exitMBB->splice(exitMBB->begin(), BB,
6187                   llvm::next(MachineBasicBlock::iterator(MI)),
6188                   BB->end());
6189   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6190
6191   const TargetRegisterClass *TRC = isThumb2 ?
6192     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6193     (const TargetRegisterClass*)&ARM::GPRRegClass;
6194   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6195
6196   //  thisMBB:
6197   //   ...
6198   //   fallthrough --> loopMBB
6199   BB->addSuccessor(loopMBB);
6200
6201   //  loopMBB:
6202   //   ldrexd r2, r3, ptr
6203   //   <binopa> r0, r2, incr
6204   //   <binopb> r1, r3, incr
6205   //   strexd storesuccess, r0, r1, ptr
6206   //   cmp storesuccess, #0
6207   //   bne- loopMBB
6208   //   fallthrough --> exitMBB
6209   BB = loopMBB;
6210
6211   // Load
6212   if (isThumb2) {
6213     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6214                    .addReg(destlo, RegState::Define)
6215                    .addReg(desthi, RegState::Define)
6216                    .addReg(ptr));
6217   } else {
6218     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6219     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6220                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6221     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6222     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6223       .addReg(GPRPair0, 0, ARM::gsub_0);
6224     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6225       .addReg(GPRPair0, 0, ARM::gsub_1);
6226   }
6227
6228   unsigned StoreLo, StoreHi;
6229   if (IsCmpxchg) {
6230     // Add early exit
6231     for (unsigned i = 0; i < 2; i++) {
6232       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6233                                                          ARM::CMPrr))
6234                      .addReg(i == 0 ? destlo : desthi)
6235                      .addReg(i == 0 ? vallo : valhi));
6236       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6237         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6238       BB->addSuccessor(exitMBB);
6239       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6240       BB = (i == 0 ? contBB : cont2BB);
6241     }
6242
6243     // Copy to physregs for strexd
6244     StoreLo = MI->getOperand(5).getReg();
6245     StoreHi = MI->getOperand(6).getReg();
6246   } else if (Op1) {
6247     // Perform binary operation
6248     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6249     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6250                    .addReg(destlo).addReg(vallo))
6251         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6252     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6253     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6254                    .addReg(desthi).addReg(valhi))
6255         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6256
6257     StoreLo = tmpRegLo;
6258     StoreHi = tmpRegHi;
6259   } else {
6260     // Copy to physregs for strexd
6261     StoreLo = vallo;
6262     StoreHi = valhi;
6263   }
6264   if (IsMinMax) {
6265     // Compare and branch to exit block.
6266     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6267       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6268     BB->addSuccessor(exitMBB);
6269     BB->addSuccessor(contBB);
6270     BB = contBB;
6271     StoreLo = vallo;
6272     StoreHi = valhi;
6273   }
6274
6275   // Store
6276   if (isThumb2) {
6277     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6278                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6279   } else {
6280     // Marshal a pair...
6281     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6282     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6283     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6284     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6285     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6286       .addReg(UndefPair)
6287       .addReg(StoreLo)
6288       .addImm(ARM::gsub_0);
6289     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6290       .addReg(r1)
6291       .addReg(StoreHi)
6292       .addImm(ARM::gsub_1);
6293
6294     // ...and store it
6295     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6296                    .addReg(StorePair).addReg(ptr));
6297   }
6298   // Cmp+jump
6299   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6300                  .addReg(storesuccess).addImm(0));
6301   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6302     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6303
6304   BB->addSuccessor(loopMBB);
6305   BB->addSuccessor(exitMBB);
6306
6307   //  exitMBB:
6308   //   ...
6309   BB = exitMBB;
6310
6311   MI->eraseFromParent();   // The instruction is gone now.
6312
6313   return BB;
6314 }
6315
6316 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6317 /// registers the function context.
6318 void ARMTargetLowering::
6319 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6320                        MachineBasicBlock *DispatchBB, int FI) const {
6321   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6322   DebugLoc dl = MI->getDebugLoc();
6323   MachineFunction *MF = MBB->getParent();
6324   MachineRegisterInfo *MRI = &MF->getRegInfo();
6325   MachineConstantPool *MCP = MF->getConstantPool();
6326   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6327   const Function *F = MF->getFunction();
6328
6329   bool isThumb = Subtarget->isThumb();
6330   bool isThumb2 = Subtarget->isThumb2();
6331
6332   unsigned PCLabelId = AFI->createPICLabelUId();
6333   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6334   ARMConstantPoolValue *CPV =
6335     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6336   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6337
6338   const TargetRegisterClass *TRC = isThumb ?
6339     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6340     (const TargetRegisterClass*)&ARM::GPRRegClass;
6341
6342   // Grab constant pool and fixed stack memory operands.
6343   MachineMemOperand *CPMMO =
6344     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6345                              MachineMemOperand::MOLoad, 4, 4);
6346
6347   MachineMemOperand *FIMMOSt =
6348     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6349                              MachineMemOperand::MOStore, 4, 4);
6350
6351   // Load the address of the dispatch MBB into the jump buffer.
6352   if (isThumb2) {
6353     // Incoming value: jbuf
6354     //   ldr.n  r5, LCPI1_1
6355     //   orr    r5, r5, #1
6356     //   add    r5, pc
6357     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6358     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6359     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6360                    .addConstantPoolIndex(CPI)
6361                    .addMemOperand(CPMMO));
6362     // Set the low bit because of thumb mode.
6363     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6364     AddDefaultCC(
6365       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6366                      .addReg(NewVReg1, RegState::Kill)
6367                      .addImm(0x01)));
6368     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6369     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6370       .addReg(NewVReg2, RegState::Kill)
6371       .addImm(PCLabelId);
6372     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6373                    .addReg(NewVReg3, RegState::Kill)
6374                    .addFrameIndex(FI)
6375                    .addImm(36)  // &jbuf[1] :: pc
6376                    .addMemOperand(FIMMOSt));
6377   } else if (isThumb) {
6378     // Incoming value: jbuf
6379     //   ldr.n  r1, LCPI1_4
6380     //   add    r1, pc
6381     //   mov    r2, #1
6382     //   orrs   r1, r2
6383     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6384     //   str    r1, [r2]
6385     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6386     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6387                    .addConstantPoolIndex(CPI)
6388                    .addMemOperand(CPMMO));
6389     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6390     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6391       .addReg(NewVReg1, RegState::Kill)
6392       .addImm(PCLabelId);
6393     // Set the low bit because of thumb mode.
6394     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6395     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6396                    .addReg(ARM::CPSR, RegState::Define)
6397                    .addImm(1));
6398     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6399     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6400                    .addReg(ARM::CPSR, RegState::Define)
6401                    .addReg(NewVReg2, RegState::Kill)
6402                    .addReg(NewVReg3, RegState::Kill));
6403     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6404     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6405                    .addFrameIndex(FI)
6406                    .addImm(36)); // &jbuf[1] :: pc
6407     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6408                    .addReg(NewVReg4, RegState::Kill)
6409                    .addReg(NewVReg5, RegState::Kill)
6410                    .addImm(0)
6411                    .addMemOperand(FIMMOSt));
6412   } else {
6413     // Incoming value: jbuf
6414     //   ldr  r1, LCPI1_1
6415     //   add  r1, pc, r1
6416     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6417     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6418     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6419                    .addConstantPoolIndex(CPI)
6420                    .addImm(0)
6421                    .addMemOperand(CPMMO));
6422     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6423     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6424                    .addReg(NewVReg1, RegState::Kill)
6425                    .addImm(PCLabelId));
6426     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6427                    .addReg(NewVReg2, RegState::Kill)
6428                    .addFrameIndex(FI)
6429                    .addImm(36)  // &jbuf[1] :: pc
6430                    .addMemOperand(FIMMOSt));
6431   }
6432 }
6433
6434 MachineBasicBlock *ARMTargetLowering::
6435 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6436   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6437   DebugLoc dl = MI->getDebugLoc();
6438   MachineFunction *MF = MBB->getParent();
6439   MachineRegisterInfo *MRI = &MF->getRegInfo();
6440   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6441   MachineFrameInfo *MFI = MF->getFrameInfo();
6442   int FI = MFI->getFunctionContextIndex();
6443
6444   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6445     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6446     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6447
6448   // Get a mapping of the call site numbers to all of the landing pads they're
6449   // associated with.
6450   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6451   unsigned MaxCSNum = 0;
6452   MachineModuleInfo &MMI = MF->getMMI();
6453   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6454        ++BB) {
6455     if (!BB->isLandingPad()) continue;
6456
6457     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6458     // pad.
6459     for (MachineBasicBlock::iterator
6460            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6461       if (!II->isEHLabel()) continue;
6462
6463       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6464       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6465
6466       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6467       for (SmallVectorImpl<unsigned>::iterator
6468              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6469            CSI != CSE; ++CSI) {
6470         CallSiteNumToLPad[*CSI].push_back(BB);
6471         MaxCSNum = std::max(MaxCSNum, *CSI);
6472       }
6473       break;
6474     }
6475   }
6476
6477   // Get an ordered list of the machine basic blocks for the jump table.
6478   std::vector<MachineBasicBlock*> LPadList;
6479   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6480   LPadList.reserve(CallSiteNumToLPad.size());
6481   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6482     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6483     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6484            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6485       LPadList.push_back(*II);
6486       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6487     }
6488   }
6489
6490   assert(!LPadList.empty() &&
6491          "No landing pad destinations for the dispatch jump table!");
6492
6493   // Create the jump table and associated information.
6494   MachineJumpTableInfo *JTI =
6495     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6496   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6497   unsigned UId = AFI->createJumpTableUId();
6498   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6499
6500   // Create the MBBs for the dispatch code.
6501
6502   // Shove the dispatch's address into the return slot in the function context.
6503   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6504   DispatchBB->setIsLandingPad();
6505
6506   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6507   unsigned trap_opcode;
6508   if (Subtarget->isThumb())
6509     trap_opcode = ARM::tTRAP;
6510   else
6511     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6512
6513   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6514   DispatchBB->addSuccessor(TrapBB);
6515
6516   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6517   DispatchBB->addSuccessor(DispContBB);
6518
6519   // Insert and MBBs.
6520   MF->insert(MF->end(), DispatchBB);
6521   MF->insert(MF->end(), DispContBB);
6522   MF->insert(MF->end(), TrapBB);
6523
6524   // Insert code into the entry block that creates and registers the function
6525   // context.
6526   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6527
6528   MachineMemOperand *FIMMOLd =
6529     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6530                              MachineMemOperand::MOLoad |
6531                              MachineMemOperand::MOVolatile, 4, 4);
6532
6533   MachineInstrBuilder MIB;
6534   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6535
6536   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6537   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6538
6539   // Add a register mask with no preserved registers.  This results in all
6540   // registers being marked as clobbered.
6541   MIB.addRegMask(RI.getNoPreservedMask());
6542
6543   unsigned NumLPads = LPadList.size();
6544   if (Subtarget->isThumb2()) {
6545     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6546     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6547                    .addFrameIndex(FI)
6548                    .addImm(4)
6549                    .addMemOperand(FIMMOLd));
6550
6551     if (NumLPads < 256) {
6552       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6553                      .addReg(NewVReg1)
6554                      .addImm(LPadList.size()));
6555     } else {
6556       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6557       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6558                      .addImm(NumLPads & 0xFFFF));
6559
6560       unsigned VReg2 = VReg1;
6561       if ((NumLPads & 0xFFFF0000) != 0) {
6562         VReg2 = MRI->createVirtualRegister(TRC);
6563         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6564                        .addReg(VReg1)
6565                        .addImm(NumLPads >> 16));
6566       }
6567
6568       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6569                      .addReg(NewVReg1)
6570                      .addReg(VReg2));
6571     }
6572
6573     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6574       .addMBB(TrapBB)
6575       .addImm(ARMCC::HI)
6576       .addReg(ARM::CPSR);
6577
6578     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6579     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6580                    .addJumpTableIndex(MJTI)
6581                    .addImm(UId));
6582
6583     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6584     AddDefaultCC(
6585       AddDefaultPred(
6586         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6587         .addReg(NewVReg3, RegState::Kill)
6588         .addReg(NewVReg1)
6589         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6590
6591     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6592       .addReg(NewVReg4, RegState::Kill)
6593       .addReg(NewVReg1)
6594       .addJumpTableIndex(MJTI)
6595       .addImm(UId);
6596   } else if (Subtarget->isThumb()) {
6597     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6598     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6599                    .addFrameIndex(FI)
6600                    .addImm(1)
6601                    .addMemOperand(FIMMOLd));
6602
6603     if (NumLPads < 256) {
6604       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6605                      .addReg(NewVReg1)
6606                      .addImm(NumLPads));
6607     } else {
6608       MachineConstantPool *ConstantPool = MF->getConstantPool();
6609       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6610       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6611
6612       // MachineConstantPool wants an explicit alignment.
6613       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6614       if (Align == 0)
6615         Align = getDataLayout()->getTypeAllocSize(C->getType());
6616       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6617
6618       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6619       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6620                      .addReg(VReg1, RegState::Define)
6621                      .addConstantPoolIndex(Idx));
6622       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6623                      .addReg(NewVReg1)
6624                      .addReg(VReg1));
6625     }
6626
6627     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6628       .addMBB(TrapBB)
6629       .addImm(ARMCC::HI)
6630       .addReg(ARM::CPSR);
6631
6632     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6633     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6634                    .addReg(ARM::CPSR, RegState::Define)
6635                    .addReg(NewVReg1)
6636                    .addImm(2));
6637
6638     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6639     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6640                    .addJumpTableIndex(MJTI)
6641                    .addImm(UId));
6642
6643     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6644     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6645                    .addReg(ARM::CPSR, RegState::Define)
6646                    .addReg(NewVReg2, RegState::Kill)
6647                    .addReg(NewVReg3));
6648
6649     MachineMemOperand *JTMMOLd =
6650       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6651                                MachineMemOperand::MOLoad, 4, 4);
6652
6653     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6654     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6655                    .addReg(NewVReg4, RegState::Kill)
6656                    .addImm(0)
6657                    .addMemOperand(JTMMOLd));
6658
6659     unsigned NewVReg6 = NewVReg5;
6660     if (RelocM == Reloc::PIC_) {
6661       NewVReg6 = MRI->createVirtualRegister(TRC);
6662       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6663                      .addReg(ARM::CPSR, RegState::Define)
6664                      .addReg(NewVReg5, RegState::Kill)
6665                      .addReg(NewVReg3));
6666     }
6667
6668     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6669       .addReg(NewVReg6, RegState::Kill)
6670       .addJumpTableIndex(MJTI)
6671       .addImm(UId);
6672   } else {
6673     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6674     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6675                    .addFrameIndex(FI)
6676                    .addImm(4)
6677                    .addMemOperand(FIMMOLd));
6678
6679     if (NumLPads < 256) {
6680       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6681                      .addReg(NewVReg1)
6682                      .addImm(NumLPads));
6683     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6684       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6685       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6686                      .addImm(NumLPads & 0xFFFF));
6687
6688       unsigned VReg2 = VReg1;
6689       if ((NumLPads & 0xFFFF0000) != 0) {
6690         VReg2 = MRI->createVirtualRegister(TRC);
6691         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6692                        .addReg(VReg1)
6693                        .addImm(NumLPads >> 16));
6694       }
6695
6696       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6697                      .addReg(NewVReg1)
6698                      .addReg(VReg2));
6699     } else {
6700       MachineConstantPool *ConstantPool = MF->getConstantPool();
6701       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6702       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6703
6704       // MachineConstantPool wants an explicit alignment.
6705       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6706       if (Align == 0)
6707         Align = getDataLayout()->getTypeAllocSize(C->getType());
6708       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6709
6710       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6711       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6712                      .addReg(VReg1, RegState::Define)
6713                      .addConstantPoolIndex(Idx)
6714                      .addImm(0));
6715       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6716                      .addReg(NewVReg1)
6717                      .addReg(VReg1, RegState::Kill));
6718     }
6719
6720     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6721       .addMBB(TrapBB)
6722       .addImm(ARMCC::HI)
6723       .addReg(ARM::CPSR);
6724
6725     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6726     AddDefaultCC(
6727       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6728                      .addReg(NewVReg1)
6729                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6730     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6731     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6732                    .addJumpTableIndex(MJTI)
6733                    .addImm(UId));
6734
6735     MachineMemOperand *JTMMOLd =
6736       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6737                                MachineMemOperand::MOLoad, 4, 4);
6738     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6739     AddDefaultPred(
6740       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6741       .addReg(NewVReg3, RegState::Kill)
6742       .addReg(NewVReg4)
6743       .addImm(0)
6744       .addMemOperand(JTMMOLd));
6745
6746     if (RelocM == Reloc::PIC_) {
6747       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6748         .addReg(NewVReg5, RegState::Kill)
6749         .addReg(NewVReg4)
6750         .addJumpTableIndex(MJTI)
6751         .addImm(UId);
6752     } else {
6753       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6754         .addReg(NewVReg5, RegState::Kill)
6755         .addJumpTableIndex(MJTI)
6756         .addImm(UId);
6757     }
6758   }
6759
6760   // Add the jump table entries as successors to the MBB.
6761   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6762   for (std::vector<MachineBasicBlock*>::iterator
6763          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6764     MachineBasicBlock *CurMBB = *I;
6765     if (SeenMBBs.insert(CurMBB))
6766       DispContBB->addSuccessor(CurMBB);
6767   }
6768
6769   // N.B. the order the invoke BBs are processed in doesn't matter here.
6770   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6771   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6772   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6773          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6774     MachineBasicBlock *BB = *I;
6775
6776     // Remove the landing pad successor from the invoke block and replace it
6777     // with the new dispatch block.
6778     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6779                                                   BB->succ_end());
6780     while (!Successors.empty()) {
6781       MachineBasicBlock *SMBB = Successors.pop_back_val();
6782       if (SMBB->isLandingPad()) {
6783         BB->removeSuccessor(SMBB);
6784         MBBLPads.push_back(SMBB);
6785       }
6786     }
6787
6788     BB->addSuccessor(DispatchBB);
6789
6790     // Find the invoke call and mark all of the callee-saved registers as
6791     // 'implicit defined' so that they're spilled. This prevents code from
6792     // moving instructions to before the EH block, where they will never be
6793     // executed.
6794     for (MachineBasicBlock::reverse_iterator
6795            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6796       if (!II->isCall()) continue;
6797
6798       DenseMap<unsigned, bool> DefRegs;
6799       for (MachineInstr::mop_iterator
6800              OI = II->operands_begin(), OE = II->operands_end();
6801            OI != OE; ++OI) {
6802         if (!OI->isReg()) continue;
6803         DefRegs[OI->getReg()] = true;
6804       }
6805
6806       MachineInstrBuilder MIB(*MF, &*II);
6807
6808       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6809         unsigned Reg = SavedRegs[i];
6810         if (Subtarget->isThumb2() &&
6811             !ARM::tGPRRegClass.contains(Reg) &&
6812             !ARM::hGPRRegClass.contains(Reg))
6813           continue;
6814         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6815           continue;
6816         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6817           continue;
6818         if (!DefRegs[Reg])
6819           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6820       }
6821
6822       break;
6823     }
6824   }
6825
6826   // Mark all former landing pads as non-landing pads. The dispatch is the only
6827   // landing pad now.
6828   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6829          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6830     (*I)->setIsLandingPad(false);
6831
6832   // The instruction is gone now.
6833   MI->eraseFromParent();
6834
6835   return MBB;
6836 }
6837
6838 static
6839 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6840   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6841        E = MBB->succ_end(); I != E; ++I)
6842     if (*I != Succ)
6843       return *I;
6844   llvm_unreachable("Expecting a BB with two successors!");
6845 }
6846
6847 MachineBasicBlock *ARMTargetLowering::
6848 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6849   // This pseudo instruction has 3 operands: dst, src, size
6850   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6851   // Otherwise, we will generate unrolled scalar copies.
6852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6853   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6854   MachineFunction::iterator It = BB;
6855   ++It;
6856
6857   unsigned dest = MI->getOperand(0).getReg();
6858   unsigned src = MI->getOperand(1).getReg();
6859   unsigned SizeVal = MI->getOperand(2).getImm();
6860   unsigned Align = MI->getOperand(3).getImm();
6861   DebugLoc dl = MI->getDebugLoc();
6862
6863   bool isThumb2 = Subtarget->isThumb2();
6864   MachineFunction *MF = BB->getParent();
6865   MachineRegisterInfo &MRI = MF->getRegInfo();
6866   unsigned ldrOpc, strOpc, UnitSize = 0;
6867
6868   const TargetRegisterClass *TRC = isThumb2 ?
6869     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6870     (const TargetRegisterClass*)&ARM::GPRRegClass;
6871   const TargetRegisterClass *TRC_Vec = 0;
6872
6873   if (Align & 1) {
6874     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6875     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6876     UnitSize = 1;
6877   } else if (Align & 2) {
6878     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6879     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6880     UnitSize = 2;
6881   } else {
6882     // Check whether we can use NEON instructions.
6883     if (!MF->getFunction()->getAttributes().
6884           hasAttribute(AttributeSet::FunctionIndex,
6885                        Attribute::NoImplicitFloat) &&
6886         Subtarget->hasNEON()) {
6887       if ((Align % 16 == 0) && SizeVal >= 16) {
6888         ldrOpc = ARM::VLD1q32wb_fixed;
6889         strOpc = ARM::VST1q32wb_fixed;
6890         UnitSize = 16;
6891         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6892       }
6893       else if ((Align % 8 == 0) && SizeVal >= 8) {
6894         ldrOpc = ARM::VLD1d32wb_fixed;
6895         strOpc = ARM::VST1d32wb_fixed;
6896         UnitSize = 8;
6897         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6898       }
6899     }
6900     // Can't use NEON instructions.
6901     if (UnitSize == 0) {
6902       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6903       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6904       UnitSize = 4;
6905     }
6906   }
6907
6908   unsigned BytesLeft = SizeVal % UnitSize;
6909   unsigned LoopSize = SizeVal - BytesLeft;
6910
6911   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6912     // Use LDR and STR to copy.
6913     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6914     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6915     unsigned srcIn = src;
6916     unsigned destIn = dest;
6917     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6918       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6919       unsigned srcOut = MRI.createVirtualRegister(TRC);
6920       unsigned destOut = MRI.createVirtualRegister(TRC);
6921       if (UnitSize >= 8) {
6922         AddDefaultPred(BuildMI(*BB, MI, dl,
6923           TII->get(ldrOpc), scratch)
6924           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6925
6926         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6927           .addReg(destIn).addImm(0).addReg(scratch));
6928       } else if (isThumb2) {
6929         AddDefaultPred(BuildMI(*BB, MI, dl,
6930           TII->get(ldrOpc), scratch)
6931           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6932
6933         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6934           .addReg(scratch).addReg(destIn)
6935           .addImm(UnitSize));
6936       } else {
6937         AddDefaultPred(BuildMI(*BB, MI, dl,
6938           TII->get(ldrOpc), scratch)
6939           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6940           .addImm(UnitSize));
6941
6942         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6943           .addReg(scratch).addReg(destIn)
6944           .addReg(0).addImm(UnitSize));
6945       }
6946       srcIn = srcOut;
6947       destIn = destOut;
6948     }
6949
6950     // Handle the leftover bytes with LDRB and STRB.
6951     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6952     // [destOut] = STRB_POST(scratch, destIn, 1)
6953     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6954     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6955     for (unsigned i = 0; i < BytesLeft; i++) {
6956       unsigned scratch = MRI.createVirtualRegister(TRC);
6957       unsigned srcOut = MRI.createVirtualRegister(TRC);
6958       unsigned destOut = MRI.createVirtualRegister(TRC);
6959       if (isThumb2) {
6960         AddDefaultPred(BuildMI(*BB, MI, dl,
6961           TII->get(ldrOpc),scratch)
6962           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6963
6964         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6965           .addReg(scratch).addReg(destIn)
6966           .addReg(0).addImm(1));
6967       } else {
6968         AddDefaultPred(BuildMI(*BB, MI, dl,
6969           TII->get(ldrOpc),scratch)
6970           .addReg(srcOut, RegState::Define).addReg(srcIn)
6971           .addReg(0).addImm(1));
6972
6973         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6974           .addReg(scratch).addReg(destIn)
6975           .addReg(0).addImm(1));
6976       }
6977       srcIn = srcOut;
6978       destIn = destOut;
6979     }
6980     MI->eraseFromParent();   // The instruction is gone now.
6981     return BB;
6982   }
6983
6984   // Expand the pseudo op to a loop.
6985   // thisMBB:
6986   //   ...
6987   //   movw varEnd, # --> with thumb2
6988   //   movt varEnd, #
6989   //   ldrcp varEnd, idx --> without thumb2
6990   //   fallthrough --> loopMBB
6991   // loopMBB:
6992   //   PHI varPhi, varEnd, varLoop
6993   //   PHI srcPhi, src, srcLoop
6994   //   PHI destPhi, dst, destLoop
6995   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6996   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6997   //   subs varLoop, varPhi, #UnitSize
6998   //   bne loopMBB
6999   //   fallthrough --> exitMBB
7000   // exitMBB:
7001   //   epilogue to handle left-over bytes
7002   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7003   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7004   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7005   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7006   MF->insert(It, loopMBB);
7007   MF->insert(It, exitMBB);
7008
7009   // Transfer the remainder of BB and its successor edges to exitMBB.
7010   exitMBB->splice(exitMBB->begin(), BB,
7011                   llvm::next(MachineBasicBlock::iterator(MI)),
7012                   BB->end());
7013   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7014
7015   // Load an immediate to varEnd.
7016   unsigned varEnd = MRI.createVirtualRegister(TRC);
7017   if (isThumb2) {
7018     unsigned VReg1 = varEnd;
7019     if ((LoopSize & 0xFFFF0000) != 0)
7020       VReg1 = MRI.createVirtualRegister(TRC);
7021     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7022                    .addImm(LoopSize & 0xFFFF));
7023
7024     if ((LoopSize & 0xFFFF0000) != 0)
7025       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7026                      .addReg(VReg1)
7027                      .addImm(LoopSize >> 16));
7028   } else {
7029     MachineConstantPool *ConstantPool = MF->getConstantPool();
7030     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7031     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7032
7033     // MachineConstantPool wants an explicit alignment.
7034     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7035     if (Align == 0)
7036       Align = getDataLayout()->getTypeAllocSize(C->getType());
7037     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7038
7039     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7040                    .addReg(varEnd, RegState::Define)
7041                    .addConstantPoolIndex(Idx)
7042                    .addImm(0));
7043   }
7044   BB->addSuccessor(loopMBB);
7045
7046   // Generate the loop body:
7047   //   varPhi = PHI(varLoop, varEnd)
7048   //   srcPhi = PHI(srcLoop, src)
7049   //   destPhi = PHI(destLoop, dst)
7050   MachineBasicBlock *entryBB = BB;
7051   BB = loopMBB;
7052   unsigned varLoop = MRI.createVirtualRegister(TRC);
7053   unsigned varPhi = MRI.createVirtualRegister(TRC);
7054   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7055   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7056   unsigned destLoop = MRI.createVirtualRegister(TRC);
7057   unsigned destPhi = MRI.createVirtualRegister(TRC);
7058
7059   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7060     .addReg(varLoop).addMBB(loopMBB)
7061     .addReg(varEnd).addMBB(entryBB);
7062   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7063     .addReg(srcLoop).addMBB(loopMBB)
7064     .addReg(src).addMBB(entryBB);
7065   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7066     .addReg(destLoop).addMBB(loopMBB)
7067     .addReg(dest).addMBB(entryBB);
7068
7069   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7070   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7071   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7072   if (UnitSize >= 8) {
7073     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7074       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7075
7076     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7077       .addReg(destPhi).addImm(0).addReg(scratch));
7078   } else if (isThumb2) {
7079     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7080       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7081
7082     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7083       .addReg(scratch).addReg(destPhi)
7084       .addImm(UnitSize));
7085   } else {
7086     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7087       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7088       .addImm(UnitSize));
7089
7090     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7091       .addReg(scratch).addReg(destPhi)
7092       .addReg(0).addImm(UnitSize));
7093   }
7094
7095   // Decrement loop variable by UnitSize.
7096   MachineInstrBuilder MIB = BuildMI(BB, dl,
7097     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7098   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7099   MIB->getOperand(5).setReg(ARM::CPSR);
7100   MIB->getOperand(5).setIsDef(true);
7101
7102   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7103     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7104
7105   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7106   BB->addSuccessor(loopMBB);
7107   BB->addSuccessor(exitMBB);
7108
7109   // Add epilogue to handle BytesLeft.
7110   BB = exitMBB;
7111   MachineInstr *StartOfExit = exitMBB->begin();
7112   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7113   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7114
7115   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7116   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7117   unsigned srcIn = srcLoop;
7118   unsigned destIn = destLoop;
7119   for (unsigned i = 0; i < BytesLeft; i++) {
7120     unsigned scratch = MRI.createVirtualRegister(TRC);
7121     unsigned srcOut = MRI.createVirtualRegister(TRC);
7122     unsigned destOut = MRI.createVirtualRegister(TRC);
7123     if (isThumb2) {
7124       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7125         TII->get(ldrOpc),scratch)
7126         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7127
7128       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7129         .addReg(scratch).addReg(destIn)
7130         .addImm(1));
7131     } else {
7132       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7133         TII->get(ldrOpc),scratch)
7134         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7135
7136       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7137         .addReg(scratch).addReg(destIn)
7138         .addReg(0).addImm(1));
7139     }
7140     srcIn = srcOut;
7141     destIn = destOut;
7142   }
7143
7144   MI->eraseFromParent();   // The instruction is gone now.
7145   return BB;
7146 }
7147
7148 MachineBasicBlock *
7149 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7150                                                MachineBasicBlock *BB) const {
7151   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7152   DebugLoc dl = MI->getDebugLoc();
7153   bool isThumb2 = Subtarget->isThumb2();
7154   switch (MI->getOpcode()) {
7155   default: {
7156     MI->dump();
7157     llvm_unreachable("Unexpected instr type to insert");
7158   }
7159   // The Thumb2 pre-indexed stores have the same MI operands, they just
7160   // define them differently in the .td files from the isel patterns, so
7161   // they need pseudos.
7162   case ARM::t2STR_preidx:
7163     MI->setDesc(TII->get(ARM::t2STR_PRE));
7164     return BB;
7165   case ARM::t2STRB_preidx:
7166     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7167     return BB;
7168   case ARM::t2STRH_preidx:
7169     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7170     return BB;
7171
7172   case ARM::STRi_preidx:
7173   case ARM::STRBi_preidx: {
7174     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7175       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7176     // Decode the offset.
7177     unsigned Offset = MI->getOperand(4).getImm();
7178     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7179     Offset = ARM_AM::getAM2Offset(Offset);
7180     if (isSub)
7181       Offset = -Offset;
7182
7183     MachineMemOperand *MMO = *MI->memoperands_begin();
7184     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7185       .addOperand(MI->getOperand(0))  // Rn_wb
7186       .addOperand(MI->getOperand(1))  // Rt
7187       .addOperand(MI->getOperand(2))  // Rn
7188       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7189       .addOperand(MI->getOperand(5))  // pred
7190       .addOperand(MI->getOperand(6))
7191       .addMemOperand(MMO);
7192     MI->eraseFromParent();
7193     return BB;
7194   }
7195   case ARM::STRr_preidx:
7196   case ARM::STRBr_preidx:
7197   case ARM::STRH_preidx: {
7198     unsigned NewOpc;
7199     switch (MI->getOpcode()) {
7200     default: llvm_unreachable("unexpected opcode!");
7201     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7202     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7203     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7204     }
7205     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7206     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7207       MIB.addOperand(MI->getOperand(i));
7208     MI->eraseFromParent();
7209     return BB;
7210   }
7211   case ARM::ATOMIC_LOAD_ADD_I8:
7212      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7213   case ARM::ATOMIC_LOAD_ADD_I16:
7214      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7215   case ARM::ATOMIC_LOAD_ADD_I32:
7216      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7217
7218   case ARM::ATOMIC_LOAD_AND_I8:
7219      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7220   case ARM::ATOMIC_LOAD_AND_I16:
7221      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7222   case ARM::ATOMIC_LOAD_AND_I32:
7223      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7224
7225   case ARM::ATOMIC_LOAD_OR_I8:
7226      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7227   case ARM::ATOMIC_LOAD_OR_I16:
7228      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7229   case ARM::ATOMIC_LOAD_OR_I32:
7230      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7231
7232   case ARM::ATOMIC_LOAD_XOR_I8:
7233      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7234   case ARM::ATOMIC_LOAD_XOR_I16:
7235      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7236   case ARM::ATOMIC_LOAD_XOR_I32:
7237      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7238
7239   case ARM::ATOMIC_LOAD_NAND_I8:
7240      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7241   case ARM::ATOMIC_LOAD_NAND_I16:
7242      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7243   case ARM::ATOMIC_LOAD_NAND_I32:
7244      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7245
7246   case ARM::ATOMIC_LOAD_SUB_I8:
7247      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7248   case ARM::ATOMIC_LOAD_SUB_I16:
7249      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7250   case ARM::ATOMIC_LOAD_SUB_I32:
7251      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7252
7253   case ARM::ATOMIC_LOAD_MIN_I8:
7254      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7255   case ARM::ATOMIC_LOAD_MIN_I16:
7256      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7257   case ARM::ATOMIC_LOAD_MIN_I32:
7258      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7259
7260   case ARM::ATOMIC_LOAD_MAX_I8:
7261      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7262   case ARM::ATOMIC_LOAD_MAX_I16:
7263      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7264   case ARM::ATOMIC_LOAD_MAX_I32:
7265      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7266
7267   case ARM::ATOMIC_LOAD_UMIN_I8:
7268      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7269   case ARM::ATOMIC_LOAD_UMIN_I16:
7270      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7271   case ARM::ATOMIC_LOAD_UMIN_I32:
7272      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7273
7274   case ARM::ATOMIC_LOAD_UMAX_I8:
7275      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7276   case ARM::ATOMIC_LOAD_UMAX_I16:
7277      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7278   case ARM::ATOMIC_LOAD_UMAX_I32:
7279      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7280
7281   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7282   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7283   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7284
7285   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7286   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7287   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7288
7289
7290   case ARM::ATOMADD6432:
7291     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7292                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7293                               /*NeedsCarry*/ true);
7294   case ARM::ATOMSUB6432:
7295     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7296                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7297                               /*NeedsCarry*/ true);
7298   case ARM::ATOMOR6432:
7299     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7300                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7301   case ARM::ATOMXOR6432:
7302     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7303                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7304   case ARM::ATOMAND6432:
7305     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7306                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7307   case ARM::ATOMSWAP6432:
7308     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7309   case ARM::ATOMCMPXCHG6432:
7310     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7311                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7312                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7313   case ARM::ATOMMIN6432:
7314     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7315                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7316                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7317                               /*IsMinMax*/ true, ARMCC::LT);
7318   case ARM::ATOMMAX6432:
7319     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7320                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7321                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7322                               /*IsMinMax*/ true, ARMCC::GE);
7323   case ARM::ATOMUMIN6432:
7324     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7325                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7326                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7327                               /*IsMinMax*/ true, ARMCC::LO);
7328   case ARM::ATOMUMAX6432:
7329     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7330                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7331                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7332                               /*IsMinMax*/ true, ARMCC::HS);
7333
7334   case ARM::tMOVCCr_pseudo: {
7335     // To "insert" a SELECT_CC instruction, we actually have to insert the
7336     // diamond control-flow pattern.  The incoming instruction knows the
7337     // destination vreg to set, the condition code register to branch on, the
7338     // true/false values to select between, and a branch opcode to use.
7339     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7340     MachineFunction::iterator It = BB;
7341     ++It;
7342
7343     //  thisMBB:
7344     //  ...
7345     //   TrueVal = ...
7346     //   cmpTY ccX, r1, r2
7347     //   bCC copy1MBB
7348     //   fallthrough --> copy0MBB
7349     MachineBasicBlock *thisMBB  = BB;
7350     MachineFunction *F = BB->getParent();
7351     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7352     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7353     F->insert(It, copy0MBB);
7354     F->insert(It, sinkMBB);
7355
7356     // Transfer the remainder of BB and its successor edges to sinkMBB.
7357     sinkMBB->splice(sinkMBB->begin(), BB,
7358                     llvm::next(MachineBasicBlock::iterator(MI)),
7359                     BB->end());
7360     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7361
7362     BB->addSuccessor(copy0MBB);
7363     BB->addSuccessor(sinkMBB);
7364
7365     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7366       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7367
7368     //  copy0MBB:
7369     //   %FalseValue = ...
7370     //   # fallthrough to sinkMBB
7371     BB = copy0MBB;
7372
7373     // Update machine-CFG edges
7374     BB->addSuccessor(sinkMBB);
7375
7376     //  sinkMBB:
7377     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7378     //  ...
7379     BB = sinkMBB;
7380     BuildMI(*BB, BB->begin(), dl,
7381             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7382       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7383       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7384
7385     MI->eraseFromParent();   // The pseudo instruction is gone now.
7386     return BB;
7387   }
7388
7389   case ARM::BCCi64:
7390   case ARM::BCCZi64: {
7391     // If there is an unconditional branch to the other successor, remove it.
7392     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7393
7394     // Compare both parts that make up the double comparison separately for
7395     // equality.
7396     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7397
7398     unsigned LHS1 = MI->getOperand(1).getReg();
7399     unsigned LHS2 = MI->getOperand(2).getReg();
7400     if (RHSisZero) {
7401       AddDefaultPred(BuildMI(BB, dl,
7402                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7403                      .addReg(LHS1).addImm(0));
7404       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7405         .addReg(LHS2).addImm(0)
7406         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7407     } else {
7408       unsigned RHS1 = MI->getOperand(3).getReg();
7409       unsigned RHS2 = MI->getOperand(4).getReg();
7410       AddDefaultPred(BuildMI(BB, dl,
7411                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7412                      .addReg(LHS1).addReg(RHS1));
7413       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7414         .addReg(LHS2).addReg(RHS2)
7415         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7416     }
7417
7418     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7419     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7420     if (MI->getOperand(0).getImm() == ARMCC::NE)
7421       std::swap(destMBB, exitMBB);
7422
7423     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7424       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7425     if (isThumb2)
7426       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7427     else
7428       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7429
7430     MI->eraseFromParent();   // The pseudo instruction is gone now.
7431     return BB;
7432   }
7433
7434   case ARM::Int_eh_sjlj_setjmp:
7435   case ARM::Int_eh_sjlj_setjmp_nofp:
7436   case ARM::tInt_eh_sjlj_setjmp:
7437   case ARM::t2Int_eh_sjlj_setjmp:
7438   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7439     EmitSjLjDispatchBlock(MI, BB);
7440     return BB;
7441
7442   case ARM::ABS:
7443   case ARM::t2ABS: {
7444     // To insert an ABS instruction, we have to insert the
7445     // diamond control-flow pattern.  The incoming instruction knows the
7446     // source vreg to test against 0, the destination vreg to set,
7447     // the condition code register to branch on, the
7448     // true/false values to select between, and a branch opcode to use.
7449     // It transforms
7450     //     V1 = ABS V0
7451     // into
7452     //     V2 = MOVS V0
7453     //     BCC                      (branch to SinkBB if V0 >= 0)
7454     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7455     //     SinkBB: V1 = PHI(V2, V3)
7456     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7457     MachineFunction::iterator BBI = BB;
7458     ++BBI;
7459     MachineFunction *Fn = BB->getParent();
7460     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7461     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7462     Fn->insert(BBI, RSBBB);
7463     Fn->insert(BBI, SinkBB);
7464
7465     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7466     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7467     bool isThumb2 = Subtarget->isThumb2();
7468     MachineRegisterInfo &MRI = Fn->getRegInfo();
7469     // In Thumb mode S must not be specified if source register is the SP or
7470     // PC and if destination register is the SP, so restrict register class
7471     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7472       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7473       (const TargetRegisterClass*)&ARM::GPRRegClass);
7474
7475     // Transfer the remainder of BB and its successor edges to sinkMBB.
7476     SinkBB->splice(SinkBB->begin(), BB,
7477       llvm::next(MachineBasicBlock::iterator(MI)),
7478       BB->end());
7479     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7480
7481     BB->addSuccessor(RSBBB);
7482     BB->addSuccessor(SinkBB);
7483
7484     // fall through to SinkMBB
7485     RSBBB->addSuccessor(SinkBB);
7486
7487     // insert a cmp at the end of BB
7488     AddDefaultPred(BuildMI(BB, dl,
7489                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7490                    .addReg(ABSSrcReg).addImm(0));
7491
7492     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7493     BuildMI(BB, dl,
7494       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7495       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7496
7497     // insert rsbri in RSBBB
7498     // Note: BCC and rsbri will be converted into predicated rsbmi
7499     // by if-conversion pass
7500     BuildMI(*RSBBB, RSBBB->begin(), dl,
7501       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7502       .addReg(ABSSrcReg, RegState::Kill)
7503       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7504
7505     // insert PHI in SinkBB,
7506     // reuse ABSDstReg to not change uses of ABS instruction
7507     BuildMI(*SinkBB, SinkBB->begin(), dl,
7508       TII->get(ARM::PHI), ABSDstReg)
7509       .addReg(NewRsbDstReg).addMBB(RSBBB)
7510       .addReg(ABSSrcReg).addMBB(BB);
7511
7512     // remove ABS instruction
7513     MI->eraseFromParent();
7514
7515     // return last added BB
7516     return SinkBB;
7517   }
7518   case ARM::COPY_STRUCT_BYVAL_I32:
7519     ++NumLoopByVals;
7520     return EmitStructByval(MI, BB);
7521   }
7522 }
7523
7524 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7525                                                       SDNode *Node) const {
7526   if (!MI->hasPostISelHook()) {
7527     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7528            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7529     return;
7530   }
7531
7532   const MCInstrDesc *MCID = &MI->getDesc();
7533   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7534   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7535   // operand is still set to noreg. If needed, set the optional operand's
7536   // register to CPSR, and remove the redundant implicit def.
7537   //
7538   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7539
7540   // Rename pseudo opcodes.
7541   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7542   if (NewOpc) {
7543     const ARMBaseInstrInfo *TII =
7544       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7545     MCID = &TII->get(NewOpc);
7546
7547     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7548            "converted opcode should be the same except for cc_out");
7549
7550     MI->setDesc(*MCID);
7551
7552     // Add the optional cc_out operand
7553     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7554   }
7555   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7556
7557   // Any ARM instruction that sets the 's' bit should specify an optional
7558   // "cc_out" operand in the last operand position.
7559   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7560     assert(!NewOpc && "Optional cc_out operand required");
7561     return;
7562   }
7563   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7564   // since we already have an optional CPSR def.
7565   bool definesCPSR = false;
7566   bool deadCPSR = false;
7567   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7568        i != e; ++i) {
7569     const MachineOperand &MO = MI->getOperand(i);
7570     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7571       definesCPSR = true;
7572       if (MO.isDead())
7573         deadCPSR = true;
7574       MI->RemoveOperand(i);
7575       break;
7576     }
7577   }
7578   if (!definesCPSR) {
7579     assert(!NewOpc && "Optional cc_out operand required");
7580     return;
7581   }
7582   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7583   if (deadCPSR) {
7584     assert(!MI->getOperand(ccOutIdx).getReg() &&
7585            "expect uninitialized optional cc_out operand");
7586     return;
7587   }
7588
7589   // If this instruction was defined with an optional CPSR def and its dag node
7590   // had a live implicit CPSR def, then activate the optional CPSR def.
7591   MachineOperand &MO = MI->getOperand(ccOutIdx);
7592   MO.setReg(ARM::CPSR);
7593   MO.setIsDef(true);
7594 }
7595
7596 //===----------------------------------------------------------------------===//
7597 //                           ARM Optimization Hooks
7598 //===----------------------------------------------------------------------===//
7599
7600 // Helper function that checks if N is a null or all ones constant.
7601 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7602   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7603   if (!C)
7604     return false;
7605   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7606 }
7607
7608 // Return true if N is conditionally 0 or all ones.
7609 // Detects these expressions where cc is an i1 value:
7610 //
7611 //   (select cc 0, y)   [AllOnes=0]
7612 //   (select cc y, 0)   [AllOnes=0]
7613 //   (zext cc)          [AllOnes=0]
7614 //   (sext cc)          [AllOnes=0/1]
7615 //   (select cc -1, y)  [AllOnes=1]
7616 //   (select cc y, -1)  [AllOnes=1]
7617 //
7618 // Invert is set when N is the null/all ones constant when CC is false.
7619 // OtherOp is set to the alternative value of N.
7620 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7621                                        SDValue &CC, bool &Invert,
7622                                        SDValue &OtherOp,
7623                                        SelectionDAG &DAG) {
7624   switch (N->getOpcode()) {
7625   default: return false;
7626   case ISD::SELECT: {
7627     CC = N->getOperand(0);
7628     SDValue N1 = N->getOperand(1);
7629     SDValue N2 = N->getOperand(2);
7630     if (isZeroOrAllOnes(N1, AllOnes)) {
7631       Invert = false;
7632       OtherOp = N2;
7633       return true;
7634     }
7635     if (isZeroOrAllOnes(N2, AllOnes)) {
7636       Invert = true;
7637       OtherOp = N1;
7638       return true;
7639     }
7640     return false;
7641   }
7642   case ISD::ZERO_EXTEND:
7643     // (zext cc) can never be the all ones value.
7644     if (AllOnes)
7645       return false;
7646     // Fall through.
7647   case ISD::SIGN_EXTEND: {
7648     EVT VT = N->getValueType(0);
7649     CC = N->getOperand(0);
7650     if (CC.getValueType() != MVT::i1)
7651       return false;
7652     Invert = !AllOnes;
7653     if (AllOnes)
7654       // When looking for an AllOnes constant, N is an sext, and the 'other'
7655       // value is 0.
7656       OtherOp = DAG.getConstant(0, VT);
7657     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7658       // When looking for a 0 constant, N can be zext or sext.
7659       OtherOp = DAG.getConstant(1, VT);
7660     else
7661       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7662     return true;
7663   }
7664   }
7665 }
7666
7667 // Combine a constant select operand into its use:
7668 //
7669 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7670 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7671 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7672 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7673 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7674 //
7675 // The transform is rejected if the select doesn't have a constant operand that
7676 // is null, or all ones when AllOnes is set.
7677 //
7678 // Also recognize sext/zext from i1:
7679 //
7680 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7681 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7682 //
7683 // These transformations eventually create predicated instructions.
7684 //
7685 // @param N       The node to transform.
7686 // @param Slct    The N operand that is a select.
7687 // @param OtherOp The other N operand (x above).
7688 // @param DCI     Context.
7689 // @param AllOnes Require the select constant to be all ones instead of null.
7690 // @returns The new node, or SDValue() on failure.
7691 static
7692 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7693                             TargetLowering::DAGCombinerInfo &DCI,
7694                             bool AllOnes = false) {
7695   SelectionDAG &DAG = DCI.DAG;
7696   EVT VT = N->getValueType(0);
7697   SDValue NonConstantVal;
7698   SDValue CCOp;
7699   bool SwapSelectOps;
7700   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7701                                   NonConstantVal, DAG))
7702     return SDValue();
7703
7704   // Slct is now know to be the desired identity constant when CC is true.
7705   SDValue TrueVal = OtherOp;
7706   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7707                                  OtherOp, NonConstantVal);
7708   // Unless SwapSelectOps says CC should be false.
7709   if (SwapSelectOps)
7710     std::swap(TrueVal, FalseVal);
7711
7712   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7713                      CCOp, TrueVal, FalseVal);
7714 }
7715
7716 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7717 static
7718 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7719                                        TargetLowering::DAGCombinerInfo &DCI) {
7720   SDValue N0 = N->getOperand(0);
7721   SDValue N1 = N->getOperand(1);
7722   if (N0.getNode()->hasOneUse()) {
7723     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7724     if (Result.getNode())
7725       return Result;
7726   }
7727   if (N1.getNode()->hasOneUse()) {
7728     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7729     if (Result.getNode())
7730       return Result;
7731   }
7732   return SDValue();
7733 }
7734
7735 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7736 // (only after legalization).
7737 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7738                                  TargetLowering::DAGCombinerInfo &DCI,
7739                                  const ARMSubtarget *Subtarget) {
7740
7741   // Only perform optimization if after legalize, and if NEON is available. We
7742   // also expected both operands to be BUILD_VECTORs.
7743   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7744       || N0.getOpcode() != ISD::BUILD_VECTOR
7745       || N1.getOpcode() != ISD::BUILD_VECTOR)
7746     return SDValue();
7747
7748   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7749   EVT VT = N->getValueType(0);
7750   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7751     return SDValue();
7752
7753   // Check that the vector operands are of the right form.
7754   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7755   // operands, where N is the size of the formed vector.
7756   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7757   // index such that we have a pair wise add pattern.
7758
7759   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7760   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7761     return SDValue();
7762   SDValue Vec = N0->getOperand(0)->getOperand(0);
7763   SDNode *V = Vec.getNode();
7764   unsigned nextIndex = 0;
7765
7766   // For each operands to the ADD which are BUILD_VECTORs,
7767   // check to see if each of their operands are an EXTRACT_VECTOR with
7768   // the same vector and appropriate index.
7769   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7770     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7771         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7772
7773       SDValue ExtVec0 = N0->getOperand(i);
7774       SDValue ExtVec1 = N1->getOperand(i);
7775
7776       // First operand is the vector, verify its the same.
7777       if (V != ExtVec0->getOperand(0).getNode() ||
7778           V != ExtVec1->getOperand(0).getNode())
7779         return SDValue();
7780
7781       // Second is the constant, verify its correct.
7782       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7783       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7784
7785       // For the constant, we want to see all the even or all the odd.
7786       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7787           || C1->getZExtValue() != nextIndex+1)
7788         return SDValue();
7789
7790       // Increment index.
7791       nextIndex+=2;
7792     } else
7793       return SDValue();
7794   }
7795
7796   // Create VPADDL node.
7797   SelectionDAG &DAG = DCI.DAG;
7798   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7799
7800   // Build operand list.
7801   SmallVector<SDValue, 8> Ops;
7802   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7803                                 TLI.getPointerTy()));
7804
7805   // Input is the vector.
7806   Ops.push_back(Vec);
7807
7808   // Get widened type and narrowed type.
7809   MVT widenType;
7810   unsigned numElem = VT.getVectorNumElements();
7811   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7812     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7813     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7814     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7815     default:
7816       llvm_unreachable("Invalid vector element type for padd optimization.");
7817   }
7818
7819   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7820                             widenType, &Ops[0], Ops.size());
7821   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7822 }
7823
7824 static SDValue findMUL_LOHI(SDValue V) {
7825   if (V->getOpcode() == ISD::UMUL_LOHI ||
7826       V->getOpcode() == ISD::SMUL_LOHI)
7827     return V;
7828   return SDValue();
7829 }
7830
7831 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7832                                      TargetLowering::DAGCombinerInfo &DCI,
7833                                      const ARMSubtarget *Subtarget) {
7834
7835   if (Subtarget->isThumb1Only()) return SDValue();
7836
7837   // Only perform the checks after legalize when the pattern is available.
7838   if (DCI.isBeforeLegalize()) return SDValue();
7839
7840   // Look for multiply add opportunities.
7841   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7842   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7843   // a glue link from the first add to the second add.
7844   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7845   // a S/UMLAL instruction.
7846   //          loAdd   UMUL_LOHI
7847   //            \    / :lo    \ :hi
7848   //             \  /          \          [no multiline comment]
7849   //              ADDC         |  hiAdd
7850   //                 \ :glue  /  /
7851   //                  \      /  /
7852   //                    ADDE
7853   //
7854   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7855   SDValue AddcOp0 = AddcNode->getOperand(0);
7856   SDValue AddcOp1 = AddcNode->getOperand(1);
7857
7858   // Check if the two operands are from the same mul_lohi node.
7859   if (AddcOp0.getNode() == AddcOp1.getNode())
7860     return SDValue();
7861
7862   assert(AddcNode->getNumValues() == 2 &&
7863          AddcNode->getValueType(0) == MVT::i32 &&
7864          AddcNode->getValueType(1) == MVT::Glue &&
7865          "Expect ADDC with two result values: i32, glue");
7866
7867   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7868   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7869       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7870       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7871       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7872     return SDValue();
7873
7874   // Look for the glued ADDE.
7875   SDNode* AddeNode = AddcNode->getGluedUser();
7876   if (AddeNode == NULL)
7877     return SDValue();
7878
7879   // Make sure it is really an ADDE.
7880   if (AddeNode->getOpcode() != ISD::ADDE)
7881     return SDValue();
7882
7883   assert(AddeNode->getNumOperands() == 3 &&
7884          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7885          "ADDE node has the wrong inputs");
7886
7887   // Check for the triangle shape.
7888   SDValue AddeOp0 = AddeNode->getOperand(0);
7889   SDValue AddeOp1 = AddeNode->getOperand(1);
7890
7891   // Make sure that the ADDE operands are not coming from the same node.
7892   if (AddeOp0.getNode() == AddeOp1.getNode())
7893     return SDValue();
7894
7895   // Find the MUL_LOHI node walking up ADDE's operands.
7896   bool IsLeftOperandMUL = false;
7897   SDValue MULOp = findMUL_LOHI(AddeOp0);
7898   if (MULOp == SDValue())
7899    MULOp = findMUL_LOHI(AddeOp1);
7900   else
7901     IsLeftOperandMUL = true;
7902   if (MULOp == SDValue())
7903      return SDValue();
7904
7905   // Figure out the right opcode.
7906   unsigned Opc = MULOp->getOpcode();
7907   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7908
7909   // Figure out the high and low input values to the MLAL node.
7910   SDValue* HiMul = &MULOp;
7911   SDValue* HiAdd = NULL;
7912   SDValue* LoMul = NULL;
7913   SDValue* LowAdd = NULL;
7914
7915   if (IsLeftOperandMUL)
7916     HiAdd = &AddeOp1;
7917   else
7918     HiAdd = &AddeOp0;
7919
7920
7921   if (AddcOp0->getOpcode() == Opc) {
7922     LoMul = &AddcOp0;
7923     LowAdd = &AddcOp1;
7924   }
7925   if (AddcOp1->getOpcode() == Opc) {
7926     LoMul = &AddcOp1;
7927     LowAdd = &AddcOp0;
7928   }
7929
7930   if (LoMul == NULL)
7931     return SDValue();
7932
7933   if (LoMul->getNode() != HiMul->getNode())
7934     return SDValue();
7935
7936   // Create the merged node.
7937   SelectionDAG &DAG = DCI.DAG;
7938
7939   // Build operand list.
7940   SmallVector<SDValue, 8> Ops;
7941   Ops.push_back(LoMul->getOperand(0));
7942   Ops.push_back(LoMul->getOperand(1));
7943   Ops.push_back(*LowAdd);
7944   Ops.push_back(*HiAdd);
7945
7946   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7947                                  DAG.getVTList(MVT::i32, MVT::i32),
7948                                  &Ops[0], Ops.size());
7949
7950   // Replace the ADDs' nodes uses by the MLA node's values.
7951   SDValue HiMLALResult(MLALNode.getNode(), 1);
7952   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7953
7954   SDValue LoMLALResult(MLALNode.getNode(), 0);
7955   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7956
7957   // Return original node to notify the driver to stop replacing.
7958   SDValue resNode(AddcNode, 0);
7959   return resNode;
7960 }
7961
7962 /// PerformADDCCombine - Target-specific dag combine transform from
7963 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7964 static SDValue PerformADDCCombine(SDNode *N,
7965                                  TargetLowering::DAGCombinerInfo &DCI,
7966                                  const ARMSubtarget *Subtarget) {
7967
7968   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7969
7970 }
7971
7972 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7973 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7974 /// called with the default operands, and if that fails, with commuted
7975 /// operands.
7976 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7977                                           TargetLowering::DAGCombinerInfo &DCI,
7978                                           const ARMSubtarget *Subtarget){
7979
7980   // Attempt to create vpaddl for this add.
7981   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7982   if (Result.getNode())
7983     return Result;
7984
7985   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7986   if (N0.getNode()->hasOneUse()) {
7987     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7988     if (Result.getNode()) return Result;
7989   }
7990   return SDValue();
7991 }
7992
7993 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7994 ///
7995 static SDValue PerformADDCombine(SDNode *N,
7996                                  TargetLowering::DAGCombinerInfo &DCI,
7997                                  const ARMSubtarget *Subtarget) {
7998   SDValue N0 = N->getOperand(0);
7999   SDValue N1 = N->getOperand(1);
8000
8001   // First try with the default operand order.
8002   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8003   if (Result.getNode())
8004     return Result;
8005
8006   // If that didn't work, try again with the operands commuted.
8007   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8008 }
8009
8010 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8011 ///
8012 static SDValue PerformSUBCombine(SDNode *N,
8013                                  TargetLowering::DAGCombinerInfo &DCI) {
8014   SDValue N0 = N->getOperand(0);
8015   SDValue N1 = N->getOperand(1);
8016
8017   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8018   if (N1.getNode()->hasOneUse()) {
8019     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8020     if (Result.getNode()) return Result;
8021   }
8022
8023   return SDValue();
8024 }
8025
8026 /// PerformVMULCombine
8027 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8028 /// special multiplier accumulator forwarding.
8029 ///   vmul d3, d0, d2
8030 ///   vmla d3, d1, d2
8031 /// is faster than
8032 ///   vadd d3, d0, d1
8033 ///   vmul d3, d3, d2
8034 static SDValue PerformVMULCombine(SDNode *N,
8035                                   TargetLowering::DAGCombinerInfo &DCI,
8036                                   const ARMSubtarget *Subtarget) {
8037   if (!Subtarget->hasVMLxForwarding())
8038     return SDValue();
8039
8040   SelectionDAG &DAG = DCI.DAG;
8041   SDValue N0 = N->getOperand(0);
8042   SDValue N1 = N->getOperand(1);
8043   unsigned Opcode = N0.getOpcode();
8044   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8045       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8046     Opcode = N1.getOpcode();
8047     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8048         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8049       return SDValue();
8050     std::swap(N0, N1);
8051   }
8052
8053   EVT VT = N->getValueType(0);
8054   DebugLoc DL = N->getDebugLoc();
8055   SDValue N00 = N0->getOperand(0);
8056   SDValue N01 = N0->getOperand(1);
8057   return DAG.getNode(Opcode, DL, VT,
8058                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8059                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8060 }
8061
8062 static SDValue PerformMULCombine(SDNode *N,
8063                                  TargetLowering::DAGCombinerInfo &DCI,
8064                                  const ARMSubtarget *Subtarget) {
8065   SelectionDAG &DAG = DCI.DAG;
8066
8067   if (Subtarget->isThumb1Only())
8068     return SDValue();
8069
8070   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8071     return SDValue();
8072
8073   EVT VT = N->getValueType(0);
8074   if (VT.is64BitVector() || VT.is128BitVector())
8075     return PerformVMULCombine(N, DCI, Subtarget);
8076   if (VT != MVT::i32)
8077     return SDValue();
8078
8079   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8080   if (!C)
8081     return SDValue();
8082
8083   int64_t MulAmt = C->getSExtValue();
8084   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
8085
8086   ShiftAmt = ShiftAmt & (32 - 1);
8087   SDValue V = N->getOperand(0);
8088   DebugLoc DL = N->getDebugLoc();
8089
8090   SDValue Res;
8091   MulAmt >>= ShiftAmt;
8092
8093   if (MulAmt >= 0) {
8094     if (isPowerOf2_32(MulAmt - 1)) {
8095       // (mul x, 2^N + 1) => (add (shl x, N), x)
8096       Res = DAG.getNode(ISD::ADD, DL, VT,
8097                         V,
8098                         DAG.getNode(ISD::SHL, DL, VT,
8099                                     V,
8100                                     DAG.getConstant(Log2_32(MulAmt - 1),
8101                                                     MVT::i32)));
8102     } else if (isPowerOf2_32(MulAmt + 1)) {
8103       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8104       Res = DAG.getNode(ISD::SUB, DL, VT,
8105                         DAG.getNode(ISD::SHL, DL, VT,
8106                                     V,
8107                                     DAG.getConstant(Log2_32(MulAmt + 1),
8108                                                     MVT::i32)),
8109                         V);
8110     } else
8111       return SDValue();
8112   } else {
8113     uint64_t MulAmtAbs = -MulAmt;
8114     if (isPowerOf2_32(MulAmtAbs + 1)) {
8115       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8116       Res = DAG.getNode(ISD::SUB, DL, VT,
8117                         V,
8118                         DAG.getNode(ISD::SHL, DL, VT,
8119                                     V,
8120                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8121                                                     MVT::i32)));
8122     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8123       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8124       Res = DAG.getNode(ISD::ADD, DL, VT,
8125                         V,
8126                         DAG.getNode(ISD::SHL, DL, VT,
8127                                     V,
8128                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8129                                                     MVT::i32)));
8130       Res = DAG.getNode(ISD::SUB, DL, VT,
8131                         DAG.getConstant(0, MVT::i32),Res);
8132
8133     } else
8134       return SDValue();
8135   }
8136
8137   if (ShiftAmt != 0)
8138     Res = DAG.getNode(ISD::SHL, DL, VT,
8139                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8140
8141   // Do not add new nodes to DAG combiner worklist.
8142   DCI.CombineTo(N, Res, false);
8143   return SDValue();
8144 }
8145
8146 static SDValue PerformANDCombine(SDNode *N,
8147                                  TargetLowering::DAGCombinerInfo &DCI,
8148                                  const ARMSubtarget *Subtarget) {
8149
8150   // Attempt to use immediate-form VBIC
8151   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8152   DebugLoc dl = N->getDebugLoc();
8153   EVT VT = N->getValueType(0);
8154   SelectionDAG &DAG = DCI.DAG;
8155
8156   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8157     return SDValue();
8158
8159   APInt SplatBits, SplatUndef;
8160   unsigned SplatBitSize;
8161   bool HasAnyUndefs;
8162   if (BVN &&
8163       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8164     if (SplatBitSize <= 64) {
8165       EVT VbicVT;
8166       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8167                                       SplatUndef.getZExtValue(), SplatBitSize,
8168                                       DAG, VbicVT, VT.is128BitVector(),
8169                                       OtherModImm);
8170       if (Val.getNode()) {
8171         SDValue Input =
8172           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8173         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8174         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8175       }
8176     }
8177   }
8178
8179   if (!Subtarget->isThumb1Only()) {
8180     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8181     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8182     if (Result.getNode())
8183       return Result;
8184   }
8185
8186   return SDValue();
8187 }
8188
8189 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8190 static SDValue PerformORCombine(SDNode *N,
8191                                 TargetLowering::DAGCombinerInfo &DCI,
8192                                 const ARMSubtarget *Subtarget) {
8193   // Attempt to use immediate-form VORR
8194   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8195   DebugLoc dl = N->getDebugLoc();
8196   EVT VT = N->getValueType(0);
8197   SelectionDAG &DAG = DCI.DAG;
8198
8199   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8200     return SDValue();
8201
8202   APInt SplatBits, SplatUndef;
8203   unsigned SplatBitSize;
8204   bool HasAnyUndefs;
8205   if (BVN && Subtarget->hasNEON() &&
8206       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8207     if (SplatBitSize <= 64) {
8208       EVT VorrVT;
8209       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8210                                       SplatUndef.getZExtValue(), SplatBitSize,
8211                                       DAG, VorrVT, VT.is128BitVector(),
8212                                       OtherModImm);
8213       if (Val.getNode()) {
8214         SDValue Input =
8215           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8216         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8217         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8218       }
8219     }
8220   }
8221
8222   if (!Subtarget->isThumb1Only()) {
8223     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8224     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8225     if (Result.getNode())
8226       return Result;
8227   }
8228
8229   // The code below optimizes (or (and X, Y), Z).
8230   // The AND operand needs to have a single user to make these optimizations
8231   // profitable.
8232   SDValue N0 = N->getOperand(0);
8233   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8234     return SDValue();
8235   SDValue N1 = N->getOperand(1);
8236
8237   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8238   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8239       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8240     APInt SplatUndef;
8241     unsigned SplatBitSize;
8242     bool HasAnyUndefs;
8243
8244     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8245     APInt SplatBits0;
8246     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8247                                   HasAnyUndefs) && !HasAnyUndefs) {
8248       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8249       APInt SplatBits1;
8250       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8251                                     HasAnyUndefs) && !HasAnyUndefs &&
8252           SplatBits0 == ~SplatBits1) {
8253         // Canonicalize the vector type to make instruction selection simpler.
8254         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8255         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8256                                      N0->getOperand(1), N0->getOperand(0),
8257                                      N1->getOperand(0));
8258         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8259       }
8260     }
8261   }
8262
8263   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8264   // reasonable.
8265
8266   // BFI is only available on V6T2+
8267   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8268     return SDValue();
8269
8270   DebugLoc DL = N->getDebugLoc();
8271   // 1) or (and A, mask), val => ARMbfi A, val, mask
8272   //      iff (val & mask) == val
8273   //
8274   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8275   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8276   //          && mask == ~mask2
8277   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8278   //          && ~mask == mask2
8279   //  (i.e., copy a bitfield value into another bitfield of the same width)
8280
8281   if (VT != MVT::i32)
8282     return SDValue();
8283
8284   SDValue N00 = N0.getOperand(0);
8285
8286   // The value and the mask need to be constants so we can verify this is
8287   // actually a bitfield set. If the mask is 0xffff, we can do better
8288   // via a movt instruction, so don't use BFI in that case.
8289   SDValue MaskOp = N0.getOperand(1);
8290   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8291   if (!MaskC)
8292     return SDValue();
8293   unsigned Mask = MaskC->getZExtValue();
8294   if (Mask == 0xffff)
8295     return SDValue();
8296   SDValue Res;
8297   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8298   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8299   if (N1C) {
8300     unsigned Val = N1C->getZExtValue();
8301     if ((Val & ~Mask) != Val)
8302       return SDValue();
8303
8304     if (ARM::isBitFieldInvertedMask(Mask)) {
8305       Val >>= CountTrailingZeros_32(~Mask);
8306
8307       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8308                         DAG.getConstant(Val, MVT::i32),
8309                         DAG.getConstant(Mask, MVT::i32));
8310
8311       // Do not add new nodes to DAG combiner worklist.
8312       DCI.CombineTo(N, Res, false);
8313       return SDValue();
8314     }
8315   } else if (N1.getOpcode() == ISD::AND) {
8316     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8317     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8318     if (!N11C)
8319       return SDValue();
8320     unsigned Mask2 = N11C->getZExtValue();
8321
8322     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8323     // as is to match.
8324     if (ARM::isBitFieldInvertedMask(Mask) &&
8325         (Mask == ~Mask2)) {
8326       // The pack halfword instruction works better for masks that fit it,
8327       // so use that when it's available.
8328       if (Subtarget->hasT2ExtractPack() &&
8329           (Mask == 0xffff || Mask == 0xffff0000))
8330         return SDValue();
8331       // 2a
8332       unsigned amt = CountTrailingZeros_32(Mask2);
8333       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8334                         DAG.getConstant(amt, MVT::i32));
8335       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8336                         DAG.getConstant(Mask, MVT::i32));
8337       // Do not add new nodes to DAG combiner worklist.
8338       DCI.CombineTo(N, Res, false);
8339       return SDValue();
8340     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8341                (~Mask == Mask2)) {
8342       // The pack halfword instruction works better for masks that fit it,
8343       // so use that when it's available.
8344       if (Subtarget->hasT2ExtractPack() &&
8345           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8346         return SDValue();
8347       // 2b
8348       unsigned lsb = CountTrailingZeros_32(Mask);
8349       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8350                         DAG.getConstant(lsb, MVT::i32));
8351       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8352                         DAG.getConstant(Mask2, MVT::i32));
8353       // Do not add new nodes to DAG combiner worklist.
8354       DCI.CombineTo(N, Res, false);
8355       return SDValue();
8356     }
8357   }
8358
8359   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8360       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8361       ARM::isBitFieldInvertedMask(~Mask)) {
8362     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8363     // where lsb(mask) == #shamt and masked bits of B are known zero.
8364     SDValue ShAmt = N00.getOperand(1);
8365     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8366     unsigned LSB = CountTrailingZeros_32(Mask);
8367     if (ShAmtC != LSB)
8368       return SDValue();
8369
8370     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8371                       DAG.getConstant(~Mask, MVT::i32));
8372
8373     // Do not add new nodes to DAG combiner worklist.
8374     DCI.CombineTo(N, Res, false);
8375   }
8376
8377   return SDValue();
8378 }
8379
8380 static SDValue PerformXORCombine(SDNode *N,
8381                                  TargetLowering::DAGCombinerInfo &DCI,
8382                                  const ARMSubtarget *Subtarget) {
8383   EVT VT = N->getValueType(0);
8384   SelectionDAG &DAG = DCI.DAG;
8385
8386   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8387     return SDValue();
8388
8389   if (!Subtarget->isThumb1Only()) {
8390     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8391     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8392     if (Result.getNode())
8393       return Result;
8394   }
8395
8396   return SDValue();
8397 }
8398
8399 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8400 /// the bits being cleared by the AND are not demanded by the BFI.
8401 static SDValue PerformBFICombine(SDNode *N,
8402                                  TargetLowering::DAGCombinerInfo &DCI) {
8403   SDValue N1 = N->getOperand(1);
8404   if (N1.getOpcode() == ISD::AND) {
8405     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8406     if (!N11C)
8407       return SDValue();
8408     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8409     unsigned LSB = CountTrailingZeros_32(~InvMask);
8410     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8411     unsigned Mask = (1 << Width)-1;
8412     unsigned Mask2 = N11C->getZExtValue();
8413     if ((Mask & (~Mask2)) == 0)
8414       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8415                              N->getOperand(0), N1.getOperand(0),
8416                              N->getOperand(2));
8417   }
8418   return SDValue();
8419 }
8420
8421 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8422 /// ARMISD::VMOVRRD.
8423 static SDValue PerformVMOVRRDCombine(SDNode *N,
8424                                      TargetLowering::DAGCombinerInfo &DCI) {
8425   // vmovrrd(vmovdrr x, y) -> x,y
8426   SDValue InDouble = N->getOperand(0);
8427   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8428     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8429
8430   // vmovrrd(load f64) -> (load i32), (load i32)
8431   SDNode *InNode = InDouble.getNode();
8432   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8433       InNode->getValueType(0) == MVT::f64 &&
8434       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8435       !cast<LoadSDNode>(InNode)->isVolatile()) {
8436     // TODO: Should this be done for non-FrameIndex operands?
8437     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8438
8439     SelectionDAG &DAG = DCI.DAG;
8440     DebugLoc DL = LD->getDebugLoc();
8441     SDValue BasePtr = LD->getBasePtr();
8442     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8443                                  LD->getPointerInfo(), LD->isVolatile(),
8444                                  LD->isNonTemporal(), LD->isInvariant(),
8445                                  LD->getAlignment());
8446
8447     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8448                                     DAG.getConstant(4, MVT::i32));
8449     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8450                                  LD->getPointerInfo(), LD->isVolatile(),
8451                                  LD->isNonTemporal(), LD->isInvariant(),
8452                                  std::min(4U, LD->getAlignment() / 2));
8453
8454     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8455     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8456     DCI.RemoveFromWorklist(LD);
8457     DAG.DeleteNode(LD);
8458     return Result;
8459   }
8460
8461   return SDValue();
8462 }
8463
8464 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8465 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8466 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8467   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8468   SDValue Op0 = N->getOperand(0);
8469   SDValue Op1 = N->getOperand(1);
8470   if (Op0.getOpcode() == ISD::BITCAST)
8471     Op0 = Op0.getOperand(0);
8472   if (Op1.getOpcode() == ISD::BITCAST)
8473     Op1 = Op1.getOperand(0);
8474   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8475       Op0.getNode() == Op1.getNode() &&
8476       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8477     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8478                        N->getValueType(0), Op0.getOperand(0));
8479   return SDValue();
8480 }
8481
8482 /// PerformSTORECombine - Target-specific dag combine xforms for
8483 /// ISD::STORE.
8484 static SDValue PerformSTORECombine(SDNode *N,
8485                                    TargetLowering::DAGCombinerInfo &DCI) {
8486   StoreSDNode *St = cast<StoreSDNode>(N);
8487   if (St->isVolatile())
8488     return SDValue();
8489
8490   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8491   // pack all of the elements in one place.  Next, store to memory in fewer
8492   // chunks.
8493   SDValue StVal = St->getValue();
8494   EVT VT = StVal.getValueType();
8495   if (St->isTruncatingStore() && VT.isVector()) {
8496     SelectionDAG &DAG = DCI.DAG;
8497     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8498     EVT StVT = St->getMemoryVT();
8499     unsigned NumElems = VT.getVectorNumElements();
8500     assert(StVT != VT && "Cannot truncate to the same type");
8501     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8502     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8503
8504     // From, To sizes and ElemCount must be pow of two
8505     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8506
8507     // We are going to use the original vector elt for storing.
8508     // Accumulated smaller vector elements must be a multiple of the store size.
8509     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8510
8511     unsigned SizeRatio  = FromEltSz / ToEltSz;
8512     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8513
8514     // Create a type on which we perform the shuffle.
8515     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8516                                      NumElems*SizeRatio);
8517     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8518
8519     DebugLoc DL = St->getDebugLoc();
8520     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8521     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8522     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8523
8524     // Can't shuffle using an illegal type.
8525     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8526
8527     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8528                                 DAG.getUNDEF(WideVec.getValueType()),
8529                                 ShuffleVec.data());
8530     // At this point all of the data is stored at the bottom of the
8531     // register. We now need to save it to mem.
8532
8533     // Find the largest store unit
8534     MVT StoreType = MVT::i8;
8535     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8536          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8537       MVT Tp = (MVT::SimpleValueType)tp;
8538       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8539         StoreType = Tp;
8540     }
8541     // Didn't find a legal store type.
8542     if (!TLI.isTypeLegal(StoreType))
8543       return SDValue();
8544
8545     // Bitcast the original vector into a vector of store-size units
8546     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8547             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8548     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8549     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8550     SmallVector<SDValue, 8> Chains;
8551     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8552                                         TLI.getPointerTy());
8553     SDValue BasePtr = St->getBasePtr();
8554
8555     // Perform one or more big stores into memory.
8556     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8557     for (unsigned I = 0; I < E; I++) {
8558       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8559                                    StoreType, ShuffWide,
8560                                    DAG.getIntPtrConstant(I));
8561       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8562                                 St->getPointerInfo(), St->isVolatile(),
8563                                 St->isNonTemporal(), St->getAlignment());
8564       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8565                             Increment);
8566       Chains.push_back(Ch);
8567     }
8568     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8569                        Chains.size());
8570   }
8571
8572   if (!ISD::isNormalStore(St))
8573     return SDValue();
8574
8575   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8576   // ARM stores of arguments in the same cache line.
8577   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8578       StVal.getNode()->hasOneUse()) {
8579     SelectionDAG  &DAG = DCI.DAG;
8580     DebugLoc DL = St->getDebugLoc();
8581     SDValue BasePtr = St->getBasePtr();
8582     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8583                                   StVal.getNode()->getOperand(0), BasePtr,
8584                                   St->getPointerInfo(), St->isVolatile(),
8585                                   St->isNonTemporal(), St->getAlignment());
8586
8587     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8588                                     DAG.getConstant(4, MVT::i32));
8589     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8590                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8591                         St->isNonTemporal(),
8592                         std::min(4U, St->getAlignment() / 2));
8593   }
8594
8595   if (StVal.getValueType() != MVT::i64 ||
8596       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8597     return SDValue();
8598
8599   // Bitcast an i64 store extracted from a vector to f64.
8600   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8601   SelectionDAG &DAG = DCI.DAG;
8602   DebugLoc dl = StVal.getDebugLoc();
8603   SDValue IntVec = StVal.getOperand(0);
8604   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8605                                  IntVec.getValueType().getVectorNumElements());
8606   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8607   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8608                                Vec, StVal.getOperand(1));
8609   dl = N->getDebugLoc();
8610   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8611   // Make the DAGCombiner fold the bitcasts.
8612   DCI.AddToWorklist(Vec.getNode());
8613   DCI.AddToWorklist(ExtElt.getNode());
8614   DCI.AddToWorklist(V.getNode());
8615   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8616                       St->getPointerInfo(), St->isVolatile(),
8617                       St->isNonTemporal(), St->getAlignment(),
8618                       St->getTBAAInfo());
8619 }
8620
8621 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8622 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8623 /// i64 vector to have f64 elements, since the value can then be loaded
8624 /// directly into a VFP register.
8625 static bool hasNormalLoadOperand(SDNode *N) {
8626   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8627   for (unsigned i = 0; i < NumElts; ++i) {
8628     SDNode *Elt = N->getOperand(i).getNode();
8629     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8630       return true;
8631   }
8632   return false;
8633 }
8634
8635 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8636 /// ISD::BUILD_VECTOR.
8637 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8638                                           TargetLowering::DAGCombinerInfo &DCI){
8639   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8640   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8641   // into a pair of GPRs, which is fine when the value is used as a scalar,
8642   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8643   SelectionDAG &DAG = DCI.DAG;
8644   if (N->getNumOperands() == 2) {
8645     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8646     if (RV.getNode())
8647       return RV;
8648   }
8649
8650   // Load i64 elements as f64 values so that type legalization does not split
8651   // them up into i32 values.
8652   EVT VT = N->getValueType(0);
8653   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8654     return SDValue();
8655   DebugLoc dl = N->getDebugLoc();
8656   SmallVector<SDValue, 8> Ops;
8657   unsigned NumElts = VT.getVectorNumElements();
8658   for (unsigned i = 0; i < NumElts; ++i) {
8659     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8660     Ops.push_back(V);
8661     // Make the DAGCombiner fold the bitcast.
8662     DCI.AddToWorklist(V.getNode());
8663   }
8664   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8665   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8666   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8667 }
8668
8669 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8670 /// ISD::INSERT_VECTOR_ELT.
8671 static SDValue PerformInsertEltCombine(SDNode *N,
8672                                        TargetLowering::DAGCombinerInfo &DCI) {
8673   // Bitcast an i64 load inserted into a vector to f64.
8674   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8675   EVT VT = N->getValueType(0);
8676   SDNode *Elt = N->getOperand(1).getNode();
8677   if (VT.getVectorElementType() != MVT::i64 ||
8678       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8679     return SDValue();
8680
8681   SelectionDAG &DAG = DCI.DAG;
8682   DebugLoc dl = N->getDebugLoc();
8683   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8684                                  VT.getVectorNumElements());
8685   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8686   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8687   // Make the DAGCombiner fold the bitcasts.
8688   DCI.AddToWorklist(Vec.getNode());
8689   DCI.AddToWorklist(V.getNode());
8690   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8691                                Vec, V, N->getOperand(2));
8692   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8693 }
8694
8695 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8696 /// ISD::VECTOR_SHUFFLE.
8697 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8698   // The LLVM shufflevector instruction does not require the shuffle mask
8699   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8700   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8701   // operands do not match the mask length, they are extended by concatenating
8702   // them with undef vectors.  That is probably the right thing for other
8703   // targets, but for NEON it is better to concatenate two double-register
8704   // size vector operands into a single quad-register size vector.  Do that
8705   // transformation here:
8706   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8707   //   shuffle(concat(v1, v2), undef)
8708   SDValue Op0 = N->getOperand(0);
8709   SDValue Op1 = N->getOperand(1);
8710   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8711       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8712       Op0.getNumOperands() != 2 ||
8713       Op1.getNumOperands() != 2)
8714     return SDValue();
8715   SDValue Concat0Op1 = Op0.getOperand(1);
8716   SDValue Concat1Op1 = Op1.getOperand(1);
8717   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8718       Concat1Op1.getOpcode() != ISD::UNDEF)
8719     return SDValue();
8720   // Skip the transformation if any of the types are illegal.
8721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8722   EVT VT = N->getValueType(0);
8723   if (!TLI.isTypeLegal(VT) ||
8724       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8725       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8726     return SDValue();
8727
8728   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8729                                   Op0.getOperand(0), Op1.getOperand(0));
8730   // Translate the shuffle mask.
8731   SmallVector<int, 16> NewMask;
8732   unsigned NumElts = VT.getVectorNumElements();
8733   unsigned HalfElts = NumElts/2;
8734   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8735   for (unsigned n = 0; n < NumElts; ++n) {
8736     int MaskElt = SVN->getMaskElt(n);
8737     int NewElt = -1;
8738     if (MaskElt < (int)HalfElts)
8739       NewElt = MaskElt;
8740     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8741       NewElt = HalfElts + MaskElt - NumElts;
8742     NewMask.push_back(NewElt);
8743   }
8744   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8745                               DAG.getUNDEF(VT), NewMask.data());
8746 }
8747
8748 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8749 /// NEON load/store intrinsics to merge base address updates.
8750 static SDValue CombineBaseUpdate(SDNode *N,
8751                                  TargetLowering::DAGCombinerInfo &DCI) {
8752   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8753     return SDValue();
8754
8755   SelectionDAG &DAG = DCI.DAG;
8756   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8757                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8758   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8759   SDValue Addr = N->getOperand(AddrOpIdx);
8760
8761   // Search for a use of the address operand that is an increment.
8762   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8763          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8764     SDNode *User = *UI;
8765     if (User->getOpcode() != ISD::ADD ||
8766         UI.getUse().getResNo() != Addr.getResNo())
8767       continue;
8768
8769     // Check that the add is independent of the load/store.  Otherwise, folding
8770     // it would create a cycle.
8771     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8772       continue;
8773
8774     // Find the new opcode for the updating load/store.
8775     bool isLoad = true;
8776     bool isLaneOp = false;
8777     unsigned NewOpc = 0;
8778     unsigned NumVecs = 0;
8779     if (isIntrinsic) {
8780       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8781       switch (IntNo) {
8782       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8783       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8784         NumVecs = 1; break;
8785       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8786         NumVecs = 2; break;
8787       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8788         NumVecs = 3; break;
8789       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8790         NumVecs = 4; break;
8791       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8792         NumVecs = 2; isLaneOp = true; break;
8793       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8794         NumVecs = 3; isLaneOp = true; break;
8795       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8796         NumVecs = 4; isLaneOp = true; break;
8797       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8798         NumVecs = 1; isLoad = false; break;
8799       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8800         NumVecs = 2; isLoad = false; break;
8801       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8802         NumVecs = 3; isLoad = false; break;
8803       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8804         NumVecs = 4; isLoad = false; break;
8805       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8806         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8807       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8808         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8809       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8810         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8811       }
8812     } else {
8813       isLaneOp = true;
8814       switch (N->getOpcode()) {
8815       default: llvm_unreachable("unexpected opcode for Neon base update");
8816       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8817       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8818       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8819       }
8820     }
8821
8822     // Find the size of memory referenced by the load/store.
8823     EVT VecTy;
8824     if (isLoad)
8825       VecTy = N->getValueType(0);
8826     else
8827       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8828     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8829     if (isLaneOp)
8830       NumBytes /= VecTy.getVectorNumElements();
8831
8832     // If the increment is a constant, it must match the memory ref size.
8833     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8834     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8835       uint64_t IncVal = CInc->getZExtValue();
8836       if (IncVal != NumBytes)
8837         continue;
8838     } else if (NumBytes >= 3 * 16) {
8839       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8840       // separate instructions that make it harder to use a non-constant update.
8841       continue;
8842     }
8843
8844     // Create the new updating load/store node.
8845     EVT Tys[6];
8846     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8847     unsigned n;
8848     for (n = 0; n < NumResultVecs; ++n)
8849       Tys[n] = VecTy;
8850     Tys[n++] = MVT::i32;
8851     Tys[n] = MVT::Other;
8852     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8853     SmallVector<SDValue, 8> Ops;
8854     Ops.push_back(N->getOperand(0)); // incoming chain
8855     Ops.push_back(N->getOperand(AddrOpIdx));
8856     Ops.push_back(Inc);
8857     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8858       Ops.push_back(N->getOperand(i));
8859     }
8860     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8861     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8862                                            Ops.data(), Ops.size(),
8863                                            MemInt->getMemoryVT(),
8864                                            MemInt->getMemOperand());
8865
8866     // Update the uses.
8867     std::vector<SDValue> NewResults;
8868     for (unsigned i = 0; i < NumResultVecs; ++i) {
8869       NewResults.push_back(SDValue(UpdN.getNode(), i));
8870     }
8871     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8872     DCI.CombineTo(N, NewResults);
8873     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8874
8875     break;
8876   }
8877   return SDValue();
8878 }
8879
8880 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8881 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8882 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8883 /// return true.
8884 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8885   SelectionDAG &DAG = DCI.DAG;
8886   EVT VT = N->getValueType(0);
8887   // vldN-dup instructions only support 64-bit vectors for N > 1.
8888   if (!VT.is64BitVector())
8889     return false;
8890
8891   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8892   SDNode *VLD = N->getOperand(0).getNode();
8893   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8894     return false;
8895   unsigned NumVecs = 0;
8896   unsigned NewOpc = 0;
8897   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8898   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8899     NumVecs = 2;
8900     NewOpc = ARMISD::VLD2DUP;
8901   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8902     NumVecs = 3;
8903     NewOpc = ARMISD::VLD3DUP;
8904   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8905     NumVecs = 4;
8906     NewOpc = ARMISD::VLD4DUP;
8907   } else {
8908     return false;
8909   }
8910
8911   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8912   // numbers match the load.
8913   unsigned VLDLaneNo =
8914     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8915   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8916        UI != UE; ++UI) {
8917     // Ignore uses of the chain result.
8918     if (UI.getUse().getResNo() == NumVecs)
8919       continue;
8920     SDNode *User = *UI;
8921     if (User->getOpcode() != ARMISD::VDUPLANE ||
8922         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8923       return false;
8924   }
8925
8926   // Create the vldN-dup node.
8927   EVT Tys[5];
8928   unsigned n;
8929   for (n = 0; n < NumVecs; ++n)
8930     Tys[n] = VT;
8931   Tys[n] = MVT::Other;
8932   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8933   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8934   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8935   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8936                                            Ops, 2, VLDMemInt->getMemoryVT(),
8937                                            VLDMemInt->getMemOperand());
8938
8939   // Update the uses.
8940   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8941        UI != UE; ++UI) {
8942     unsigned ResNo = UI.getUse().getResNo();
8943     // Ignore uses of the chain result.
8944     if (ResNo == NumVecs)
8945       continue;
8946     SDNode *User = *UI;
8947     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8948   }
8949
8950   // Now the vldN-lane intrinsic is dead except for its chain result.
8951   // Update uses of the chain.
8952   std::vector<SDValue> VLDDupResults;
8953   for (unsigned n = 0; n < NumVecs; ++n)
8954     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8955   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8956   DCI.CombineTo(VLD, VLDDupResults);
8957
8958   return true;
8959 }
8960
8961 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8962 /// ARMISD::VDUPLANE.
8963 static SDValue PerformVDUPLANECombine(SDNode *N,
8964                                       TargetLowering::DAGCombinerInfo &DCI) {
8965   SDValue Op = N->getOperand(0);
8966
8967   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8968   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8969   if (CombineVLDDUP(N, DCI))
8970     return SDValue(N, 0);
8971
8972   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8973   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8974   while (Op.getOpcode() == ISD::BITCAST)
8975     Op = Op.getOperand(0);
8976   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8977     return SDValue();
8978
8979   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8980   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8981   // The canonical VMOV for a zero vector uses a 32-bit element size.
8982   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8983   unsigned EltBits;
8984   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8985     EltSize = 8;
8986   EVT VT = N->getValueType(0);
8987   if (EltSize > VT.getVectorElementType().getSizeInBits())
8988     return SDValue();
8989
8990   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8991 }
8992
8993 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8994 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8995 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8996 {
8997   integerPart cN;
8998   integerPart c0 = 0;
8999   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9000        I != E; I++) {
9001     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9002     if (!C)
9003       return false;
9004
9005     bool isExact;
9006     APFloat APF = C->getValueAPF();
9007     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9008         != APFloat::opOK || !isExact)
9009       return false;
9010
9011     c0 = (I == 0) ? cN : c0;
9012     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9013       return false;
9014   }
9015   C = c0;
9016   return true;
9017 }
9018
9019 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9020 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9021 /// when the VMUL has a constant operand that is a power of 2.
9022 ///
9023 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9024 ///  vmul.f32        d16, d17, d16
9025 ///  vcvt.s32.f32    d16, d16
9026 /// becomes:
9027 ///  vcvt.s32.f32    d16, d16, #3
9028 static SDValue PerformVCVTCombine(SDNode *N,
9029                                   TargetLowering::DAGCombinerInfo &DCI,
9030                                   const ARMSubtarget *Subtarget) {
9031   SelectionDAG &DAG = DCI.DAG;
9032   SDValue Op = N->getOperand(0);
9033
9034   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9035       Op.getOpcode() != ISD::FMUL)
9036     return SDValue();
9037
9038   uint64_t C;
9039   SDValue N0 = Op->getOperand(0);
9040   SDValue ConstVec = Op->getOperand(1);
9041   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9042
9043   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9044       !isConstVecPow2(ConstVec, isSigned, C))
9045     return SDValue();
9046
9047   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9048     Intrinsic::arm_neon_vcvtfp2fxu;
9049   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9050                      N->getValueType(0),
9051                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9052                      DAG.getConstant(Log2_64(C), MVT::i32));
9053 }
9054
9055 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9056 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9057 /// when the VDIV has a constant operand that is a power of 2.
9058 ///
9059 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9060 ///  vcvt.f32.s32    d16, d16
9061 ///  vdiv.f32        d16, d17, d16
9062 /// becomes:
9063 ///  vcvt.f32.s32    d16, d16, #3
9064 static SDValue PerformVDIVCombine(SDNode *N,
9065                                   TargetLowering::DAGCombinerInfo &DCI,
9066                                   const ARMSubtarget *Subtarget) {
9067   SelectionDAG &DAG = DCI.DAG;
9068   SDValue Op = N->getOperand(0);
9069   unsigned OpOpcode = Op.getNode()->getOpcode();
9070
9071   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9072       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9073     return SDValue();
9074
9075   uint64_t C;
9076   SDValue ConstVec = N->getOperand(1);
9077   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9078
9079   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9080       !isConstVecPow2(ConstVec, isSigned, C))
9081     return SDValue();
9082
9083   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9084     Intrinsic::arm_neon_vcvtfxu2fp;
9085   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9086                      Op.getValueType(),
9087                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9088                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
9089 }
9090
9091 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9092 /// operand of a vector shift operation, where all the elements of the
9093 /// build_vector must have the same constant integer value.
9094 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9095   // Ignore bit_converts.
9096   while (Op.getOpcode() == ISD::BITCAST)
9097     Op = Op.getOperand(0);
9098   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9099   APInt SplatBits, SplatUndef;
9100   unsigned SplatBitSize;
9101   bool HasAnyUndefs;
9102   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9103                                       HasAnyUndefs, ElementBits) ||
9104       SplatBitSize > ElementBits)
9105     return false;
9106   Cnt = SplatBits.getSExtValue();
9107   return true;
9108 }
9109
9110 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9111 /// operand of a vector shift left operation.  That value must be in the range:
9112 ///   0 <= Value < ElementBits for a left shift; or
9113 ///   0 <= Value <= ElementBits for a long left shift.
9114 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9115   assert(VT.isVector() && "vector shift count is not a vector type");
9116   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9117   if (! getVShiftImm(Op, ElementBits, Cnt))
9118     return false;
9119   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9120 }
9121
9122 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9123 /// operand of a vector shift right operation.  For a shift opcode, the value
9124 /// is positive, but for an intrinsic the value count must be negative. The
9125 /// absolute value must be in the range:
9126 ///   1 <= |Value| <= ElementBits for a right shift; or
9127 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9128 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9129                          int64_t &Cnt) {
9130   assert(VT.isVector() && "vector shift count is not a vector type");
9131   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9132   if (! getVShiftImm(Op, ElementBits, Cnt))
9133     return false;
9134   if (isIntrinsic)
9135     Cnt = -Cnt;
9136   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9137 }
9138
9139 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9140 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9141   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9142   switch (IntNo) {
9143   default:
9144     // Don't do anything for most intrinsics.
9145     break;
9146
9147   // Vector shifts: check for immediate versions and lower them.
9148   // Note: This is done during DAG combining instead of DAG legalizing because
9149   // the build_vectors for 64-bit vector element shift counts are generally
9150   // not legal, and it is hard to see their values after they get legalized to
9151   // loads from a constant pool.
9152   case Intrinsic::arm_neon_vshifts:
9153   case Intrinsic::arm_neon_vshiftu:
9154   case Intrinsic::arm_neon_vshiftls:
9155   case Intrinsic::arm_neon_vshiftlu:
9156   case Intrinsic::arm_neon_vshiftn:
9157   case Intrinsic::arm_neon_vrshifts:
9158   case Intrinsic::arm_neon_vrshiftu:
9159   case Intrinsic::arm_neon_vrshiftn:
9160   case Intrinsic::arm_neon_vqshifts:
9161   case Intrinsic::arm_neon_vqshiftu:
9162   case Intrinsic::arm_neon_vqshiftsu:
9163   case Intrinsic::arm_neon_vqshiftns:
9164   case Intrinsic::arm_neon_vqshiftnu:
9165   case Intrinsic::arm_neon_vqshiftnsu:
9166   case Intrinsic::arm_neon_vqrshiftns:
9167   case Intrinsic::arm_neon_vqrshiftnu:
9168   case Intrinsic::arm_neon_vqrshiftnsu: {
9169     EVT VT = N->getOperand(1).getValueType();
9170     int64_t Cnt;
9171     unsigned VShiftOpc = 0;
9172
9173     switch (IntNo) {
9174     case Intrinsic::arm_neon_vshifts:
9175     case Intrinsic::arm_neon_vshiftu:
9176       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9177         VShiftOpc = ARMISD::VSHL;
9178         break;
9179       }
9180       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9181         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9182                      ARMISD::VSHRs : ARMISD::VSHRu);
9183         break;
9184       }
9185       return SDValue();
9186
9187     case Intrinsic::arm_neon_vshiftls:
9188     case Intrinsic::arm_neon_vshiftlu:
9189       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9190         break;
9191       llvm_unreachable("invalid shift count for vshll intrinsic");
9192
9193     case Intrinsic::arm_neon_vrshifts:
9194     case Intrinsic::arm_neon_vrshiftu:
9195       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9196         break;
9197       return SDValue();
9198
9199     case Intrinsic::arm_neon_vqshifts:
9200     case Intrinsic::arm_neon_vqshiftu:
9201       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9202         break;
9203       return SDValue();
9204
9205     case Intrinsic::arm_neon_vqshiftsu:
9206       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9207         break;
9208       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9209
9210     case Intrinsic::arm_neon_vshiftn:
9211     case Intrinsic::arm_neon_vrshiftn:
9212     case Intrinsic::arm_neon_vqshiftns:
9213     case Intrinsic::arm_neon_vqshiftnu:
9214     case Intrinsic::arm_neon_vqshiftnsu:
9215     case Intrinsic::arm_neon_vqrshiftns:
9216     case Intrinsic::arm_neon_vqrshiftnu:
9217     case Intrinsic::arm_neon_vqrshiftnsu:
9218       // Narrowing shifts require an immediate right shift.
9219       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9220         break;
9221       llvm_unreachable("invalid shift count for narrowing vector shift "
9222                        "intrinsic");
9223
9224     default:
9225       llvm_unreachable("unhandled vector shift");
9226     }
9227
9228     switch (IntNo) {
9229     case Intrinsic::arm_neon_vshifts:
9230     case Intrinsic::arm_neon_vshiftu:
9231       // Opcode already set above.
9232       break;
9233     case Intrinsic::arm_neon_vshiftls:
9234     case Intrinsic::arm_neon_vshiftlu:
9235       if (Cnt == VT.getVectorElementType().getSizeInBits())
9236         VShiftOpc = ARMISD::VSHLLi;
9237       else
9238         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9239                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9240       break;
9241     case Intrinsic::arm_neon_vshiftn:
9242       VShiftOpc = ARMISD::VSHRN; break;
9243     case Intrinsic::arm_neon_vrshifts:
9244       VShiftOpc = ARMISD::VRSHRs; break;
9245     case Intrinsic::arm_neon_vrshiftu:
9246       VShiftOpc = ARMISD::VRSHRu; break;
9247     case Intrinsic::arm_neon_vrshiftn:
9248       VShiftOpc = ARMISD::VRSHRN; break;
9249     case Intrinsic::arm_neon_vqshifts:
9250       VShiftOpc = ARMISD::VQSHLs; break;
9251     case Intrinsic::arm_neon_vqshiftu:
9252       VShiftOpc = ARMISD::VQSHLu; break;
9253     case Intrinsic::arm_neon_vqshiftsu:
9254       VShiftOpc = ARMISD::VQSHLsu; break;
9255     case Intrinsic::arm_neon_vqshiftns:
9256       VShiftOpc = ARMISD::VQSHRNs; break;
9257     case Intrinsic::arm_neon_vqshiftnu:
9258       VShiftOpc = ARMISD::VQSHRNu; break;
9259     case Intrinsic::arm_neon_vqshiftnsu:
9260       VShiftOpc = ARMISD::VQSHRNsu; break;
9261     case Intrinsic::arm_neon_vqrshiftns:
9262       VShiftOpc = ARMISD::VQRSHRNs; break;
9263     case Intrinsic::arm_neon_vqrshiftnu:
9264       VShiftOpc = ARMISD::VQRSHRNu; break;
9265     case Intrinsic::arm_neon_vqrshiftnsu:
9266       VShiftOpc = ARMISD::VQRSHRNsu; break;
9267     }
9268
9269     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9270                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9271   }
9272
9273   case Intrinsic::arm_neon_vshiftins: {
9274     EVT VT = N->getOperand(1).getValueType();
9275     int64_t Cnt;
9276     unsigned VShiftOpc = 0;
9277
9278     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9279       VShiftOpc = ARMISD::VSLI;
9280     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9281       VShiftOpc = ARMISD::VSRI;
9282     else {
9283       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9284     }
9285
9286     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9287                        N->getOperand(1), N->getOperand(2),
9288                        DAG.getConstant(Cnt, MVT::i32));
9289   }
9290
9291   case Intrinsic::arm_neon_vqrshifts:
9292   case Intrinsic::arm_neon_vqrshiftu:
9293     // No immediate versions of these to check for.
9294     break;
9295   }
9296
9297   return SDValue();
9298 }
9299
9300 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9301 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9302 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9303 /// vector element shift counts are generally not legal, and it is hard to see
9304 /// their values after they get legalized to loads from a constant pool.
9305 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9306                                    const ARMSubtarget *ST) {
9307   EVT VT = N->getValueType(0);
9308   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9309     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9310     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9311     SDValue N1 = N->getOperand(1);
9312     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9313       SDValue N0 = N->getOperand(0);
9314       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9315           DAG.MaskedValueIsZero(N0.getOperand(0),
9316                                 APInt::getHighBitsSet(32, 16)))
9317         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9318     }
9319   }
9320
9321   // Nothing to be done for scalar shifts.
9322   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9323   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9324     return SDValue();
9325
9326   assert(ST->hasNEON() && "unexpected vector shift");
9327   int64_t Cnt;
9328
9329   switch (N->getOpcode()) {
9330   default: llvm_unreachable("unexpected shift opcode");
9331
9332   case ISD::SHL:
9333     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9334       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9335                          DAG.getConstant(Cnt, MVT::i32));
9336     break;
9337
9338   case ISD::SRA:
9339   case ISD::SRL:
9340     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9341       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9342                             ARMISD::VSHRs : ARMISD::VSHRu);
9343       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9344                          DAG.getConstant(Cnt, MVT::i32));
9345     }
9346   }
9347   return SDValue();
9348 }
9349
9350 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9351 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9352 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9353                                     const ARMSubtarget *ST) {
9354   SDValue N0 = N->getOperand(0);
9355
9356   // Check for sign- and zero-extensions of vector extract operations of 8-
9357   // and 16-bit vector elements.  NEON supports these directly.  They are
9358   // handled during DAG combining because type legalization will promote them
9359   // to 32-bit types and it is messy to recognize the operations after that.
9360   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9361     SDValue Vec = N0.getOperand(0);
9362     SDValue Lane = N0.getOperand(1);
9363     EVT VT = N->getValueType(0);
9364     EVT EltVT = N0.getValueType();
9365     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9366
9367     if (VT == MVT::i32 &&
9368         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9369         TLI.isTypeLegal(Vec.getValueType()) &&
9370         isa<ConstantSDNode>(Lane)) {
9371
9372       unsigned Opc = 0;
9373       switch (N->getOpcode()) {
9374       default: llvm_unreachable("unexpected opcode");
9375       case ISD::SIGN_EXTEND:
9376         Opc = ARMISD::VGETLANEs;
9377         break;
9378       case ISD::ZERO_EXTEND:
9379       case ISD::ANY_EXTEND:
9380         Opc = ARMISD::VGETLANEu;
9381         break;
9382       }
9383       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9384     }
9385   }
9386
9387   return SDValue();
9388 }
9389
9390 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9391 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9392 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9393                                        const ARMSubtarget *ST) {
9394   // If the target supports NEON, try to use vmax/vmin instructions for f32
9395   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9396   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9397   // a NaN; only do the transformation when it matches that behavior.
9398
9399   // For now only do this when using NEON for FP operations; if using VFP, it
9400   // is not obvious that the benefit outweighs the cost of switching to the
9401   // NEON pipeline.
9402   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9403       N->getValueType(0) != MVT::f32)
9404     return SDValue();
9405
9406   SDValue CondLHS = N->getOperand(0);
9407   SDValue CondRHS = N->getOperand(1);
9408   SDValue LHS = N->getOperand(2);
9409   SDValue RHS = N->getOperand(3);
9410   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9411
9412   unsigned Opcode = 0;
9413   bool IsReversed;
9414   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9415     IsReversed = false; // x CC y ? x : y
9416   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9417     IsReversed = true ; // x CC y ? y : x
9418   } else {
9419     return SDValue();
9420   }
9421
9422   bool IsUnordered;
9423   switch (CC) {
9424   default: break;
9425   case ISD::SETOLT:
9426   case ISD::SETOLE:
9427   case ISD::SETLT:
9428   case ISD::SETLE:
9429   case ISD::SETULT:
9430   case ISD::SETULE:
9431     // If LHS is NaN, an ordered comparison will be false and the result will
9432     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9433     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9434     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9435     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9436       break;
9437     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9438     // will return -0, so vmin can only be used for unsafe math or if one of
9439     // the operands is known to be nonzero.
9440     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9441         !DAG.getTarget().Options.UnsafeFPMath &&
9442         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9443       break;
9444     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9445     break;
9446
9447   case ISD::SETOGT:
9448   case ISD::SETOGE:
9449   case ISD::SETGT:
9450   case ISD::SETGE:
9451   case ISD::SETUGT:
9452   case ISD::SETUGE:
9453     // If LHS is NaN, an ordered comparison will be false and the result will
9454     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9455     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9456     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9457     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9458       break;
9459     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9460     // will return +0, so vmax can only be used for unsafe math or if one of
9461     // the operands is known to be nonzero.
9462     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9463         !DAG.getTarget().Options.UnsafeFPMath &&
9464         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9465       break;
9466     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9467     break;
9468   }
9469
9470   if (!Opcode)
9471     return SDValue();
9472   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9473 }
9474
9475 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9476 SDValue
9477 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9478   SDValue Cmp = N->getOperand(4);
9479   if (Cmp.getOpcode() != ARMISD::CMPZ)
9480     // Only looking at EQ and NE cases.
9481     return SDValue();
9482
9483   EVT VT = N->getValueType(0);
9484   DebugLoc dl = N->getDebugLoc();
9485   SDValue LHS = Cmp.getOperand(0);
9486   SDValue RHS = Cmp.getOperand(1);
9487   SDValue FalseVal = N->getOperand(0);
9488   SDValue TrueVal = N->getOperand(1);
9489   SDValue ARMcc = N->getOperand(2);
9490   ARMCC::CondCodes CC =
9491     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9492
9493   // Simplify
9494   //   mov     r1, r0
9495   //   cmp     r1, x
9496   //   mov     r0, y
9497   //   moveq   r0, x
9498   // to
9499   //   cmp     r0, x
9500   //   movne   r0, y
9501   //
9502   //   mov     r1, r0
9503   //   cmp     r1, x
9504   //   mov     r0, x
9505   //   movne   r0, y
9506   // to
9507   //   cmp     r0, x
9508   //   movne   r0, y
9509   /// FIXME: Turn this into a target neutral optimization?
9510   SDValue Res;
9511   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9512     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9513                       N->getOperand(3), Cmp);
9514   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9515     SDValue ARMcc;
9516     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9517     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9518                       N->getOperand(3), NewCmp);
9519   }
9520
9521   if (Res.getNode()) {
9522     APInt KnownZero, KnownOne;
9523     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9524     // Capture demanded bits information that would be otherwise lost.
9525     if (KnownZero == 0xfffffffe)
9526       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9527                         DAG.getValueType(MVT::i1));
9528     else if (KnownZero == 0xffffff00)
9529       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9530                         DAG.getValueType(MVT::i8));
9531     else if (KnownZero == 0xffff0000)
9532       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9533                         DAG.getValueType(MVT::i16));
9534   }
9535
9536   return Res;
9537 }
9538
9539 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9540                                              DAGCombinerInfo &DCI) const {
9541   switch (N->getOpcode()) {
9542   default: break;
9543   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9544   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9545   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9546   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9547   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9548   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9549   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9550   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9551   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9552   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9553   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9554   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9555   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9556   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9557   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9558   case ISD::FP_TO_SINT:
9559   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9560   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9561   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9562   case ISD::SHL:
9563   case ISD::SRA:
9564   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9565   case ISD::SIGN_EXTEND:
9566   case ISD::ZERO_EXTEND:
9567   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9568   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9569   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9570   case ARMISD::VLD2DUP:
9571   case ARMISD::VLD3DUP:
9572   case ARMISD::VLD4DUP:
9573     return CombineBaseUpdate(N, DCI);
9574   case ISD::INTRINSIC_VOID:
9575   case ISD::INTRINSIC_W_CHAIN:
9576     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9577     case Intrinsic::arm_neon_vld1:
9578     case Intrinsic::arm_neon_vld2:
9579     case Intrinsic::arm_neon_vld3:
9580     case Intrinsic::arm_neon_vld4:
9581     case Intrinsic::arm_neon_vld2lane:
9582     case Intrinsic::arm_neon_vld3lane:
9583     case Intrinsic::arm_neon_vld4lane:
9584     case Intrinsic::arm_neon_vst1:
9585     case Intrinsic::arm_neon_vst2:
9586     case Intrinsic::arm_neon_vst3:
9587     case Intrinsic::arm_neon_vst4:
9588     case Intrinsic::arm_neon_vst2lane:
9589     case Intrinsic::arm_neon_vst3lane:
9590     case Intrinsic::arm_neon_vst4lane:
9591       return CombineBaseUpdate(N, DCI);
9592     default: break;
9593     }
9594     break;
9595   }
9596   return SDValue();
9597 }
9598
9599 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9600                                                           EVT VT) const {
9601   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9602 }
9603
9604 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9605   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9606   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9607
9608   switch (VT.getSimpleVT().SimpleTy) {
9609   default:
9610     return false;
9611   case MVT::i8:
9612   case MVT::i16:
9613   case MVT::i32: {
9614     // Unaligned access can use (for example) LRDB, LRDH, LDR
9615     if (AllowsUnaligned) {
9616       if (Fast)
9617         *Fast = Subtarget->hasV7Ops();
9618       return true;
9619     }
9620     return false;
9621   }
9622   case MVT::f64:
9623   case MVT::v2f64: {
9624     // For any little-endian targets with neon, we can support unaligned ld/st
9625     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9626     // A big-endian target may also explictly support unaligned accesses
9627     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9628       if (Fast)
9629         *Fast = true;
9630       return true;
9631     }
9632     return false;
9633   }
9634   }
9635 }
9636
9637 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9638                        unsigned AlignCheck) {
9639   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9640           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9641 }
9642
9643 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9644                                            unsigned DstAlign, unsigned SrcAlign,
9645                                            bool IsMemset, bool ZeroMemset,
9646                                            bool MemcpyStrSrc,
9647                                            MachineFunction &MF) const {
9648   const Function *F = MF.getFunction();
9649
9650   // See if we can use NEON instructions for this...
9651   if ((!IsMemset || ZeroMemset) &&
9652       Subtarget->hasNEON() &&
9653       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9654                                        Attribute::NoImplicitFloat)) {
9655     bool Fast;
9656     if (Size >= 16 &&
9657         (memOpAlign(SrcAlign, DstAlign, 16) ||
9658          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9659       return MVT::v2f64;
9660     } else if (Size >= 8 &&
9661                (memOpAlign(SrcAlign, DstAlign, 8) ||
9662                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9663       return MVT::f64;
9664     }
9665   }
9666
9667   // Lowering to i32/i16 if the size permits.
9668   if (Size >= 4)
9669     return MVT::i32;
9670   else if (Size >= 2)
9671     return MVT::i16;
9672
9673   // Let the target-independent logic figure it out.
9674   return MVT::Other;
9675 }
9676
9677 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9678   if (Val.getOpcode() != ISD::LOAD)
9679     return false;
9680
9681   EVT VT1 = Val.getValueType();
9682   if (!VT1.isSimple() || !VT1.isInteger() ||
9683       !VT2.isSimple() || !VT2.isInteger())
9684     return false;
9685
9686   switch (VT1.getSimpleVT().SimpleTy) {
9687   default: break;
9688   case MVT::i1:
9689   case MVT::i8:
9690   case MVT::i16:
9691     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9692     return true;
9693   }
9694
9695   return false;
9696 }
9697
9698 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9699   if (V < 0)
9700     return false;
9701
9702   unsigned Scale = 1;
9703   switch (VT.getSimpleVT().SimpleTy) {
9704   default: return false;
9705   case MVT::i1:
9706   case MVT::i8:
9707     // Scale == 1;
9708     break;
9709   case MVT::i16:
9710     // Scale == 2;
9711     Scale = 2;
9712     break;
9713   case MVT::i32:
9714     // Scale == 4;
9715     Scale = 4;
9716     break;
9717   }
9718
9719   if ((V & (Scale - 1)) != 0)
9720     return false;
9721   V /= Scale;
9722   return V == (V & ((1LL << 5) - 1));
9723 }
9724
9725 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9726                                       const ARMSubtarget *Subtarget) {
9727   bool isNeg = false;
9728   if (V < 0) {
9729     isNeg = true;
9730     V = - V;
9731   }
9732
9733   switch (VT.getSimpleVT().SimpleTy) {
9734   default: return false;
9735   case MVT::i1:
9736   case MVT::i8:
9737   case MVT::i16:
9738   case MVT::i32:
9739     // + imm12 or - imm8
9740     if (isNeg)
9741       return V == (V & ((1LL << 8) - 1));
9742     return V == (V & ((1LL << 12) - 1));
9743   case MVT::f32:
9744   case MVT::f64:
9745     // Same as ARM mode. FIXME: NEON?
9746     if (!Subtarget->hasVFP2())
9747       return false;
9748     if ((V & 3) != 0)
9749       return false;
9750     V >>= 2;
9751     return V == (V & ((1LL << 8) - 1));
9752   }
9753 }
9754
9755 /// isLegalAddressImmediate - Return true if the integer value can be used
9756 /// as the offset of the target addressing mode for load / store of the
9757 /// given type.
9758 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9759                                     const ARMSubtarget *Subtarget) {
9760   if (V == 0)
9761     return true;
9762
9763   if (!VT.isSimple())
9764     return false;
9765
9766   if (Subtarget->isThumb1Only())
9767     return isLegalT1AddressImmediate(V, VT);
9768   else if (Subtarget->isThumb2())
9769     return isLegalT2AddressImmediate(V, VT, Subtarget);
9770
9771   // ARM mode.
9772   if (V < 0)
9773     V = - V;
9774   switch (VT.getSimpleVT().SimpleTy) {
9775   default: return false;
9776   case MVT::i1:
9777   case MVT::i8:
9778   case MVT::i32:
9779     // +- imm12
9780     return V == (V & ((1LL << 12) - 1));
9781   case MVT::i16:
9782     // +- imm8
9783     return V == (V & ((1LL << 8) - 1));
9784   case MVT::f32:
9785   case MVT::f64:
9786     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9787       return false;
9788     if ((V & 3) != 0)
9789       return false;
9790     V >>= 2;
9791     return V == (V & ((1LL << 8) - 1));
9792   }
9793 }
9794
9795 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9796                                                       EVT VT) const {
9797   int Scale = AM.Scale;
9798   if (Scale < 0)
9799     return false;
9800
9801   switch (VT.getSimpleVT().SimpleTy) {
9802   default: return false;
9803   case MVT::i1:
9804   case MVT::i8:
9805   case MVT::i16:
9806   case MVT::i32:
9807     if (Scale == 1)
9808       return true;
9809     // r + r << imm
9810     Scale = Scale & ~1;
9811     return Scale == 2 || Scale == 4 || Scale == 8;
9812   case MVT::i64:
9813     // r + r
9814     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9815       return true;
9816     return false;
9817   case MVT::isVoid:
9818     // Note, we allow "void" uses (basically, uses that aren't loads or
9819     // stores), because arm allows folding a scale into many arithmetic
9820     // operations.  This should be made more precise and revisited later.
9821
9822     // Allow r << imm, but the imm has to be a multiple of two.
9823     if (Scale & 1) return false;
9824     return isPowerOf2_32(Scale);
9825   }
9826 }
9827
9828 /// isLegalAddressingMode - Return true if the addressing mode represented
9829 /// by AM is legal for this target, for a load/store of the specified type.
9830 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9831                                               Type *Ty) const {
9832   EVT VT = getValueType(Ty, true);
9833   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9834     return false;
9835
9836   // Can never fold addr of global into load/store.
9837   if (AM.BaseGV)
9838     return false;
9839
9840   switch (AM.Scale) {
9841   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9842     break;
9843   case 1:
9844     if (Subtarget->isThumb1Only())
9845       return false;
9846     // FALL THROUGH.
9847   default:
9848     // ARM doesn't support any R+R*scale+imm addr modes.
9849     if (AM.BaseOffs)
9850       return false;
9851
9852     if (!VT.isSimple())
9853       return false;
9854
9855     if (Subtarget->isThumb2())
9856       return isLegalT2ScaledAddressingMode(AM, VT);
9857
9858     int Scale = AM.Scale;
9859     switch (VT.getSimpleVT().SimpleTy) {
9860     default: return false;
9861     case MVT::i1:
9862     case MVT::i8:
9863     case MVT::i32:
9864       if (Scale < 0) Scale = -Scale;
9865       if (Scale == 1)
9866         return true;
9867       // r + r << imm
9868       return isPowerOf2_32(Scale & ~1);
9869     case MVT::i16:
9870     case MVT::i64:
9871       // r + r
9872       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9873         return true;
9874       return false;
9875
9876     case MVT::isVoid:
9877       // Note, we allow "void" uses (basically, uses that aren't loads or
9878       // stores), because arm allows folding a scale into many arithmetic
9879       // operations.  This should be made more precise and revisited later.
9880
9881       // Allow r << imm, but the imm has to be a multiple of two.
9882       if (Scale & 1) return false;
9883       return isPowerOf2_32(Scale);
9884     }
9885   }
9886   return true;
9887 }
9888
9889 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9890 /// icmp immediate, that is the target has icmp instructions which can compare
9891 /// a register against the immediate without having to materialize the
9892 /// immediate into a register.
9893 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9894   // Thumb2 and ARM modes can use cmn for negative immediates.
9895   if (!Subtarget->isThumb())
9896     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9897   if (Subtarget->isThumb2())
9898     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9899   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9900   return Imm >= 0 && Imm <= 255;
9901 }
9902
9903 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9904 /// *or sub* immediate, that is the target has add or sub instructions which can
9905 /// add a register with the immediate without having to materialize the
9906 /// immediate into a register.
9907 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9908   // Same encoding for add/sub, just flip the sign.
9909   int64_t AbsImm = llvm::abs64(Imm);
9910   if (!Subtarget->isThumb())
9911     return ARM_AM::getSOImmVal(AbsImm) != -1;
9912   if (Subtarget->isThumb2())
9913     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9914   // Thumb1 only has 8-bit unsigned immediate.
9915   return AbsImm >= 0 && AbsImm <= 255;
9916 }
9917
9918 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9919                                       bool isSEXTLoad, SDValue &Base,
9920                                       SDValue &Offset, bool &isInc,
9921                                       SelectionDAG &DAG) {
9922   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9923     return false;
9924
9925   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9926     // AddressingMode 3
9927     Base = Ptr->getOperand(0);
9928     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9929       int RHSC = (int)RHS->getZExtValue();
9930       if (RHSC < 0 && RHSC > -256) {
9931         assert(Ptr->getOpcode() == ISD::ADD);
9932         isInc = false;
9933         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9934         return true;
9935       }
9936     }
9937     isInc = (Ptr->getOpcode() == ISD::ADD);
9938     Offset = Ptr->getOperand(1);
9939     return true;
9940   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9941     // AddressingMode 2
9942     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9943       int RHSC = (int)RHS->getZExtValue();
9944       if (RHSC < 0 && RHSC > -0x1000) {
9945         assert(Ptr->getOpcode() == ISD::ADD);
9946         isInc = false;
9947         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9948         Base = Ptr->getOperand(0);
9949         return true;
9950       }
9951     }
9952
9953     if (Ptr->getOpcode() == ISD::ADD) {
9954       isInc = true;
9955       ARM_AM::ShiftOpc ShOpcVal=
9956         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9957       if (ShOpcVal != ARM_AM::no_shift) {
9958         Base = Ptr->getOperand(1);
9959         Offset = Ptr->getOperand(0);
9960       } else {
9961         Base = Ptr->getOperand(0);
9962         Offset = Ptr->getOperand(1);
9963       }
9964       return true;
9965     }
9966
9967     isInc = (Ptr->getOpcode() == ISD::ADD);
9968     Base = Ptr->getOperand(0);
9969     Offset = Ptr->getOperand(1);
9970     return true;
9971   }
9972
9973   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9974   return false;
9975 }
9976
9977 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9978                                      bool isSEXTLoad, SDValue &Base,
9979                                      SDValue &Offset, bool &isInc,
9980                                      SelectionDAG &DAG) {
9981   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9982     return false;
9983
9984   Base = Ptr->getOperand(0);
9985   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9986     int RHSC = (int)RHS->getZExtValue();
9987     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9988       assert(Ptr->getOpcode() == ISD::ADD);
9989       isInc = false;
9990       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9991       return true;
9992     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9993       isInc = Ptr->getOpcode() == ISD::ADD;
9994       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9995       return true;
9996     }
9997   }
9998
9999   return false;
10000 }
10001
10002 /// getPreIndexedAddressParts - returns true by value, base pointer and
10003 /// offset pointer and addressing mode by reference if the node's address
10004 /// can be legally represented as pre-indexed load / store address.
10005 bool
10006 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10007                                              SDValue &Offset,
10008                                              ISD::MemIndexedMode &AM,
10009                                              SelectionDAG &DAG) const {
10010   if (Subtarget->isThumb1Only())
10011     return false;
10012
10013   EVT VT;
10014   SDValue Ptr;
10015   bool isSEXTLoad = false;
10016   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10017     Ptr = LD->getBasePtr();
10018     VT  = LD->getMemoryVT();
10019     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10020   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10021     Ptr = ST->getBasePtr();
10022     VT  = ST->getMemoryVT();
10023   } else
10024     return false;
10025
10026   bool isInc;
10027   bool isLegal = false;
10028   if (Subtarget->isThumb2())
10029     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10030                                        Offset, isInc, DAG);
10031   else
10032     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10033                                         Offset, isInc, DAG);
10034   if (!isLegal)
10035     return false;
10036
10037   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10038   return true;
10039 }
10040
10041 /// getPostIndexedAddressParts - returns true by value, base pointer and
10042 /// offset pointer and addressing mode by reference if this node can be
10043 /// combined with a load / store to form a post-indexed load / store.
10044 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10045                                                    SDValue &Base,
10046                                                    SDValue &Offset,
10047                                                    ISD::MemIndexedMode &AM,
10048                                                    SelectionDAG &DAG) const {
10049   if (Subtarget->isThumb1Only())
10050     return false;
10051
10052   EVT VT;
10053   SDValue Ptr;
10054   bool isSEXTLoad = false;
10055   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10056     VT  = LD->getMemoryVT();
10057     Ptr = LD->getBasePtr();
10058     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10059   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10060     VT  = ST->getMemoryVT();
10061     Ptr = ST->getBasePtr();
10062   } else
10063     return false;
10064
10065   bool isInc;
10066   bool isLegal = false;
10067   if (Subtarget->isThumb2())
10068     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10069                                        isInc, DAG);
10070   else
10071     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10072                                         isInc, DAG);
10073   if (!isLegal)
10074     return false;
10075
10076   if (Ptr != Base) {
10077     // Swap base ptr and offset to catch more post-index load / store when
10078     // it's legal. In Thumb2 mode, offset must be an immediate.
10079     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10080         !Subtarget->isThumb2())
10081       std::swap(Base, Offset);
10082
10083     // Post-indexed load / store update the base pointer.
10084     if (Ptr != Base)
10085       return false;
10086   }
10087
10088   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10089   return true;
10090 }
10091
10092 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10093                                                        APInt &KnownZero,
10094                                                        APInt &KnownOne,
10095                                                        const SelectionDAG &DAG,
10096                                                        unsigned Depth) const {
10097   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10098   switch (Op.getOpcode()) {
10099   default: break;
10100   case ARMISD::CMOV: {
10101     // Bits are known zero/one if known on the LHS and RHS.
10102     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10103     if (KnownZero == 0 && KnownOne == 0) return;
10104
10105     APInt KnownZeroRHS, KnownOneRHS;
10106     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10107     KnownZero &= KnownZeroRHS;
10108     KnownOne  &= KnownOneRHS;
10109     return;
10110   }
10111   }
10112 }
10113
10114 //===----------------------------------------------------------------------===//
10115 //                           ARM Inline Assembly Support
10116 //===----------------------------------------------------------------------===//
10117
10118 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10119   // Looking for "rev" which is V6+.
10120   if (!Subtarget->hasV6Ops())
10121     return false;
10122
10123   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10124   std::string AsmStr = IA->getAsmString();
10125   SmallVector<StringRef, 4> AsmPieces;
10126   SplitString(AsmStr, AsmPieces, ";\n");
10127
10128   switch (AsmPieces.size()) {
10129   default: return false;
10130   case 1:
10131     AsmStr = AsmPieces[0];
10132     AsmPieces.clear();
10133     SplitString(AsmStr, AsmPieces, " \t,");
10134
10135     // rev $0, $1
10136     if (AsmPieces.size() == 3 &&
10137         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10138         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10139       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10140       if (Ty && Ty->getBitWidth() == 32)
10141         return IntrinsicLowering::LowerToByteSwap(CI);
10142     }
10143     break;
10144   }
10145
10146   return false;
10147 }
10148
10149 /// getConstraintType - Given a constraint letter, return the type of
10150 /// constraint it is for this target.
10151 ARMTargetLowering::ConstraintType
10152 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10153   if (Constraint.size() == 1) {
10154     switch (Constraint[0]) {
10155     default:  break;
10156     case 'l': return C_RegisterClass;
10157     case 'w': return C_RegisterClass;
10158     case 'h': return C_RegisterClass;
10159     case 'x': return C_RegisterClass;
10160     case 't': return C_RegisterClass;
10161     case 'j': return C_Other; // Constant for movw.
10162       // An address with a single base register. Due to the way we
10163       // currently handle addresses it is the same as an 'r' memory constraint.
10164     case 'Q': return C_Memory;
10165     }
10166   } else if (Constraint.size() == 2) {
10167     switch (Constraint[0]) {
10168     default: break;
10169     // All 'U+' constraints are addresses.
10170     case 'U': return C_Memory;
10171     }
10172   }
10173   return TargetLowering::getConstraintType(Constraint);
10174 }
10175
10176 /// Examine constraint type and operand type and determine a weight value.
10177 /// This object must already have been set up with the operand type
10178 /// and the current alternative constraint selected.
10179 TargetLowering::ConstraintWeight
10180 ARMTargetLowering::getSingleConstraintMatchWeight(
10181     AsmOperandInfo &info, const char *constraint) const {
10182   ConstraintWeight weight = CW_Invalid;
10183   Value *CallOperandVal = info.CallOperandVal;
10184     // If we don't have a value, we can't do a match,
10185     // but allow it at the lowest weight.
10186   if (CallOperandVal == NULL)
10187     return CW_Default;
10188   Type *type = CallOperandVal->getType();
10189   // Look at the constraint type.
10190   switch (*constraint) {
10191   default:
10192     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10193     break;
10194   case 'l':
10195     if (type->isIntegerTy()) {
10196       if (Subtarget->isThumb())
10197         weight = CW_SpecificReg;
10198       else
10199         weight = CW_Register;
10200     }
10201     break;
10202   case 'w':
10203     if (type->isFloatingPointTy())
10204       weight = CW_Register;
10205     break;
10206   }
10207   return weight;
10208 }
10209
10210 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10211 RCPair
10212 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10213                                                 EVT VT) const {
10214   if (Constraint.size() == 1) {
10215     // GCC ARM Constraint Letters
10216     switch (Constraint[0]) {
10217     case 'l': // Low regs or general regs.
10218       if (Subtarget->isThumb())
10219         return RCPair(0U, &ARM::tGPRRegClass);
10220       return RCPair(0U, &ARM::GPRRegClass);
10221     case 'h': // High regs or no regs.
10222       if (Subtarget->isThumb())
10223         return RCPair(0U, &ARM::hGPRRegClass);
10224       break;
10225     case 'r':
10226       return RCPair(0U, &ARM::GPRRegClass);
10227     case 'w':
10228       if (VT == MVT::f32)
10229         return RCPair(0U, &ARM::SPRRegClass);
10230       if (VT.getSizeInBits() == 64)
10231         return RCPair(0U, &ARM::DPRRegClass);
10232       if (VT.getSizeInBits() == 128)
10233         return RCPair(0U, &ARM::QPRRegClass);
10234       break;
10235     case 'x':
10236       if (VT == MVT::f32)
10237         return RCPair(0U, &ARM::SPR_8RegClass);
10238       if (VT.getSizeInBits() == 64)
10239         return RCPair(0U, &ARM::DPR_8RegClass);
10240       if (VT.getSizeInBits() == 128)
10241         return RCPair(0U, &ARM::QPR_8RegClass);
10242       break;
10243     case 't':
10244       if (VT == MVT::f32)
10245         return RCPair(0U, &ARM::SPRRegClass);
10246       break;
10247     }
10248   }
10249   if (StringRef("{cc}").equals_lower(Constraint))
10250     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10251
10252   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10253 }
10254
10255 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10256 /// vector.  If it is invalid, don't add anything to Ops.
10257 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10258                                                      std::string &Constraint,
10259                                                      std::vector<SDValue>&Ops,
10260                                                      SelectionDAG &DAG) const {
10261   SDValue Result(0, 0);
10262
10263   // Currently only support length 1 constraints.
10264   if (Constraint.length() != 1) return;
10265
10266   char ConstraintLetter = Constraint[0];
10267   switch (ConstraintLetter) {
10268   default: break;
10269   case 'j':
10270   case 'I': case 'J': case 'K': case 'L':
10271   case 'M': case 'N': case 'O':
10272     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10273     if (!C)
10274       return;
10275
10276     int64_t CVal64 = C->getSExtValue();
10277     int CVal = (int) CVal64;
10278     // None of these constraints allow values larger than 32 bits.  Check
10279     // that the value fits in an int.
10280     if (CVal != CVal64)
10281       return;
10282
10283     switch (ConstraintLetter) {
10284       case 'j':
10285         // Constant suitable for movw, must be between 0 and
10286         // 65535.
10287         if (Subtarget->hasV6T2Ops())
10288           if (CVal >= 0 && CVal <= 65535)
10289             break;
10290         return;
10291       case 'I':
10292         if (Subtarget->isThumb1Only()) {
10293           // This must be a constant between 0 and 255, for ADD
10294           // immediates.
10295           if (CVal >= 0 && CVal <= 255)
10296             break;
10297         } else if (Subtarget->isThumb2()) {
10298           // A constant that can be used as an immediate value in a
10299           // data-processing instruction.
10300           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10301             break;
10302         } else {
10303           // A constant that can be used as an immediate value in a
10304           // data-processing instruction.
10305           if (ARM_AM::getSOImmVal(CVal) != -1)
10306             break;
10307         }
10308         return;
10309
10310       case 'J':
10311         if (Subtarget->isThumb()) {  // FIXME thumb2
10312           // This must be a constant between -255 and -1, for negated ADD
10313           // immediates. This can be used in GCC with an "n" modifier that
10314           // prints the negated value, for use with SUB instructions. It is
10315           // not useful otherwise but is implemented for compatibility.
10316           if (CVal >= -255 && CVal <= -1)
10317             break;
10318         } else {
10319           // This must be a constant between -4095 and 4095. It is not clear
10320           // what this constraint is intended for. Implemented for
10321           // compatibility with GCC.
10322           if (CVal >= -4095 && CVal <= 4095)
10323             break;
10324         }
10325         return;
10326
10327       case 'K':
10328         if (Subtarget->isThumb1Only()) {
10329           // A 32-bit value where only one byte has a nonzero value. Exclude
10330           // zero to match GCC. This constraint is used by GCC internally for
10331           // constants that can be loaded with a move/shift combination.
10332           // It is not useful otherwise but is implemented for compatibility.
10333           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10334             break;
10335         } else if (Subtarget->isThumb2()) {
10336           // A constant whose bitwise inverse can be used as an immediate
10337           // value in a data-processing instruction. This can be used in GCC
10338           // with a "B" modifier that prints the inverted value, for use with
10339           // BIC and MVN instructions. It is not useful otherwise but is
10340           // implemented for compatibility.
10341           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10342             break;
10343         } else {
10344           // A constant whose bitwise inverse can be used as an immediate
10345           // value in a data-processing instruction. This can be used in GCC
10346           // with a "B" modifier that prints the inverted value, for use with
10347           // BIC and MVN instructions. It is not useful otherwise but is
10348           // implemented for compatibility.
10349           if (ARM_AM::getSOImmVal(~CVal) != -1)
10350             break;
10351         }
10352         return;
10353
10354       case 'L':
10355         if (Subtarget->isThumb1Only()) {
10356           // This must be a constant between -7 and 7,
10357           // for 3-operand ADD/SUB immediate instructions.
10358           if (CVal >= -7 && CVal < 7)
10359             break;
10360         } else if (Subtarget->isThumb2()) {
10361           // A constant whose negation can be used as an immediate value in a
10362           // data-processing instruction. This can be used in GCC with an "n"
10363           // modifier that prints the negated value, for use with SUB
10364           // instructions. It is not useful otherwise but is implemented for
10365           // compatibility.
10366           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10367             break;
10368         } else {
10369           // A constant whose negation can be used as an immediate value in a
10370           // data-processing instruction. This can be used in GCC with an "n"
10371           // modifier that prints the negated value, for use with SUB
10372           // instructions. It is not useful otherwise but is implemented for
10373           // compatibility.
10374           if (ARM_AM::getSOImmVal(-CVal) != -1)
10375             break;
10376         }
10377         return;
10378
10379       case 'M':
10380         if (Subtarget->isThumb()) { // FIXME thumb2
10381           // This must be a multiple of 4 between 0 and 1020, for
10382           // ADD sp + immediate.
10383           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10384             break;
10385         } else {
10386           // A power of two or a constant between 0 and 32.  This is used in
10387           // GCC for the shift amount on shifted register operands, but it is
10388           // useful in general for any shift amounts.
10389           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10390             break;
10391         }
10392         return;
10393
10394       case 'N':
10395         if (Subtarget->isThumb()) {  // FIXME thumb2
10396           // This must be a constant between 0 and 31, for shift amounts.
10397           if (CVal >= 0 && CVal <= 31)
10398             break;
10399         }
10400         return;
10401
10402       case 'O':
10403         if (Subtarget->isThumb()) {  // FIXME thumb2
10404           // This must be a multiple of 4 between -508 and 508, for
10405           // ADD/SUB sp = sp + immediate.
10406           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10407             break;
10408         }
10409         return;
10410     }
10411     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10412     break;
10413   }
10414
10415   if (Result.getNode()) {
10416     Ops.push_back(Result);
10417     return;
10418   }
10419   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10420 }
10421
10422 bool
10423 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10424   // The ARM target isn't yet aware of offsets.
10425   return false;
10426 }
10427
10428 bool ARM::isBitFieldInvertedMask(unsigned v) {
10429   if (v == 0xffffffff)
10430     return 0;
10431   // there can be 1's on either or both "outsides", all the "inside"
10432   // bits must be 0's
10433   unsigned int lsb = 0, msb = 31;
10434   while (v & (1 << msb)) --msb;
10435   while (v & (1 << lsb)) ++lsb;
10436   for (unsigned int i = lsb; i <= msb; ++i) {
10437     if (v & (1 << i))
10438       return 0;
10439   }
10440   return 1;
10441 }
10442
10443 /// isFPImmLegal - Returns true if the target can instruction select the
10444 /// specified FP immediate natively. If false, the legalizer will
10445 /// materialize the FP immediate as a load from a constant pool.
10446 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10447   if (!Subtarget->hasVFP3())
10448     return false;
10449   if (VT == MVT::f32)
10450     return ARM_AM::getFP32Imm(Imm) != -1;
10451   if (VT == MVT::f64)
10452     return ARM_AM::getFP64Imm(Imm) != -1;
10453   return false;
10454 }
10455
10456 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10457 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10458 /// specified in the intrinsic calls.
10459 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10460                                            const CallInst &I,
10461                                            unsigned Intrinsic) const {
10462   switch (Intrinsic) {
10463   case Intrinsic::arm_neon_vld1:
10464   case Intrinsic::arm_neon_vld2:
10465   case Intrinsic::arm_neon_vld3:
10466   case Intrinsic::arm_neon_vld4:
10467   case Intrinsic::arm_neon_vld2lane:
10468   case Intrinsic::arm_neon_vld3lane:
10469   case Intrinsic::arm_neon_vld4lane: {
10470     Info.opc = ISD::INTRINSIC_W_CHAIN;
10471     // Conservatively set memVT to the entire set of vectors loaded.
10472     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10473     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10474     Info.ptrVal = I.getArgOperand(0);
10475     Info.offset = 0;
10476     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10477     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10478     Info.vol = false; // volatile loads with NEON intrinsics not supported
10479     Info.readMem = true;
10480     Info.writeMem = false;
10481     return true;
10482   }
10483   case Intrinsic::arm_neon_vst1:
10484   case Intrinsic::arm_neon_vst2:
10485   case Intrinsic::arm_neon_vst3:
10486   case Intrinsic::arm_neon_vst4:
10487   case Intrinsic::arm_neon_vst2lane:
10488   case Intrinsic::arm_neon_vst3lane:
10489   case Intrinsic::arm_neon_vst4lane: {
10490     Info.opc = ISD::INTRINSIC_VOID;
10491     // Conservatively set memVT to the entire set of vectors stored.
10492     unsigned NumElts = 0;
10493     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10494       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10495       if (!ArgTy->isVectorTy())
10496         break;
10497       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10498     }
10499     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10500     Info.ptrVal = I.getArgOperand(0);
10501     Info.offset = 0;
10502     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10503     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10504     Info.vol = false; // volatile stores with NEON intrinsics not supported
10505     Info.readMem = false;
10506     Info.writeMem = true;
10507     return true;
10508   }
10509   case Intrinsic::arm_strexd: {
10510     Info.opc = ISD::INTRINSIC_W_CHAIN;
10511     Info.memVT = MVT::i64;
10512     Info.ptrVal = I.getArgOperand(2);
10513     Info.offset = 0;
10514     Info.align = 8;
10515     Info.vol = true;
10516     Info.readMem = false;
10517     Info.writeMem = true;
10518     return true;
10519   }
10520   case Intrinsic::arm_ldrexd: {
10521     Info.opc = ISD::INTRINSIC_W_CHAIN;
10522     Info.memVT = MVT::i64;
10523     Info.ptrVal = I.getArgOperand(0);
10524     Info.offset = 0;
10525     Info.align = 8;
10526     Info.vol = true;
10527     Info.readMem = true;
10528     Info.writeMem = false;
10529     return true;
10530   }
10531   default:
10532     break;
10533   }
10534
10535   return false;
10536 }