ARM: tail-call inside a function where part of a byval argument is on caller's
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(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
508     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
509     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
510     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
519
520     // Neon does not support some operations on v1i64 and v2i64 types.
521     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
522     // Custom handling for some quad-vector types to detect VMULL.
523     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
524     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
525     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
526     // Custom handling for some vector types to avoid expensive expansions
527     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
528     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
529     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
532     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
533     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
534     // a destination type that is wider than the source, and nor does
535     // it have a FP_TO_[SU]INT instruction with a narrower destination than
536     // source.
537     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
538     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
539     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
540     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
541
542     setTargetDAGCombine(ISD::INTRINSIC_VOID);
543     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
544     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
545     setTargetDAGCombine(ISD::SHL);
546     setTargetDAGCombine(ISD::SRL);
547     setTargetDAGCombine(ISD::SRA);
548     setTargetDAGCombine(ISD::SIGN_EXTEND);
549     setTargetDAGCombine(ISD::ZERO_EXTEND);
550     setTargetDAGCombine(ISD::ANY_EXTEND);
551     setTargetDAGCombine(ISD::SELECT_CC);
552     setTargetDAGCombine(ISD::BUILD_VECTOR);
553     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
554     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
555     setTargetDAGCombine(ISD::STORE);
556     setTargetDAGCombine(ISD::FP_TO_SINT);
557     setTargetDAGCombine(ISD::FP_TO_UINT);
558     setTargetDAGCombine(ISD::FDIV);
559
560     // It is legal to extload from v4i8 to v4i16 or v4i32.
561     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
562                   MVT::v4i16, MVT::v2i16,
563                   MVT::v2i32};
564     for (unsigned i = 0; i < 6; ++i) {
565       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
566       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
567       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
568     }
569   }
570
571   // ARM and Thumb2 support UMLAL/SMLAL.
572   if (!Subtarget->isThumb1Only())
573     setTargetDAGCombine(ISD::ADDC);
574
575
576   computeRegisterProperties();
577
578   // ARM does not have f32 extending load.
579   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
580
581   // ARM does not have i1 sign extending load.
582   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
583
584   // ARM supports all 4 flavors of integer indexed load / store.
585   if (!Subtarget->isThumb1Only()) {
586     for (unsigned im = (unsigned)ISD::PRE_INC;
587          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
588       setIndexedLoadAction(im,  MVT::i1,  Legal);
589       setIndexedLoadAction(im,  MVT::i8,  Legal);
590       setIndexedLoadAction(im,  MVT::i16, Legal);
591       setIndexedLoadAction(im,  MVT::i32, Legal);
592       setIndexedStoreAction(im, MVT::i1,  Legal);
593       setIndexedStoreAction(im, MVT::i8,  Legal);
594       setIndexedStoreAction(im, MVT::i16, Legal);
595       setIndexedStoreAction(im, MVT::i32, Legal);
596     }
597   }
598
599   // i64 operation support.
600   setOperationAction(ISD::MUL,     MVT::i64, Expand);
601   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
602   if (Subtarget->isThumb1Only()) {
603     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
604     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
605   }
606   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
607       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
608     setOperationAction(ISD::MULHS, MVT::i32, Expand);
609
610   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
611   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
612   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
613   setOperationAction(ISD::SRL,       MVT::i64, Custom);
614   setOperationAction(ISD::SRA,       MVT::i64, Custom);
615
616   if (!Subtarget->isThumb1Only()) {
617     // FIXME: We should do this for Thumb1 as well.
618     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
619     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
620     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
621     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
622   }
623
624   // ARM does not have ROTL.
625   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
626   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
627   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
628   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
629     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
630
631   // These just redirect to CTTZ and CTLZ on ARM.
632   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
633   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
634
635   // Only ARMv6 has BSWAP.
636   if (!Subtarget->hasV6Ops())
637     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
638
639   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
640       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
641     // These are expanded into libcalls if the cpu doesn't have HW divider.
642     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
643     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
644   }
645   setOperationAction(ISD::SREM,  MVT::i32, Expand);
646   setOperationAction(ISD::UREM,  MVT::i32, Expand);
647   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
648   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
649
650   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
651   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
652   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
653   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
654   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
655
656   setOperationAction(ISD::TRAP, MVT::Other, Legal);
657
658   // Use the default implementation.
659   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
660   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
661   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
662   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
663   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
664   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
665
666   if (!Subtarget->isTargetDarwin()) {
667     // Non-Darwin platforms may return values in these registers via the
668     // personality function.
669     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
670     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
671     setExceptionPointerRegister(ARM::R0);
672     setExceptionSelectorRegister(ARM::R1);
673   }
674
675   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
676   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
677   // the default expansion.
678   // FIXME: This should be checking for v6k, not just v6.
679   if (Subtarget->hasDataBarrier() ||
680       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
681     // membarrier needs custom lowering; the rest are legal and handled
682     // normally.
683     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
684     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
685     // Custom lowering for 64-bit ops
686     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
690     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
691     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
692     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
693     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
694     setInsertFencesForAtomic(true);
695   } else {
696     // Set them all for expansion, which will force libcalls.
697     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
698     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
699     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
710     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
711     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
712     // Unordered/Monotonic case.
713     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
714     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
715     // Since the libcalls include locking, fold in the fences
716     setShouldFoldAtomicFences(true);
717   }
718
719   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
720
721   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
722   if (!Subtarget->hasV6Ops()) {
723     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
725   }
726   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
727
728   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
729       !Subtarget->isThumb1Only()) {
730     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
731     // iff target supports vfp2.
732     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
733     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
734   }
735
736   // We want to custom lower some of our intrinsics.
737   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
738   if (Subtarget->isTargetDarwin()) {
739     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
740     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
741     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
742   }
743
744   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
745   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
746   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
747   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
748   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
749   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
750   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
751   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
752   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
753
754   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
755   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
756   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
757   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
758   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
759
760   // We don't support sin/cos/fmod/copysign/pow
761   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
762   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
763   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
764   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
765   setOperationAction(ISD::FREM,      MVT::f64, Expand);
766   setOperationAction(ISD::FREM,      MVT::f32, Expand);
767   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
768       !Subtarget->isThumb1Only()) {
769     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
770     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
771   }
772   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
773   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
774
775   if (!Subtarget->hasVFP4()) {
776     setOperationAction(ISD::FMA, MVT::f64, Expand);
777     setOperationAction(ISD::FMA, MVT::f32, Expand);
778   }
779
780   // Various VFP goodness
781   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
782     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
783     if (Subtarget->hasVFP2()) {
784       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
785       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
786       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
787       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
788     }
789     // Special handling for half-precision FP.
790     if (!Subtarget->hasFP16()) {
791       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
792       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
793     }
794   }
795
796   // We have target-specific dag combine patterns for the following nodes:
797   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
798   setTargetDAGCombine(ISD::ADD);
799   setTargetDAGCombine(ISD::SUB);
800   setTargetDAGCombine(ISD::MUL);
801   setTargetDAGCombine(ISD::AND);
802   setTargetDAGCombine(ISD::OR);
803   setTargetDAGCombine(ISD::XOR);
804
805   if (Subtarget->hasV6Ops())
806     setTargetDAGCombine(ISD::SRL);
807
808   setStackPointerRegisterToSaveRestore(ARM::SP);
809
810   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
811       !Subtarget->hasVFP2())
812     setSchedulingPreference(Sched::RegPressure);
813   else
814     setSchedulingPreference(Sched::Hybrid);
815
816   //// temporary - rewrite interface to use type
817   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
818   maxStoresPerMemset = 16;
819   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
820
821   // On ARM arguments smaller than 4 bytes are extended, so all arguments
822   // are at least 4 bytes aligned.
823   setMinStackArgumentAlignment(4);
824
825   benefitFromCodePlacementOpt = true;
826
827   // Prefer likely predicted branches to selects on out-of-order cores.
828   predictableSelectIsExpensive = Subtarget->isLikeA9();
829
830   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
831 }
832
833 // FIXME: It might make sense to define the representative register class as the
834 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
835 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
836 // SPR's representative would be DPR_VFP2. This should work well if register
837 // pressure tracking were modified such that a register use would increment the
838 // pressure of the register class's representative and all of it's super
839 // classes' representatives transitively. We have not implemented this because
840 // of the difficulty prior to coalescing of modeling operand register classes
841 // due to the common occurrence of cross class copies and subregister insertions
842 // and extractions.
843 std::pair<const TargetRegisterClass*, uint8_t>
844 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
845   const TargetRegisterClass *RRC = 0;
846   uint8_t Cost = 1;
847   switch (VT.getSimpleVT().SimpleTy) {
848   default:
849     return TargetLowering::findRepresentativeClass(VT);
850   // Use DPR as representative register class for all floating point
851   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
852   // the cost is 1 for both f32 and f64.
853   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
854   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
855     RRC = &ARM::DPRRegClass;
856     // When NEON is used for SP, only half of the register file is available
857     // because operations that define both SP and DP results will be constrained
858     // to the VFP2 class (D0-D15). We currently model this constraint prior to
859     // coalescing by double-counting the SP regs. See the FIXME above.
860     if (Subtarget->useNEONForSinglePrecisionFP())
861       Cost = 2;
862     break;
863   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
864   case MVT::v4f32: case MVT::v2f64:
865     RRC = &ARM::DPRRegClass;
866     Cost = 2;
867     break;
868   case MVT::v4i64:
869     RRC = &ARM::DPRRegClass;
870     Cost = 4;
871     break;
872   case MVT::v8i64:
873     RRC = &ARM::DPRRegClass;
874     Cost = 8;
875     break;
876   }
877   return std::make_pair(RRC, Cost);
878 }
879
880 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
881   switch (Opcode) {
882   default: return 0;
883   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
884   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
885   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
886   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
887   case ARMISD::CALL:          return "ARMISD::CALL";
888   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
889   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
890   case ARMISD::tCALL:         return "ARMISD::tCALL";
891   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
892   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
893   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
894   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
895   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
896   case ARMISD::CMP:           return "ARMISD::CMP";
897   case ARMISD::CMN:           return "ARMISD::CMN";
898   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
899   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
900   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
901   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
902   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
903
904   case ARMISD::CMOV:          return "ARMISD::CMOV";
905
906   case ARMISD::RBIT:          return "ARMISD::RBIT";
907
908   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
909   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
910   case ARMISD::SITOF:         return "ARMISD::SITOF";
911   case ARMISD::UITOF:         return "ARMISD::UITOF";
912
913   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
914   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
915   case ARMISD::RRX:           return "ARMISD::RRX";
916
917   case ARMISD::ADDC:          return "ARMISD::ADDC";
918   case ARMISD::ADDE:          return "ARMISD::ADDE";
919   case ARMISD::SUBC:          return "ARMISD::SUBC";
920   case ARMISD::SUBE:          return "ARMISD::SUBE";
921
922   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
923   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
924
925   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
926   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
927
928   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
929
930   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
931
932   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
933
934   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
935   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
936
937   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
938
939   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
940   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
941   case ARMISD::VCGE:          return "ARMISD::VCGE";
942   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
943   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
944   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
945   case ARMISD::VCGT:          return "ARMISD::VCGT";
946   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
947   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
948   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
949   case ARMISD::VTST:          return "ARMISD::VTST";
950
951   case ARMISD::VSHL:          return "ARMISD::VSHL";
952   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
953   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
954   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
955   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
956   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
957   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
958   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
959   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
960   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
961   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
962   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
963   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
964   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
965   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
966   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
967   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
968   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
969   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
970   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
971   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
972   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
973   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
974   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
975   case ARMISD::VDUP:          return "ARMISD::VDUP";
976   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
977   case ARMISD::VEXT:          return "ARMISD::VEXT";
978   case ARMISD::VREV64:        return "ARMISD::VREV64";
979   case ARMISD::VREV32:        return "ARMISD::VREV32";
980   case ARMISD::VREV16:        return "ARMISD::VREV16";
981   case ARMISD::VZIP:          return "ARMISD::VZIP";
982   case ARMISD::VUZP:          return "ARMISD::VUZP";
983   case ARMISD::VTRN:          return "ARMISD::VTRN";
984   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
985   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
986   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
987   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
988   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
989   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
990   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
991   case ARMISD::FMAX:          return "ARMISD::FMAX";
992   case ARMISD::FMIN:          return "ARMISD::FMIN";
993   case ARMISD::BFI:           return "ARMISD::BFI";
994   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
995   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
996   case ARMISD::VBSL:          return "ARMISD::VBSL";
997   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
998   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
999   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1000   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1001   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1002   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1003   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1004   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1005   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1006   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1007   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1008   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1009   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1010   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1011   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1012   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1013   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1014   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1015   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1016   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1017   }
1018 }
1019
1020 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1021   if (!VT.isVector()) return getPointerTy();
1022   return VT.changeVectorElementTypeToInteger();
1023 }
1024
1025 /// getRegClassFor - Return the register class that should be used for the
1026 /// specified value type.
1027 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1028   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1029   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1030   // load / store 4 to 8 consecutive D registers.
1031   if (Subtarget->hasNEON()) {
1032     if (VT == MVT::v4i64)
1033       return &ARM::QQPRRegClass;
1034     if (VT == MVT::v8i64)
1035       return &ARM::QQQQPRRegClass;
1036   }
1037   return TargetLowering::getRegClassFor(VT);
1038 }
1039
1040 // Create a fast isel object.
1041 FastISel *
1042 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1043                                   const TargetLibraryInfo *libInfo) const {
1044   return ARM::createFastISel(funcInfo, libInfo);
1045 }
1046
1047 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1048 /// be used for loads / stores from the global.
1049 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1050   return (Subtarget->isThumb1Only() ? 127 : 4095);
1051 }
1052
1053 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1054   unsigned NumVals = N->getNumValues();
1055   if (!NumVals)
1056     return Sched::RegPressure;
1057
1058   for (unsigned i = 0; i != NumVals; ++i) {
1059     EVT VT = N->getValueType(i);
1060     if (VT == MVT::Glue || VT == MVT::Other)
1061       continue;
1062     if (VT.isFloatingPoint() || VT.isVector())
1063       return Sched::ILP;
1064   }
1065
1066   if (!N->isMachineOpcode())
1067     return Sched::RegPressure;
1068
1069   // Load are scheduled for latency even if there instruction itinerary
1070   // is not available.
1071   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1072   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1073
1074   if (MCID.getNumDefs() == 0)
1075     return Sched::RegPressure;
1076   if (!Itins->isEmpty() &&
1077       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1078     return Sched::ILP;
1079
1080   return Sched::RegPressure;
1081 }
1082
1083 //===----------------------------------------------------------------------===//
1084 // Lowering Code
1085 //===----------------------------------------------------------------------===//
1086
1087 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1088 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1089   switch (CC) {
1090   default: llvm_unreachable("Unknown condition code!");
1091   case ISD::SETNE:  return ARMCC::NE;
1092   case ISD::SETEQ:  return ARMCC::EQ;
1093   case ISD::SETGT:  return ARMCC::GT;
1094   case ISD::SETGE:  return ARMCC::GE;
1095   case ISD::SETLT:  return ARMCC::LT;
1096   case ISD::SETLE:  return ARMCC::LE;
1097   case ISD::SETUGT: return ARMCC::HI;
1098   case ISD::SETUGE: return ARMCC::HS;
1099   case ISD::SETULT: return ARMCC::LO;
1100   case ISD::SETULE: return ARMCC::LS;
1101   }
1102 }
1103
1104 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1105 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1106                         ARMCC::CondCodes &CondCode2) {
1107   CondCode2 = ARMCC::AL;
1108   switch (CC) {
1109   default: llvm_unreachable("Unknown FP condition!");
1110   case ISD::SETEQ:
1111   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1112   case ISD::SETGT:
1113   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1114   case ISD::SETGE:
1115   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1116   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1117   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1118   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1119   case ISD::SETO:   CondCode = ARMCC::VC; break;
1120   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1121   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1122   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1123   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1124   case ISD::SETLT:
1125   case ISD::SETULT: CondCode = ARMCC::LT; break;
1126   case ISD::SETLE:
1127   case ISD::SETULE: CondCode = ARMCC::LE; break;
1128   case ISD::SETNE:
1129   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1130   }
1131 }
1132
1133 //===----------------------------------------------------------------------===//
1134 //                      Calling Convention Implementation
1135 //===----------------------------------------------------------------------===//
1136
1137 #include "ARMGenCallingConv.inc"
1138
1139 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1140 /// given CallingConvention value.
1141 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1142                                                  bool Return,
1143                                                  bool isVarArg) const {
1144   switch (CC) {
1145   default:
1146     llvm_unreachable("Unsupported calling convention");
1147   case CallingConv::Fast:
1148     if (Subtarget->hasVFP2() && !isVarArg) {
1149       if (!Subtarget->isAAPCS_ABI())
1150         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1151       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1152       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1153     }
1154     // Fallthrough
1155   case CallingConv::C: {
1156     // Use target triple & subtarget features to do actual dispatch.
1157     if (!Subtarget->isAAPCS_ABI())
1158       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1159     else if (Subtarget->hasVFP2() &&
1160              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1161              !isVarArg)
1162       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1163     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1164   }
1165   case CallingConv::ARM_AAPCS_VFP:
1166     if (!isVarArg)
1167       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1168     // Fallthrough
1169   case CallingConv::ARM_AAPCS:
1170     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1171   case CallingConv::ARM_APCS:
1172     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1173   case CallingConv::GHC:
1174     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1175   }
1176 }
1177
1178 /// LowerCallResult - Lower the result values of a call into the
1179 /// appropriate copies out of appropriate physical registers.
1180 SDValue
1181 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1182                                    CallingConv::ID CallConv, bool isVarArg,
1183                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1184                                    DebugLoc dl, SelectionDAG &DAG,
1185                                    SmallVectorImpl<SDValue> &InVals) const {
1186
1187   // Assign locations to each value returned by this call.
1188   SmallVector<CCValAssign, 16> RVLocs;
1189   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1190                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1191   CCInfo.AnalyzeCallResult(Ins,
1192                            CCAssignFnForNode(CallConv, /* Return*/ true,
1193                                              isVarArg));
1194
1195   // Copy all of the result registers out of their specified physreg.
1196   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1197     CCValAssign VA = RVLocs[i];
1198
1199     SDValue Val;
1200     if (VA.needsCustom()) {
1201       // Handle f64 or half of a v2f64.
1202       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1203                                       InFlag);
1204       Chain = Lo.getValue(1);
1205       InFlag = Lo.getValue(2);
1206       VA = RVLocs[++i]; // skip ahead to next loc
1207       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1208                                       InFlag);
1209       Chain = Hi.getValue(1);
1210       InFlag = Hi.getValue(2);
1211       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1212
1213       if (VA.getLocVT() == MVT::v2f64) {
1214         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1215         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1216                           DAG.getConstant(0, MVT::i32));
1217
1218         VA = RVLocs[++i]; // skip ahead to next loc
1219         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1220         Chain = Lo.getValue(1);
1221         InFlag = Lo.getValue(2);
1222         VA = RVLocs[++i]; // skip ahead to next loc
1223         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1224         Chain = Hi.getValue(1);
1225         InFlag = Hi.getValue(2);
1226         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1227         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1228                           DAG.getConstant(1, MVT::i32));
1229       }
1230     } else {
1231       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1232                                InFlag);
1233       Chain = Val.getValue(1);
1234       InFlag = Val.getValue(2);
1235     }
1236
1237     switch (VA.getLocInfo()) {
1238     default: llvm_unreachable("Unknown loc info!");
1239     case CCValAssign::Full: break;
1240     case CCValAssign::BCvt:
1241       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1242       break;
1243     }
1244
1245     InVals.push_back(Val);
1246   }
1247
1248   return Chain;
1249 }
1250
1251 /// LowerMemOpCallTo - Store the argument to the stack.
1252 SDValue
1253 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1254                                     SDValue StackPtr, SDValue Arg,
1255                                     DebugLoc dl, SelectionDAG &DAG,
1256                                     const CCValAssign &VA,
1257                                     ISD::ArgFlagsTy Flags) const {
1258   unsigned LocMemOffset = VA.getLocMemOffset();
1259   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1260   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1261   return DAG.getStore(Chain, dl, Arg, PtrOff,
1262                       MachinePointerInfo::getStack(LocMemOffset),
1263                       false, false, 0);
1264 }
1265
1266 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1267                                          SDValue Chain, SDValue &Arg,
1268                                          RegsToPassVector &RegsToPass,
1269                                          CCValAssign &VA, CCValAssign &NextVA,
1270                                          SDValue &StackPtr,
1271                                          SmallVector<SDValue, 8> &MemOpChains,
1272                                          ISD::ArgFlagsTy Flags) const {
1273
1274   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1275                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1276   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1277
1278   if (NextVA.isRegLoc())
1279     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1280   else {
1281     assert(NextVA.isMemLoc());
1282     if (StackPtr.getNode() == 0)
1283       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1284
1285     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1286                                            dl, DAG, NextVA,
1287                                            Flags));
1288   }
1289 }
1290
1291 /// LowerCall - Lowering a call into a callseq_start <-
1292 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1293 /// nodes.
1294 SDValue
1295 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1296                              SmallVectorImpl<SDValue> &InVals) const {
1297   SelectionDAG &DAG                     = CLI.DAG;
1298   DebugLoc &dl                          = CLI.DL;
1299   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1300   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1301   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1302   SDValue Chain                         = CLI.Chain;
1303   SDValue Callee                        = CLI.Callee;
1304   bool &isTailCall                      = CLI.IsTailCall;
1305   CallingConv::ID CallConv              = CLI.CallConv;
1306   bool doesNotRet                       = CLI.DoesNotReturn;
1307   bool isVarArg                         = CLI.IsVarArg;
1308
1309   MachineFunction &MF = DAG.getMachineFunction();
1310   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1311   bool IsSibCall = false;
1312   // Disable tail calls if they're not supported.
1313   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1314     isTailCall = false;
1315   if (isTailCall) {
1316     // Check if it's really possible to do a tail call.
1317     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1318                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1319                                                    Outs, OutVals, Ins, DAG);
1320     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1321     // detected sibcalls.
1322     if (isTailCall) {
1323       ++NumTailCalls;
1324       IsSibCall = true;
1325     }
1326   }
1327
1328   // Analyze operands of the call, assigning locations to each operand.
1329   SmallVector<CCValAssign, 16> ArgLocs;
1330   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1331                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1332   CCInfo.AnalyzeCallOperands(Outs,
1333                              CCAssignFnForNode(CallConv, /* Return*/ false,
1334                                                isVarArg));
1335
1336   // Get a count of how many bytes are to be pushed on the stack.
1337   unsigned NumBytes = CCInfo.getNextStackOffset();
1338
1339   // For tail calls, memory operands are available in our caller's stack.
1340   if (IsSibCall)
1341     NumBytes = 0;
1342
1343   // Adjust the stack pointer for the new arguments...
1344   // These operations are automatically eliminated by the prolog/epilog pass
1345   if (!IsSibCall)
1346     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1347
1348   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1349
1350   RegsToPassVector RegsToPass;
1351   SmallVector<SDValue, 8> MemOpChains;
1352
1353   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1354   // of tail call optimization, arguments are handled later.
1355   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1356        i != e;
1357        ++i, ++realArgIdx) {
1358     CCValAssign &VA = ArgLocs[i];
1359     SDValue Arg = OutVals[realArgIdx];
1360     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1361     bool isByVal = Flags.isByVal();
1362
1363     // Promote the value if needed.
1364     switch (VA.getLocInfo()) {
1365     default: llvm_unreachable("Unknown loc info!");
1366     case CCValAssign::Full: break;
1367     case CCValAssign::SExt:
1368       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1369       break;
1370     case CCValAssign::ZExt:
1371       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1372       break;
1373     case CCValAssign::AExt:
1374       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1375       break;
1376     case CCValAssign::BCvt:
1377       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1378       break;
1379     }
1380
1381     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1382     if (VA.needsCustom()) {
1383       if (VA.getLocVT() == MVT::v2f64) {
1384         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1385                                   DAG.getConstant(0, MVT::i32));
1386         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1387                                   DAG.getConstant(1, MVT::i32));
1388
1389         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1390                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1391
1392         VA = ArgLocs[++i]; // skip ahead to next loc
1393         if (VA.isRegLoc()) {
1394           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1395                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1396         } else {
1397           assert(VA.isMemLoc());
1398
1399           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1400                                                  dl, DAG, VA, Flags));
1401         }
1402       } else {
1403         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1404                          StackPtr, MemOpChains, Flags);
1405       }
1406     } else if (VA.isRegLoc()) {
1407       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1408     } else if (isByVal) {
1409       assert(VA.isMemLoc());
1410       unsigned offset = 0;
1411
1412       // True if this byval aggregate will be split between registers
1413       // and memory.
1414       if (CCInfo.isFirstByValRegValid()) {
1415         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1416         unsigned int i, j;
1417         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1418           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1419           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1420           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1421                                      MachinePointerInfo(),
1422                                      false, false, false, 0);
1423           MemOpChains.push_back(Load.getValue(1));
1424           RegsToPass.push_back(std::make_pair(j, Load));
1425         }
1426         offset = ARM::R4 - CCInfo.getFirstByValReg();
1427         CCInfo.clearFirstByValReg();
1428       }
1429
1430       if (Flags.getByValSize() - 4*offset > 0) {
1431         unsigned LocMemOffset = VA.getLocMemOffset();
1432         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1433         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1434                                   StkPtrOff);
1435         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1436         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1437         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1438                                            MVT::i32);
1439         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1440
1441         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1442         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1443         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1444                                           Ops, array_lengthof(Ops)));
1445       }
1446     } else if (!IsSibCall) {
1447       assert(VA.isMemLoc());
1448
1449       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1450                                              dl, DAG, VA, Flags));
1451     }
1452   }
1453
1454   if (!MemOpChains.empty())
1455     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1456                         &MemOpChains[0], MemOpChains.size());
1457
1458   // Build a sequence of copy-to-reg nodes chained together with token chain
1459   // and flag operands which copy the outgoing args into the appropriate regs.
1460   SDValue InFlag;
1461   // Tail call byval lowering might overwrite argument registers so in case of
1462   // tail call optimization the copies to registers are lowered later.
1463   if (!isTailCall)
1464     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1465       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1466                                RegsToPass[i].second, InFlag);
1467       InFlag = Chain.getValue(1);
1468     }
1469
1470   // For tail calls lower the arguments to the 'real' stack slot.
1471   if (isTailCall) {
1472     // Force all the incoming stack arguments to be loaded from the stack
1473     // before any new outgoing arguments are stored to the stack, because the
1474     // outgoing stack slots may alias the incoming argument stack slots, and
1475     // the alias isn't otherwise explicit. This is slightly more conservative
1476     // than necessary, because it means that each store effectively depends
1477     // on every argument instead of just those arguments it would clobber.
1478
1479     // Do not flag preceding copytoreg stuff together with the following stuff.
1480     InFlag = SDValue();
1481     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1482       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1483                                RegsToPass[i].second, InFlag);
1484       InFlag = Chain.getValue(1);
1485     }
1486     InFlag =SDValue();
1487   }
1488
1489   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1490   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1491   // node so that legalize doesn't hack it.
1492   bool isDirect = false;
1493   bool isARMFunc = false;
1494   bool isLocalARMFunc = false;
1495   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1496
1497   if (EnableARMLongCalls) {
1498     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1499             && "long-calls with non-static relocation model!");
1500     // Handle a global address or an external symbol. If it's not one of
1501     // those, the target's already in a register, so we don't need to do
1502     // anything extra.
1503     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1504       const GlobalValue *GV = G->getGlobal();
1505       // Create a constant pool entry for the callee address
1506       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1507       ARMConstantPoolValue *CPV =
1508         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1509
1510       // Get the address of the callee into a register
1511       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1512       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1513       Callee = DAG.getLoad(getPointerTy(), dl,
1514                            DAG.getEntryNode(), CPAddr,
1515                            MachinePointerInfo::getConstantPool(),
1516                            false, false, false, 0);
1517     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1518       const char *Sym = S->getSymbol();
1519
1520       // Create a constant pool entry for the callee address
1521       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1522       ARMConstantPoolValue *CPV =
1523         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1524                                       ARMPCLabelIndex, 0);
1525       // Get the address of the callee into a register
1526       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1527       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1528       Callee = DAG.getLoad(getPointerTy(), dl,
1529                            DAG.getEntryNode(), CPAddr,
1530                            MachinePointerInfo::getConstantPool(),
1531                            false, false, false, 0);
1532     }
1533   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1534     const GlobalValue *GV = G->getGlobal();
1535     isDirect = true;
1536     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1537     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1538                    getTargetMachine().getRelocationModel() != Reloc::Static;
1539     isARMFunc = !Subtarget->isThumb() || isStub;
1540     // ARM call to a local ARM function is predicable.
1541     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1542     // tBX takes a register source operand.
1543     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1544       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1545       ARMConstantPoolValue *CPV =
1546         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1547       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1548       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1549       Callee = DAG.getLoad(getPointerTy(), dl,
1550                            DAG.getEntryNode(), CPAddr,
1551                            MachinePointerInfo::getConstantPool(),
1552                            false, false, false, 0);
1553       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1554       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1555                            getPointerTy(), Callee, PICLabel);
1556     } else {
1557       // On ELF targets for PIC code, direct calls should go through the PLT
1558       unsigned OpFlags = 0;
1559       if (Subtarget->isTargetELF() &&
1560                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1561         OpFlags = ARMII::MO_PLT;
1562       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1563     }
1564   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1565     isDirect = true;
1566     bool isStub = Subtarget->isTargetDarwin() &&
1567                   getTargetMachine().getRelocationModel() != Reloc::Static;
1568     isARMFunc = !Subtarget->isThumb() || isStub;
1569     // tBX takes a register source operand.
1570     const char *Sym = S->getSymbol();
1571     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1572       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1573       ARMConstantPoolValue *CPV =
1574         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1575                                       ARMPCLabelIndex, 4);
1576       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1577       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1578       Callee = DAG.getLoad(getPointerTy(), dl,
1579                            DAG.getEntryNode(), CPAddr,
1580                            MachinePointerInfo::getConstantPool(),
1581                            false, false, false, 0);
1582       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1583       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1584                            getPointerTy(), Callee, PICLabel);
1585     } else {
1586       unsigned OpFlags = 0;
1587       // On ELF targets for PIC code, direct calls should go through the PLT
1588       if (Subtarget->isTargetELF() &&
1589                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1590         OpFlags = ARMII::MO_PLT;
1591       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1592     }
1593   }
1594
1595   // FIXME: handle tail calls differently.
1596   unsigned CallOpc;
1597   if (Subtarget->isThumb()) {
1598     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1599       CallOpc = ARMISD::CALL_NOLINK;
1600     else if (doesNotRet && isDirect && !isARMFunc &&
1601              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1602       // "mov lr, pc; b _foo" to avoid confusing the RSP
1603       CallOpc = ARMISD::CALL_NOLINK;
1604     else
1605       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1606   } else {
1607     if (!isDirect && !Subtarget->hasV5TOps()) {
1608       CallOpc = ARMISD::CALL_NOLINK;
1609     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1610       // "mov lr, pc; b _foo" to avoid confusing the RSP
1611       CallOpc = ARMISD::CALL_NOLINK;
1612     else
1613       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1614   }
1615
1616   std::vector<SDValue> Ops;
1617   Ops.push_back(Chain);
1618   Ops.push_back(Callee);
1619
1620   // Add argument registers to the end of the list so that they are known live
1621   // into the call.
1622   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1623     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1624                                   RegsToPass[i].second.getValueType()));
1625
1626   // Add a register mask operand representing the call-preserved registers.
1627   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1628   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1629   assert(Mask && "Missing call preserved mask for calling convention");
1630   Ops.push_back(DAG.getRegisterMask(Mask));
1631
1632   if (InFlag.getNode())
1633     Ops.push_back(InFlag);
1634
1635   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1636   if (isTailCall)
1637     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1638
1639   // Returns a chain and a flag for retval copy to use.
1640   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1641   InFlag = Chain.getValue(1);
1642
1643   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1644                              DAG.getIntPtrConstant(0, true), InFlag);
1645   if (!Ins.empty())
1646     InFlag = Chain.getValue(1);
1647
1648   // Handle result values, copying them out of physregs into vregs that we
1649   // return.
1650   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1651                          dl, DAG, InVals);
1652 }
1653
1654 /// HandleByVal - Every parameter *after* a byval parameter is passed
1655 /// on the stack.  Remember the next parameter register to allocate,
1656 /// and then confiscate the rest of the parameter registers to insure
1657 /// this.
1658 void
1659 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1660   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1661   assert((State->getCallOrPrologue() == Prologue ||
1662           State->getCallOrPrologue() == Call) &&
1663          "unhandled ParmContext");
1664   if ((!State->isFirstByValRegValid()) &&
1665       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1666     State->setFirstByValReg(reg);
1667     // At a call site, a byval parameter that is split between
1668     // registers and memory needs its size truncated here.  In a
1669     // function prologue, such byval parameters are reassembled in
1670     // memory, and are not truncated.
1671     if (State->getCallOrPrologue() == Call) {
1672       unsigned excess = 4 * (ARM::R4 - reg);
1673       assert(size >= excess && "expected larger existing stack allocation");
1674       size -= excess;
1675     }
1676   }
1677   // Confiscate any remaining parameter registers to preclude their
1678   // assignment to subsequent parameters.
1679   while (State->AllocateReg(GPRArgRegs, 4))
1680     ;
1681 }
1682
1683 /// MatchingStackOffset - Return true if the given stack call argument is
1684 /// already available in the same position (relatively) of the caller's
1685 /// incoming argument stack.
1686 static
1687 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1688                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1689                          const TargetInstrInfo *TII) {
1690   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1691   int FI = INT_MAX;
1692   if (Arg.getOpcode() == ISD::CopyFromReg) {
1693     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1694     if (!TargetRegisterInfo::isVirtualRegister(VR))
1695       return false;
1696     MachineInstr *Def = MRI->getVRegDef(VR);
1697     if (!Def)
1698       return false;
1699     if (!Flags.isByVal()) {
1700       if (!TII->isLoadFromStackSlot(Def, FI))
1701         return false;
1702     } else {
1703       return false;
1704     }
1705   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1706     if (Flags.isByVal())
1707       // ByVal argument is passed in as a pointer but it's now being
1708       // dereferenced. e.g.
1709       // define @foo(%struct.X* %A) {
1710       //   tail call @bar(%struct.X* byval %A)
1711       // }
1712       return false;
1713     SDValue Ptr = Ld->getBasePtr();
1714     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1715     if (!FINode)
1716       return false;
1717     FI = FINode->getIndex();
1718   } else
1719     return false;
1720
1721   assert(FI != INT_MAX);
1722   if (!MFI->isFixedObjectIndex(FI))
1723     return false;
1724   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1725 }
1726
1727 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1728 /// for tail call optimization. Targets which want to do tail call
1729 /// optimization should implement this function.
1730 bool
1731 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1732                                                      CallingConv::ID CalleeCC,
1733                                                      bool isVarArg,
1734                                                      bool isCalleeStructRet,
1735                                                      bool isCallerStructRet,
1736                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1737                                     const SmallVectorImpl<SDValue> &OutVals,
1738                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1739                                                      SelectionDAG& DAG) const {
1740   const Function *CallerF = DAG.getMachineFunction().getFunction();
1741   CallingConv::ID CallerCC = CallerF->getCallingConv();
1742   bool CCMatch = CallerCC == CalleeCC;
1743
1744   // Look for obvious safe cases to perform tail call optimization that do not
1745   // require ABI changes. This is what gcc calls sibcall.
1746
1747   // Do not sibcall optimize vararg calls unless the call site is not passing
1748   // any arguments.
1749   if (isVarArg && !Outs.empty())
1750     return false;
1751
1752   // Also avoid sibcall optimization if either caller or callee uses struct
1753   // return semantics.
1754   if (isCalleeStructRet || isCallerStructRet)
1755     return false;
1756
1757   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1758   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1759   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1760   // support in the assembler and linker to be used. This would need to be
1761   // fixed to fully support tail calls in Thumb1.
1762   //
1763   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1764   // LR.  This means if we need to reload LR, it takes an extra instructions,
1765   // which outweighs the value of the tail call; but here we don't know yet
1766   // whether LR is going to be used.  Probably the right approach is to
1767   // generate the tail call here and turn it back into CALL/RET in
1768   // emitEpilogue if LR is used.
1769
1770   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1771   // but we need to make sure there are enough registers; the only valid
1772   // registers are the 4 used for parameters.  We don't currently do this
1773   // case.
1774   if (Subtarget->isThumb1Only())
1775     return false;
1776
1777   // If the calling conventions do not match, then we'd better make sure the
1778   // results are returned in the same way as what the caller expects.
1779   if (!CCMatch) {
1780     SmallVector<CCValAssign, 16> RVLocs1;
1781     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1782                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1783     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1784
1785     SmallVector<CCValAssign, 16> RVLocs2;
1786     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1787                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1788     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1789
1790     if (RVLocs1.size() != RVLocs2.size())
1791       return false;
1792     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1793       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1794         return false;
1795       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1796         return false;
1797       if (RVLocs1[i].isRegLoc()) {
1798         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1799           return false;
1800       } else {
1801         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1802           return false;
1803       }
1804     }
1805   }
1806
1807   // If Caller's vararg or byval argument has been split between registers and
1808   // stack, do not perform tail call, since part of the argument is in caller's
1809   // local frame.
1810   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1811                                       getInfo<ARMFunctionInfo>();
1812   if (AFI_Caller->getVarArgsRegSaveSize())
1813     return false;
1814
1815   // If the callee takes no arguments then go on to check the results of the
1816   // call.
1817   if (!Outs.empty()) {
1818     // Check if stack adjustment is needed. For now, do not do this if any
1819     // argument is passed on the stack.
1820     SmallVector<CCValAssign, 16> ArgLocs;
1821     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1822                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1823     CCInfo.AnalyzeCallOperands(Outs,
1824                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1825     if (CCInfo.getNextStackOffset()) {
1826       MachineFunction &MF = DAG.getMachineFunction();
1827
1828       // Check if the arguments are already laid out in the right way as
1829       // the caller's fixed stack objects.
1830       MachineFrameInfo *MFI = MF.getFrameInfo();
1831       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1832       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1833       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1834            i != e;
1835            ++i, ++realArgIdx) {
1836         CCValAssign &VA = ArgLocs[i];
1837         EVT RegVT = VA.getLocVT();
1838         SDValue Arg = OutVals[realArgIdx];
1839         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1840         if (VA.getLocInfo() == CCValAssign::Indirect)
1841           return false;
1842         if (VA.needsCustom()) {
1843           // f64 and vector types are split into multiple registers or
1844           // register/stack-slot combinations.  The types will not match
1845           // the registers; give up on memory f64 refs until we figure
1846           // out what to do about this.
1847           if (!VA.isRegLoc())
1848             return false;
1849           if (!ArgLocs[++i].isRegLoc())
1850             return false;
1851           if (RegVT == MVT::v2f64) {
1852             if (!ArgLocs[++i].isRegLoc())
1853               return false;
1854             if (!ArgLocs[++i].isRegLoc())
1855               return false;
1856           }
1857         } else if (!VA.isRegLoc()) {
1858           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1859                                    MFI, MRI, TII))
1860             return false;
1861         }
1862       }
1863     }
1864   }
1865
1866   return true;
1867 }
1868
1869 SDValue
1870 ARMTargetLowering::LowerReturn(SDValue Chain,
1871                                CallingConv::ID CallConv, bool isVarArg,
1872                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1873                                const SmallVectorImpl<SDValue> &OutVals,
1874                                DebugLoc dl, SelectionDAG &DAG) const {
1875
1876   // CCValAssign - represent the assignment of the return value to a location.
1877   SmallVector<CCValAssign, 16> RVLocs;
1878
1879   // CCState - Info about the registers and stack slots.
1880   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1881                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1882
1883   // Analyze outgoing return values.
1884   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1885                                                isVarArg));
1886
1887   // If this is the first return lowered for this function, add
1888   // the regs to the liveout set for the function.
1889   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1890     for (unsigned i = 0; i != RVLocs.size(); ++i)
1891       if (RVLocs[i].isRegLoc())
1892         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1893   }
1894
1895   SDValue Flag;
1896
1897   // Copy the result values into the output registers.
1898   for (unsigned i = 0, realRVLocIdx = 0;
1899        i != RVLocs.size();
1900        ++i, ++realRVLocIdx) {
1901     CCValAssign &VA = RVLocs[i];
1902     assert(VA.isRegLoc() && "Can only return in registers!");
1903
1904     SDValue Arg = OutVals[realRVLocIdx];
1905
1906     switch (VA.getLocInfo()) {
1907     default: llvm_unreachable("Unknown loc info!");
1908     case CCValAssign::Full: break;
1909     case CCValAssign::BCvt:
1910       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1911       break;
1912     }
1913
1914     if (VA.needsCustom()) {
1915       if (VA.getLocVT() == MVT::v2f64) {
1916         // Extract the first half and return it in two registers.
1917         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1918                                    DAG.getConstant(0, MVT::i32));
1919         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1920                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1921
1922         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1923         Flag = Chain.getValue(1);
1924         VA = RVLocs[++i]; // skip ahead to next loc
1925         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1926                                  HalfGPRs.getValue(1), Flag);
1927         Flag = Chain.getValue(1);
1928         VA = RVLocs[++i]; // skip ahead to next loc
1929
1930         // Extract the 2nd half and fall through to handle it as an f64 value.
1931         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1932                           DAG.getConstant(1, MVT::i32));
1933       }
1934       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1935       // available.
1936       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1937                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1938       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1939       Flag = Chain.getValue(1);
1940       VA = RVLocs[++i]; // skip ahead to next loc
1941       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1942                                Flag);
1943     } else
1944       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1945
1946     // Guarantee that all emitted copies are
1947     // stuck together, avoiding something bad.
1948     Flag = Chain.getValue(1);
1949   }
1950
1951   SDValue result;
1952   if (Flag.getNode())
1953     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1954   else // Return Void
1955     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1956
1957   return result;
1958 }
1959
1960 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1961   if (N->getNumValues() != 1)
1962     return false;
1963   if (!N->hasNUsesOfValue(1, 0))
1964     return false;
1965
1966   SDValue TCChain = Chain;
1967   SDNode *Copy = *N->use_begin();
1968   if (Copy->getOpcode() == ISD::CopyToReg) {
1969     // If the copy has a glue operand, we conservatively assume it isn't safe to
1970     // perform a tail call.
1971     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1972       return false;
1973     TCChain = Copy->getOperand(0);
1974   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1975     SDNode *VMov = Copy;
1976     // f64 returned in a pair of GPRs.
1977     SmallPtrSet<SDNode*, 2> Copies;
1978     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1979          UI != UE; ++UI) {
1980       if (UI->getOpcode() != ISD::CopyToReg)
1981         return false;
1982       Copies.insert(*UI);
1983     }
1984     if (Copies.size() > 2)
1985       return false;
1986
1987     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1988          UI != UE; ++UI) {
1989       SDValue UseChain = UI->getOperand(0);
1990       if (Copies.count(UseChain.getNode()))
1991         // Second CopyToReg
1992         Copy = *UI;
1993       else
1994         // First CopyToReg
1995         TCChain = UseChain;
1996     }
1997   } else if (Copy->getOpcode() == ISD::BITCAST) {
1998     // f32 returned in a single GPR.
1999     if (!Copy->hasOneUse())
2000       return false;
2001     Copy = *Copy->use_begin();
2002     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2003       return false;
2004     Chain = Copy->getOperand(0);
2005   } else {
2006     return false;
2007   }
2008
2009   bool HasRet = false;
2010   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2011        UI != UE; ++UI) {
2012     if (UI->getOpcode() != ARMISD::RET_FLAG)
2013       return false;
2014     HasRet = true;
2015   }
2016
2017   if (!HasRet)
2018     return false;
2019
2020   Chain = TCChain;
2021   return true;
2022 }
2023
2024 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2025   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2026     return false;
2027
2028   if (!CI->isTailCall())
2029     return false;
2030
2031   return !Subtarget->isThumb1Only();
2032 }
2033
2034 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2035 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2036 // one of the above mentioned nodes. It has to be wrapped because otherwise
2037 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2038 // be used to form addressing mode. These wrapped nodes will be selected
2039 // into MOVi.
2040 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2041   EVT PtrVT = Op.getValueType();
2042   // FIXME there is no actual debug info here
2043   DebugLoc dl = Op.getDebugLoc();
2044   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2045   SDValue Res;
2046   if (CP->isMachineConstantPoolEntry())
2047     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2048                                     CP->getAlignment());
2049   else
2050     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2051                                     CP->getAlignment());
2052   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2053 }
2054
2055 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2056   return MachineJumpTableInfo::EK_Inline;
2057 }
2058
2059 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2060                                              SelectionDAG &DAG) const {
2061   MachineFunction &MF = DAG.getMachineFunction();
2062   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2063   unsigned ARMPCLabelIndex = 0;
2064   DebugLoc DL = Op.getDebugLoc();
2065   EVT PtrVT = getPointerTy();
2066   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2067   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2068   SDValue CPAddr;
2069   if (RelocM == Reloc::Static) {
2070     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2071   } else {
2072     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2073     ARMPCLabelIndex = AFI->createPICLabelUId();
2074     ARMConstantPoolValue *CPV =
2075       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2076                                       ARMCP::CPBlockAddress, PCAdj);
2077     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2078   }
2079   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2080   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2081                                MachinePointerInfo::getConstantPool(),
2082                                false, false, false, 0);
2083   if (RelocM == Reloc::Static)
2084     return Result;
2085   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2086   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2087 }
2088
2089 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2090 SDValue
2091 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2092                                                  SelectionDAG &DAG) const {
2093   DebugLoc dl = GA->getDebugLoc();
2094   EVT PtrVT = getPointerTy();
2095   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2096   MachineFunction &MF = DAG.getMachineFunction();
2097   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2098   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2099   ARMConstantPoolValue *CPV =
2100     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2101                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2102   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2103   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2104   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2105                          MachinePointerInfo::getConstantPool(),
2106                          false, false, false, 0);
2107   SDValue Chain = Argument.getValue(1);
2108
2109   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2110   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2111
2112   // call __tls_get_addr.
2113   ArgListTy Args;
2114   ArgListEntry Entry;
2115   Entry.Node = Argument;
2116   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2117   Args.push_back(Entry);
2118   // FIXME: is there useful debug info available here?
2119   TargetLowering::CallLoweringInfo CLI(Chain,
2120                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2121                 false, false, false, false,
2122                 0, CallingConv::C, /*isTailCall=*/false,
2123                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2124                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2125   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2126   return CallResult.first;
2127 }
2128
2129 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2130 // "local exec" model.
2131 SDValue
2132 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2133                                         SelectionDAG &DAG,
2134                                         TLSModel::Model model) const {
2135   const GlobalValue *GV = GA->getGlobal();
2136   DebugLoc dl = GA->getDebugLoc();
2137   SDValue Offset;
2138   SDValue Chain = DAG.getEntryNode();
2139   EVT PtrVT = getPointerTy();
2140   // Get the Thread Pointer
2141   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2142
2143   if (model == TLSModel::InitialExec) {
2144     MachineFunction &MF = DAG.getMachineFunction();
2145     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2146     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2147     // Initial exec model.
2148     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2149     ARMConstantPoolValue *CPV =
2150       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2151                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2152                                       true);
2153     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2154     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2155     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2156                          MachinePointerInfo::getConstantPool(),
2157                          false, false, false, 0);
2158     Chain = Offset.getValue(1);
2159
2160     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2161     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2162
2163     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2164                          MachinePointerInfo::getConstantPool(),
2165                          false, false, false, 0);
2166   } else {
2167     // local exec model
2168     assert(model == TLSModel::LocalExec);
2169     ARMConstantPoolValue *CPV =
2170       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2171     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2172     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2173     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2174                          MachinePointerInfo::getConstantPool(),
2175                          false, false, false, 0);
2176   }
2177
2178   // The address of the thread local variable is the add of the thread
2179   // pointer with the offset of the variable.
2180   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2181 }
2182
2183 SDValue
2184 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2185   // TODO: implement the "local dynamic" model
2186   assert(Subtarget->isTargetELF() &&
2187          "TLS not implemented for non-ELF targets");
2188   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2189
2190   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2191
2192   switch (model) {
2193     case TLSModel::GeneralDynamic:
2194     case TLSModel::LocalDynamic:
2195       return LowerToTLSGeneralDynamicModel(GA, DAG);
2196     case TLSModel::InitialExec:
2197     case TLSModel::LocalExec:
2198       return LowerToTLSExecModels(GA, DAG, model);
2199   }
2200   llvm_unreachable("bogus TLS model");
2201 }
2202
2203 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2204                                                  SelectionDAG &DAG) const {
2205   EVT PtrVT = getPointerTy();
2206   DebugLoc dl = Op.getDebugLoc();
2207   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2208   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2209   if (RelocM == Reloc::PIC_) {
2210     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2211     ARMConstantPoolValue *CPV =
2212       ARMConstantPoolConstant::Create(GV,
2213                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2214     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2215     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2216     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2217                                  CPAddr,
2218                                  MachinePointerInfo::getConstantPool(),
2219                                  false, false, false, 0);
2220     SDValue Chain = Result.getValue(1);
2221     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2222     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2223     if (!UseGOTOFF)
2224       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2225                            MachinePointerInfo::getGOT(),
2226                            false, false, false, 0);
2227     return Result;
2228   }
2229
2230   // If we have T2 ops, we can materialize the address directly via movt/movw
2231   // pair. This is always cheaper.
2232   if (Subtarget->useMovt()) {
2233     ++NumMovwMovt;
2234     // FIXME: Once remat is capable of dealing with instructions with register
2235     // operands, expand this into two nodes.
2236     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2237                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2238   } else {
2239     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2240     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2241     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2242                        MachinePointerInfo::getConstantPool(),
2243                        false, false, false, 0);
2244   }
2245 }
2246
2247 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2248                                                     SelectionDAG &DAG) const {
2249   EVT PtrVT = getPointerTy();
2250   DebugLoc dl = Op.getDebugLoc();
2251   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2252   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2253   MachineFunction &MF = DAG.getMachineFunction();
2254   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2255
2256   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2257   // update ARMFastISel::ARMMaterializeGV.
2258   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2259     ++NumMovwMovt;
2260     // FIXME: Once remat is capable of dealing with instructions with register
2261     // operands, expand this into two nodes.
2262     if (RelocM == Reloc::Static)
2263       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2264                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2265
2266     unsigned Wrapper = (RelocM == Reloc::PIC_)
2267       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2268     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2269                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2270     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2271       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2272                            MachinePointerInfo::getGOT(),
2273                            false, false, false, 0);
2274     return Result;
2275   }
2276
2277   unsigned ARMPCLabelIndex = 0;
2278   SDValue CPAddr;
2279   if (RelocM == Reloc::Static) {
2280     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2281   } else {
2282     ARMPCLabelIndex = AFI->createPICLabelUId();
2283     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2284     ARMConstantPoolValue *CPV =
2285       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2286                                       PCAdj);
2287     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2288   }
2289   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2290
2291   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2292                                MachinePointerInfo::getConstantPool(),
2293                                false, false, false, 0);
2294   SDValue Chain = Result.getValue(1);
2295
2296   if (RelocM == Reloc::PIC_) {
2297     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2298     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2299   }
2300
2301   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2302     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2303                          false, false, false, 0);
2304
2305   return Result;
2306 }
2307
2308 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2309                                                     SelectionDAG &DAG) const {
2310   assert(Subtarget->isTargetELF() &&
2311          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2312   MachineFunction &MF = DAG.getMachineFunction();
2313   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2314   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2315   EVT PtrVT = getPointerTy();
2316   DebugLoc dl = Op.getDebugLoc();
2317   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2318   ARMConstantPoolValue *CPV =
2319     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2320                                   ARMPCLabelIndex, PCAdj);
2321   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2322   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2323   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2324                                MachinePointerInfo::getConstantPool(),
2325                                false, false, false, 0);
2326   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2327   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2328 }
2329
2330 SDValue
2331 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2332   DebugLoc dl = Op.getDebugLoc();
2333   SDValue Val = DAG.getConstant(0, MVT::i32);
2334   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2335                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2336                      Op.getOperand(1), Val);
2337 }
2338
2339 SDValue
2340 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2341   DebugLoc dl = Op.getDebugLoc();
2342   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2343                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2344 }
2345
2346 SDValue
2347 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2348                                           const ARMSubtarget *Subtarget) const {
2349   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2350   DebugLoc dl = Op.getDebugLoc();
2351   switch (IntNo) {
2352   default: return SDValue();    // Don't custom lower most intrinsics.
2353   case Intrinsic::arm_thread_pointer: {
2354     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2355     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2356   }
2357   case Intrinsic::eh_sjlj_lsda: {
2358     MachineFunction &MF = DAG.getMachineFunction();
2359     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2360     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2361     EVT PtrVT = getPointerTy();
2362     DebugLoc dl = Op.getDebugLoc();
2363     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2364     SDValue CPAddr;
2365     unsigned PCAdj = (RelocM != Reloc::PIC_)
2366       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2367     ARMConstantPoolValue *CPV =
2368       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2369                                       ARMCP::CPLSDA, PCAdj);
2370     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2371     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2372     SDValue Result =
2373       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2374                   MachinePointerInfo::getConstantPool(),
2375                   false, false, false, 0);
2376
2377     if (RelocM == Reloc::PIC_) {
2378       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2379       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2380     }
2381     return Result;
2382   }
2383   case Intrinsic::arm_neon_vmulls:
2384   case Intrinsic::arm_neon_vmullu: {
2385     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2386       ? ARMISD::VMULLs : ARMISD::VMULLu;
2387     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2388                        Op.getOperand(1), Op.getOperand(2));
2389   }
2390   }
2391 }
2392
2393 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2394                                const ARMSubtarget *Subtarget) {
2395   DebugLoc dl = Op.getDebugLoc();
2396   if (!Subtarget->hasDataBarrier()) {
2397     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2398     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2399     // here.
2400     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2401            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2402     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2403                        DAG.getConstant(0, MVT::i32));
2404   }
2405
2406   SDValue Op5 = Op.getOperand(5);
2407   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2408   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2409   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2410   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2411
2412   ARM_MB::MemBOpt DMBOpt;
2413   if (isDeviceBarrier)
2414     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2415   else
2416     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2417   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2418                      DAG.getConstant(DMBOpt, MVT::i32));
2419 }
2420
2421
2422 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2423                                  const ARMSubtarget *Subtarget) {
2424   // FIXME: handle "fence singlethread" more efficiently.
2425   DebugLoc dl = Op.getDebugLoc();
2426   if (!Subtarget->hasDataBarrier()) {
2427     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2428     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2429     // here.
2430     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2431            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2432     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2433                        DAG.getConstant(0, MVT::i32));
2434   }
2435
2436   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2437                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2438 }
2439
2440 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2441                              const ARMSubtarget *Subtarget) {
2442   // ARM pre v5TE and Thumb1 does not have preload instructions.
2443   if (!(Subtarget->isThumb2() ||
2444         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2445     // Just preserve the chain.
2446     return Op.getOperand(0);
2447
2448   DebugLoc dl = Op.getDebugLoc();
2449   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2450   if (!isRead &&
2451       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2452     // ARMv7 with MP extension has PLDW.
2453     return Op.getOperand(0);
2454
2455   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2456   if (Subtarget->isThumb()) {
2457     // Invert the bits.
2458     isRead = ~isRead & 1;
2459     isData = ~isData & 1;
2460   }
2461
2462   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2463                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2464                      DAG.getConstant(isData, MVT::i32));
2465 }
2466
2467 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2468   MachineFunction &MF = DAG.getMachineFunction();
2469   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2470
2471   // vastart just stores the address of the VarArgsFrameIndex slot into the
2472   // memory location argument.
2473   DebugLoc dl = Op.getDebugLoc();
2474   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2475   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2476   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2477   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2478                       MachinePointerInfo(SV), false, false, 0);
2479 }
2480
2481 SDValue
2482 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2483                                         SDValue &Root, SelectionDAG &DAG,
2484                                         DebugLoc dl) const {
2485   MachineFunction &MF = DAG.getMachineFunction();
2486   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2487
2488   const TargetRegisterClass *RC;
2489   if (AFI->isThumb1OnlyFunction())
2490     RC = &ARM::tGPRRegClass;
2491   else
2492     RC = &ARM::GPRRegClass;
2493
2494   // Transform the arguments stored in physical registers into virtual ones.
2495   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2496   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2497
2498   SDValue ArgValue2;
2499   if (NextVA.isMemLoc()) {
2500     MachineFrameInfo *MFI = MF.getFrameInfo();
2501     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2502
2503     // Create load node to retrieve arguments from the stack.
2504     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2505     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2506                             MachinePointerInfo::getFixedStack(FI),
2507                             false, false, false, 0);
2508   } else {
2509     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2510     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2511   }
2512
2513   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2514 }
2515
2516 void
2517 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2518                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2519   const {
2520   unsigned NumGPRs;
2521   if (CCInfo.isFirstByValRegValid())
2522     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2523   else {
2524     unsigned int firstUnalloced;
2525     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2526                                                 sizeof(GPRArgRegs) /
2527                                                 sizeof(GPRArgRegs[0]));
2528     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2529   }
2530
2531   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2532   VARegSize = NumGPRs * 4;
2533   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2534 }
2535
2536 // The remaining GPRs hold either the beginning of variable-argument
2537 // data, or the beginning of an aggregate passed by value (usuall
2538 // byval).  Either way, we allocate stack slots adjacent to the data
2539 // provided by our caller, and store the unallocated registers there.
2540 // If this is a variadic function, the va_list pointer will begin with
2541 // these values; otherwise, this reassembles a (byval) structure that
2542 // was split between registers and memory.
2543 void
2544 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2545                                         DebugLoc dl, SDValue &Chain,
2546                                         const Value *OrigArg,
2547                                         unsigned OffsetFromOrigArg,
2548                                         unsigned ArgOffset) const {
2549   MachineFunction &MF = DAG.getMachineFunction();
2550   MachineFrameInfo *MFI = MF.getFrameInfo();
2551   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2552   unsigned firstRegToSaveIndex;
2553   if (CCInfo.isFirstByValRegValid())
2554     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2555   else {
2556     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2557       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2558   }
2559
2560   unsigned VARegSize, VARegSaveSize;
2561   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2562   if (VARegSaveSize) {
2563     // If this function is vararg, store any remaining integer argument regs
2564     // to their spots on the stack so that they may be loaded by deferencing
2565     // the result of va_next.
2566     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2567     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2568                                                      ArgOffset + VARegSaveSize
2569                                                      - VARegSize,
2570                                                      false));
2571     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2572                                     getPointerTy());
2573
2574     SmallVector<SDValue, 4> MemOps;
2575     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2576       const TargetRegisterClass *RC;
2577       if (AFI->isThumb1OnlyFunction())
2578         RC = &ARM::tGPRRegClass;
2579       else
2580         RC = &ARM::GPRRegClass;
2581
2582       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2583       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2584       SDValue Store =
2585         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2586                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2587                      false, false, 0);
2588       MemOps.push_back(Store);
2589       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2590                         DAG.getConstant(4, getPointerTy()));
2591     }
2592     if (!MemOps.empty())
2593       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2594                           &MemOps[0], MemOps.size());
2595   } else
2596     // This will point to the next argument passed via stack.
2597     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2598 }
2599
2600 SDValue
2601 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2602                                         CallingConv::ID CallConv, bool isVarArg,
2603                                         const SmallVectorImpl<ISD::InputArg>
2604                                           &Ins,
2605                                         DebugLoc dl, SelectionDAG &DAG,
2606                                         SmallVectorImpl<SDValue> &InVals)
2607                                           const {
2608   MachineFunction &MF = DAG.getMachineFunction();
2609   MachineFrameInfo *MFI = MF.getFrameInfo();
2610
2611   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2612
2613   // Assign locations to all of the incoming arguments.
2614   SmallVector<CCValAssign, 16> ArgLocs;
2615   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2616                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2617   CCInfo.AnalyzeFormalArguments(Ins,
2618                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2619                                                   isVarArg));
2620   
2621   SmallVector<SDValue, 16> ArgValues;
2622   int lastInsIndex = -1;
2623   SDValue ArgValue;
2624   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2625   unsigned CurArgIdx = 0;
2626   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2627     CCValAssign &VA = ArgLocs[i];
2628     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2629     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2630     // Arguments stored in registers.
2631     if (VA.isRegLoc()) {
2632       EVT RegVT = VA.getLocVT();
2633
2634       if (VA.needsCustom()) {
2635         // f64 and vector types are split up into multiple registers or
2636         // combinations of registers and stack slots.
2637         if (VA.getLocVT() == MVT::v2f64) {
2638           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2639                                                    Chain, DAG, dl);
2640           VA = ArgLocs[++i]; // skip ahead to next loc
2641           SDValue ArgValue2;
2642           if (VA.isMemLoc()) {
2643             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2644             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2645             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2646                                     MachinePointerInfo::getFixedStack(FI),
2647                                     false, false, false, 0);
2648           } else {
2649             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2650                                              Chain, DAG, dl);
2651           }
2652           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2653           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2654                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2655           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2656                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2657         } else
2658           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2659
2660       } else {
2661         const TargetRegisterClass *RC;
2662
2663         if (RegVT == MVT::f32)
2664           RC = &ARM::SPRRegClass;
2665         else if (RegVT == MVT::f64)
2666           RC = &ARM::DPRRegClass;
2667         else if (RegVT == MVT::v2f64)
2668           RC = &ARM::QPRRegClass;
2669         else if (RegVT == MVT::i32)
2670           RC = AFI->isThumb1OnlyFunction() ?
2671             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2672             (const TargetRegisterClass*)&ARM::GPRRegClass;
2673         else
2674           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2675
2676         // Transform the arguments in physical registers into virtual ones.
2677         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2678         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2679       }
2680
2681       // If this is an 8 or 16-bit value, it is really passed promoted
2682       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2683       // truncate to the right size.
2684       switch (VA.getLocInfo()) {
2685       default: llvm_unreachable("Unknown loc info!");
2686       case CCValAssign::Full: break;
2687       case CCValAssign::BCvt:
2688         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2689         break;
2690       case CCValAssign::SExt:
2691         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2692                                DAG.getValueType(VA.getValVT()));
2693         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2694         break;
2695       case CCValAssign::ZExt:
2696         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2697                                DAG.getValueType(VA.getValVT()));
2698         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2699         break;
2700       }
2701
2702       InVals.push_back(ArgValue);
2703
2704     } else { // VA.isRegLoc()
2705
2706       // sanity check
2707       assert(VA.isMemLoc());
2708       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2709
2710       int index = ArgLocs[i].getValNo();
2711
2712       // Some Ins[] entries become multiple ArgLoc[] entries.
2713       // Process them only once.
2714       if (index != lastInsIndex)
2715         {
2716           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2717           // FIXME: For now, all byval parameter objects are marked mutable.
2718           // This can be changed with more analysis.
2719           // In case of tail call optimization mark all arguments mutable.
2720           // Since they could be overwritten by lowering of arguments in case of
2721           // a tail call.
2722           if (Flags.isByVal()) {
2723             unsigned VARegSize, VARegSaveSize;
2724             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2725             VarArgStyleRegisters(CCInfo, DAG,
2726                                  dl, Chain, CurOrigArg, Ins[VA.getValNo()].PartOffset, 0);
2727             unsigned Bytes = Flags.getByValSize() - VARegSize;
2728             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2729             int FI = MFI->CreateFixedObject(Bytes,
2730                                             VA.getLocMemOffset(), false);
2731             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2732           } else {
2733             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2734                                             VA.getLocMemOffset(), true);
2735
2736             // Create load nodes to retrieve arguments from the stack.
2737             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2738             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2739                                          MachinePointerInfo::getFixedStack(FI),
2740                                          false, false, false, 0));
2741           }
2742           lastInsIndex = index;
2743         }
2744     }
2745   }
2746
2747   // varargs
2748   if (isVarArg)
2749     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2750                          CCInfo.getNextStackOffset());
2751
2752   return Chain;
2753 }
2754
2755 /// isFloatingPointZero - Return true if this is +0.0.
2756 static bool isFloatingPointZero(SDValue Op) {
2757   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2758     return CFP->getValueAPF().isPosZero();
2759   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2760     // Maybe this has already been legalized into the constant pool?
2761     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2762       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2763       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2764         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2765           return CFP->getValueAPF().isPosZero();
2766     }
2767   }
2768   return false;
2769 }
2770
2771 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2772 /// the given operands.
2773 SDValue
2774 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2775                              SDValue &ARMcc, SelectionDAG &DAG,
2776                              DebugLoc dl) const {
2777   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2778     unsigned C = RHSC->getZExtValue();
2779     if (!isLegalICmpImmediate(C)) {
2780       // Constant does not fit, try adjusting it by one?
2781       switch (CC) {
2782       default: break;
2783       case ISD::SETLT:
2784       case ISD::SETGE:
2785         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2786           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2787           RHS = DAG.getConstant(C-1, MVT::i32);
2788         }
2789         break;
2790       case ISD::SETULT:
2791       case ISD::SETUGE:
2792         if (C != 0 && isLegalICmpImmediate(C-1)) {
2793           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2794           RHS = DAG.getConstant(C-1, MVT::i32);
2795         }
2796         break;
2797       case ISD::SETLE:
2798       case ISD::SETGT:
2799         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2800           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2801           RHS = DAG.getConstant(C+1, MVT::i32);
2802         }
2803         break;
2804       case ISD::SETULE:
2805       case ISD::SETUGT:
2806         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2807           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2808           RHS = DAG.getConstant(C+1, MVT::i32);
2809         }
2810         break;
2811       }
2812     }
2813   }
2814
2815   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2816   ARMISD::NodeType CompareType;
2817   switch (CondCode) {
2818   default:
2819     CompareType = ARMISD::CMP;
2820     break;
2821   case ARMCC::EQ:
2822   case ARMCC::NE:
2823     // Uses only Z Flag
2824     CompareType = ARMISD::CMPZ;
2825     break;
2826   }
2827   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2828   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2829 }
2830
2831 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2832 SDValue
2833 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2834                              DebugLoc dl) const {
2835   SDValue Cmp;
2836   if (!isFloatingPointZero(RHS))
2837     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2838   else
2839     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2840   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2841 }
2842
2843 /// duplicateCmp - Glue values can have only one use, so this function
2844 /// duplicates a comparison node.
2845 SDValue
2846 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2847   unsigned Opc = Cmp.getOpcode();
2848   DebugLoc DL = Cmp.getDebugLoc();
2849   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2850     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2851
2852   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2853   Cmp = Cmp.getOperand(0);
2854   Opc = Cmp.getOpcode();
2855   if (Opc == ARMISD::CMPFP)
2856     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2857   else {
2858     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2859     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2860   }
2861   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2862 }
2863
2864 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2865   SDValue Cond = Op.getOperand(0);
2866   SDValue SelectTrue = Op.getOperand(1);
2867   SDValue SelectFalse = Op.getOperand(2);
2868   DebugLoc dl = Op.getDebugLoc();
2869
2870   // Convert:
2871   //
2872   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2873   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2874   //
2875   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2876     const ConstantSDNode *CMOVTrue =
2877       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2878     const ConstantSDNode *CMOVFalse =
2879       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2880
2881     if (CMOVTrue && CMOVFalse) {
2882       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2883       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2884
2885       SDValue True;
2886       SDValue False;
2887       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2888         True = SelectTrue;
2889         False = SelectFalse;
2890       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2891         True = SelectFalse;
2892         False = SelectTrue;
2893       }
2894
2895       if (True.getNode() && False.getNode()) {
2896         EVT VT = Op.getValueType();
2897         SDValue ARMcc = Cond.getOperand(2);
2898         SDValue CCR = Cond.getOperand(3);
2899         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2900         assert(True.getValueType() == VT);
2901         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2902       }
2903     }
2904   }
2905
2906   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2907   // undefined bits before doing a full-word comparison with zero.
2908   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2909                      DAG.getConstant(1, Cond.getValueType()));
2910
2911   return DAG.getSelectCC(dl, Cond,
2912                          DAG.getConstant(0, Cond.getValueType()),
2913                          SelectTrue, SelectFalse, ISD::SETNE);
2914 }
2915
2916 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2917   EVT VT = Op.getValueType();
2918   SDValue LHS = Op.getOperand(0);
2919   SDValue RHS = Op.getOperand(1);
2920   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2921   SDValue TrueVal = Op.getOperand(2);
2922   SDValue FalseVal = Op.getOperand(3);
2923   DebugLoc dl = Op.getDebugLoc();
2924
2925   if (LHS.getValueType() == MVT::i32) {
2926     SDValue ARMcc;
2927     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2928     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2929     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2930   }
2931
2932   ARMCC::CondCodes CondCode, CondCode2;
2933   FPCCToARMCC(CC, CondCode, CondCode2);
2934
2935   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2936   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2937   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2938   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2939                                ARMcc, CCR, Cmp);
2940   if (CondCode2 != ARMCC::AL) {
2941     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2942     // FIXME: Needs another CMP because flag can have but one use.
2943     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2944     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2945                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2946   }
2947   return Result;
2948 }
2949
2950 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2951 /// to morph to an integer compare sequence.
2952 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2953                            const ARMSubtarget *Subtarget) {
2954   SDNode *N = Op.getNode();
2955   if (!N->hasOneUse())
2956     // Otherwise it requires moving the value from fp to integer registers.
2957     return false;
2958   if (!N->getNumValues())
2959     return false;
2960   EVT VT = Op.getValueType();
2961   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2962     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2963     // vmrs are very slow, e.g. cortex-a8.
2964     return false;
2965
2966   if (isFloatingPointZero(Op)) {
2967     SeenZero = true;
2968     return true;
2969   }
2970   return ISD::isNormalLoad(N);
2971 }
2972
2973 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2974   if (isFloatingPointZero(Op))
2975     return DAG.getConstant(0, MVT::i32);
2976
2977   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2978     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2979                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2980                        Ld->isVolatile(), Ld->isNonTemporal(),
2981                        Ld->isInvariant(), Ld->getAlignment());
2982
2983   llvm_unreachable("Unknown VFP cmp argument!");
2984 }
2985
2986 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2987                            SDValue &RetVal1, SDValue &RetVal2) {
2988   if (isFloatingPointZero(Op)) {
2989     RetVal1 = DAG.getConstant(0, MVT::i32);
2990     RetVal2 = DAG.getConstant(0, MVT::i32);
2991     return;
2992   }
2993
2994   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2995     SDValue Ptr = Ld->getBasePtr();
2996     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2997                           Ld->getChain(), Ptr,
2998                           Ld->getPointerInfo(),
2999                           Ld->isVolatile(), Ld->isNonTemporal(),
3000                           Ld->isInvariant(), Ld->getAlignment());
3001
3002     EVT PtrType = Ptr.getValueType();
3003     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3004     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3005                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3006     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3007                           Ld->getChain(), NewPtr,
3008                           Ld->getPointerInfo().getWithOffset(4),
3009                           Ld->isVolatile(), Ld->isNonTemporal(),
3010                           Ld->isInvariant(), NewAlign);
3011     return;
3012   }
3013
3014   llvm_unreachable("Unknown VFP cmp argument!");
3015 }
3016
3017 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3018 /// f32 and even f64 comparisons to integer ones.
3019 SDValue
3020 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3021   SDValue Chain = Op.getOperand(0);
3022   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3023   SDValue LHS = Op.getOperand(2);
3024   SDValue RHS = Op.getOperand(3);
3025   SDValue Dest = Op.getOperand(4);
3026   DebugLoc dl = Op.getDebugLoc();
3027
3028   bool LHSSeenZero = false;
3029   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3030   bool RHSSeenZero = false;
3031   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3032   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3033     // If unsafe fp math optimization is enabled and there are no other uses of
3034     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3035     // to an integer comparison.
3036     if (CC == ISD::SETOEQ)
3037       CC = ISD::SETEQ;
3038     else if (CC == ISD::SETUNE)
3039       CC = ISD::SETNE;
3040
3041     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3042     SDValue ARMcc;
3043     if (LHS.getValueType() == MVT::f32) {
3044       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3045                         bitcastf32Toi32(LHS, DAG), Mask);
3046       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3047                         bitcastf32Toi32(RHS, DAG), Mask);
3048       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3049       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3050       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3051                          Chain, Dest, ARMcc, CCR, Cmp);
3052     }
3053
3054     SDValue LHS1, LHS2;
3055     SDValue RHS1, RHS2;
3056     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3057     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3058     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3059     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3060     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3061     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3062     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3063     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3064     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3065   }
3066
3067   return SDValue();
3068 }
3069
3070 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3071   SDValue Chain = Op.getOperand(0);
3072   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3073   SDValue LHS = Op.getOperand(2);
3074   SDValue RHS = Op.getOperand(3);
3075   SDValue Dest = Op.getOperand(4);
3076   DebugLoc dl = Op.getDebugLoc();
3077
3078   if (LHS.getValueType() == MVT::i32) {
3079     SDValue ARMcc;
3080     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3081     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3082     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3083                        Chain, Dest, ARMcc, CCR, Cmp);
3084   }
3085
3086   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3087
3088   if (getTargetMachine().Options.UnsafeFPMath &&
3089       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3090        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3091     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3092     if (Result.getNode())
3093       return Result;
3094   }
3095
3096   ARMCC::CondCodes CondCode, CondCode2;
3097   FPCCToARMCC(CC, CondCode, CondCode2);
3098
3099   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3100   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3101   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3102   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3103   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3104   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3105   if (CondCode2 != ARMCC::AL) {
3106     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3107     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3108     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3109   }
3110   return Res;
3111 }
3112
3113 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3114   SDValue Chain = Op.getOperand(0);
3115   SDValue Table = Op.getOperand(1);
3116   SDValue Index = Op.getOperand(2);
3117   DebugLoc dl = Op.getDebugLoc();
3118
3119   EVT PTy = getPointerTy();
3120   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3121   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3122   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3123   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3124   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3125   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3126   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3127   if (Subtarget->isThumb2()) {
3128     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3129     // which does another jump to the destination. This also makes it easier
3130     // to translate it to TBB / TBH later.
3131     // FIXME: This might not work if the function is extremely large.
3132     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3133                        Addr, Op.getOperand(2), JTI, UId);
3134   }
3135   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3136     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3137                        MachinePointerInfo::getJumpTable(),
3138                        false, false, false, 0);
3139     Chain = Addr.getValue(1);
3140     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3141     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3142   } else {
3143     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3144                        MachinePointerInfo::getJumpTable(),
3145                        false, false, false, 0);
3146     Chain = Addr.getValue(1);
3147     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3148   }
3149 }
3150
3151 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3152   EVT VT = Op.getValueType();
3153   DebugLoc dl = Op.getDebugLoc();
3154
3155   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3156     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3157       return Op;
3158     return DAG.UnrollVectorOp(Op.getNode());
3159   }
3160
3161   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3162          "Invalid type for custom lowering!");
3163   if (VT != MVT::v4i16)
3164     return DAG.UnrollVectorOp(Op.getNode());
3165
3166   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3167   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3168 }
3169
3170 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3171   EVT VT = Op.getValueType();
3172   if (VT.isVector())
3173     return LowerVectorFP_TO_INT(Op, DAG);
3174
3175   DebugLoc dl = Op.getDebugLoc();
3176   unsigned Opc;
3177
3178   switch (Op.getOpcode()) {
3179   default: llvm_unreachable("Invalid opcode!");
3180   case ISD::FP_TO_SINT:
3181     Opc = ARMISD::FTOSI;
3182     break;
3183   case ISD::FP_TO_UINT:
3184     Opc = ARMISD::FTOUI;
3185     break;
3186   }
3187   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3188   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3189 }
3190
3191 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3192   EVT VT = Op.getValueType();
3193   DebugLoc dl = Op.getDebugLoc();
3194
3195   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3196     if (VT.getVectorElementType() == MVT::f32)
3197       return Op;
3198     return DAG.UnrollVectorOp(Op.getNode());
3199   }
3200
3201   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3202          "Invalid type for custom lowering!");
3203   if (VT != MVT::v4f32)
3204     return DAG.UnrollVectorOp(Op.getNode());
3205
3206   unsigned CastOpc;
3207   unsigned Opc;
3208   switch (Op.getOpcode()) {
3209   default: llvm_unreachable("Invalid opcode!");
3210   case ISD::SINT_TO_FP:
3211     CastOpc = ISD::SIGN_EXTEND;
3212     Opc = ISD::SINT_TO_FP;
3213     break;
3214   case ISD::UINT_TO_FP:
3215     CastOpc = ISD::ZERO_EXTEND;
3216     Opc = ISD::UINT_TO_FP;
3217     break;
3218   }
3219
3220   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3221   return DAG.getNode(Opc, dl, VT, Op);
3222 }
3223
3224 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3225   EVT VT = Op.getValueType();
3226   if (VT.isVector())
3227     return LowerVectorINT_TO_FP(Op, DAG);
3228
3229   DebugLoc dl = Op.getDebugLoc();
3230   unsigned Opc;
3231
3232   switch (Op.getOpcode()) {
3233   default: llvm_unreachable("Invalid opcode!");
3234   case ISD::SINT_TO_FP:
3235     Opc = ARMISD::SITOF;
3236     break;
3237   case ISD::UINT_TO_FP:
3238     Opc = ARMISD::UITOF;
3239     break;
3240   }
3241
3242   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3243   return DAG.getNode(Opc, dl, VT, Op);
3244 }
3245
3246 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3247   // Implement fcopysign with a fabs and a conditional fneg.
3248   SDValue Tmp0 = Op.getOperand(0);
3249   SDValue Tmp1 = Op.getOperand(1);
3250   DebugLoc dl = Op.getDebugLoc();
3251   EVT VT = Op.getValueType();
3252   EVT SrcVT = Tmp1.getValueType();
3253   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3254     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3255   bool UseNEON = !InGPR && Subtarget->hasNEON();
3256
3257   if (UseNEON) {
3258     // Use VBSL to copy the sign bit.
3259     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3260     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3261                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3262     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3263     if (VT == MVT::f64)
3264       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3265                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3266                          DAG.getConstant(32, MVT::i32));
3267     else /*if (VT == MVT::f32)*/
3268       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3269     if (SrcVT == MVT::f32) {
3270       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3271       if (VT == MVT::f64)
3272         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3273                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3274                            DAG.getConstant(32, MVT::i32));
3275     } else if (VT == MVT::f32)
3276       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3277                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3278                          DAG.getConstant(32, MVT::i32));
3279     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3280     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3281
3282     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3283                                             MVT::i32);
3284     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3285     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3286                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3287
3288     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3289                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3290                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3291     if (VT == MVT::f32) {
3292       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3293       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3294                         DAG.getConstant(0, MVT::i32));
3295     } else {
3296       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3297     }
3298
3299     return Res;
3300   }
3301
3302   // Bitcast operand 1 to i32.
3303   if (SrcVT == MVT::f64)
3304     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3305                        &Tmp1, 1).getValue(1);
3306   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3307
3308   // Or in the signbit with integer operations.
3309   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3310   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3311   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3312   if (VT == MVT::f32) {
3313     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3314                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3315     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3316                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3317   }
3318
3319   // f64: Or the high part with signbit and then combine two parts.
3320   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3321                      &Tmp0, 1);
3322   SDValue Lo = Tmp0.getValue(0);
3323   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3324   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3325   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3326 }
3327
3328 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3329   MachineFunction &MF = DAG.getMachineFunction();
3330   MachineFrameInfo *MFI = MF.getFrameInfo();
3331   MFI->setReturnAddressIsTaken(true);
3332
3333   EVT VT = Op.getValueType();
3334   DebugLoc dl = Op.getDebugLoc();
3335   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3336   if (Depth) {
3337     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3338     SDValue Offset = DAG.getConstant(4, MVT::i32);
3339     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3340                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3341                        MachinePointerInfo(), false, false, false, 0);
3342   }
3343
3344   // Return LR, which contains the return address. Mark it an implicit live-in.
3345   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3346   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3347 }
3348
3349 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3350   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3351   MFI->setFrameAddressIsTaken(true);
3352
3353   EVT VT = Op.getValueType();
3354   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3355   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3356   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3357     ? ARM::R7 : ARM::R11;
3358   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3359   while (Depth--)
3360     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3361                             MachinePointerInfo(),
3362                             false, false, false, 0);
3363   return FrameAddr;
3364 }
3365
3366 /// ExpandBITCAST - If the target supports VFP, this function is called to
3367 /// expand a bit convert where either the source or destination type is i64 to
3368 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3369 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3370 /// vectors), since the legalizer won't know what to do with that.
3371 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3373   DebugLoc dl = N->getDebugLoc();
3374   SDValue Op = N->getOperand(0);
3375
3376   // This function is only supposed to be called for i64 types, either as the
3377   // source or destination of the bit convert.
3378   EVT SrcVT = Op.getValueType();
3379   EVT DstVT = N->getValueType(0);
3380   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3381          "ExpandBITCAST called for non-i64 type");
3382
3383   // Turn i64->f64 into VMOVDRR.
3384   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3385     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3386                              DAG.getConstant(0, MVT::i32));
3387     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3388                              DAG.getConstant(1, MVT::i32));
3389     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3390                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3391   }
3392
3393   // Turn f64->i64 into VMOVRRD.
3394   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3395     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3396                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3397     // Merge the pieces into a single i64 value.
3398     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3399   }
3400
3401   return SDValue();
3402 }
3403
3404 /// getZeroVector - Returns a vector of specified type with all zero elements.
3405 /// Zero vectors are used to represent vector negation and in those cases
3406 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3407 /// not support i64 elements, so sometimes the zero vectors will need to be
3408 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3409 /// zero vector.
3410 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3411   assert(VT.isVector() && "Expected a vector type");
3412   // The canonical modified immediate encoding of a zero vector is....0!
3413   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3414   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3415   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3416   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3417 }
3418
3419 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3420 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3421 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3422                                                 SelectionDAG &DAG) const {
3423   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3424   EVT VT = Op.getValueType();
3425   unsigned VTBits = VT.getSizeInBits();
3426   DebugLoc dl = Op.getDebugLoc();
3427   SDValue ShOpLo = Op.getOperand(0);
3428   SDValue ShOpHi = Op.getOperand(1);
3429   SDValue ShAmt  = Op.getOperand(2);
3430   SDValue ARMcc;
3431   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3432
3433   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3434
3435   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3436                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3437   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3438   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3439                                    DAG.getConstant(VTBits, MVT::i32));
3440   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3441   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3442   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3443
3444   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3445   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3446                           ARMcc, DAG, dl);
3447   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3448   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3449                            CCR, Cmp);
3450
3451   SDValue Ops[2] = { Lo, Hi };
3452   return DAG.getMergeValues(Ops, 2, dl);
3453 }
3454
3455 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3456 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3457 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3458                                                SelectionDAG &DAG) const {
3459   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3460   EVT VT = Op.getValueType();
3461   unsigned VTBits = VT.getSizeInBits();
3462   DebugLoc dl = Op.getDebugLoc();
3463   SDValue ShOpLo = Op.getOperand(0);
3464   SDValue ShOpHi = Op.getOperand(1);
3465   SDValue ShAmt  = Op.getOperand(2);
3466   SDValue ARMcc;
3467
3468   assert(Op.getOpcode() == ISD::SHL_PARTS);
3469   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3470                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3471   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3472   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3473                                    DAG.getConstant(VTBits, MVT::i32));
3474   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3475   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3476
3477   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3478   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3479   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3480                           ARMcc, DAG, dl);
3481   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3482   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3483                            CCR, Cmp);
3484
3485   SDValue Ops[2] = { Lo, Hi };
3486   return DAG.getMergeValues(Ops, 2, dl);
3487 }
3488
3489 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3490                                             SelectionDAG &DAG) const {
3491   // The rounding mode is in bits 23:22 of the FPSCR.
3492   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3493   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3494   // so that the shift + and get folded into a bitfield extract.
3495   DebugLoc dl = Op.getDebugLoc();
3496   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3497                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3498                                               MVT::i32));
3499   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3500                                   DAG.getConstant(1U << 22, MVT::i32));
3501   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3502                               DAG.getConstant(22, MVT::i32));
3503   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3504                      DAG.getConstant(3, MVT::i32));
3505 }
3506
3507 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3508                          const ARMSubtarget *ST) {
3509   EVT VT = N->getValueType(0);
3510   DebugLoc dl = N->getDebugLoc();
3511
3512   if (!ST->hasV6T2Ops())
3513     return SDValue();
3514
3515   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3516   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3517 }
3518
3519 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3520                           const ARMSubtarget *ST) {
3521   EVT VT = N->getValueType(0);
3522   DebugLoc dl = N->getDebugLoc();
3523
3524   if (!VT.isVector())
3525     return SDValue();
3526
3527   // Lower vector shifts on NEON to use VSHL.
3528   assert(ST->hasNEON() && "unexpected vector shift");
3529
3530   // Left shifts translate directly to the vshiftu intrinsic.
3531   if (N->getOpcode() == ISD::SHL)
3532     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3533                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3534                        N->getOperand(0), N->getOperand(1));
3535
3536   assert((N->getOpcode() == ISD::SRA ||
3537           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3538
3539   // NEON uses the same intrinsics for both left and right shifts.  For
3540   // right shifts, the shift amounts are negative, so negate the vector of
3541   // shift amounts.
3542   EVT ShiftVT = N->getOperand(1).getValueType();
3543   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3544                                      getZeroVector(ShiftVT, DAG, dl),
3545                                      N->getOperand(1));
3546   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3547                              Intrinsic::arm_neon_vshifts :
3548                              Intrinsic::arm_neon_vshiftu);
3549   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3550                      DAG.getConstant(vshiftInt, MVT::i32),
3551                      N->getOperand(0), NegatedCount);
3552 }
3553
3554 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3555                                 const ARMSubtarget *ST) {
3556   EVT VT = N->getValueType(0);
3557   DebugLoc dl = N->getDebugLoc();
3558
3559   // We can get here for a node like i32 = ISD::SHL i32, i64
3560   if (VT != MVT::i64)
3561     return SDValue();
3562
3563   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3564          "Unknown shift to lower!");
3565
3566   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3567   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3568       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3569     return SDValue();
3570
3571   // If we are in thumb mode, we don't have RRX.
3572   if (ST->isThumb1Only()) return SDValue();
3573
3574   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3575   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3576                            DAG.getConstant(0, MVT::i32));
3577   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3578                            DAG.getConstant(1, MVT::i32));
3579
3580   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3581   // captures the result into a carry flag.
3582   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3583   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3584
3585   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3586   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3587
3588   // Merge the pieces into a single i64 value.
3589  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3590 }
3591
3592 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3593   SDValue TmpOp0, TmpOp1;
3594   bool Invert = false;
3595   bool Swap = false;
3596   unsigned Opc = 0;
3597
3598   SDValue Op0 = Op.getOperand(0);
3599   SDValue Op1 = Op.getOperand(1);
3600   SDValue CC = Op.getOperand(2);
3601   EVT VT = Op.getValueType();
3602   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3603   DebugLoc dl = Op.getDebugLoc();
3604
3605   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3606     switch (SetCCOpcode) {
3607     default: llvm_unreachable("Illegal FP comparison");
3608     case ISD::SETUNE:
3609     case ISD::SETNE:  Invert = true; // Fallthrough
3610     case ISD::SETOEQ:
3611     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3612     case ISD::SETOLT:
3613     case ISD::SETLT: Swap = true; // Fallthrough
3614     case ISD::SETOGT:
3615     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3616     case ISD::SETOLE:
3617     case ISD::SETLE:  Swap = true; // Fallthrough
3618     case ISD::SETOGE:
3619     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3620     case ISD::SETUGE: Swap = true; // Fallthrough
3621     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3622     case ISD::SETUGT: Swap = true; // Fallthrough
3623     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3624     case ISD::SETUEQ: Invert = true; // Fallthrough
3625     case ISD::SETONE:
3626       // Expand this to (OLT | OGT).
3627       TmpOp0 = Op0;
3628       TmpOp1 = Op1;
3629       Opc = ISD::OR;
3630       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3631       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3632       break;
3633     case ISD::SETUO: Invert = true; // Fallthrough
3634     case ISD::SETO:
3635       // Expand this to (OLT | OGE).
3636       TmpOp0 = Op0;
3637       TmpOp1 = Op1;
3638       Opc = ISD::OR;
3639       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3640       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3641       break;
3642     }
3643   } else {
3644     // Integer comparisons.
3645     switch (SetCCOpcode) {
3646     default: llvm_unreachable("Illegal integer comparison");
3647     case ISD::SETNE:  Invert = true;
3648     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3649     case ISD::SETLT:  Swap = true;
3650     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3651     case ISD::SETLE:  Swap = true;
3652     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3653     case ISD::SETULT: Swap = true;
3654     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3655     case ISD::SETULE: Swap = true;
3656     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3657     }
3658
3659     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3660     if (Opc == ARMISD::VCEQ) {
3661
3662       SDValue AndOp;
3663       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3664         AndOp = Op0;
3665       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3666         AndOp = Op1;
3667
3668       // Ignore bitconvert.
3669       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3670         AndOp = AndOp.getOperand(0);
3671
3672       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3673         Opc = ARMISD::VTST;
3674         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3675         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3676         Invert = !Invert;
3677       }
3678     }
3679   }
3680
3681   if (Swap)
3682     std::swap(Op0, Op1);
3683
3684   // If one of the operands is a constant vector zero, attempt to fold the
3685   // comparison to a specialized compare-against-zero form.
3686   SDValue SingleOp;
3687   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3688     SingleOp = Op0;
3689   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3690     if (Opc == ARMISD::VCGE)
3691       Opc = ARMISD::VCLEZ;
3692     else if (Opc == ARMISD::VCGT)
3693       Opc = ARMISD::VCLTZ;
3694     SingleOp = Op1;
3695   }
3696
3697   SDValue Result;
3698   if (SingleOp.getNode()) {
3699     switch (Opc) {
3700     case ARMISD::VCEQ:
3701       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3702     case ARMISD::VCGE:
3703       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3704     case ARMISD::VCLEZ:
3705       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3706     case ARMISD::VCGT:
3707       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3708     case ARMISD::VCLTZ:
3709       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3710     default:
3711       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3712     }
3713   } else {
3714      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3715   }
3716
3717   if (Invert)
3718     Result = DAG.getNOT(dl, Result, VT);
3719
3720   return Result;
3721 }
3722
3723 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3724 /// valid vector constant for a NEON instruction with a "modified immediate"
3725 /// operand (e.g., VMOV).  If so, return the encoded value.
3726 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3727                                  unsigned SplatBitSize, SelectionDAG &DAG,
3728                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3729   unsigned OpCmode, Imm;
3730
3731   // SplatBitSize is set to the smallest size that splats the vector, so a
3732   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3733   // immediate instructions others than VMOV do not support the 8-bit encoding
3734   // of a zero vector, and the default encoding of zero is supposed to be the
3735   // 32-bit version.
3736   if (SplatBits == 0)
3737     SplatBitSize = 32;
3738
3739   switch (SplatBitSize) {
3740   case 8:
3741     if (type != VMOVModImm)
3742       return SDValue();
3743     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3744     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3745     OpCmode = 0xe;
3746     Imm = SplatBits;
3747     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3748     break;
3749
3750   case 16:
3751     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3752     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3753     if ((SplatBits & ~0xff) == 0) {
3754       // Value = 0x00nn: Op=x, Cmode=100x.
3755       OpCmode = 0x8;
3756       Imm = SplatBits;
3757       break;
3758     }
3759     if ((SplatBits & ~0xff00) == 0) {
3760       // Value = 0xnn00: Op=x, Cmode=101x.
3761       OpCmode = 0xa;
3762       Imm = SplatBits >> 8;
3763       break;
3764     }
3765     return SDValue();
3766
3767   case 32:
3768     // NEON's 32-bit VMOV supports splat values where:
3769     // * only one byte is nonzero, or
3770     // * the least significant byte is 0xff and the second byte is nonzero, or
3771     // * the least significant 2 bytes are 0xff and the third is nonzero.
3772     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3773     if ((SplatBits & ~0xff) == 0) {
3774       // Value = 0x000000nn: Op=x, Cmode=000x.
3775       OpCmode = 0;
3776       Imm = SplatBits;
3777       break;
3778     }
3779     if ((SplatBits & ~0xff00) == 0) {
3780       // Value = 0x0000nn00: Op=x, Cmode=001x.
3781       OpCmode = 0x2;
3782       Imm = SplatBits >> 8;
3783       break;
3784     }
3785     if ((SplatBits & ~0xff0000) == 0) {
3786       // Value = 0x00nn0000: Op=x, Cmode=010x.
3787       OpCmode = 0x4;
3788       Imm = SplatBits >> 16;
3789       break;
3790     }
3791     if ((SplatBits & ~0xff000000) == 0) {
3792       // Value = 0xnn000000: Op=x, Cmode=011x.
3793       OpCmode = 0x6;
3794       Imm = SplatBits >> 24;
3795       break;
3796     }
3797
3798     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3799     if (type == OtherModImm) return SDValue();
3800
3801     if ((SplatBits & ~0xffff) == 0 &&
3802         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3803       // Value = 0x0000nnff: Op=x, Cmode=1100.
3804       OpCmode = 0xc;
3805       Imm = SplatBits >> 8;
3806       SplatBits |= 0xff;
3807       break;
3808     }
3809
3810     if ((SplatBits & ~0xffffff) == 0 &&
3811         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3812       // Value = 0x00nnffff: Op=x, Cmode=1101.
3813       OpCmode = 0xd;
3814       Imm = SplatBits >> 16;
3815       SplatBits |= 0xffff;
3816       break;
3817     }
3818
3819     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3820     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3821     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3822     // and fall through here to test for a valid 64-bit splat.  But, then the
3823     // caller would also need to check and handle the change in size.
3824     return SDValue();
3825
3826   case 64: {
3827     if (type != VMOVModImm)
3828       return SDValue();
3829     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3830     uint64_t BitMask = 0xff;
3831     uint64_t Val = 0;
3832     unsigned ImmMask = 1;
3833     Imm = 0;
3834     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3835       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3836         Val |= BitMask;
3837         Imm |= ImmMask;
3838       } else if ((SplatBits & BitMask) != 0) {
3839         return SDValue();
3840       }
3841       BitMask <<= 8;
3842       ImmMask <<= 1;
3843     }
3844     // Op=1, Cmode=1110.
3845     OpCmode = 0x1e;
3846     SplatBits = Val;
3847     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3848     break;
3849   }
3850
3851   default:
3852     llvm_unreachable("unexpected size for isNEONModifiedImm");
3853   }
3854
3855   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3856   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3857 }
3858
3859 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3860                                            const ARMSubtarget *ST) const {
3861   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3862     return SDValue();
3863
3864   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3865   assert(Op.getValueType() == MVT::f32 &&
3866          "ConstantFP custom lowering should only occur for f32.");
3867
3868   // Try splatting with a VMOV.f32...
3869   APFloat FPVal = CFP->getValueAPF();
3870   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3871   if (ImmVal != -1) {
3872     DebugLoc DL = Op.getDebugLoc();
3873     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3874     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3875                                       NewVal);
3876     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3877                        DAG.getConstant(0, MVT::i32));
3878   }
3879
3880   // If that fails, try a VMOV.i32
3881   EVT VMovVT;
3882   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3883   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3884                                      VMOVModImm);
3885   if (NewVal != SDValue()) {
3886     DebugLoc DL = Op.getDebugLoc();
3887     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3888                                       NewVal);
3889     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3890                                        VecConstant);
3891     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3892                        DAG.getConstant(0, MVT::i32));
3893   }
3894
3895   // Finally, try a VMVN.i32
3896   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3897                              VMVNModImm);
3898   if (NewVal != SDValue()) {
3899     DebugLoc DL = Op.getDebugLoc();
3900     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3901     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3902                                        VecConstant);
3903     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3904                        DAG.getConstant(0, MVT::i32));
3905   }
3906
3907   return SDValue();
3908 }
3909
3910
3911 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3912                        bool &ReverseVEXT, unsigned &Imm) {
3913   unsigned NumElts = VT.getVectorNumElements();
3914   ReverseVEXT = false;
3915
3916   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3917   if (M[0] < 0)
3918     return false;
3919
3920   Imm = M[0];
3921
3922   // If this is a VEXT shuffle, the immediate value is the index of the first
3923   // element.  The other shuffle indices must be the successive elements after
3924   // the first one.
3925   unsigned ExpectedElt = Imm;
3926   for (unsigned i = 1; i < NumElts; ++i) {
3927     // Increment the expected index.  If it wraps around, it may still be
3928     // a VEXT but the source vectors must be swapped.
3929     ExpectedElt += 1;
3930     if (ExpectedElt == NumElts * 2) {
3931       ExpectedElt = 0;
3932       ReverseVEXT = true;
3933     }
3934
3935     if (M[i] < 0) continue; // ignore UNDEF indices
3936     if (ExpectedElt != static_cast<unsigned>(M[i]))
3937       return false;
3938   }
3939
3940   // Adjust the index value if the source operands will be swapped.
3941   if (ReverseVEXT)
3942     Imm -= NumElts;
3943
3944   return true;
3945 }
3946
3947 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3948 /// instruction with the specified blocksize.  (The order of the elements
3949 /// within each block of the vector is reversed.)
3950 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3951   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3952          "Only possible block sizes for VREV are: 16, 32, 64");
3953
3954   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3955   if (EltSz == 64)
3956     return false;
3957
3958   unsigned NumElts = VT.getVectorNumElements();
3959   unsigned BlockElts = M[0] + 1;
3960   // If the first shuffle index is UNDEF, be optimistic.
3961   if (M[0] < 0)
3962     BlockElts = BlockSize / EltSz;
3963
3964   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3965     return false;
3966
3967   for (unsigned i = 0; i < NumElts; ++i) {
3968     if (M[i] < 0) continue; // ignore UNDEF indices
3969     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3970       return false;
3971   }
3972
3973   return true;
3974 }
3975
3976 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3977   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3978   // range, then 0 is placed into the resulting vector. So pretty much any mask
3979   // of 8 elements can work here.
3980   return VT == MVT::v8i8 && M.size() == 8;
3981 }
3982
3983 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3984   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3985   if (EltSz == 64)
3986     return false;
3987
3988   unsigned NumElts = VT.getVectorNumElements();
3989   WhichResult = (M[0] == 0 ? 0 : 1);
3990   for (unsigned i = 0; i < NumElts; i += 2) {
3991     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3992         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3993       return false;
3994   }
3995   return true;
3996 }
3997
3998 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3999 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4000 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4001 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4002   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4003   if (EltSz == 64)
4004     return false;
4005
4006   unsigned NumElts = VT.getVectorNumElements();
4007   WhichResult = (M[0] == 0 ? 0 : 1);
4008   for (unsigned i = 0; i < NumElts; i += 2) {
4009     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4010         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4011       return false;
4012   }
4013   return true;
4014 }
4015
4016 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4017   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4018   if (EltSz == 64)
4019     return false;
4020
4021   unsigned NumElts = VT.getVectorNumElements();
4022   WhichResult = (M[0] == 0 ? 0 : 1);
4023   for (unsigned i = 0; i != NumElts; ++i) {
4024     if (M[i] < 0) continue; // ignore UNDEF indices
4025     if ((unsigned) M[i] != 2 * i + WhichResult)
4026       return false;
4027   }
4028
4029   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4030   if (VT.is64BitVector() && EltSz == 32)
4031     return false;
4032
4033   return true;
4034 }
4035
4036 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4037 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4038 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4039 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4040   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4041   if (EltSz == 64)
4042     return false;
4043
4044   unsigned Half = VT.getVectorNumElements() / 2;
4045   WhichResult = (M[0] == 0 ? 0 : 1);
4046   for (unsigned j = 0; j != 2; ++j) {
4047     unsigned Idx = WhichResult;
4048     for (unsigned i = 0; i != Half; ++i) {
4049       int MIdx = M[i + j * Half];
4050       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4051         return false;
4052       Idx += 2;
4053     }
4054   }
4055
4056   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4057   if (VT.is64BitVector() && EltSz == 32)
4058     return false;
4059
4060   return true;
4061 }
4062
4063 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4064   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4065   if (EltSz == 64)
4066     return false;
4067
4068   unsigned NumElts = VT.getVectorNumElements();
4069   WhichResult = (M[0] == 0 ? 0 : 1);
4070   unsigned Idx = WhichResult * NumElts / 2;
4071   for (unsigned i = 0; i != NumElts; i += 2) {
4072     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4073         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4074       return false;
4075     Idx += 1;
4076   }
4077
4078   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4079   if (VT.is64BitVector() && EltSz == 32)
4080     return false;
4081
4082   return true;
4083 }
4084
4085 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4086 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4087 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4088 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4089   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4090   if (EltSz == 64)
4091     return false;
4092
4093   unsigned NumElts = VT.getVectorNumElements();
4094   WhichResult = (M[0] == 0 ? 0 : 1);
4095   unsigned Idx = WhichResult * NumElts / 2;
4096   for (unsigned i = 0; i != NumElts; i += 2) {
4097     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4098         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4099       return false;
4100     Idx += 1;
4101   }
4102
4103   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4104   if (VT.is64BitVector() && EltSz == 32)
4105     return false;
4106
4107   return true;
4108 }
4109
4110 // If N is an integer constant that can be moved into a register in one
4111 // instruction, return an SDValue of such a constant (will become a MOV
4112 // instruction).  Otherwise return null.
4113 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4114                                      const ARMSubtarget *ST, DebugLoc dl) {
4115   uint64_t Val;
4116   if (!isa<ConstantSDNode>(N))
4117     return SDValue();
4118   Val = cast<ConstantSDNode>(N)->getZExtValue();
4119
4120   if (ST->isThumb1Only()) {
4121     if (Val <= 255 || ~Val <= 255)
4122       return DAG.getConstant(Val, MVT::i32);
4123   } else {
4124     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4125       return DAG.getConstant(Val, MVT::i32);
4126   }
4127   return SDValue();
4128 }
4129
4130 // If this is a case we can't handle, return null and let the default
4131 // expansion code take care of it.
4132 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4133                                              const ARMSubtarget *ST) const {
4134   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4135   DebugLoc dl = Op.getDebugLoc();
4136   EVT VT = Op.getValueType();
4137
4138   APInt SplatBits, SplatUndef;
4139   unsigned SplatBitSize;
4140   bool HasAnyUndefs;
4141   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4142     if (SplatBitSize <= 64) {
4143       // Check if an immediate VMOV works.
4144       EVT VmovVT;
4145       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4146                                       SplatUndef.getZExtValue(), SplatBitSize,
4147                                       DAG, VmovVT, VT.is128BitVector(),
4148                                       VMOVModImm);
4149       if (Val.getNode()) {
4150         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4151         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4152       }
4153
4154       // Try an immediate VMVN.
4155       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4156       Val = isNEONModifiedImm(NegatedImm,
4157                                       SplatUndef.getZExtValue(), SplatBitSize,
4158                                       DAG, VmovVT, VT.is128BitVector(),
4159                                       VMVNModImm);
4160       if (Val.getNode()) {
4161         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4162         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4163       }
4164
4165       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4166       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4167         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4168         if (ImmVal != -1) {
4169           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4170           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4171         }
4172       }
4173     }
4174   }
4175
4176   // Scan through the operands to see if only one value is used.
4177   //
4178   // As an optimisation, even if more than one value is used it may be more
4179   // profitable to splat with one value then change some lanes.
4180   //
4181   // Heuristically we decide to do this if the vector has a "dominant" value,
4182   // defined as splatted to more than half of the lanes.
4183   unsigned NumElts = VT.getVectorNumElements();
4184   bool isOnlyLowElement = true;
4185   bool usesOnlyOneValue = true;
4186   bool hasDominantValue = false;
4187   bool isConstant = true;
4188
4189   // Map of the number of times a particular SDValue appears in the
4190   // element list.
4191   DenseMap<SDValue, unsigned> ValueCounts;
4192   SDValue Value;
4193   for (unsigned i = 0; i < NumElts; ++i) {
4194     SDValue V = Op.getOperand(i);
4195     if (V.getOpcode() == ISD::UNDEF)
4196       continue;
4197     if (i > 0)
4198       isOnlyLowElement = false;
4199     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4200       isConstant = false;
4201
4202     ValueCounts.insert(std::make_pair(V, 0));
4203     unsigned &Count = ValueCounts[V];
4204     
4205     // Is this value dominant? (takes up more than half of the lanes)
4206     if (++Count > (NumElts / 2)) {
4207       hasDominantValue = true;
4208       Value = V;
4209     }
4210   }
4211   if (ValueCounts.size() != 1)
4212     usesOnlyOneValue = false;
4213   if (!Value.getNode() && ValueCounts.size() > 0)
4214     Value = ValueCounts.begin()->first;
4215
4216   if (ValueCounts.size() == 0)
4217     return DAG.getUNDEF(VT);
4218
4219   if (isOnlyLowElement)
4220     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4221
4222   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4223
4224   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4225   // i32 and try again.
4226   if (hasDominantValue && EltSize <= 32) {
4227     if (!isConstant) {
4228       SDValue N;
4229
4230       // If we are VDUPing a value that comes directly from a vector, that will
4231       // cause an unnecessary move to and from a GPR, where instead we could
4232       // just use VDUPLANE.
4233       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT)
4234         N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4235                         Value->getOperand(0), Value->getOperand(1));
4236       else
4237         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4238
4239       if (!usesOnlyOneValue) {
4240         // The dominant value was splatted as 'N', but we now have to insert
4241         // all differing elements.
4242         for (unsigned I = 0; I < NumElts; ++I) {
4243           if (Op.getOperand(I) == Value)
4244             continue;
4245           SmallVector<SDValue, 3> Ops;
4246           Ops.push_back(N);
4247           Ops.push_back(Op.getOperand(I));
4248           Ops.push_back(DAG.getConstant(I, MVT::i32));
4249           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4250         }
4251       }
4252       return N;
4253     }
4254     if (VT.getVectorElementType().isFloatingPoint()) {
4255       SmallVector<SDValue, 8> Ops;
4256       for (unsigned i = 0; i < NumElts; ++i)
4257         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4258                                   Op.getOperand(i)));
4259       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4260       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4261       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4262       if (Val.getNode())
4263         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4264     }
4265     if (usesOnlyOneValue) {
4266       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4267       if (isConstant && Val.getNode())
4268         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4269     }
4270   }
4271
4272   // If all elements are constants and the case above didn't get hit, fall back
4273   // to the default expansion, which will generate a load from the constant
4274   // pool.
4275   if (isConstant)
4276     return SDValue();
4277
4278   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4279   if (NumElts >= 4) {
4280     SDValue shuffle = ReconstructShuffle(Op, DAG);
4281     if (shuffle != SDValue())
4282       return shuffle;
4283   }
4284
4285   // Vectors with 32- or 64-bit elements can be built by directly assigning
4286   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4287   // will be legalized.
4288   if (EltSize >= 32) {
4289     // Do the expansion with floating-point types, since that is what the VFP
4290     // registers are defined to use, and since i64 is not legal.
4291     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4292     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4293     SmallVector<SDValue, 8> Ops;
4294     for (unsigned i = 0; i < NumElts; ++i)
4295       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4296     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4297     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4298   }
4299
4300   return SDValue();
4301 }
4302
4303 // Gather data to see if the operation can be modelled as a
4304 // shuffle in combination with VEXTs.
4305 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4306                                               SelectionDAG &DAG) const {
4307   DebugLoc dl = Op.getDebugLoc();
4308   EVT VT = Op.getValueType();
4309   unsigned NumElts = VT.getVectorNumElements();
4310
4311   SmallVector<SDValue, 2> SourceVecs;
4312   SmallVector<unsigned, 2> MinElts;
4313   SmallVector<unsigned, 2> MaxElts;
4314
4315   for (unsigned i = 0; i < NumElts; ++i) {
4316     SDValue V = Op.getOperand(i);
4317     if (V.getOpcode() == ISD::UNDEF)
4318       continue;
4319     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4320       // A shuffle can only come from building a vector from various
4321       // elements of other vectors.
4322       return SDValue();
4323     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4324                VT.getVectorElementType()) {
4325       // This code doesn't know how to handle shuffles where the vector
4326       // element types do not match (this happens because type legalization
4327       // promotes the return type of EXTRACT_VECTOR_ELT).
4328       // FIXME: It might be appropriate to extend this code to handle
4329       // mismatched types.
4330       return SDValue();
4331     }
4332
4333     // Record this extraction against the appropriate vector if possible...
4334     SDValue SourceVec = V.getOperand(0);
4335     // If the element number isn't a constant, we can't effectively
4336     // analyze what's going on.
4337     if (!isa<ConstantSDNode>(V.getOperand(1)))
4338       return SDValue();
4339     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4340     bool FoundSource = false;
4341     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4342       if (SourceVecs[j] == SourceVec) {
4343         if (MinElts[j] > EltNo)
4344           MinElts[j] = EltNo;
4345         if (MaxElts[j] < EltNo)
4346           MaxElts[j] = EltNo;
4347         FoundSource = true;
4348         break;
4349       }
4350     }
4351
4352     // Or record a new source if not...
4353     if (!FoundSource) {
4354       SourceVecs.push_back(SourceVec);
4355       MinElts.push_back(EltNo);
4356       MaxElts.push_back(EltNo);
4357     }
4358   }
4359
4360   // Currently only do something sane when at most two source vectors
4361   // involved.
4362   if (SourceVecs.size() > 2)
4363     return SDValue();
4364
4365   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4366   int VEXTOffsets[2] = {0, 0};
4367
4368   // This loop extracts the usage patterns of the source vectors
4369   // and prepares appropriate SDValues for a shuffle if possible.
4370   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4371     if (SourceVecs[i].getValueType() == VT) {
4372       // No VEXT necessary
4373       ShuffleSrcs[i] = SourceVecs[i];
4374       VEXTOffsets[i] = 0;
4375       continue;
4376     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4377       // It probably isn't worth padding out a smaller vector just to
4378       // break it down again in a shuffle.
4379       return SDValue();
4380     }
4381
4382     // Since only 64-bit and 128-bit vectors are legal on ARM and
4383     // we've eliminated the other cases...
4384     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4385            "unexpected vector sizes in ReconstructShuffle");
4386
4387     if (MaxElts[i] - MinElts[i] >= NumElts) {
4388       // Span too large for a VEXT to cope
4389       return SDValue();
4390     }
4391
4392     if (MinElts[i] >= NumElts) {
4393       // The extraction can just take the second half
4394       VEXTOffsets[i] = NumElts;
4395       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4396                                    SourceVecs[i],
4397                                    DAG.getIntPtrConstant(NumElts));
4398     } else if (MaxElts[i] < NumElts) {
4399       // The extraction can just take the first half
4400       VEXTOffsets[i] = 0;
4401       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4402                                    SourceVecs[i],
4403                                    DAG.getIntPtrConstant(0));
4404     } else {
4405       // An actual VEXT is needed
4406       VEXTOffsets[i] = MinElts[i];
4407       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4408                                      SourceVecs[i],
4409                                      DAG.getIntPtrConstant(0));
4410       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4411                                      SourceVecs[i],
4412                                      DAG.getIntPtrConstant(NumElts));
4413       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4414                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4415     }
4416   }
4417
4418   SmallVector<int, 8> Mask;
4419
4420   for (unsigned i = 0; i < NumElts; ++i) {
4421     SDValue Entry = Op.getOperand(i);
4422     if (Entry.getOpcode() == ISD::UNDEF) {
4423       Mask.push_back(-1);
4424       continue;
4425     }
4426
4427     SDValue ExtractVec = Entry.getOperand(0);
4428     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4429                                           .getOperand(1))->getSExtValue();
4430     if (ExtractVec == SourceVecs[0]) {
4431       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4432     } else {
4433       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4434     }
4435   }
4436
4437   // Final check before we try to produce nonsense...
4438   if (isShuffleMaskLegal(Mask, VT))
4439     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4440                                 &Mask[0]);
4441
4442   return SDValue();
4443 }
4444
4445 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4446 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4447 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4448 /// are assumed to be legal.
4449 bool
4450 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4451                                       EVT VT) const {
4452   if (VT.getVectorNumElements() == 4 &&
4453       (VT.is128BitVector() || VT.is64BitVector())) {
4454     unsigned PFIndexes[4];
4455     for (unsigned i = 0; i != 4; ++i) {
4456       if (M[i] < 0)
4457         PFIndexes[i] = 8;
4458       else
4459         PFIndexes[i] = M[i];
4460     }
4461
4462     // Compute the index in the perfect shuffle table.
4463     unsigned PFTableIndex =
4464       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4465     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4466     unsigned Cost = (PFEntry >> 30);
4467
4468     if (Cost <= 4)
4469       return true;
4470   }
4471
4472   bool ReverseVEXT;
4473   unsigned Imm, WhichResult;
4474
4475   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4476   return (EltSize >= 32 ||
4477           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4478           isVREVMask(M, VT, 64) ||
4479           isVREVMask(M, VT, 32) ||
4480           isVREVMask(M, VT, 16) ||
4481           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4482           isVTBLMask(M, VT) ||
4483           isVTRNMask(M, VT, WhichResult) ||
4484           isVUZPMask(M, VT, WhichResult) ||
4485           isVZIPMask(M, VT, WhichResult) ||
4486           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4487           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4488           isVZIP_v_undef_Mask(M, VT, WhichResult));
4489 }
4490
4491 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4492 /// the specified operations to build the shuffle.
4493 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4494                                       SDValue RHS, SelectionDAG &DAG,
4495                                       DebugLoc dl) {
4496   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4497   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4498   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4499
4500   enum {
4501     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4502     OP_VREV,
4503     OP_VDUP0,
4504     OP_VDUP1,
4505     OP_VDUP2,
4506     OP_VDUP3,
4507     OP_VEXT1,
4508     OP_VEXT2,
4509     OP_VEXT3,
4510     OP_VUZPL, // VUZP, left result
4511     OP_VUZPR, // VUZP, right result
4512     OP_VZIPL, // VZIP, left result
4513     OP_VZIPR, // VZIP, right result
4514     OP_VTRNL, // VTRN, left result
4515     OP_VTRNR  // VTRN, right result
4516   };
4517
4518   if (OpNum == OP_COPY) {
4519     if (LHSID == (1*9+2)*9+3) return LHS;
4520     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4521     return RHS;
4522   }
4523
4524   SDValue OpLHS, OpRHS;
4525   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4526   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4527   EVT VT = OpLHS.getValueType();
4528
4529   switch (OpNum) {
4530   default: llvm_unreachable("Unknown shuffle opcode!");
4531   case OP_VREV:
4532     // VREV divides the vector in half and swaps within the half.
4533     if (VT.getVectorElementType() == MVT::i32 ||
4534         VT.getVectorElementType() == MVT::f32)
4535       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4536     // vrev <4 x i16> -> VREV32
4537     if (VT.getVectorElementType() == MVT::i16)
4538       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4539     // vrev <4 x i8> -> VREV16
4540     assert(VT.getVectorElementType() == MVT::i8);
4541     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4542   case OP_VDUP0:
4543   case OP_VDUP1:
4544   case OP_VDUP2:
4545   case OP_VDUP3:
4546     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4547                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4548   case OP_VEXT1:
4549   case OP_VEXT2:
4550   case OP_VEXT3:
4551     return DAG.getNode(ARMISD::VEXT, dl, VT,
4552                        OpLHS, OpRHS,
4553                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4554   case OP_VUZPL:
4555   case OP_VUZPR:
4556     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4557                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4558   case OP_VZIPL:
4559   case OP_VZIPR:
4560     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4561                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4562   case OP_VTRNL:
4563   case OP_VTRNR:
4564     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4565                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4566   }
4567 }
4568
4569 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4570                                        ArrayRef<int> ShuffleMask,
4571                                        SelectionDAG &DAG) {
4572   // Check to see if we can use the VTBL instruction.
4573   SDValue V1 = Op.getOperand(0);
4574   SDValue V2 = Op.getOperand(1);
4575   DebugLoc DL = Op.getDebugLoc();
4576
4577   SmallVector<SDValue, 8> VTBLMask;
4578   for (ArrayRef<int>::iterator
4579          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4580     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4581
4582   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4583     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4584                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4585                                    &VTBLMask[0], 8));
4586
4587   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4588                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4589                                  &VTBLMask[0], 8));
4590 }
4591
4592 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4593   SDValue V1 = Op.getOperand(0);
4594   SDValue V2 = Op.getOperand(1);
4595   DebugLoc dl = Op.getDebugLoc();
4596   EVT VT = Op.getValueType();
4597   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4598
4599   // Convert shuffles that are directly supported on NEON to target-specific
4600   // DAG nodes, instead of keeping them as shuffles and matching them again
4601   // during code selection.  This is more efficient and avoids the possibility
4602   // of inconsistencies between legalization and selection.
4603   // FIXME: floating-point vectors should be canonicalized to integer vectors
4604   // of the same time so that they get CSEd properly.
4605   ArrayRef<int> ShuffleMask = SVN->getMask();
4606
4607   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4608   if (EltSize <= 32) {
4609     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4610       int Lane = SVN->getSplatIndex();
4611       // If this is undef splat, generate it via "just" vdup, if possible.
4612       if (Lane == -1) Lane = 0;
4613
4614       // Test if V1 is a SCALAR_TO_VECTOR.
4615       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4616         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4617       }
4618       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4619       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4620       // reaches it).
4621       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4622           !isa<ConstantSDNode>(V1.getOperand(0))) {
4623         bool IsScalarToVector = true;
4624         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4625           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4626             IsScalarToVector = false;
4627             break;
4628           }
4629         if (IsScalarToVector)
4630           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4631       }
4632       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4633                          DAG.getConstant(Lane, MVT::i32));
4634     }
4635
4636     bool ReverseVEXT;
4637     unsigned Imm;
4638     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4639       if (ReverseVEXT)
4640         std::swap(V1, V2);
4641       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4642                          DAG.getConstant(Imm, MVT::i32));
4643     }
4644
4645     if (isVREVMask(ShuffleMask, VT, 64))
4646       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4647     if (isVREVMask(ShuffleMask, VT, 32))
4648       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4649     if (isVREVMask(ShuffleMask, VT, 16))
4650       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4651
4652     // Check for Neon shuffles that modify both input vectors in place.
4653     // If both results are used, i.e., if there are two shuffles with the same
4654     // source operands and with masks corresponding to both results of one of
4655     // these operations, DAG memoization will ensure that a single node is
4656     // used for both shuffles.
4657     unsigned WhichResult;
4658     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4659       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4660                          V1, V2).getValue(WhichResult);
4661     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4662       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4663                          V1, V2).getValue(WhichResult);
4664     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4665       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4666                          V1, V2).getValue(WhichResult);
4667
4668     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4669       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4670                          V1, V1).getValue(WhichResult);
4671     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4672       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4673                          V1, V1).getValue(WhichResult);
4674     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4675       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4676                          V1, V1).getValue(WhichResult);
4677   }
4678
4679   // If the shuffle is not directly supported and it has 4 elements, use
4680   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4681   unsigned NumElts = VT.getVectorNumElements();
4682   if (NumElts == 4) {
4683     unsigned PFIndexes[4];
4684     for (unsigned i = 0; i != 4; ++i) {
4685       if (ShuffleMask[i] < 0)
4686         PFIndexes[i] = 8;
4687       else
4688         PFIndexes[i] = ShuffleMask[i];
4689     }
4690
4691     // Compute the index in the perfect shuffle table.
4692     unsigned PFTableIndex =
4693       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4694     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4695     unsigned Cost = (PFEntry >> 30);
4696
4697     if (Cost <= 4)
4698       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4699   }
4700
4701   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4702   if (EltSize >= 32) {
4703     // Do the expansion with floating-point types, since that is what the VFP
4704     // registers are defined to use, and since i64 is not legal.
4705     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4706     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4707     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4708     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4709     SmallVector<SDValue, 8> Ops;
4710     for (unsigned i = 0; i < NumElts; ++i) {
4711       if (ShuffleMask[i] < 0)
4712         Ops.push_back(DAG.getUNDEF(EltVT));
4713       else
4714         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4715                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4716                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4717                                                   MVT::i32)));
4718     }
4719     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4720     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4721   }
4722
4723   if (VT == MVT::v8i8) {
4724     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4725     if (NewOp.getNode())
4726       return NewOp;
4727   }
4728
4729   return SDValue();
4730 }
4731
4732 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4733   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4734   SDValue Lane = Op.getOperand(2);
4735   if (!isa<ConstantSDNode>(Lane))
4736     return SDValue();
4737
4738   return Op;
4739 }
4740
4741 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4742   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4743   SDValue Lane = Op.getOperand(1);
4744   if (!isa<ConstantSDNode>(Lane))
4745     return SDValue();
4746
4747   SDValue Vec = Op.getOperand(0);
4748   if (Op.getValueType() == MVT::i32 &&
4749       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4750     DebugLoc dl = Op.getDebugLoc();
4751     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4752   }
4753
4754   return Op;
4755 }
4756
4757 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4758   // The only time a CONCAT_VECTORS operation can have legal types is when
4759   // two 64-bit vectors are concatenated to a 128-bit vector.
4760   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4761          "unexpected CONCAT_VECTORS");
4762   DebugLoc dl = Op.getDebugLoc();
4763   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4764   SDValue Op0 = Op.getOperand(0);
4765   SDValue Op1 = Op.getOperand(1);
4766   if (Op0.getOpcode() != ISD::UNDEF)
4767     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4768                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4769                       DAG.getIntPtrConstant(0));
4770   if (Op1.getOpcode() != ISD::UNDEF)
4771     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4772                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4773                       DAG.getIntPtrConstant(1));
4774   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4775 }
4776
4777 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4778 /// element has been zero/sign-extended, depending on the isSigned parameter,
4779 /// from an integer type half its size.
4780 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4781                                    bool isSigned) {
4782   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4783   EVT VT = N->getValueType(0);
4784   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4785     SDNode *BVN = N->getOperand(0).getNode();
4786     if (BVN->getValueType(0) != MVT::v4i32 ||
4787         BVN->getOpcode() != ISD::BUILD_VECTOR)
4788       return false;
4789     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4790     unsigned HiElt = 1 - LoElt;
4791     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4792     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4793     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4794     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4795     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4796       return false;
4797     if (isSigned) {
4798       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4799           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4800         return true;
4801     } else {
4802       if (Hi0->isNullValue() && Hi1->isNullValue())
4803         return true;
4804     }
4805     return false;
4806   }
4807
4808   if (N->getOpcode() != ISD::BUILD_VECTOR)
4809     return false;
4810
4811   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4812     SDNode *Elt = N->getOperand(i).getNode();
4813     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4814       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4815       unsigned HalfSize = EltSize / 2;
4816       if (isSigned) {
4817         if (!isIntN(HalfSize, C->getSExtValue()))
4818           return false;
4819       } else {
4820         if (!isUIntN(HalfSize, C->getZExtValue()))
4821           return false;
4822       }
4823       continue;
4824     }
4825     return false;
4826   }
4827
4828   return true;
4829 }
4830
4831 /// isSignExtended - Check if a node is a vector value that is sign-extended
4832 /// or a constant BUILD_VECTOR with sign-extended elements.
4833 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4834   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4835     return true;
4836   if (isExtendedBUILD_VECTOR(N, DAG, true))
4837     return true;
4838   return false;
4839 }
4840
4841 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4842 /// or a constant BUILD_VECTOR with zero-extended elements.
4843 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4844   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4845     return true;
4846   if (isExtendedBUILD_VECTOR(N, DAG, false))
4847     return true;
4848   return false;
4849 }
4850
4851 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4852 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4853 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4854   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4855     return N->getOperand(0);
4856   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4857     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4858                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4859                        LD->isNonTemporal(), LD->isInvariant(),
4860                        LD->getAlignment());
4861   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4862   // have been legalized as a BITCAST from v4i32.
4863   if (N->getOpcode() == ISD::BITCAST) {
4864     SDNode *BVN = N->getOperand(0).getNode();
4865     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4866            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4867     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4868     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4869                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4870   }
4871   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4872   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4873   EVT VT = N->getValueType(0);
4874   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4875   unsigned NumElts = VT.getVectorNumElements();
4876   MVT TruncVT = MVT::getIntegerVT(EltSize);
4877   SmallVector<SDValue, 8> Ops;
4878   for (unsigned i = 0; i != NumElts; ++i) {
4879     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4880     const APInt &CInt = C->getAPIntValue();
4881     // Element types smaller than 32 bits are not legal, so use i32 elements.
4882     // The values are implicitly truncated so sext vs. zext doesn't matter.
4883     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4884   }
4885   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4886                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4887 }
4888
4889 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4890   unsigned Opcode = N->getOpcode();
4891   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4892     SDNode *N0 = N->getOperand(0).getNode();
4893     SDNode *N1 = N->getOperand(1).getNode();
4894     return N0->hasOneUse() && N1->hasOneUse() &&
4895       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4896   }
4897   return false;
4898 }
4899
4900 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4901   unsigned Opcode = N->getOpcode();
4902   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4903     SDNode *N0 = N->getOperand(0).getNode();
4904     SDNode *N1 = N->getOperand(1).getNode();
4905     return N0->hasOneUse() && N1->hasOneUse() &&
4906       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4907   }
4908   return false;
4909 }
4910
4911 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4912   // Multiplications are only custom-lowered for 128-bit vectors so that
4913   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4914   EVT VT = Op.getValueType();
4915   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4916   SDNode *N0 = Op.getOperand(0).getNode();
4917   SDNode *N1 = Op.getOperand(1).getNode();
4918   unsigned NewOpc = 0;
4919   bool isMLA = false;
4920   bool isN0SExt = isSignExtended(N0, DAG);
4921   bool isN1SExt = isSignExtended(N1, DAG);
4922   if (isN0SExt && isN1SExt)
4923     NewOpc = ARMISD::VMULLs;
4924   else {
4925     bool isN0ZExt = isZeroExtended(N0, DAG);
4926     bool isN1ZExt = isZeroExtended(N1, DAG);
4927     if (isN0ZExt && isN1ZExt)
4928       NewOpc = ARMISD::VMULLu;
4929     else if (isN1SExt || isN1ZExt) {
4930       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4931       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4932       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4933         NewOpc = ARMISD::VMULLs;
4934         isMLA = true;
4935       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4936         NewOpc = ARMISD::VMULLu;
4937         isMLA = true;
4938       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4939         std::swap(N0, N1);
4940         NewOpc = ARMISD::VMULLu;
4941         isMLA = true;
4942       }
4943     }
4944
4945     if (!NewOpc) {
4946       if (VT == MVT::v2i64)
4947         // Fall through to expand this.  It is not legal.
4948         return SDValue();
4949       else
4950         // Other vector multiplications are legal.
4951         return Op;
4952     }
4953   }
4954
4955   // Legalize to a VMULL instruction.
4956   DebugLoc DL = Op.getDebugLoc();
4957   SDValue Op0;
4958   SDValue Op1 = SkipExtension(N1, DAG);
4959   if (!isMLA) {
4960     Op0 = SkipExtension(N0, DAG);
4961     assert(Op0.getValueType().is64BitVector() &&
4962            Op1.getValueType().is64BitVector() &&
4963            "unexpected types for extended operands to VMULL");
4964     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4965   }
4966
4967   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4968   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4969   //   vmull q0, d4, d6
4970   //   vmlal q0, d5, d6
4971   // is faster than
4972   //   vaddl q0, d4, d5
4973   //   vmovl q1, d6
4974   //   vmul  q0, q0, q1
4975   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4976   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4977   EVT Op1VT = Op1.getValueType();
4978   return DAG.getNode(N0->getOpcode(), DL, VT,
4979                      DAG.getNode(NewOpc, DL, VT,
4980                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4981                      DAG.getNode(NewOpc, DL, VT,
4982                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4983 }
4984
4985 static SDValue
4986 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4987   // Convert to float
4988   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4989   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4990   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4991   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4992   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4993   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4994   // Get reciprocal estimate.
4995   // float4 recip = vrecpeq_f32(yf);
4996   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4997                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4998   // Because char has a smaller range than uchar, we can actually get away
4999   // without any newton steps.  This requires that we use a weird bias
5000   // of 0xb000, however (again, this has been exhaustively tested).
5001   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5002   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5003   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5004   Y = DAG.getConstant(0xb000, MVT::i32);
5005   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5006   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5007   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5008   // Convert back to short.
5009   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5010   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5011   return X;
5012 }
5013
5014 static SDValue
5015 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5016   SDValue N2;
5017   // Convert to float.
5018   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5019   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5020   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5021   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5022   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5023   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5024
5025   // Use reciprocal estimate and one refinement step.
5026   // float4 recip = vrecpeq_f32(yf);
5027   // recip *= vrecpsq_f32(yf, recip);
5028   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5029                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5030   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5031                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5032                    N1, N2);
5033   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5034   // Because short has a smaller range than ushort, we can actually get away
5035   // with only a single newton step.  This requires that we use a weird bias
5036   // of 89, however (again, this has been exhaustively tested).
5037   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5038   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5039   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5040   N1 = DAG.getConstant(0x89, MVT::i32);
5041   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5042   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5043   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5044   // Convert back to integer and return.
5045   // return vmovn_s32(vcvt_s32_f32(result));
5046   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5047   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5048   return N0;
5049 }
5050
5051 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5052   EVT VT = Op.getValueType();
5053   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5054          "unexpected type for custom-lowering ISD::SDIV");
5055
5056   DebugLoc dl = Op.getDebugLoc();
5057   SDValue N0 = Op.getOperand(0);
5058   SDValue N1 = Op.getOperand(1);
5059   SDValue N2, N3;
5060
5061   if (VT == MVT::v8i8) {
5062     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5063     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5064
5065     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5066                      DAG.getIntPtrConstant(4));
5067     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5068                      DAG.getIntPtrConstant(4));
5069     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5070                      DAG.getIntPtrConstant(0));
5071     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5072                      DAG.getIntPtrConstant(0));
5073
5074     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5075     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5076
5077     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5078     N0 = LowerCONCAT_VECTORS(N0, DAG);
5079
5080     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5081     return N0;
5082   }
5083   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5084 }
5085
5086 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5087   EVT VT = Op.getValueType();
5088   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5089          "unexpected type for custom-lowering ISD::UDIV");
5090
5091   DebugLoc dl = Op.getDebugLoc();
5092   SDValue N0 = Op.getOperand(0);
5093   SDValue N1 = Op.getOperand(1);
5094   SDValue N2, N3;
5095
5096   if (VT == MVT::v8i8) {
5097     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5098     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5099
5100     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5101                      DAG.getIntPtrConstant(4));
5102     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5103                      DAG.getIntPtrConstant(4));
5104     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5105                      DAG.getIntPtrConstant(0));
5106     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5107                      DAG.getIntPtrConstant(0));
5108
5109     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5110     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5111
5112     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5113     N0 = LowerCONCAT_VECTORS(N0, DAG);
5114
5115     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5116                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5117                      N0);
5118     return N0;
5119   }
5120
5121   // v4i16 sdiv ... Convert to float.
5122   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5123   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5124   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5125   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5126   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5127   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5128
5129   // Use reciprocal estimate and two refinement steps.
5130   // float4 recip = vrecpeq_f32(yf);
5131   // recip *= vrecpsq_f32(yf, recip);
5132   // recip *= vrecpsq_f32(yf, recip);
5133   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5134                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5135   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5136                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5137                    BN1, N2);
5138   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5139   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5140                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5141                    BN1, N2);
5142   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5143   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5144   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5145   // and that it will never cause us to return an answer too large).
5146   // float4 result = as_float4(as_int4(xf*recip) + 2);
5147   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5148   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5149   N1 = DAG.getConstant(2, MVT::i32);
5150   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5151   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5152   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5153   // Convert back to integer and return.
5154   // return vmovn_u32(vcvt_s32_f32(result));
5155   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5156   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5157   return N0;
5158 }
5159
5160 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5161   EVT VT = Op.getNode()->getValueType(0);
5162   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5163
5164   unsigned Opc;
5165   bool ExtraOp = false;
5166   switch (Op.getOpcode()) {
5167   default: llvm_unreachable("Invalid code");
5168   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5169   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5170   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5171   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5172   }
5173
5174   if (!ExtraOp)
5175     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5176                        Op.getOperand(1));
5177   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5178                      Op.getOperand(1), Op.getOperand(2));
5179 }
5180
5181 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5182   // Monotonic load/store is legal for all targets
5183   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5184     return Op;
5185
5186   // Aquire/Release load/store is not legal for targets without a
5187   // dmb or equivalent available.
5188   return SDValue();
5189 }
5190
5191
5192 static void
5193 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5194                     SelectionDAG &DAG, unsigned NewOp) {
5195   DebugLoc dl = Node->getDebugLoc();
5196   assert (Node->getValueType(0) == MVT::i64 &&
5197           "Only know how to expand i64 atomics");
5198
5199   SmallVector<SDValue, 6> Ops;
5200   Ops.push_back(Node->getOperand(0)); // Chain
5201   Ops.push_back(Node->getOperand(1)); // Ptr
5202   // Low part of Val1
5203   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5204                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5205   // High part of Val1
5206   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5207                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5208   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5209     // High part of Val1
5210     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5211                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5212     // High part of Val2
5213     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5214                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5215   }
5216   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5217   SDValue Result =
5218     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5219                             cast<MemSDNode>(Node)->getMemOperand());
5220   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5221   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5222   Results.push_back(Result.getValue(2));
5223 }
5224
5225 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5226   switch (Op.getOpcode()) {
5227   default: llvm_unreachable("Don't know how to custom lower this!");
5228   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5229   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5230   case ISD::GlobalAddress:
5231     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5232       LowerGlobalAddressELF(Op, DAG);
5233   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5234   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5235   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5236   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5237   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5238   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5239   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5240   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5241   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5242   case ISD::SINT_TO_FP:
5243   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5244   case ISD::FP_TO_SINT:
5245   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5246   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5247   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5248   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5249   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5250   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5251   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5252   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5253                                                                Subtarget);
5254   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5255   case ISD::SHL:
5256   case ISD::SRL:
5257   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5258   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5259   case ISD::SRL_PARTS:
5260   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5261   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5262   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5263   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5264   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5265   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5266   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5267   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5268   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5269   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5270   case ISD::MUL:           return LowerMUL(Op, DAG);
5271   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5272   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5273   case ISD::ADDC:
5274   case ISD::ADDE:
5275   case ISD::SUBC:
5276   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5277   case ISD::ATOMIC_LOAD:
5278   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5279   }
5280 }
5281
5282 /// ReplaceNodeResults - Replace the results of node with an illegal result
5283 /// type with new values built out of custom code.
5284 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5285                                            SmallVectorImpl<SDValue>&Results,
5286                                            SelectionDAG &DAG) const {
5287   SDValue Res;
5288   switch (N->getOpcode()) {
5289   default:
5290     llvm_unreachable("Don't know how to custom expand this!");
5291   case ISD::BITCAST:
5292     Res = ExpandBITCAST(N, DAG);
5293     break;
5294   case ISD::SRL:
5295   case ISD::SRA:
5296     Res = Expand64BitShift(N, DAG, Subtarget);
5297     break;
5298   case ISD::ATOMIC_LOAD_ADD:
5299     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5300     return;
5301   case ISD::ATOMIC_LOAD_AND:
5302     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5303     return;
5304   case ISD::ATOMIC_LOAD_NAND:
5305     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5306     return;
5307   case ISD::ATOMIC_LOAD_OR:
5308     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5309     return;
5310   case ISD::ATOMIC_LOAD_SUB:
5311     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5312     return;
5313   case ISD::ATOMIC_LOAD_XOR:
5314     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5315     return;
5316   case ISD::ATOMIC_SWAP:
5317     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5318     return;
5319   case ISD::ATOMIC_CMP_SWAP:
5320     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5321     return;
5322   }
5323   if (Res.getNode())
5324     Results.push_back(Res);
5325 }
5326
5327 //===----------------------------------------------------------------------===//
5328 //                           ARM Scheduler Hooks
5329 //===----------------------------------------------------------------------===//
5330
5331 MachineBasicBlock *
5332 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5333                                      MachineBasicBlock *BB,
5334                                      unsigned Size) const {
5335   unsigned dest    = MI->getOperand(0).getReg();
5336   unsigned ptr     = MI->getOperand(1).getReg();
5337   unsigned oldval  = MI->getOperand(2).getReg();
5338   unsigned newval  = MI->getOperand(3).getReg();
5339   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5340   DebugLoc dl = MI->getDebugLoc();
5341   bool isThumb2 = Subtarget->isThumb2();
5342
5343   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5344   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5345     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5346     (const TargetRegisterClass*)&ARM::GPRRegClass);
5347
5348   if (isThumb2) {
5349     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5350     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5351     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5352   }
5353
5354   unsigned ldrOpc, strOpc;
5355   switch (Size) {
5356   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5357   case 1:
5358     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5359     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5360     break;
5361   case 2:
5362     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5363     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5364     break;
5365   case 4:
5366     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5367     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5368     break;
5369   }
5370
5371   MachineFunction *MF = BB->getParent();
5372   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5373   MachineFunction::iterator It = BB;
5374   ++It; // insert the new blocks after the current block
5375
5376   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5377   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5378   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5379   MF->insert(It, loop1MBB);
5380   MF->insert(It, loop2MBB);
5381   MF->insert(It, exitMBB);
5382
5383   // Transfer the remainder of BB and its successor edges to exitMBB.
5384   exitMBB->splice(exitMBB->begin(), BB,
5385                   llvm::next(MachineBasicBlock::iterator(MI)),
5386                   BB->end());
5387   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5388
5389   //  thisMBB:
5390   //   ...
5391   //   fallthrough --> loop1MBB
5392   BB->addSuccessor(loop1MBB);
5393
5394   // loop1MBB:
5395   //   ldrex dest, [ptr]
5396   //   cmp dest, oldval
5397   //   bne exitMBB
5398   BB = loop1MBB;
5399   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5400   if (ldrOpc == ARM::t2LDREX)
5401     MIB.addImm(0);
5402   AddDefaultPred(MIB);
5403   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5404                  .addReg(dest).addReg(oldval));
5405   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5406     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5407   BB->addSuccessor(loop2MBB);
5408   BB->addSuccessor(exitMBB);
5409
5410   // loop2MBB:
5411   //   strex scratch, newval, [ptr]
5412   //   cmp scratch, #0
5413   //   bne loop1MBB
5414   BB = loop2MBB;
5415   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5416   if (strOpc == ARM::t2STREX)
5417     MIB.addImm(0);
5418   AddDefaultPred(MIB);
5419   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5420                  .addReg(scratch).addImm(0));
5421   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5422     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5423   BB->addSuccessor(loop1MBB);
5424   BB->addSuccessor(exitMBB);
5425
5426   //  exitMBB:
5427   //   ...
5428   BB = exitMBB;
5429
5430   MI->eraseFromParent();   // The instruction is gone now.
5431
5432   return BB;
5433 }
5434
5435 MachineBasicBlock *
5436 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5437                                     unsigned Size, unsigned BinOpcode) const {
5438   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5439   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5440
5441   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5442   MachineFunction *MF = BB->getParent();
5443   MachineFunction::iterator It = BB;
5444   ++It;
5445
5446   unsigned dest = MI->getOperand(0).getReg();
5447   unsigned ptr = MI->getOperand(1).getReg();
5448   unsigned incr = MI->getOperand(2).getReg();
5449   DebugLoc dl = MI->getDebugLoc();
5450   bool isThumb2 = Subtarget->isThumb2();
5451
5452   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5453   if (isThumb2) {
5454     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5455     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5456   }
5457
5458   unsigned ldrOpc, strOpc;
5459   switch (Size) {
5460   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5461   case 1:
5462     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5463     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5464     break;
5465   case 2:
5466     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5467     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5468     break;
5469   case 4:
5470     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5471     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5472     break;
5473   }
5474
5475   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5476   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5477   MF->insert(It, loopMBB);
5478   MF->insert(It, exitMBB);
5479
5480   // Transfer the remainder of BB and its successor edges to exitMBB.
5481   exitMBB->splice(exitMBB->begin(), BB,
5482                   llvm::next(MachineBasicBlock::iterator(MI)),
5483                   BB->end());
5484   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5485
5486   const TargetRegisterClass *TRC = isThumb2 ?
5487     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5488     (const TargetRegisterClass*)&ARM::GPRRegClass;
5489   unsigned scratch = MRI.createVirtualRegister(TRC);
5490   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5491
5492   //  thisMBB:
5493   //   ...
5494   //   fallthrough --> loopMBB
5495   BB->addSuccessor(loopMBB);
5496
5497   //  loopMBB:
5498   //   ldrex dest, ptr
5499   //   <binop> scratch2, dest, incr
5500   //   strex scratch, scratch2, ptr
5501   //   cmp scratch, #0
5502   //   bne- loopMBB
5503   //   fallthrough --> exitMBB
5504   BB = loopMBB;
5505   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5506   if (ldrOpc == ARM::t2LDREX)
5507     MIB.addImm(0);
5508   AddDefaultPred(MIB);
5509   if (BinOpcode) {
5510     // operand order needs to go the other way for NAND
5511     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5512       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5513                      addReg(incr).addReg(dest)).addReg(0);
5514     else
5515       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5516                      addReg(dest).addReg(incr)).addReg(0);
5517   }
5518
5519   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5520   if (strOpc == ARM::t2STREX)
5521     MIB.addImm(0);
5522   AddDefaultPred(MIB);
5523   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5524                  .addReg(scratch).addImm(0));
5525   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5526     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5527
5528   BB->addSuccessor(loopMBB);
5529   BB->addSuccessor(exitMBB);
5530
5531   //  exitMBB:
5532   //   ...
5533   BB = exitMBB;
5534
5535   MI->eraseFromParent();   // The instruction is gone now.
5536
5537   return BB;
5538 }
5539
5540 MachineBasicBlock *
5541 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5542                                           MachineBasicBlock *BB,
5543                                           unsigned Size,
5544                                           bool signExtend,
5545                                           ARMCC::CondCodes Cond) const {
5546   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5547
5548   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5549   MachineFunction *MF = BB->getParent();
5550   MachineFunction::iterator It = BB;
5551   ++It;
5552
5553   unsigned dest = MI->getOperand(0).getReg();
5554   unsigned ptr = MI->getOperand(1).getReg();
5555   unsigned incr = MI->getOperand(2).getReg();
5556   unsigned oldval = dest;
5557   DebugLoc dl = MI->getDebugLoc();
5558   bool isThumb2 = Subtarget->isThumb2();
5559
5560   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5561   if (isThumb2) {
5562     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5563     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5564   }
5565
5566   unsigned ldrOpc, strOpc, extendOpc;
5567   switch (Size) {
5568   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5569   case 1:
5570     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5571     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5572     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5573     break;
5574   case 2:
5575     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5576     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5577     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5578     break;
5579   case 4:
5580     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5581     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5582     extendOpc = 0;
5583     break;
5584   }
5585
5586   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5587   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5588   MF->insert(It, loopMBB);
5589   MF->insert(It, exitMBB);
5590
5591   // Transfer the remainder of BB and its successor edges to exitMBB.
5592   exitMBB->splice(exitMBB->begin(), BB,
5593                   llvm::next(MachineBasicBlock::iterator(MI)),
5594                   BB->end());
5595   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5596
5597   const TargetRegisterClass *TRC = isThumb2 ?
5598     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5599     (const TargetRegisterClass*)&ARM::GPRRegClass;
5600   unsigned scratch = MRI.createVirtualRegister(TRC);
5601   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5602
5603   //  thisMBB:
5604   //   ...
5605   //   fallthrough --> loopMBB
5606   BB->addSuccessor(loopMBB);
5607
5608   //  loopMBB:
5609   //   ldrex dest, ptr
5610   //   (sign extend dest, if required)
5611   //   cmp dest, incr
5612   //   cmov.cond scratch2, incr, dest
5613   //   strex scratch, scratch2, ptr
5614   //   cmp scratch, #0
5615   //   bne- loopMBB
5616   //   fallthrough --> exitMBB
5617   BB = loopMBB;
5618   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5619   if (ldrOpc == ARM::t2LDREX)
5620     MIB.addImm(0);
5621   AddDefaultPred(MIB);
5622
5623   // Sign extend the value, if necessary.
5624   if (signExtend && extendOpc) {
5625     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5626     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5627                      .addReg(dest)
5628                      .addImm(0));
5629   }
5630
5631   // Build compare and cmov instructions.
5632   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5633                  .addReg(oldval).addReg(incr));
5634   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5635          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5636
5637   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5638   if (strOpc == ARM::t2STREX)
5639     MIB.addImm(0);
5640   AddDefaultPred(MIB);
5641   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5642                  .addReg(scratch).addImm(0));
5643   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5644     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5645
5646   BB->addSuccessor(loopMBB);
5647   BB->addSuccessor(exitMBB);
5648
5649   //  exitMBB:
5650   //   ...
5651   BB = exitMBB;
5652
5653   MI->eraseFromParent();   // The instruction is gone now.
5654
5655   return BB;
5656 }
5657
5658 MachineBasicBlock *
5659 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5660                                       unsigned Op1, unsigned Op2,
5661                                       bool NeedsCarry, bool IsCmpxchg) const {
5662   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5663   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5664
5665   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5666   MachineFunction *MF = BB->getParent();
5667   MachineFunction::iterator It = BB;
5668   ++It;
5669
5670   unsigned destlo = MI->getOperand(0).getReg();
5671   unsigned desthi = MI->getOperand(1).getReg();
5672   unsigned ptr = MI->getOperand(2).getReg();
5673   unsigned vallo = MI->getOperand(3).getReg();
5674   unsigned valhi = MI->getOperand(4).getReg();
5675   DebugLoc dl = MI->getDebugLoc();
5676   bool isThumb2 = Subtarget->isThumb2();
5677
5678   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5679   if (isThumb2) {
5680     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5681     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5682     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5683   }
5684
5685   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5686   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5687
5688   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5689   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5690   if (IsCmpxchg) {
5691     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5692     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5693   }
5694   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5695   MF->insert(It, loopMBB);
5696   if (IsCmpxchg) {
5697     MF->insert(It, contBB);
5698     MF->insert(It, cont2BB);
5699   }
5700   MF->insert(It, exitMBB);
5701
5702   // Transfer the remainder of BB and its successor edges to exitMBB.
5703   exitMBB->splice(exitMBB->begin(), BB,
5704                   llvm::next(MachineBasicBlock::iterator(MI)),
5705                   BB->end());
5706   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5707
5708   const TargetRegisterClass *TRC = isThumb2 ?
5709     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5710     (const TargetRegisterClass*)&ARM::GPRRegClass;
5711   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5712
5713   //  thisMBB:
5714   //   ...
5715   //   fallthrough --> loopMBB
5716   BB->addSuccessor(loopMBB);
5717
5718   //  loopMBB:
5719   //   ldrexd r2, r3, ptr
5720   //   <binopa> r0, r2, incr
5721   //   <binopb> r1, r3, incr
5722   //   strexd storesuccess, r0, r1, ptr
5723   //   cmp storesuccess, #0
5724   //   bne- loopMBB
5725   //   fallthrough --> exitMBB
5726   //
5727   // Note that the registers are explicitly specified because there is not any
5728   // way to force the register allocator to allocate a register pair.
5729   //
5730   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5731   // need to properly enforce the restriction that the two output registers
5732   // for ldrexd must be different.
5733   BB = loopMBB;
5734   // Load
5735   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5736                  .addReg(ARM::R2, RegState::Define)
5737                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5738   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5739   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5740   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5741
5742   if (IsCmpxchg) {
5743     // Add early exit
5744     for (unsigned i = 0; i < 2; i++) {
5745       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5746                                                          ARM::CMPrr))
5747                      .addReg(i == 0 ? destlo : desthi)
5748                      .addReg(i == 0 ? vallo : valhi));
5749       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5750         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5751       BB->addSuccessor(exitMBB);
5752       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5753       BB = (i == 0 ? contBB : cont2BB);
5754     }
5755
5756     // Copy to physregs for strexd
5757     unsigned setlo = MI->getOperand(5).getReg();
5758     unsigned sethi = MI->getOperand(6).getReg();
5759     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5760     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5761   } else if (Op1) {
5762     // Perform binary operation
5763     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5764                    .addReg(destlo).addReg(vallo))
5765         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5766     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5767                    .addReg(desthi).addReg(valhi)).addReg(0);
5768   } else {
5769     // Copy to physregs for strexd
5770     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5771     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5772   }
5773
5774   // Store
5775   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5776                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5777   // Cmp+jump
5778   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5779                  .addReg(storesuccess).addImm(0));
5780   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5781     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5782
5783   BB->addSuccessor(loopMBB);
5784   BB->addSuccessor(exitMBB);
5785
5786   //  exitMBB:
5787   //   ...
5788   BB = exitMBB;
5789
5790   MI->eraseFromParent();   // The instruction is gone now.
5791
5792   return BB;
5793 }
5794
5795 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5796 /// registers the function context.
5797 void ARMTargetLowering::
5798 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5799                        MachineBasicBlock *DispatchBB, int FI) const {
5800   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5801   DebugLoc dl = MI->getDebugLoc();
5802   MachineFunction *MF = MBB->getParent();
5803   MachineRegisterInfo *MRI = &MF->getRegInfo();
5804   MachineConstantPool *MCP = MF->getConstantPool();
5805   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5806   const Function *F = MF->getFunction();
5807
5808   bool isThumb = Subtarget->isThumb();
5809   bool isThumb2 = Subtarget->isThumb2();
5810
5811   unsigned PCLabelId = AFI->createPICLabelUId();
5812   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5813   ARMConstantPoolValue *CPV =
5814     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5815   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5816
5817   const TargetRegisterClass *TRC = isThumb ?
5818     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5819     (const TargetRegisterClass*)&ARM::GPRRegClass;
5820
5821   // Grab constant pool and fixed stack memory operands.
5822   MachineMemOperand *CPMMO =
5823     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5824                              MachineMemOperand::MOLoad, 4, 4);
5825
5826   MachineMemOperand *FIMMOSt =
5827     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5828                              MachineMemOperand::MOStore, 4, 4);
5829
5830   // Load the address of the dispatch MBB into the jump buffer.
5831   if (isThumb2) {
5832     // Incoming value: jbuf
5833     //   ldr.n  r5, LCPI1_1
5834     //   orr    r5, r5, #1
5835     //   add    r5, pc
5836     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5837     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5838     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5839                    .addConstantPoolIndex(CPI)
5840                    .addMemOperand(CPMMO));
5841     // Set the low bit because of thumb mode.
5842     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5843     AddDefaultCC(
5844       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5845                      .addReg(NewVReg1, RegState::Kill)
5846                      .addImm(0x01)));
5847     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5848     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5849       .addReg(NewVReg2, RegState::Kill)
5850       .addImm(PCLabelId);
5851     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5852                    .addReg(NewVReg3, RegState::Kill)
5853                    .addFrameIndex(FI)
5854                    .addImm(36)  // &jbuf[1] :: pc
5855                    .addMemOperand(FIMMOSt));
5856   } else if (isThumb) {
5857     // Incoming value: jbuf
5858     //   ldr.n  r1, LCPI1_4
5859     //   add    r1, pc
5860     //   mov    r2, #1
5861     //   orrs   r1, r2
5862     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5863     //   str    r1, [r2]
5864     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5865     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5866                    .addConstantPoolIndex(CPI)
5867                    .addMemOperand(CPMMO));
5868     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5869     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5870       .addReg(NewVReg1, RegState::Kill)
5871       .addImm(PCLabelId);
5872     // Set the low bit because of thumb mode.
5873     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5874     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5875                    .addReg(ARM::CPSR, RegState::Define)
5876                    .addImm(1));
5877     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5878     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5879                    .addReg(ARM::CPSR, RegState::Define)
5880                    .addReg(NewVReg2, RegState::Kill)
5881                    .addReg(NewVReg3, RegState::Kill));
5882     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5883     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5884                    .addFrameIndex(FI)
5885                    .addImm(36)); // &jbuf[1] :: pc
5886     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5887                    .addReg(NewVReg4, RegState::Kill)
5888                    .addReg(NewVReg5, RegState::Kill)
5889                    .addImm(0)
5890                    .addMemOperand(FIMMOSt));
5891   } else {
5892     // Incoming value: jbuf
5893     //   ldr  r1, LCPI1_1
5894     //   add  r1, pc, r1
5895     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5896     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5897     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5898                    .addConstantPoolIndex(CPI)
5899                    .addImm(0)
5900                    .addMemOperand(CPMMO));
5901     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5902     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5903                    .addReg(NewVReg1, RegState::Kill)
5904                    .addImm(PCLabelId));
5905     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5906                    .addReg(NewVReg2, RegState::Kill)
5907                    .addFrameIndex(FI)
5908                    .addImm(36)  // &jbuf[1] :: pc
5909                    .addMemOperand(FIMMOSt));
5910   }
5911 }
5912
5913 MachineBasicBlock *ARMTargetLowering::
5914 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5915   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5916   DebugLoc dl = MI->getDebugLoc();
5917   MachineFunction *MF = MBB->getParent();
5918   MachineRegisterInfo *MRI = &MF->getRegInfo();
5919   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5920   MachineFrameInfo *MFI = MF->getFrameInfo();
5921   int FI = MFI->getFunctionContextIndex();
5922
5923   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5924     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5925     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5926
5927   // Get a mapping of the call site numbers to all of the landing pads they're
5928   // associated with.
5929   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5930   unsigned MaxCSNum = 0;
5931   MachineModuleInfo &MMI = MF->getMMI();
5932   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5933        ++BB) {
5934     if (!BB->isLandingPad()) continue;
5935
5936     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5937     // pad.
5938     for (MachineBasicBlock::iterator
5939            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5940       if (!II->isEHLabel()) continue;
5941
5942       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5943       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5944
5945       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5946       for (SmallVectorImpl<unsigned>::iterator
5947              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5948            CSI != CSE; ++CSI) {
5949         CallSiteNumToLPad[*CSI].push_back(BB);
5950         MaxCSNum = std::max(MaxCSNum, *CSI);
5951       }
5952       break;
5953     }
5954   }
5955
5956   // Get an ordered list of the machine basic blocks for the jump table.
5957   std::vector<MachineBasicBlock*> LPadList;
5958   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5959   LPadList.reserve(CallSiteNumToLPad.size());
5960   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5961     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5962     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5963            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5964       LPadList.push_back(*II);
5965       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5966     }
5967   }
5968
5969   assert(!LPadList.empty() &&
5970          "No landing pad destinations for the dispatch jump table!");
5971
5972   // Create the jump table and associated information.
5973   MachineJumpTableInfo *JTI =
5974     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5975   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5976   unsigned UId = AFI->createJumpTableUId();
5977
5978   // Create the MBBs for the dispatch code.
5979
5980   // Shove the dispatch's address into the return slot in the function context.
5981   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5982   DispatchBB->setIsLandingPad();
5983
5984   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5985   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5986   DispatchBB->addSuccessor(TrapBB);
5987
5988   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5989   DispatchBB->addSuccessor(DispContBB);
5990
5991   // Insert and MBBs.
5992   MF->insert(MF->end(), DispatchBB);
5993   MF->insert(MF->end(), DispContBB);
5994   MF->insert(MF->end(), TrapBB);
5995
5996   // Insert code into the entry block that creates and registers the function
5997   // context.
5998   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5999
6000   MachineMemOperand *FIMMOLd =
6001     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6002                              MachineMemOperand::MOLoad |
6003                              MachineMemOperand::MOVolatile, 4, 4);
6004
6005   if (AFI->isThumb1OnlyFunction())
6006     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
6007   else if (!Subtarget->hasVFP2())
6008     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
6009   else
6010     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6011
6012   unsigned NumLPads = LPadList.size();
6013   if (Subtarget->isThumb2()) {
6014     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6015     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6016                    .addFrameIndex(FI)
6017                    .addImm(4)
6018                    .addMemOperand(FIMMOLd));
6019
6020     if (NumLPads < 256) {
6021       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6022                      .addReg(NewVReg1)
6023                      .addImm(LPadList.size()));
6024     } else {
6025       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6026       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6027                      .addImm(NumLPads & 0xFFFF));
6028
6029       unsigned VReg2 = VReg1;
6030       if ((NumLPads & 0xFFFF0000) != 0) {
6031         VReg2 = MRI->createVirtualRegister(TRC);
6032         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6033                        .addReg(VReg1)
6034                        .addImm(NumLPads >> 16));
6035       }
6036
6037       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6038                      .addReg(NewVReg1)
6039                      .addReg(VReg2));
6040     }
6041
6042     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6043       .addMBB(TrapBB)
6044       .addImm(ARMCC::HI)
6045       .addReg(ARM::CPSR);
6046
6047     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6048     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6049                    .addJumpTableIndex(MJTI)
6050                    .addImm(UId));
6051
6052     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6053     AddDefaultCC(
6054       AddDefaultPred(
6055         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6056         .addReg(NewVReg3, RegState::Kill)
6057         .addReg(NewVReg1)
6058         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6059
6060     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6061       .addReg(NewVReg4, RegState::Kill)
6062       .addReg(NewVReg1)
6063       .addJumpTableIndex(MJTI)
6064       .addImm(UId);
6065   } else if (Subtarget->isThumb()) {
6066     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6067     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6068                    .addFrameIndex(FI)
6069                    .addImm(1)
6070                    .addMemOperand(FIMMOLd));
6071
6072     if (NumLPads < 256) {
6073       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6074                      .addReg(NewVReg1)
6075                      .addImm(NumLPads));
6076     } else {
6077       MachineConstantPool *ConstantPool = MF->getConstantPool();
6078       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6079       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6080
6081       // MachineConstantPool wants an explicit alignment.
6082       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6083       if (Align == 0)
6084         Align = getDataLayout()->getTypeAllocSize(C->getType());
6085       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6086
6087       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6088       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6089                      .addReg(VReg1, RegState::Define)
6090                      .addConstantPoolIndex(Idx));
6091       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6092                      .addReg(NewVReg1)
6093                      .addReg(VReg1));
6094     }
6095
6096     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6097       .addMBB(TrapBB)
6098       .addImm(ARMCC::HI)
6099       .addReg(ARM::CPSR);
6100
6101     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6102     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6103                    .addReg(ARM::CPSR, RegState::Define)
6104                    .addReg(NewVReg1)
6105                    .addImm(2));
6106
6107     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6108     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6109                    .addJumpTableIndex(MJTI)
6110                    .addImm(UId));
6111
6112     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6113     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6114                    .addReg(ARM::CPSR, RegState::Define)
6115                    .addReg(NewVReg2, RegState::Kill)
6116                    .addReg(NewVReg3));
6117
6118     MachineMemOperand *JTMMOLd =
6119       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6120                                MachineMemOperand::MOLoad, 4, 4);
6121
6122     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6123     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6124                    .addReg(NewVReg4, RegState::Kill)
6125                    .addImm(0)
6126                    .addMemOperand(JTMMOLd));
6127
6128     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6129     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6130                    .addReg(ARM::CPSR, RegState::Define)
6131                    .addReg(NewVReg5, RegState::Kill)
6132                    .addReg(NewVReg3));
6133
6134     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6135       .addReg(NewVReg6, RegState::Kill)
6136       .addJumpTableIndex(MJTI)
6137       .addImm(UId);
6138   } else {
6139     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6140     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6141                    .addFrameIndex(FI)
6142                    .addImm(4)
6143                    .addMemOperand(FIMMOLd));
6144
6145     if (NumLPads < 256) {
6146       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6147                      .addReg(NewVReg1)
6148                      .addImm(NumLPads));
6149     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6150       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6151       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6152                      .addImm(NumLPads & 0xFFFF));
6153
6154       unsigned VReg2 = VReg1;
6155       if ((NumLPads & 0xFFFF0000) != 0) {
6156         VReg2 = MRI->createVirtualRegister(TRC);
6157         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6158                        .addReg(VReg1)
6159                        .addImm(NumLPads >> 16));
6160       }
6161
6162       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6163                      .addReg(NewVReg1)
6164                      .addReg(VReg2));
6165     } else {
6166       MachineConstantPool *ConstantPool = MF->getConstantPool();
6167       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6168       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6169
6170       // MachineConstantPool wants an explicit alignment.
6171       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6172       if (Align == 0)
6173         Align = getDataLayout()->getTypeAllocSize(C->getType());
6174       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6175
6176       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6177       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6178                      .addReg(VReg1, RegState::Define)
6179                      .addConstantPoolIndex(Idx)
6180                      .addImm(0));
6181       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6182                      .addReg(NewVReg1)
6183                      .addReg(VReg1, RegState::Kill));
6184     }
6185
6186     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6187       .addMBB(TrapBB)
6188       .addImm(ARMCC::HI)
6189       .addReg(ARM::CPSR);
6190
6191     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6192     AddDefaultCC(
6193       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6194                      .addReg(NewVReg1)
6195                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6196     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6197     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6198                    .addJumpTableIndex(MJTI)
6199                    .addImm(UId));
6200
6201     MachineMemOperand *JTMMOLd =
6202       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6203                                MachineMemOperand::MOLoad, 4, 4);
6204     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6205     AddDefaultPred(
6206       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6207       .addReg(NewVReg3, RegState::Kill)
6208       .addReg(NewVReg4)
6209       .addImm(0)
6210       .addMemOperand(JTMMOLd));
6211
6212     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6213       .addReg(NewVReg5, RegState::Kill)
6214       .addReg(NewVReg4)
6215       .addJumpTableIndex(MJTI)
6216       .addImm(UId);
6217   }
6218
6219   // Add the jump table entries as successors to the MBB.
6220   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6221   for (std::vector<MachineBasicBlock*>::iterator
6222          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6223     MachineBasicBlock *CurMBB = *I;
6224     if (SeenMBBs.insert(CurMBB))
6225       DispContBB->addSuccessor(CurMBB);
6226   }
6227
6228   // N.B. the order the invoke BBs are processed in doesn't matter here.
6229   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6230   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6231   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6232   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6233   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6234          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6235     MachineBasicBlock *BB = *I;
6236
6237     // Remove the landing pad successor from the invoke block and replace it
6238     // with the new dispatch block.
6239     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6240                                                   BB->succ_end());
6241     while (!Successors.empty()) {
6242       MachineBasicBlock *SMBB = Successors.pop_back_val();
6243       if (SMBB->isLandingPad()) {
6244         BB->removeSuccessor(SMBB);
6245         MBBLPads.push_back(SMBB);
6246       }
6247     }
6248
6249     BB->addSuccessor(DispatchBB);
6250
6251     // Find the invoke call and mark all of the callee-saved registers as
6252     // 'implicit defined' so that they're spilled. This prevents code from
6253     // moving instructions to before the EH block, where they will never be
6254     // executed.
6255     for (MachineBasicBlock::reverse_iterator
6256            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6257       if (!II->isCall()) continue;
6258
6259       DenseMap<unsigned, bool> DefRegs;
6260       for (MachineInstr::mop_iterator
6261              OI = II->operands_begin(), OE = II->operands_end();
6262            OI != OE; ++OI) {
6263         if (!OI->isReg()) continue;
6264         DefRegs[OI->getReg()] = true;
6265       }
6266
6267       MachineInstrBuilder MIB(&*II);
6268
6269       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6270         unsigned Reg = SavedRegs[i];
6271         if (Subtarget->isThumb2() &&
6272             !ARM::tGPRRegClass.contains(Reg) &&
6273             !ARM::hGPRRegClass.contains(Reg))
6274           continue;
6275         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6276           continue;
6277         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6278           continue;
6279         if (!DefRegs[Reg])
6280           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6281       }
6282
6283       break;
6284     }
6285   }
6286
6287   // Mark all former landing pads as non-landing pads. The dispatch is the only
6288   // landing pad now.
6289   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6290          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6291     (*I)->setIsLandingPad(false);
6292
6293   // The instruction is gone now.
6294   MI->eraseFromParent();
6295
6296   return MBB;
6297 }
6298
6299 static
6300 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6301   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6302        E = MBB->succ_end(); I != E; ++I)
6303     if (*I != Succ)
6304       return *I;
6305   llvm_unreachable("Expecting a BB with two successors!");
6306 }
6307
6308 MachineBasicBlock *ARMTargetLowering::
6309 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6310   // This pseudo instruction has 3 operands: dst, src, size
6311   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6312   // Otherwise, we will generate unrolled scalar copies.
6313   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6314   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6315   MachineFunction::iterator It = BB;
6316   ++It;
6317
6318   unsigned dest = MI->getOperand(0).getReg();
6319   unsigned src = MI->getOperand(1).getReg();
6320   unsigned SizeVal = MI->getOperand(2).getImm();
6321   unsigned Align = MI->getOperand(3).getImm();
6322   DebugLoc dl = MI->getDebugLoc();
6323
6324   bool isThumb2 = Subtarget->isThumb2();
6325   MachineFunction *MF = BB->getParent();
6326   MachineRegisterInfo &MRI = MF->getRegInfo();
6327   unsigned ldrOpc, strOpc, UnitSize = 0;
6328
6329   const TargetRegisterClass *TRC = isThumb2 ?
6330     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6331     (const TargetRegisterClass*)&ARM::GPRRegClass;
6332   const TargetRegisterClass *TRC_Vec = 0;
6333
6334   if (Align & 1) {
6335     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6336     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6337     UnitSize = 1;
6338   } else if (Align & 2) {
6339     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6340     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6341     UnitSize = 2;
6342   } else {
6343     // Check whether we can use NEON instructions.
6344     if (!MF->getFunction()->getFnAttributes().
6345           hasAttribute(Attributes::NoImplicitFloat) &&
6346         Subtarget->hasNEON()) {
6347       if ((Align % 16 == 0) && SizeVal >= 16) {
6348         ldrOpc = ARM::VLD1q32wb_fixed;
6349         strOpc = ARM::VST1q32wb_fixed;
6350         UnitSize = 16;
6351         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6352       }
6353       else if ((Align % 8 == 0) && SizeVal >= 8) {
6354         ldrOpc = ARM::VLD1d32wb_fixed;
6355         strOpc = ARM::VST1d32wb_fixed;
6356         UnitSize = 8;
6357         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6358       }
6359     }
6360     // Can't use NEON instructions.
6361     if (UnitSize == 0) {
6362       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6363       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6364       UnitSize = 4;
6365     }
6366   }
6367
6368   unsigned BytesLeft = SizeVal % UnitSize;
6369   unsigned LoopSize = SizeVal - BytesLeft;
6370
6371   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6372     // Use LDR and STR to copy.
6373     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6374     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6375     unsigned srcIn = src;
6376     unsigned destIn = dest;
6377     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6378       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6379       unsigned srcOut = MRI.createVirtualRegister(TRC);
6380       unsigned destOut = MRI.createVirtualRegister(TRC);
6381       if (UnitSize >= 8) {
6382         AddDefaultPred(BuildMI(*BB, MI, dl,
6383           TII->get(ldrOpc), scratch)
6384           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6385
6386         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6387           .addReg(destIn).addImm(0).addReg(scratch));
6388       } else if (isThumb2) {
6389         AddDefaultPred(BuildMI(*BB, MI, dl,
6390           TII->get(ldrOpc), scratch)
6391           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6392
6393         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6394           .addReg(scratch).addReg(destIn)
6395           .addImm(UnitSize));
6396       } else {
6397         AddDefaultPred(BuildMI(*BB, MI, dl,
6398           TII->get(ldrOpc), scratch)
6399           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6400           .addImm(UnitSize));
6401
6402         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6403           .addReg(scratch).addReg(destIn)
6404           .addReg(0).addImm(UnitSize));
6405       }
6406       srcIn = srcOut;
6407       destIn = destOut;
6408     }
6409
6410     // Handle the leftover bytes with LDRB and STRB.
6411     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6412     // [destOut] = STRB_POST(scratch, destIn, 1)
6413     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6414     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6415     for (unsigned i = 0; i < BytesLeft; i++) {
6416       unsigned scratch = MRI.createVirtualRegister(TRC);
6417       unsigned srcOut = MRI.createVirtualRegister(TRC);
6418       unsigned destOut = MRI.createVirtualRegister(TRC);
6419       if (isThumb2) {
6420         AddDefaultPred(BuildMI(*BB, MI, dl,
6421           TII->get(ldrOpc),scratch)
6422           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6423
6424         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6425           .addReg(scratch).addReg(destIn)
6426           .addReg(0).addImm(1));
6427       } else {
6428         AddDefaultPred(BuildMI(*BB, MI, dl,
6429           TII->get(ldrOpc),scratch)
6430           .addReg(srcOut, RegState::Define).addReg(srcIn)
6431           .addReg(0).addImm(1));
6432
6433         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6434           .addReg(scratch).addReg(destIn)
6435           .addReg(0).addImm(1));
6436       }
6437       srcIn = srcOut;
6438       destIn = destOut;
6439     }
6440     MI->eraseFromParent();   // The instruction is gone now.
6441     return BB;
6442   }
6443
6444   // Expand the pseudo op to a loop.
6445   // thisMBB:
6446   //   ...
6447   //   movw varEnd, # --> with thumb2
6448   //   movt varEnd, #
6449   //   ldrcp varEnd, idx --> without thumb2
6450   //   fallthrough --> loopMBB
6451   // loopMBB:
6452   //   PHI varPhi, varEnd, varLoop
6453   //   PHI srcPhi, src, srcLoop
6454   //   PHI destPhi, dst, destLoop
6455   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6456   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6457   //   subs varLoop, varPhi, #UnitSize
6458   //   bne loopMBB
6459   //   fallthrough --> exitMBB
6460   // exitMBB:
6461   //   epilogue to handle left-over bytes
6462   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6463   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6464   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6465   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6466   MF->insert(It, loopMBB);
6467   MF->insert(It, exitMBB);
6468
6469   // Transfer the remainder of BB and its successor edges to exitMBB.
6470   exitMBB->splice(exitMBB->begin(), BB,
6471                   llvm::next(MachineBasicBlock::iterator(MI)),
6472                   BB->end());
6473   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6474
6475   // Load an immediate to varEnd.
6476   unsigned varEnd = MRI.createVirtualRegister(TRC);
6477   if (isThumb2) {
6478     unsigned VReg1 = varEnd;
6479     if ((LoopSize & 0xFFFF0000) != 0)
6480       VReg1 = MRI.createVirtualRegister(TRC);
6481     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6482                    .addImm(LoopSize & 0xFFFF));
6483
6484     if ((LoopSize & 0xFFFF0000) != 0)
6485       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6486                      .addReg(VReg1)
6487                      .addImm(LoopSize >> 16));
6488   } else {
6489     MachineConstantPool *ConstantPool = MF->getConstantPool();
6490     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6491     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6492
6493     // MachineConstantPool wants an explicit alignment.
6494     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6495     if (Align == 0)
6496       Align = getDataLayout()->getTypeAllocSize(C->getType());
6497     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6498
6499     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6500                    .addReg(varEnd, RegState::Define)
6501                    .addConstantPoolIndex(Idx)
6502                    .addImm(0));
6503   }
6504   BB->addSuccessor(loopMBB);
6505
6506   // Generate the loop body:
6507   //   varPhi = PHI(varLoop, varEnd)
6508   //   srcPhi = PHI(srcLoop, src)
6509   //   destPhi = PHI(destLoop, dst)
6510   MachineBasicBlock *entryBB = BB;
6511   BB = loopMBB;
6512   unsigned varLoop = MRI.createVirtualRegister(TRC);
6513   unsigned varPhi = MRI.createVirtualRegister(TRC);
6514   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6515   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6516   unsigned destLoop = MRI.createVirtualRegister(TRC);
6517   unsigned destPhi = MRI.createVirtualRegister(TRC);
6518
6519   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6520     .addReg(varLoop).addMBB(loopMBB)
6521     .addReg(varEnd).addMBB(entryBB);
6522   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6523     .addReg(srcLoop).addMBB(loopMBB)
6524     .addReg(src).addMBB(entryBB);
6525   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6526     .addReg(destLoop).addMBB(loopMBB)
6527     .addReg(dest).addMBB(entryBB);
6528
6529   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6530   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6531   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6532   if (UnitSize >= 8) {
6533     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6534       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6535
6536     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6537       .addReg(destPhi).addImm(0).addReg(scratch));
6538   } else if (isThumb2) {
6539     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6540       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6541
6542     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6543       .addReg(scratch).addReg(destPhi)
6544       .addImm(UnitSize));
6545   } else {
6546     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6547       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6548       .addImm(UnitSize));
6549
6550     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6551       .addReg(scratch).addReg(destPhi)
6552       .addReg(0).addImm(UnitSize));
6553   }
6554
6555   // Decrement loop variable by UnitSize.
6556   MachineInstrBuilder MIB = BuildMI(BB, dl,
6557     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6558   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6559   MIB->getOperand(5).setReg(ARM::CPSR);
6560   MIB->getOperand(5).setIsDef(true);
6561
6562   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6563     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6564
6565   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6566   BB->addSuccessor(loopMBB);
6567   BB->addSuccessor(exitMBB);
6568
6569   // Add epilogue to handle BytesLeft.
6570   BB = exitMBB;
6571   MachineInstr *StartOfExit = exitMBB->begin();
6572   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6573   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6574
6575   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6576   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6577   unsigned srcIn = srcLoop;
6578   unsigned destIn = destLoop;
6579   for (unsigned i = 0; i < BytesLeft; i++) {
6580     unsigned scratch = MRI.createVirtualRegister(TRC);
6581     unsigned srcOut = MRI.createVirtualRegister(TRC);
6582     unsigned destOut = MRI.createVirtualRegister(TRC);
6583     if (isThumb2) {
6584       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6585         TII->get(ldrOpc),scratch)
6586         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6587
6588       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6589         .addReg(scratch).addReg(destIn)
6590         .addImm(1));
6591     } else {
6592       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6593         TII->get(ldrOpc),scratch)
6594         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6595
6596       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6597         .addReg(scratch).addReg(destIn)
6598         .addReg(0).addImm(1));
6599     }
6600     srcIn = srcOut;
6601     destIn = destOut;
6602   }
6603
6604   MI->eraseFromParent();   // The instruction is gone now.
6605   return BB;
6606 }
6607
6608 MachineBasicBlock *
6609 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6610                                                MachineBasicBlock *BB) const {
6611   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6612   DebugLoc dl = MI->getDebugLoc();
6613   bool isThumb2 = Subtarget->isThumb2();
6614   switch (MI->getOpcode()) {
6615   default: {
6616     MI->dump();
6617     llvm_unreachable("Unexpected instr type to insert");
6618   }
6619   // The Thumb2 pre-indexed stores have the same MI operands, they just
6620   // define them differently in the .td files from the isel patterns, so
6621   // they need pseudos.
6622   case ARM::t2STR_preidx:
6623     MI->setDesc(TII->get(ARM::t2STR_PRE));
6624     return BB;
6625   case ARM::t2STRB_preidx:
6626     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6627     return BB;
6628   case ARM::t2STRH_preidx:
6629     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6630     return BB;
6631
6632   case ARM::STRi_preidx:
6633   case ARM::STRBi_preidx: {
6634     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6635       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6636     // Decode the offset.
6637     unsigned Offset = MI->getOperand(4).getImm();
6638     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6639     Offset = ARM_AM::getAM2Offset(Offset);
6640     if (isSub)
6641       Offset = -Offset;
6642
6643     MachineMemOperand *MMO = *MI->memoperands_begin();
6644     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6645       .addOperand(MI->getOperand(0))  // Rn_wb
6646       .addOperand(MI->getOperand(1))  // Rt
6647       .addOperand(MI->getOperand(2))  // Rn
6648       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6649       .addOperand(MI->getOperand(5))  // pred
6650       .addOperand(MI->getOperand(6))
6651       .addMemOperand(MMO);
6652     MI->eraseFromParent();
6653     return BB;
6654   }
6655   case ARM::STRr_preidx:
6656   case ARM::STRBr_preidx:
6657   case ARM::STRH_preidx: {
6658     unsigned NewOpc;
6659     switch (MI->getOpcode()) {
6660     default: llvm_unreachable("unexpected opcode!");
6661     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6662     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6663     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6664     }
6665     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6666     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6667       MIB.addOperand(MI->getOperand(i));
6668     MI->eraseFromParent();
6669     return BB;
6670   }
6671   case ARM::ATOMIC_LOAD_ADD_I8:
6672      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6673   case ARM::ATOMIC_LOAD_ADD_I16:
6674      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6675   case ARM::ATOMIC_LOAD_ADD_I32:
6676      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6677
6678   case ARM::ATOMIC_LOAD_AND_I8:
6679      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6680   case ARM::ATOMIC_LOAD_AND_I16:
6681      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6682   case ARM::ATOMIC_LOAD_AND_I32:
6683      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6684
6685   case ARM::ATOMIC_LOAD_OR_I8:
6686      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6687   case ARM::ATOMIC_LOAD_OR_I16:
6688      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6689   case ARM::ATOMIC_LOAD_OR_I32:
6690      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6691
6692   case ARM::ATOMIC_LOAD_XOR_I8:
6693      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6694   case ARM::ATOMIC_LOAD_XOR_I16:
6695      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6696   case ARM::ATOMIC_LOAD_XOR_I32:
6697      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6698
6699   case ARM::ATOMIC_LOAD_NAND_I8:
6700      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6701   case ARM::ATOMIC_LOAD_NAND_I16:
6702      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6703   case ARM::ATOMIC_LOAD_NAND_I32:
6704      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6705
6706   case ARM::ATOMIC_LOAD_SUB_I8:
6707      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6708   case ARM::ATOMIC_LOAD_SUB_I16:
6709      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6710   case ARM::ATOMIC_LOAD_SUB_I32:
6711      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6712
6713   case ARM::ATOMIC_LOAD_MIN_I8:
6714      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6715   case ARM::ATOMIC_LOAD_MIN_I16:
6716      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6717   case ARM::ATOMIC_LOAD_MIN_I32:
6718      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6719
6720   case ARM::ATOMIC_LOAD_MAX_I8:
6721      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6722   case ARM::ATOMIC_LOAD_MAX_I16:
6723      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6724   case ARM::ATOMIC_LOAD_MAX_I32:
6725      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6726
6727   case ARM::ATOMIC_LOAD_UMIN_I8:
6728      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6729   case ARM::ATOMIC_LOAD_UMIN_I16:
6730      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6731   case ARM::ATOMIC_LOAD_UMIN_I32:
6732      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6733
6734   case ARM::ATOMIC_LOAD_UMAX_I8:
6735      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6736   case ARM::ATOMIC_LOAD_UMAX_I16:
6737      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6738   case ARM::ATOMIC_LOAD_UMAX_I32:
6739      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6740
6741   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6742   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6743   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6744
6745   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6746   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6747   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6748
6749
6750   case ARM::ATOMADD6432:
6751     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6752                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6753                               /*NeedsCarry*/ true);
6754   case ARM::ATOMSUB6432:
6755     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6756                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6757                               /*NeedsCarry*/ true);
6758   case ARM::ATOMOR6432:
6759     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6760                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6761   case ARM::ATOMXOR6432:
6762     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6763                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6764   case ARM::ATOMAND6432:
6765     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6766                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6767   case ARM::ATOMSWAP6432:
6768     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6769   case ARM::ATOMCMPXCHG6432:
6770     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6771                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6772                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6773
6774   case ARM::tMOVCCr_pseudo: {
6775     // To "insert" a SELECT_CC instruction, we actually have to insert the
6776     // diamond control-flow pattern.  The incoming instruction knows the
6777     // destination vreg to set, the condition code register to branch on, the
6778     // true/false values to select between, and a branch opcode to use.
6779     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6780     MachineFunction::iterator It = BB;
6781     ++It;
6782
6783     //  thisMBB:
6784     //  ...
6785     //   TrueVal = ...
6786     //   cmpTY ccX, r1, r2
6787     //   bCC copy1MBB
6788     //   fallthrough --> copy0MBB
6789     MachineBasicBlock *thisMBB  = BB;
6790     MachineFunction *F = BB->getParent();
6791     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6792     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6793     F->insert(It, copy0MBB);
6794     F->insert(It, sinkMBB);
6795
6796     // Transfer the remainder of BB and its successor edges to sinkMBB.
6797     sinkMBB->splice(sinkMBB->begin(), BB,
6798                     llvm::next(MachineBasicBlock::iterator(MI)),
6799                     BB->end());
6800     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6801
6802     BB->addSuccessor(copy0MBB);
6803     BB->addSuccessor(sinkMBB);
6804
6805     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6806       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6807
6808     //  copy0MBB:
6809     //   %FalseValue = ...
6810     //   # fallthrough to sinkMBB
6811     BB = copy0MBB;
6812
6813     // Update machine-CFG edges
6814     BB->addSuccessor(sinkMBB);
6815
6816     //  sinkMBB:
6817     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6818     //  ...
6819     BB = sinkMBB;
6820     BuildMI(*BB, BB->begin(), dl,
6821             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6822       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6823       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6824
6825     MI->eraseFromParent();   // The pseudo instruction is gone now.
6826     return BB;
6827   }
6828
6829   case ARM::BCCi64:
6830   case ARM::BCCZi64: {
6831     // If there is an unconditional branch to the other successor, remove it.
6832     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6833
6834     // Compare both parts that make up the double comparison separately for
6835     // equality.
6836     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6837
6838     unsigned LHS1 = MI->getOperand(1).getReg();
6839     unsigned LHS2 = MI->getOperand(2).getReg();
6840     if (RHSisZero) {
6841       AddDefaultPred(BuildMI(BB, dl,
6842                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6843                      .addReg(LHS1).addImm(0));
6844       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6845         .addReg(LHS2).addImm(0)
6846         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6847     } else {
6848       unsigned RHS1 = MI->getOperand(3).getReg();
6849       unsigned RHS2 = MI->getOperand(4).getReg();
6850       AddDefaultPred(BuildMI(BB, dl,
6851                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6852                      .addReg(LHS1).addReg(RHS1));
6853       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6854         .addReg(LHS2).addReg(RHS2)
6855         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6856     }
6857
6858     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6859     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6860     if (MI->getOperand(0).getImm() == ARMCC::NE)
6861       std::swap(destMBB, exitMBB);
6862
6863     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6864       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6865     if (isThumb2)
6866       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6867     else
6868       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6869
6870     MI->eraseFromParent();   // The pseudo instruction is gone now.
6871     return BB;
6872   }
6873
6874   case ARM::Int_eh_sjlj_setjmp:
6875   case ARM::Int_eh_sjlj_setjmp_nofp:
6876   case ARM::tInt_eh_sjlj_setjmp:
6877   case ARM::t2Int_eh_sjlj_setjmp:
6878   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6879     EmitSjLjDispatchBlock(MI, BB);
6880     return BB;
6881
6882   case ARM::ABS:
6883   case ARM::t2ABS: {
6884     // To insert an ABS instruction, we have to insert the
6885     // diamond control-flow pattern.  The incoming instruction knows the
6886     // source vreg to test against 0, the destination vreg to set,
6887     // the condition code register to branch on, the
6888     // true/false values to select between, and a branch opcode to use.
6889     // It transforms
6890     //     V1 = ABS V0
6891     // into
6892     //     V2 = MOVS V0
6893     //     BCC                      (branch to SinkBB if V0 >= 0)
6894     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6895     //     SinkBB: V1 = PHI(V2, V3)
6896     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6897     MachineFunction::iterator BBI = BB;
6898     ++BBI;
6899     MachineFunction *Fn = BB->getParent();
6900     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6901     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6902     Fn->insert(BBI, RSBBB);
6903     Fn->insert(BBI, SinkBB);
6904
6905     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6906     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6907     bool isThumb2 = Subtarget->isThumb2();
6908     MachineRegisterInfo &MRI = Fn->getRegInfo();
6909     // In Thumb mode S must not be specified if source register is the SP or
6910     // PC and if destination register is the SP, so restrict register class
6911     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6912       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6913       (const TargetRegisterClass*)&ARM::GPRRegClass);
6914
6915     // Transfer the remainder of BB and its successor edges to sinkMBB.
6916     SinkBB->splice(SinkBB->begin(), BB,
6917       llvm::next(MachineBasicBlock::iterator(MI)),
6918       BB->end());
6919     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6920
6921     BB->addSuccessor(RSBBB);
6922     BB->addSuccessor(SinkBB);
6923
6924     // fall through to SinkMBB
6925     RSBBB->addSuccessor(SinkBB);
6926
6927     // insert a cmp at the end of BB
6928     AddDefaultPred(BuildMI(BB, dl,
6929                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6930                    .addReg(ABSSrcReg).addImm(0));
6931
6932     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6933     BuildMI(BB, dl,
6934       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6935       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6936
6937     // insert rsbri in RSBBB
6938     // Note: BCC and rsbri will be converted into predicated rsbmi
6939     // by if-conversion pass
6940     BuildMI(*RSBBB, RSBBB->begin(), dl,
6941       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6942       .addReg(ABSSrcReg, RegState::Kill)
6943       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6944
6945     // insert PHI in SinkBB,
6946     // reuse ABSDstReg to not change uses of ABS instruction
6947     BuildMI(*SinkBB, SinkBB->begin(), dl,
6948       TII->get(ARM::PHI), ABSDstReg)
6949       .addReg(NewRsbDstReg).addMBB(RSBBB)
6950       .addReg(ABSSrcReg).addMBB(BB);
6951
6952     // remove ABS instruction
6953     MI->eraseFromParent();
6954
6955     // return last added BB
6956     return SinkBB;
6957   }
6958   case ARM::COPY_STRUCT_BYVAL_I32:
6959     ++NumLoopByVals;
6960     return EmitStructByval(MI, BB);
6961   }
6962 }
6963
6964 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6965                                                       SDNode *Node) const {
6966   if (!MI->hasPostISelHook()) {
6967     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6968            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6969     return;
6970   }
6971
6972   const MCInstrDesc *MCID = &MI->getDesc();
6973   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6974   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6975   // operand is still set to noreg. If needed, set the optional operand's
6976   // register to CPSR, and remove the redundant implicit def.
6977   //
6978   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6979
6980   // Rename pseudo opcodes.
6981   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6982   if (NewOpc) {
6983     const ARMBaseInstrInfo *TII =
6984       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6985     MCID = &TII->get(NewOpc);
6986
6987     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6988            "converted opcode should be the same except for cc_out");
6989
6990     MI->setDesc(*MCID);
6991
6992     // Add the optional cc_out operand
6993     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6994   }
6995   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6996
6997   // Any ARM instruction that sets the 's' bit should specify an optional
6998   // "cc_out" operand in the last operand position.
6999   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7000     assert(!NewOpc && "Optional cc_out operand required");
7001     return;
7002   }
7003   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7004   // since we already have an optional CPSR def.
7005   bool definesCPSR = false;
7006   bool deadCPSR = false;
7007   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7008        i != e; ++i) {
7009     const MachineOperand &MO = MI->getOperand(i);
7010     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7011       definesCPSR = true;
7012       if (MO.isDead())
7013         deadCPSR = true;
7014       MI->RemoveOperand(i);
7015       break;
7016     }
7017   }
7018   if (!definesCPSR) {
7019     assert(!NewOpc && "Optional cc_out operand required");
7020     return;
7021   }
7022   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7023   if (deadCPSR) {
7024     assert(!MI->getOperand(ccOutIdx).getReg() &&
7025            "expect uninitialized optional cc_out operand");
7026     return;
7027   }
7028
7029   // If this instruction was defined with an optional CPSR def and its dag node
7030   // had a live implicit CPSR def, then activate the optional CPSR def.
7031   MachineOperand &MO = MI->getOperand(ccOutIdx);
7032   MO.setReg(ARM::CPSR);
7033   MO.setIsDef(true);
7034 }
7035
7036 //===----------------------------------------------------------------------===//
7037 //                           ARM Optimization Hooks
7038 //===----------------------------------------------------------------------===//
7039
7040 // Helper function that checks if N is a null or all ones constant.
7041 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7042   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7043   if (!C)
7044     return false;
7045   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7046 }
7047
7048 // Return true if N is conditionally 0 or all ones.
7049 // Detects these expressions where cc is an i1 value:
7050 //
7051 //   (select cc 0, y)   [AllOnes=0]
7052 //   (select cc y, 0)   [AllOnes=0]
7053 //   (zext cc)          [AllOnes=0]
7054 //   (sext cc)          [AllOnes=0/1]
7055 //   (select cc -1, y)  [AllOnes=1]
7056 //   (select cc y, -1)  [AllOnes=1]
7057 //
7058 // Invert is set when N is the null/all ones constant when CC is false.
7059 // OtherOp is set to the alternative value of N.
7060 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7061                                        SDValue &CC, bool &Invert,
7062                                        SDValue &OtherOp,
7063                                        SelectionDAG &DAG) {
7064   switch (N->getOpcode()) {
7065   default: return false;
7066   case ISD::SELECT: {
7067     CC = N->getOperand(0);
7068     SDValue N1 = N->getOperand(1);
7069     SDValue N2 = N->getOperand(2);
7070     if (isZeroOrAllOnes(N1, AllOnes)) {
7071       Invert = false;
7072       OtherOp = N2;
7073       return true;
7074     }
7075     if (isZeroOrAllOnes(N2, AllOnes)) {
7076       Invert = true;
7077       OtherOp = N1;
7078       return true;
7079     }
7080     return false;
7081   }
7082   case ISD::ZERO_EXTEND:
7083     // (zext cc) can never be the all ones value.
7084     if (AllOnes)
7085       return false;
7086     // Fall through.
7087   case ISD::SIGN_EXTEND: {
7088     EVT VT = N->getValueType(0);
7089     CC = N->getOperand(0);
7090     if (CC.getValueType() != MVT::i1)
7091       return false;
7092     Invert = !AllOnes;
7093     if (AllOnes)
7094       // When looking for an AllOnes constant, N is an sext, and the 'other'
7095       // value is 0.
7096       OtherOp = DAG.getConstant(0, VT);
7097     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7098       // When looking for a 0 constant, N can be zext or sext.
7099       OtherOp = DAG.getConstant(1, VT);
7100     else
7101       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7102     return true;
7103   }
7104   }
7105 }
7106
7107 // Combine a constant select operand into its use:
7108 //
7109 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7110 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7111 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7112 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7113 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7114 //
7115 // The transform is rejected if the select doesn't have a constant operand that
7116 // is null, or all ones when AllOnes is set.
7117 //
7118 // Also recognize sext/zext from i1:
7119 //
7120 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7121 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7122 //
7123 // These transformations eventually create predicated instructions.
7124 //
7125 // @param N       The node to transform.
7126 // @param Slct    The N operand that is a select.
7127 // @param OtherOp The other N operand (x above).
7128 // @param DCI     Context.
7129 // @param AllOnes Require the select constant to be all ones instead of null.
7130 // @returns The new node, or SDValue() on failure.
7131 static
7132 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7133                             TargetLowering::DAGCombinerInfo &DCI,
7134                             bool AllOnes = false) {
7135   SelectionDAG &DAG = DCI.DAG;
7136   EVT VT = N->getValueType(0);
7137   SDValue NonConstantVal;
7138   SDValue CCOp;
7139   bool SwapSelectOps;
7140   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7141                                   NonConstantVal, DAG))
7142     return SDValue();
7143
7144   // Slct is now know to be the desired identity constant when CC is true.
7145   SDValue TrueVal = OtherOp;
7146   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7147                                  OtherOp, NonConstantVal);
7148   // Unless SwapSelectOps says CC should be false.
7149   if (SwapSelectOps)
7150     std::swap(TrueVal, FalseVal);
7151
7152   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7153                      CCOp, TrueVal, FalseVal);
7154 }
7155
7156 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7157 static
7158 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7159                                        TargetLowering::DAGCombinerInfo &DCI) {
7160   SDValue N0 = N->getOperand(0);
7161   SDValue N1 = N->getOperand(1);
7162   if (N0.getNode()->hasOneUse()) {
7163     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7164     if (Result.getNode())
7165       return Result;
7166   }
7167   if (N1.getNode()->hasOneUse()) {
7168     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7169     if (Result.getNode())
7170       return Result;
7171   }
7172   return SDValue();
7173 }
7174
7175 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7176 // (only after legalization).
7177 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7178                                  TargetLowering::DAGCombinerInfo &DCI,
7179                                  const ARMSubtarget *Subtarget) {
7180
7181   // Only perform optimization if after legalize, and if NEON is available. We
7182   // also expected both operands to be BUILD_VECTORs.
7183   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7184       || N0.getOpcode() != ISD::BUILD_VECTOR
7185       || N1.getOpcode() != ISD::BUILD_VECTOR)
7186     return SDValue();
7187
7188   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7189   EVT VT = N->getValueType(0);
7190   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7191     return SDValue();
7192
7193   // Check that the vector operands are of the right form.
7194   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7195   // operands, where N is the size of the formed vector.
7196   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7197   // index such that we have a pair wise add pattern.
7198
7199   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7200   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7201     return SDValue();
7202   SDValue Vec = N0->getOperand(0)->getOperand(0);
7203   SDNode *V = Vec.getNode();
7204   unsigned nextIndex = 0;
7205
7206   // For each operands to the ADD which are BUILD_VECTORs,
7207   // check to see if each of their operands are an EXTRACT_VECTOR with
7208   // the same vector and appropriate index.
7209   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7210     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7211         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7212
7213       SDValue ExtVec0 = N0->getOperand(i);
7214       SDValue ExtVec1 = N1->getOperand(i);
7215
7216       // First operand is the vector, verify its the same.
7217       if (V != ExtVec0->getOperand(0).getNode() ||
7218           V != ExtVec1->getOperand(0).getNode())
7219         return SDValue();
7220
7221       // Second is the constant, verify its correct.
7222       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7223       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7224
7225       // For the constant, we want to see all the even or all the odd.
7226       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7227           || C1->getZExtValue() != nextIndex+1)
7228         return SDValue();
7229
7230       // Increment index.
7231       nextIndex+=2;
7232     } else
7233       return SDValue();
7234   }
7235
7236   // Create VPADDL node.
7237   SelectionDAG &DAG = DCI.DAG;
7238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7239
7240   // Build operand list.
7241   SmallVector<SDValue, 8> Ops;
7242   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7243                                 TLI.getPointerTy()));
7244
7245   // Input is the vector.
7246   Ops.push_back(Vec);
7247
7248   // Get widened type and narrowed type.
7249   MVT widenType;
7250   unsigned numElem = VT.getVectorNumElements();
7251   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7252     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7253     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7254     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7255     default:
7256       llvm_unreachable("Invalid vector element type for padd optimization.");
7257   }
7258
7259   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7260                             widenType, &Ops[0], Ops.size());
7261   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7262 }
7263
7264 static SDValue findMUL_LOHI(SDValue V) {
7265   if (V->getOpcode() == ISD::UMUL_LOHI ||
7266       V->getOpcode() == ISD::SMUL_LOHI)
7267     return V;
7268   return SDValue();
7269 }
7270
7271 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7272                                      TargetLowering::DAGCombinerInfo &DCI,
7273                                      const ARMSubtarget *Subtarget) {
7274
7275   if (Subtarget->isThumb1Only()) return SDValue();
7276
7277   // Only perform the checks after legalize when the pattern is available.
7278   if (DCI.isBeforeLegalize()) return SDValue();
7279
7280   // Look for multiply add opportunities.
7281   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7282   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7283   // a glue link from the first add to the second add.
7284   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7285   // a S/UMLAL instruction.
7286   //          loAdd   UMUL_LOHI
7287   //            \    / :lo    \ :hi
7288   //             \  /          \          [no multiline comment]
7289   //              ADDC         |  hiAdd
7290   //                 \ :glue  /  /
7291   //                  \      /  /
7292   //                    ADDE
7293   //
7294   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7295   SDValue AddcOp0 = AddcNode->getOperand(0);
7296   SDValue AddcOp1 = AddcNode->getOperand(1);
7297
7298   // Check if the two operands are from the same mul_lohi node.
7299   if (AddcOp0.getNode() == AddcOp1.getNode())
7300     return SDValue();
7301
7302   assert(AddcNode->getNumValues() == 2 &&
7303          AddcNode->getValueType(0) == MVT::i32 &&
7304          AddcNode->getValueType(1) == MVT::Glue &&
7305          "Expect ADDC with two result values: i32, glue");
7306
7307   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7308   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7309       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7310       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7311       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7312     return SDValue();
7313
7314   // Look for the glued ADDE.
7315   SDNode* AddeNode = AddcNode->getGluedUser();
7316   if (AddeNode == NULL)
7317     return SDValue();
7318
7319   // Make sure it is really an ADDE.
7320   if (AddeNode->getOpcode() != ISD::ADDE)
7321     return SDValue();
7322
7323   assert(AddeNode->getNumOperands() == 3 &&
7324          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7325          "ADDE node has the wrong inputs");
7326
7327   // Check for the triangle shape.
7328   SDValue AddeOp0 = AddeNode->getOperand(0);
7329   SDValue AddeOp1 = AddeNode->getOperand(1);
7330
7331   // Make sure that the ADDE operands are not coming from the same node.
7332   if (AddeOp0.getNode() == AddeOp1.getNode())
7333     return SDValue();
7334
7335   // Find the MUL_LOHI node walking up ADDE's operands.
7336   bool IsLeftOperandMUL = false;
7337   SDValue MULOp = findMUL_LOHI(AddeOp0);
7338   if (MULOp == SDValue())
7339    MULOp = findMUL_LOHI(AddeOp1);
7340   else
7341     IsLeftOperandMUL = true;
7342   if (MULOp == SDValue())
7343      return SDValue();
7344
7345   // Figure out the right opcode.
7346   unsigned Opc = MULOp->getOpcode();
7347   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7348
7349   // Figure out the high and low input values to the MLAL node.
7350   SDValue* HiMul = &MULOp;
7351   SDValue* HiAdd = NULL;
7352   SDValue* LoMul = NULL;
7353   SDValue* LowAdd = NULL;
7354
7355   if (IsLeftOperandMUL)
7356     HiAdd = &AddeOp1;
7357   else
7358     HiAdd = &AddeOp0;
7359
7360
7361   if (AddcOp0->getOpcode() == Opc) {
7362     LoMul = &AddcOp0;
7363     LowAdd = &AddcOp1;
7364   }
7365   if (AddcOp1->getOpcode() == Opc) {
7366     LoMul = &AddcOp1;
7367     LowAdd = &AddcOp0;
7368   }
7369
7370   if (LoMul == NULL)
7371     return SDValue();
7372
7373   if (LoMul->getNode() != HiMul->getNode())
7374     return SDValue();
7375
7376   // Create the merged node.
7377   SelectionDAG &DAG = DCI.DAG;
7378
7379   // Build operand list.
7380   SmallVector<SDValue, 8> Ops;
7381   Ops.push_back(LoMul->getOperand(0));
7382   Ops.push_back(LoMul->getOperand(1));
7383   Ops.push_back(*LowAdd);
7384   Ops.push_back(*HiAdd);
7385
7386   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7387                                  DAG.getVTList(MVT::i32, MVT::i32),
7388                                  &Ops[0], Ops.size());
7389
7390   // Replace the ADDs' nodes uses by the MLA node's values.
7391   SDValue HiMLALResult(MLALNode.getNode(), 1);
7392   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7393
7394   SDValue LoMLALResult(MLALNode.getNode(), 0);
7395   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7396
7397   // Return original node to notify the driver to stop replacing.
7398   SDValue resNode(AddcNode, 0);
7399   return resNode;
7400 }
7401
7402 /// PerformADDCCombine - Target-specific dag combine transform from
7403 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7404 static SDValue PerformADDCCombine(SDNode *N,
7405                                  TargetLowering::DAGCombinerInfo &DCI,
7406                                  const ARMSubtarget *Subtarget) {
7407
7408   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7409
7410 }
7411
7412 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7413 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7414 /// called with the default operands, and if that fails, with commuted
7415 /// operands.
7416 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7417                                           TargetLowering::DAGCombinerInfo &DCI,
7418                                           const ARMSubtarget *Subtarget){
7419
7420   // Attempt to create vpaddl for this add.
7421   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7422   if (Result.getNode())
7423     return Result;
7424
7425   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7426   if (N0.getNode()->hasOneUse()) {
7427     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7428     if (Result.getNode()) return Result;
7429   }
7430   return SDValue();
7431 }
7432
7433 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7434 ///
7435 static SDValue PerformADDCombine(SDNode *N,
7436                                  TargetLowering::DAGCombinerInfo &DCI,
7437                                  const ARMSubtarget *Subtarget) {
7438   SDValue N0 = N->getOperand(0);
7439   SDValue N1 = N->getOperand(1);
7440
7441   // First try with the default operand order.
7442   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7443   if (Result.getNode())
7444     return Result;
7445
7446   // If that didn't work, try again with the operands commuted.
7447   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7448 }
7449
7450 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7451 ///
7452 static SDValue PerformSUBCombine(SDNode *N,
7453                                  TargetLowering::DAGCombinerInfo &DCI) {
7454   SDValue N0 = N->getOperand(0);
7455   SDValue N1 = N->getOperand(1);
7456
7457   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7458   if (N1.getNode()->hasOneUse()) {
7459     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7460     if (Result.getNode()) return Result;
7461   }
7462
7463   return SDValue();
7464 }
7465
7466 /// PerformVMULCombine
7467 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7468 /// special multiplier accumulator forwarding.
7469 ///   vmul d3, d0, d2
7470 ///   vmla d3, d1, d2
7471 /// is faster than
7472 ///   vadd d3, d0, d1
7473 ///   vmul d3, d3, d2
7474 static SDValue PerformVMULCombine(SDNode *N,
7475                                   TargetLowering::DAGCombinerInfo &DCI,
7476                                   const ARMSubtarget *Subtarget) {
7477   if (!Subtarget->hasVMLxForwarding())
7478     return SDValue();
7479
7480   SelectionDAG &DAG = DCI.DAG;
7481   SDValue N0 = N->getOperand(0);
7482   SDValue N1 = N->getOperand(1);
7483   unsigned Opcode = N0.getOpcode();
7484   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7485       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7486     Opcode = N1.getOpcode();
7487     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7488         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7489       return SDValue();
7490     std::swap(N0, N1);
7491   }
7492
7493   EVT VT = N->getValueType(0);
7494   DebugLoc DL = N->getDebugLoc();
7495   SDValue N00 = N0->getOperand(0);
7496   SDValue N01 = N0->getOperand(1);
7497   return DAG.getNode(Opcode, DL, VT,
7498                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7499                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7500 }
7501
7502 static SDValue PerformMULCombine(SDNode *N,
7503                                  TargetLowering::DAGCombinerInfo &DCI,
7504                                  const ARMSubtarget *Subtarget) {
7505   SelectionDAG &DAG = DCI.DAG;
7506
7507   if (Subtarget->isThumb1Only())
7508     return SDValue();
7509
7510   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7511     return SDValue();
7512
7513   EVT VT = N->getValueType(0);
7514   if (VT.is64BitVector() || VT.is128BitVector())
7515     return PerformVMULCombine(N, DCI, Subtarget);
7516   if (VT != MVT::i32)
7517     return SDValue();
7518
7519   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7520   if (!C)
7521     return SDValue();
7522
7523   int64_t MulAmt = C->getSExtValue();
7524   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7525
7526   ShiftAmt = ShiftAmt & (32 - 1);
7527   SDValue V = N->getOperand(0);
7528   DebugLoc DL = N->getDebugLoc();
7529
7530   SDValue Res;
7531   MulAmt >>= ShiftAmt;
7532
7533   if (MulAmt >= 0) {
7534     if (isPowerOf2_32(MulAmt - 1)) {
7535       // (mul x, 2^N + 1) => (add (shl x, N), x)
7536       Res = DAG.getNode(ISD::ADD, DL, VT,
7537                         V,
7538                         DAG.getNode(ISD::SHL, DL, VT,
7539                                     V,
7540                                     DAG.getConstant(Log2_32(MulAmt - 1),
7541                                                     MVT::i32)));
7542     } else if (isPowerOf2_32(MulAmt + 1)) {
7543       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7544       Res = DAG.getNode(ISD::SUB, DL, VT,
7545                         DAG.getNode(ISD::SHL, DL, VT,
7546                                     V,
7547                                     DAG.getConstant(Log2_32(MulAmt + 1),
7548                                                     MVT::i32)),
7549                         V);
7550     } else
7551       return SDValue();
7552   } else {
7553     uint64_t MulAmtAbs = -MulAmt;
7554     if (isPowerOf2_32(MulAmtAbs + 1)) {
7555       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7556       Res = DAG.getNode(ISD::SUB, DL, VT,
7557                         V,
7558                         DAG.getNode(ISD::SHL, DL, VT,
7559                                     V,
7560                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7561                                                     MVT::i32)));
7562     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7563       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7564       Res = DAG.getNode(ISD::ADD, DL, VT,
7565                         V,
7566                         DAG.getNode(ISD::SHL, DL, VT,
7567                                     V,
7568                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7569                                                     MVT::i32)));
7570       Res = DAG.getNode(ISD::SUB, DL, VT,
7571                         DAG.getConstant(0, MVT::i32),Res);
7572
7573     } else
7574       return SDValue();
7575   }
7576
7577   if (ShiftAmt != 0)
7578     Res = DAG.getNode(ISD::SHL, DL, VT,
7579                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7580
7581   // Do not add new nodes to DAG combiner worklist.
7582   DCI.CombineTo(N, Res, false);
7583   return SDValue();
7584 }
7585
7586 static SDValue PerformANDCombine(SDNode *N,
7587                                  TargetLowering::DAGCombinerInfo &DCI,
7588                                  const ARMSubtarget *Subtarget) {
7589
7590   // Attempt to use immediate-form VBIC
7591   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7592   DebugLoc dl = N->getDebugLoc();
7593   EVT VT = N->getValueType(0);
7594   SelectionDAG &DAG = DCI.DAG;
7595
7596   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7597     return SDValue();
7598
7599   APInt SplatBits, SplatUndef;
7600   unsigned SplatBitSize;
7601   bool HasAnyUndefs;
7602   if (BVN &&
7603       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7604     if (SplatBitSize <= 64) {
7605       EVT VbicVT;
7606       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7607                                       SplatUndef.getZExtValue(), SplatBitSize,
7608                                       DAG, VbicVT, VT.is128BitVector(),
7609                                       OtherModImm);
7610       if (Val.getNode()) {
7611         SDValue Input =
7612           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7613         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7614         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7615       }
7616     }
7617   }
7618
7619   if (!Subtarget->isThumb1Only()) {
7620     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7621     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7622     if (Result.getNode())
7623       return Result;
7624   }
7625
7626   return SDValue();
7627 }
7628
7629 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7630 static SDValue PerformORCombine(SDNode *N,
7631                                 TargetLowering::DAGCombinerInfo &DCI,
7632                                 const ARMSubtarget *Subtarget) {
7633   // Attempt to use immediate-form VORR
7634   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7635   DebugLoc dl = N->getDebugLoc();
7636   EVT VT = N->getValueType(0);
7637   SelectionDAG &DAG = DCI.DAG;
7638
7639   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7640     return SDValue();
7641
7642   APInt SplatBits, SplatUndef;
7643   unsigned SplatBitSize;
7644   bool HasAnyUndefs;
7645   if (BVN && Subtarget->hasNEON() &&
7646       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7647     if (SplatBitSize <= 64) {
7648       EVT VorrVT;
7649       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7650                                       SplatUndef.getZExtValue(), SplatBitSize,
7651                                       DAG, VorrVT, VT.is128BitVector(),
7652                                       OtherModImm);
7653       if (Val.getNode()) {
7654         SDValue Input =
7655           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7656         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7657         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7658       }
7659     }
7660   }
7661
7662   if (!Subtarget->isThumb1Only()) {
7663     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7664     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7665     if (Result.getNode())
7666       return Result;
7667   }
7668
7669   // The code below optimizes (or (and X, Y), Z).
7670   // The AND operand needs to have a single user to make these optimizations
7671   // profitable.
7672   SDValue N0 = N->getOperand(0);
7673   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7674     return SDValue();
7675   SDValue N1 = N->getOperand(1);
7676
7677   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7678   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7679       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7680     APInt SplatUndef;
7681     unsigned SplatBitSize;
7682     bool HasAnyUndefs;
7683
7684     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7685     APInt SplatBits0;
7686     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7687                                   HasAnyUndefs) && !HasAnyUndefs) {
7688       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7689       APInt SplatBits1;
7690       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7691                                     HasAnyUndefs) && !HasAnyUndefs &&
7692           SplatBits0 == ~SplatBits1) {
7693         // Canonicalize the vector type to make instruction selection simpler.
7694         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7695         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7696                                      N0->getOperand(1), N0->getOperand(0),
7697                                      N1->getOperand(0));
7698         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7699       }
7700     }
7701   }
7702
7703   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7704   // reasonable.
7705
7706   // BFI is only available on V6T2+
7707   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7708     return SDValue();
7709
7710   DebugLoc DL = N->getDebugLoc();
7711   // 1) or (and A, mask), val => ARMbfi A, val, mask
7712   //      iff (val & mask) == val
7713   //
7714   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7715   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7716   //          && mask == ~mask2
7717   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7718   //          && ~mask == mask2
7719   //  (i.e., copy a bitfield value into another bitfield of the same width)
7720
7721   if (VT != MVT::i32)
7722     return SDValue();
7723
7724   SDValue N00 = N0.getOperand(0);
7725
7726   // The value and the mask need to be constants so we can verify this is
7727   // actually a bitfield set. If the mask is 0xffff, we can do better
7728   // via a movt instruction, so don't use BFI in that case.
7729   SDValue MaskOp = N0.getOperand(1);
7730   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7731   if (!MaskC)
7732     return SDValue();
7733   unsigned Mask = MaskC->getZExtValue();
7734   if (Mask == 0xffff)
7735     return SDValue();
7736   SDValue Res;
7737   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7738   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7739   if (N1C) {
7740     unsigned Val = N1C->getZExtValue();
7741     if ((Val & ~Mask) != Val)
7742       return SDValue();
7743
7744     if (ARM::isBitFieldInvertedMask(Mask)) {
7745       Val >>= CountTrailingZeros_32(~Mask);
7746
7747       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7748                         DAG.getConstant(Val, MVT::i32),
7749                         DAG.getConstant(Mask, MVT::i32));
7750
7751       // Do not add new nodes to DAG combiner worklist.
7752       DCI.CombineTo(N, Res, false);
7753       return SDValue();
7754     }
7755   } else if (N1.getOpcode() == ISD::AND) {
7756     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7757     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7758     if (!N11C)
7759       return SDValue();
7760     unsigned Mask2 = N11C->getZExtValue();
7761
7762     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7763     // as is to match.
7764     if (ARM::isBitFieldInvertedMask(Mask) &&
7765         (Mask == ~Mask2)) {
7766       // The pack halfword instruction works better for masks that fit it,
7767       // so use that when it's available.
7768       if (Subtarget->hasT2ExtractPack() &&
7769           (Mask == 0xffff || Mask == 0xffff0000))
7770         return SDValue();
7771       // 2a
7772       unsigned amt = CountTrailingZeros_32(Mask2);
7773       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7774                         DAG.getConstant(amt, MVT::i32));
7775       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7776                         DAG.getConstant(Mask, MVT::i32));
7777       // Do not add new nodes to DAG combiner worklist.
7778       DCI.CombineTo(N, Res, false);
7779       return SDValue();
7780     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7781                (~Mask == Mask2)) {
7782       // The pack halfword instruction works better for masks that fit it,
7783       // so use that when it's available.
7784       if (Subtarget->hasT2ExtractPack() &&
7785           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7786         return SDValue();
7787       // 2b
7788       unsigned lsb = CountTrailingZeros_32(Mask);
7789       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7790                         DAG.getConstant(lsb, MVT::i32));
7791       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7792                         DAG.getConstant(Mask2, MVT::i32));
7793       // Do not add new nodes to DAG combiner worklist.
7794       DCI.CombineTo(N, Res, false);
7795       return SDValue();
7796     }
7797   }
7798
7799   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7800       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7801       ARM::isBitFieldInvertedMask(~Mask)) {
7802     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7803     // where lsb(mask) == #shamt and masked bits of B are known zero.
7804     SDValue ShAmt = N00.getOperand(1);
7805     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7806     unsigned LSB = CountTrailingZeros_32(Mask);
7807     if (ShAmtC != LSB)
7808       return SDValue();
7809
7810     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7811                       DAG.getConstant(~Mask, MVT::i32));
7812
7813     // Do not add new nodes to DAG combiner worklist.
7814     DCI.CombineTo(N, Res, false);
7815   }
7816
7817   return SDValue();
7818 }
7819
7820 static SDValue PerformXORCombine(SDNode *N,
7821                                  TargetLowering::DAGCombinerInfo &DCI,
7822                                  const ARMSubtarget *Subtarget) {
7823   EVT VT = N->getValueType(0);
7824   SelectionDAG &DAG = DCI.DAG;
7825
7826   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7827     return SDValue();
7828
7829   if (!Subtarget->isThumb1Only()) {
7830     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7831     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7832     if (Result.getNode())
7833       return Result;
7834   }
7835
7836   return SDValue();
7837 }
7838
7839 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7840 /// the bits being cleared by the AND are not demanded by the BFI.
7841 static SDValue PerformBFICombine(SDNode *N,
7842                                  TargetLowering::DAGCombinerInfo &DCI) {
7843   SDValue N1 = N->getOperand(1);
7844   if (N1.getOpcode() == ISD::AND) {
7845     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7846     if (!N11C)
7847       return SDValue();
7848     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7849     unsigned LSB = CountTrailingZeros_32(~InvMask);
7850     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7851     unsigned Mask = (1 << Width)-1;
7852     unsigned Mask2 = N11C->getZExtValue();
7853     if ((Mask & (~Mask2)) == 0)
7854       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7855                              N->getOperand(0), N1.getOperand(0),
7856                              N->getOperand(2));
7857   }
7858   return SDValue();
7859 }
7860
7861 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7862 /// ARMISD::VMOVRRD.
7863 static SDValue PerformVMOVRRDCombine(SDNode *N,
7864                                      TargetLowering::DAGCombinerInfo &DCI) {
7865   // vmovrrd(vmovdrr x, y) -> x,y
7866   SDValue InDouble = N->getOperand(0);
7867   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7868     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7869
7870   // vmovrrd(load f64) -> (load i32), (load i32)
7871   SDNode *InNode = InDouble.getNode();
7872   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7873       InNode->getValueType(0) == MVT::f64 &&
7874       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7875       !cast<LoadSDNode>(InNode)->isVolatile()) {
7876     // TODO: Should this be done for non-FrameIndex operands?
7877     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7878
7879     SelectionDAG &DAG = DCI.DAG;
7880     DebugLoc DL = LD->getDebugLoc();
7881     SDValue BasePtr = LD->getBasePtr();
7882     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7883                                  LD->getPointerInfo(), LD->isVolatile(),
7884                                  LD->isNonTemporal(), LD->isInvariant(),
7885                                  LD->getAlignment());
7886
7887     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7888                                     DAG.getConstant(4, MVT::i32));
7889     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7890                                  LD->getPointerInfo(), LD->isVolatile(),
7891                                  LD->isNonTemporal(), LD->isInvariant(),
7892                                  std::min(4U, LD->getAlignment() / 2));
7893
7894     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7895     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7896     DCI.RemoveFromWorklist(LD);
7897     DAG.DeleteNode(LD);
7898     return Result;
7899   }
7900
7901   return SDValue();
7902 }
7903
7904 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7905 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7906 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7907   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7908   SDValue Op0 = N->getOperand(0);
7909   SDValue Op1 = N->getOperand(1);
7910   if (Op0.getOpcode() == ISD::BITCAST)
7911     Op0 = Op0.getOperand(0);
7912   if (Op1.getOpcode() == ISD::BITCAST)
7913     Op1 = Op1.getOperand(0);
7914   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7915       Op0.getNode() == Op1.getNode() &&
7916       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7917     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7918                        N->getValueType(0), Op0.getOperand(0));
7919   return SDValue();
7920 }
7921
7922 /// PerformSTORECombine - Target-specific dag combine xforms for
7923 /// ISD::STORE.
7924 static SDValue PerformSTORECombine(SDNode *N,
7925                                    TargetLowering::DAGCombinerInfo &DCI) {
7926   StoreSDNode *St = cast<StoreSDNode>(N);
7927   if (St->isVolatile())
7928     return SDValue();
7929
7930   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
7931   // pack all of the elements in one place.  Next, store to memory in fewer
7932   // chunks.
7933   SDValue StVal = St->getValue();
7934   EVT VT = StVal.getValueType();
7935   if (St->isTruncatingStore() && VT.isVector()) {
7936     SelectionDAG &DAG = DCI.DAG;
7937     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7938     EVT StVT = St->getMemoryVT();
7939     unsigned NumElems = VT.getVectorNumElements();
7940     assert(StVT != VT && "Cannot truncate to the same type");
7941     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7942     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7943
7944     // From, To sizes and ElemCount must be pow of two
7945     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7946
7947     // We are going to use the original vector elt for storing.
7948     // Accumulated smaller vector elements must be a multiple of the store size.
7949     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7950
7951     unsigned SizeRatio  = FromEltSz / ToEltSz;
7952     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7953
7954     // Create a type on which we perform the shuffle.
7955     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7956                                      NumElems*SizeRatio);
7957     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7958
7959     DebugLoc DL = St->getDebugLoc();
7960     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7961     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7962     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7963
7964     // Can't shuffle using an illegal type.
7965     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7966
7967     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7968                                 DAG.getUNDEF(WideVec.getValueType()),
7969                                 ShuffleVec.data());
7970     // At this point all of the data is stored at the bottom of the
7971     // register. We now need to save it to mem.
7972
7973     // Find the largest store unit
7974     MVT StoreType = MVT::i8;
7975     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7976          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7977       MVT Tp = (MVT::SimpleValueType)tp;
7978       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7979         StoreType = Tp;
7980     }
7981     // Didn't find a legal store type.
7982     if (!TLI.isTypeLegal(StoreType))
7983       return SDValue();
7984
7985     // Bitcast the original vector into a vector of store-size units
7986     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7987             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7988     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7989     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7990     SmallVector<SDValue, 8> Chains;
7991     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7992                                         TLI.getPointerTy());
7993     SDValue BasePtr = St->getBasePtr();
7994
7995     // Perform one or more big stores into memory.
7996     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7997     for (unsigned I = 0; I < E; I++) {
7998       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7999                                    StoreType, ShuffWide,
8000                                    DAG.getIntPtrConstant(I));
8001       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8002                                 St->getPointerInfo(), St->isVolatile(),
8003                                 St->isNonTemporal(), St->getAlignment());
8004       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8005                             Increment);
8006       Chains.push_back(Ch);
8007     }
8008     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8009                        Chains.size());
8010   }
8011
8012   if (!ISD::isNormalStore(St))
8013     return SDValue();
8014
8015   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8016   // ARM stores of arguments in the same cache line.
8017   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8018       StVal.getNode()->hasOneUse()) {
8019     SelectionDAG  &DAG = DCI.DAG;
8020     DebugLoc DL = St->getDebugLoc();
8021     SDValue BasePtr = St->getBasePtr();
8022     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8023                                   StVal.getNode()->getOperand(0), BasePtr,
8024                                   St->getPointerInfo(), St->isVolatile(),
8025                                   St->isNonTemporal(), St->getAlignment());
8026
8027     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8028                                     DAG.getConstant(4, MVT::i32));
8029     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8030                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8031                         St->isNonTemporal(),
8032                         std::min(4U, St->getAlignment() / 2));
8033   }
8034
8035   if (StVal.getValueType() != MVT::i64 ||
8036       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8037     return SDValue();
8038
8039   // Bitcast an i64 store extracted from a vector to f64.
8040   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8041   SelectionDAG &DAG = DCI.DAG;
8042   DebugLoc dl = StVal.getDebugLoc();
8043   SDValue IntVec = StVal.getOperand(0);
8044   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8045                                  IntVec.getValueType().getVectorNumElements());
8046   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8047   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8048                                Vec, StVal.getOperand(1));
8049   dl = N->getDebugLoc();
8050   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8051   // Make the DAGCombiner fold the bitcasts.
8052   DCI.AddToWorklist(Vec.getNode());
8053   DCI.AddToWorklist(ExtElt.getNode());
8054   DCI.AddToWorklist(V.getNode());
8055   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8056                       St->getPointerInfo(), St->isVolatile(),
8057                       St->isNonTemporal(), St->getAlignment(),
8058                       St->getTBAAInfo());
8059 }
8060
8061 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8062 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8063 /// i64 vector to have f64 elements, since the value can then be loaded
8064 /// directly into a VFP register.
8065 static bool hasNormalLoadOperand(SDNode *N) {
8066   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8067   for (unsigned i = 0; i < NumElts; ++i) {
8068     SDNode *Elt = N->getOperand(i).getNode();
8069     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8070       return true;
8071   }
8072   return false;
8073 }
8074
8075 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8076 /// ISD::BUILD_VECTOR.
8077 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8078                                           TargetLowering::DAGCombinerInfo &DCI){
8079   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8080   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8081   // into a pair of GPRs, which is fine when the value is used as a scalar,
8082   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8083   SelectionDAG &DAG = DCI.DAG;
8084   if (N->getNumOperands() == 2) {
8085     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8086     if (RV.getNode())
8087       return RV;
8088   }
8089
8090   // Load i64 elements as f64 values so that type legalization does not split
8091   // them up into i32 values.
8092   EVT VT = N->getValueType(0);
8093   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8094     return SDValue();
8095   DebugLoc dl = N->getDebugLoc();
8096   SmallVector<SDValue, 8> Ops;
8097   unsigned NumElts = VT.getVectorNumElements();
8098   for (unsigned i = 0; i < NumElts; ++i) {
8099     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8100     Ops.push_back(V);
8101     // Make the DAGCombiner fold the bitcast.
8102     DCI.AddToWorklist(V.getNode());
8103   }
8104   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8105   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8106   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8107 }
8108
8109 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8110 /// ISD::INSERT_VECTOR_ELT.
8111 static SDValue PerformInsertEltCombine(SDNode *N,
8112                                        TargetLowering::DAGCombinerInfo &DCI) {
8113   // Bitcast an i64 load inserted into a vector to f64.
8114   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8115   EVT VT = N->getValueType(0);
8116   SDNode *Elt = N->getOperand(1).getNode();
8117   if (VT.getVectorElementType() != MVT::i64 ||
8118       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8119     return SDValue();
8120
8121   SelectionDAG &DAG = DCI.DAG;
8122   DebugLoc dl = N->getDebugLoc();
8123   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8124                                  VT.getVectorNumElements());
8125   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8126   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8127   // Make the DAGCombiner fold the bitcasts.
8128   DCI.AddToWorklist(Vec.getNode());
8129   DCI.AddToWorklist(V.getNode());
8130   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8131                                Vec, V, N->getOperand(2));
8132   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8133 }
8134
8135 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8136 /// ISD::VECTOR_SHUFFLE.
8137 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8138   // The LLVM shufflevector instruction does not require the shuffle mask
8139   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8140   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8141   // operands do not match the mask length, they are extended by concatenating
8142   // them with undef vectors.  That is probably the right thing for other
8143   // targets, but for NEON it is better to concatenate two double-register
8144   // size vector operands into a single quad-register size vector.  Do that
8145   // transformation here:
8146   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8147   //   shuffle(concat(v1, v2), undef)
8148   SDValue Op0 = N->getOperand(0);
8149   SDValue Op1 = N->getOperand(1);
8150   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8151       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8152       Op0.getNumOperands() != 2 ||
8153       Op1.getNumOperands() != 2)
8154     return SDValue();
8155   SDValue Concat0Op1 = Op0.getOperand(1);
8156   SDValue Concat1Op1 = Op1.getOperand(1);
8157   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8158       Concat1Op1.getOpcode() != ISD::UNDEF)
8159     return SDValue();
8160   // Skip the transformation if any of the types are illegal.
8161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8162   EVT VT = N->getValueType(0);
8163   if (!TLI.isTypeLegal(VT) ||
8164       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8165       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8166     return SDValue();
8167
8168   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8169                                   Op0.getOperand(0), Op1.getOperand(0));
8170   // Translate the shuffle mask.
8171   SmallVector<int, 16> NewMask;
8172   unsigned NumElts = VT.getVectorNumElements();
8173   unsigned HalfElts = NumElts/2;
8174   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8175   for (unsigned n = 0; n < NumElts; ++n) {
8176     int MaskElt = SVN->getMaskElt(n);
8177     int NewElt = -1;
8178     if (MaskElt < (int)HalfElts)
8179       NewElt = MaskElt;
8180     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8181       NewElt = HalfElts + MaskElt - NumElts;
8182     NewMask.push_back(NewElt);
8183   }
8184   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8185                               DAG.getUNDEF(VT), NewMask.data());
8186 }
8187
8188 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8189 /// NEON load/store intrinsics to merge base address updates.
8190 static SDValue CombineBaseUpdate(SDNode *N,
8191                                  TargetLowering::DAGCombinerInfo &DCI) {
8192   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8193     return SDValue();
8194
8195   SelectionDAG &DAG = DCI.DAG;
8196   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8197                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8198   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8199   SDValue Addr = N->getOperand(AddrOpIdx);
8200
8201   // Search for a use of the address operand that is an increment.
8202   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8203          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8204     SDNode *User = *UI;
8205     if (User->getOpcode() != ISD::ADD ||
8206         UI.getUse().getResNo() != Addr.getResNo())
8207       continue;
8208
8209     // Check that the add is independent of the load/store.  Otherwise, folding
8210     // it would create a cycle.
8211     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8212       continue;
8213
8214     // Find the new opcode for the updating load/store.
8215     bool isLoad = true;
8216     bool isLaneOp = false;
8217     unsigned NewOpc = 0;
8218     unsigned NumVecs = 0;
8219     if (isIntrinsic) {
8220       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8221       switch (IntNo) {
8222       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8223       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8224         NumVecs = 1; break;
8225       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8226         NumVecs = 2; break;
8227       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8228         NumVecs = 3; break;
8229       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8230         NumVecs = 4; break;
8231       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8232         NumVecs = 2; isLaneOp = true; break;
8233       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8234         NumVecs = 3; isLaneOp = true; break;
8235       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8236         NumVecs = 4; isLaneOp = true; break;
8237       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8238         NumVecs = 1; isLoad = false; break;
8239       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8240         NumVecs = 2; isLoad = false; break;
8241       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8242         NumVecs = 3; isLoad = false; break;
8243       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8244         NumVecs = 4; isLoad = false; break;
8245       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8246         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8247       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8248         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8249       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8250         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8251       }
8252     } else {
8253       isLaneOp = true;
8254       switch (N->getOpcode()) {
8255       default: llvm_unreachable("unexpected opcode for Neon base update");
8256       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8257       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8258       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8259       }
8260     }
8261
8262     // Find the size of memory referenced by the load/store.
8263     EVT VecTy;
8264     if (isLoad)
8265       VecTy = N->getValueType(0);
8266     else
8267       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8268     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8269     if (isLaneOp)
8270       NumBytes /= VecTy.getVectorNumElements();
8271
8272     // If the increment is a constant, it must match the memory ref size.
8273     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8274     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8275       uint64_t IncVal = CInc->getZExtValue();
8276       if (IncVal != NumBytes)
8277         continue;
8278     } else if (NumBytes >= 3 * 16) {
8279       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8280       // separate instructions that make it harder to use a non-constant update.
8281       continue;
8282     }
8283
8284     // Create the new updating load/store node.
8285     EVT Tys[6];
8286     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8287     unsigned n;
8288     for (n = 0; n < NumResultVecs; ++n)
8289       Tys[n] = VecTy;
8290     Tys[n++] = MVT::i32;
8291     Tys[n] = MVT::Other;
8292     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8293     SmallVector<SDValue, 8> Ops;
8294     Ops.push_back(N->getOperand(0)); // incoming chain
8295     Ops.push_back(N->getOperand(AddrOpIdx));
8296     Ops.push_back(Inc);
8297     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8298       Ops.push_back(N->getOperand(i));
8299     }
8300     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8301     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8302                                            Ops.data(), Ops.size(),
8303                                            MemInt->getMemoryVT(),
8304                                            MemInt->getMemOperand());
8305
8306     // Update the uses.
8307     std::vector<SDValue> NewResults;
8308     for (unsigned i = 0; i < NumResultVecs; ++i) {
8309       NewResults.push_back(SDValue(UpdN.getNode(), i));
8310     }
8311     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8312     DCI.CombineTo(N, NewResults);
8313     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8314
8315     break;
8316   }
8317   return SDValue();
8318 }
8319
8320 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8321 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8322 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8323 /// return true.
8324 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8325   SelectionDAG &DAG = DCI.DAG;
8326   EVT VT = N->getValueType(0);
8327   // vldN-dup instructions only support 64-bit vectors for N > 1.
8328   if (!VT.is64BitVector())
8329     return false;
8330
8331   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8332   SDNode *VLD = N->getOperand(0).getNode();
8333   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8334     return false;
8335   unsigned NumVecs = 0;
8336   unsigned NewOpc = 0;
8337   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8338   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8339     NumVecs = 2;
8340     NewOpc = ARMISD::VLD2DUP;
8341   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8342     NumVecs = 3;
8343     NewOpc = ARMISD::VLD3DUP;
8344   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8345     NumVecs = 4;
8346     NewOpc = ARMISD::VLD4DUP;
8347   } else {
8348     return false;
8349   }
8350
8351   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8352   // numbers match the load.
8353   unsigned VLDLaneNo =
8354     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8355   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8356        UI != UE; ++UI) {
8357     // Ignore uses of the chain result.
8358     if (UI.getUse().getResNo() == NumVecs)
8359       continue;
8360     SDNode *User = *UI;
8361     if (User->getOpcode() != ARMISD::VDUPLANE ||
8362         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8363       return false;
8364   }
8365
8366   // Create the vldN-dup node.
8367   EVT Tys[5];
8368   unsigned n;
8369   for (n = 0; n < NumVecs; ++n)
8370     Tys[n] = VT;
8371   Tys[n] = MVT::Other;
8372   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8373   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8374   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8375   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8376                                            Ops, 2, VLDMemInt->getMemoryVT(),
8377                                            VLDMemInt->getMemOperand());
8378
8379   // Update the uses.
8380   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8381        UI != UE; ++UI) {
8382     unsigned ResNo = UI.getUse().getResNo();
8383     // Ignore uses of the chain result.
8384     if (ResNo == NumVecs)
8385       continue;
8386     SDNode *User = *UI;
8387     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8388   }
8389
8390   // Now the vldN-lane intrinsic is dead except for its chain result.
8391   // Update uses of the chain.
8392   std::vector<SDValue> VLDDupResults;
8393   for (unsigned n = 0; n < NumVecs; ++n)
8394     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8395   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8396   DCI.CombineTo(VLD, VLDDupResults);
8397
8398   return true;
8399 }
8400
8401 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8402 /// ARMISD::VDUPLANE.
8403 static SDValue PerformVDUPLANECombine(SDNode *N,
8404                                       TargetLowering::DAGCombinerInfo &DCI) {
8405   SDValue Op = N->getOperand(0);
8406
8407   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8408   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8409   if (CombineVLDDUP(N, DCI))
8410     return SDValue(N, 0);
8411
8412   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8413   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8414   while (Op.getOpcode() == ISD::BITCAST)
8415     Op = Op.getOperand(0);
8416   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8417     return SDValue();
8418
8419   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8420   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8421   // The canonical VMOV for a zero vector uses a 32-bit element size.
8422   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8423   unsigned EltBits;
8424   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8425     EltSize = 8;
8426   EVT VT = N->getValueType(0);
8427   if (EltSize > VT.getVectorElementType().getSizeInBits())
8428     return SDValue();
8429
8430   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8431 }
8432
8433 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8434 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8435 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8436 {
8437   integerPart cN;
8438   integerPart c0 = 0;
8439   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8440        I != E; I++) {
8441     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8442     if (!C)
8443       return false;
8444
8445     bool isExact;
8446     APFloat APF = C->getValueAPF();
8447     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8448         != APFloat::opOK || !isExact)
8449       return false;
8450
8451     c0 = (I == 0) ? cN : c0;
8452     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8453       return false;
8454   }
8455   C = c0;
8456   return true;
8457 }
8458
8459 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8460 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8461 /// when the VMUL has a constant operand that is a power of 2.
8462 ///
8463 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8464 ///  vmul.f32        d16, d17, d16
8465 ///  vcvt.s32.f32    d16, d16
8466 /// becomes:
8467 ///  vcvt.s32.f32    d16, d16, #3
8468 static SDValue PerformVCVTCombine(SDNode *N,
8469                                   TargetLowering::DAGCombinerInfo &DCI,
8470                                   const ARMSubtarget *Subtarget) {
8471   SelectionDAG &DAG = DCI.DAG;
8472   SDValue Op = N->getOperand(0);
8473
8474   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8475       Op.getOpcode() != ISD::FMUL)
8476     return SDValue();
8477
8478   uint64_t C;
8479   SDValue N0 = Op->getOperand(0);
8480   SDValue ConstVec = Op->getOperand(1);
8481   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8482
8483   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8484       !isConstVecPow2(ConstVec, isSigned, C))
8485     return SDValue();
8486
8487   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8488     Intrinsic::arm_neon_vcvtfp2fxu;
8489   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8490                      N->getValueType(0),
8491                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8492                      DAG.getConstant(Log2_64(C), MVT::i32));
8493 }
8494
8495 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8496 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8497 /// when the VDIV has a constant operand that is a power of 2.
8498 ///
8499 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8500 ///  vcvt.f32.s32    d16, d16
8501 ///  vdiv.f32        d16, d17, d16
8502 /// becomes:
8503 ///  vcvt.f32.s32    d16, d16, #3
8504 static SDValue PerformVDIVCombine(SDNode *N,
8505                                   TargetLowering::DAGCombinerInfo &DCI,
8506                                   const ARMSubtarget *Subtarget) {
8507   SelectionDAG &DAG = DCI.DAG;
8508   SDValue Op = N->getOperand(0);
8509   unsigned OpOpcode = Op.getNode()->getOpcode();
8510
8511   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8512       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8513     return SDValue();
8514
8515   uint64_t C;
8516   SDValue ConstVec = N->getOperand(1);
8517   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8518
8519   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8520       !isConstVecPow2(ConstVec, isSigned, C))
8521     return SDValue();
8522
8523   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8524     Intrinsic::arm_neon_vcvtfxu2fp;
8525   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8526                      Op.getValueType(),
8527                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8528                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8529 }
8530
8531 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8532 /// operand of a vector shift operation, where all the elements of the
8533 /// build_vector must have the same constant integer value.
8534 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8535   // Ignore bit_converts.
8536   while (Op.getOpcode() == ISD::BITCAST)
8537     Op = Op.getOperand(0);
8538   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8539   APInt SplatBits, SplatUndef;
8540   unsigned SplatBitSize;
8541   bool HasAnyUndefs;
8542   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8543                                       HasAnyUndefs, ElementBits) ||
8544       SplatBitSize > ElementBits)
8545     return false;
8546   Cnt = SplatBits.getSExtValue();
8547   return true;
8548 }
8549
8550 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8551 /// operand of a vector shift left operation.  That value must be in the range:
8552 ///   0 <= Value < ElementBits for a left shift; or
8553 ///   0 <= Value <= ElementBits for a long left shift.
8554 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8555   assert(VT.isVector() && "vector shift count is not a vector type");
8556   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8557   if (! getVShiftImm(Op, ElementBits, Cnt))
8558     return false;
8559   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8560 }
8561
8562 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8563 /// operand of a vector shift right operation.  For a shift opcode, the value
8564 /// is positive, but for an intrinsic the value count must be negative. The
8565 /// absolute value must be in the range:
8566 ///   1 <= |Value| <= ElementBits for a right shift; or
8567 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8568 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8569                          int64_t &Cnt) {
8570   assert(VT.isVector() && "vector shift count is not a vector type");
8571   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8572   if (! getVShiftImm(Op, ElementBits, Cnt))
8573     return false;
8574   if (isIntrinsic)
8575     Cnt = -Cnt;
8576   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8577 }
8578
8579 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8580 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8581   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8582   switch (IntNo) {
8583   default:
8584     // Don't do anything for most intrinsics.
8585     break;
8586
8587   // Vector shifts: check for immediate versions and lower them.
8588   // Note: This is done during DAG combining instead of DAG legalizing because
8589   // the build_vectors for 64-bit vector element shift counts are generally
8590   // not legal, and it is hard to see their values after they get legalized to
8591   // loads from a constant pool.
8592   case Intrinsic::arm_neon_vshifts:
8593   case Intrinsic::arm_neon_vshiftu:
8594   case Intrinsic::arm_neon_vshiftls:
8595   case Intrinsic::arm_neon_vshiftlu:
8596   case Intrinsic::arm_neon_vshiftn:
8597   case Intrinsic::arm_neon_vrshifts:
8598   case Intrinsic::arm_neon_vrshiftu:
8599   case Intrinsic::arm_neon_vrshiftn:
8600   case Intrinsic::arm_neon_vqshifts:
8601   case Intrinsic::arm_neon_vqshiftu:
8602   case Intrinsic::arm_neon_vqshiftsu:
8603   case Intrinsic::arm_neon_vqshiftns:
8604   case Intrinsic::arm_neon_vqshiftnu:
8605   case Intrinsic::arm_neon_vqshiftnsu:
8606   case Intrinsic::arm_neon_vqrshiftns:
8607   case Intrinsic::arm_neon_vqrshiftnu:
8608   case Intrinsic::arm_neon_vqrshiftnsu: {
8609     EVT VT = N->getOperand(1).getValueType();
8610     int64_t Cnt;
8611     unsigned VShiftOpc = 0;
8612
8613     switch (IntNo) {
8614     case Intrinsic::arm_neon_vshifts:
8615     case Intrinsic::arm_neon_vshiftu:
8616       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8617         VShiftOpc = ARMISD::VSHL;
8618         break;
8619       }
8620       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8621         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8622                      ARMISD::VSHRs : ARMISD::VSHRu);
8623         break;
8624       }
8625       return SDValue();
8626
8627     case Intrinsic::arm_neon_vshiftls:
8628     case Intrinsic::arm_neon_vshiftlu:
8629       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8630         break;
8631       llvm_unreachable("invalid shift count for vshll intrinsic");
8632
8633     case Intrinsic::arm_neon_vrshifts:
8634     case Intrinsic::arm_neon_vrshiftu:
8635       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8636         break;
8637       return SDValue();
8638
8639     case Intrinsic::arm_neon_vqshifts:
8640     case Intrinsic::arm_neon_vqshiftu:
8641       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8642         break;
8643       return SDValue();
8644
8645     case Intrinsic::arm_neon_vqshiftsu:
8646       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8647         break;
8648       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8649
8650     case Intrinsic::arm_neon_vshiftn:
8651     case Intrinsic::arm_neon_vrshiftn:
8652     case Intrinsic::arm_neon_vqshiftns:
8653     case Intrinsic::arm_neon_vqshiftnu:
8654     case Intrinsic::arm_neon_vqshiftnsu:
8655     case Intrinsic::arm_neon_vqrshiftns:
8656     case Intrinsic::arm_neon_vqrshiftnu:
8657     case Intrinsic::arm_neon_vqrshiftnsu:
8658       // Narrowing shifts require an immediate right shift.
8659       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8660         break;
8661       llvm_unreachable("invalid shift count for narrowing vector shift "
8662                        "intrinsic");
8663
8664     default:
8665       llvm_unreachable("unhandled vector shift");
8666     }
8667
8668     switch (IntNo) {
8669     case Intrinsic::arm_neon_vshifts:
8670     case Intrinsic::arm_neon_vshiftu:
8671       // Opcode already set above.
8672       break;
8673     case Intrinsic::arm_neon_vshiftls:
8674     case Intrinsic::arm_neon_vshiftlu:
8675       if (Cnt == VT.getVectorElementType().getSizeInBits())
8676         VShiftOpc = ARMISD::VSHLLi;
8677       else
8678         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8679                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8680       break;
8681     case Intrinsic::arm_neon_vshiftn:
8682       VShiftOpc = ARMISD::VSHRN; break;
8683     case Intrinsic::arm_neon_vrshifts:
8684       VShiftOpc = ARMISD::VRSHRs; break;
8685     case Intrinsic::arm_neon_vrshiftu:
8686       VShiftOpc = ARMISD::VRSHRu; break;
8687     case Intrinsic::arm_neon_vrshiftn:
8688       VShiftOpc = ARMISD::VRSHRN; break;
8689     case Intrinsic::arm_neon_vqshifts:
8690       VShiftOpc = ARMISD::VQSHLs; break;
8691     case Intrinsic::arm_neon_vqshiftu:
8692       VShiftOpc = ARMISD::VQSHLu; break;
8693     case Intrinsic::arm_neon_vqshiftsu:
8694       VShiftOpc = ARMISD::VQSHLsu; break;
8695     case Intrinsic::arm_neon_vqshiftns:
8696       VShiftOpc = ARMISD::VQSHRNs; break;
8697     case Intrinsic::arm_neon_vqshiftnu:
8698       VShiftOpc = ARMISD::VQSHRNu; break;
8699     case Intrinsic::arm_neon_vqshiftnsu:
8700       VShiftOpc = ARMISD::VQSHRNsu; break;
8701     case Intrinsic::arm_neon_vqrshiftns:
8702       VShiftOpc = ARMISD::VQRSHRNs; break;
8703     case Intrinsic::arm_neon_vqrshiftnu:
8704       VShiftOpc = ARMISD::VQRSHRNu; break;
8705     case Intrinsic::arm_neon_vqrshiftnsu:
8706       VShiftOpc = ARMISD::VQRSHRNsu; break;
8707     }
8708
8709     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8710                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8711   }
8712
8713   case Intrinsic::arm_neon_vshiftins: {
8714     EVT VT = N->getOperand(1).getValueType();
8715     int64_t Cnt;
8716     unsigned VShiftOpc = 0;
8717
8718     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8719       VShiftOpc = ARMISD::VSLI;
8720     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8721       VShiftOpc = ARMISD::VSRI;
8722     else {
8723       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8724     }
8725
8726     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8727                        N->getOperand(1), N->getOperand(2),
8728                        DAG.getConstant(Cnt, MVT::i32));
8729   }
8730
8731   case Intrinsic::arm_neon_vqrshifts:
8732   case Intrinsic::arm_neon_vqrshiftu:
8733     // No immediate versions of these to check for.
8734     break;
8735   }
8736
8737   return SDValue();
8738 }
8739
8740 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8741 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8742 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8743 /// vector element shift counts are generally not legal, and it is hard to see
8744 /// their values after they get legalized to loads from a constant pool.
8745 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8746                                    const ARMSubtarget *ST) {
8747   EVT VT = N->getValueType(0);
8748   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8749     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8750     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8751     SDValue N1 = N->getOperand(1);
8752     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8753       SDValue N0 = N->getOperand(0);
8754       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8755           DAG.MaskedValueIsZero(N0.getOperand(0),
8756                                 APInt::getHighBitsSet(32, 16)))
8757         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8758     }
8759   }
8760
8761   // Nothing to be done for scalar shifts.
8762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8763   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8764     return SDValue();
8765
8766   assert(ST->hasNEON() && "unexpected vector shift");
8767   int64_t Cnt;
8768
8769   switch (N->getOpcode()) {
8770   default: llvm_unreachable("unexpected shift opcode");
8771
8772   case ISD::SHL:
8773     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8774       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8775                          DAG.getConstant(Cnt, MVT::i32));
8776     break;
8777
8778   case ISD::SRA:
8779   case ISD::SRL:
8780     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8781       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8782                             ARMISD::VSHRs : ARMISD::VSHRu);
8783       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8784                          DAG.getConstant(Cnt, MVT::i32));
8785     }
8786   }
8787   return SDValue();
8788 }
8789
8790 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8791 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8792 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8793                                     const ARMSubtarget *ST) {
8794   SDValue N0 = N->getOperand(0);
8795
8796   // Check for sign- and zero-extensions of vector extract operations of 8-
8797   // and 16-bit vector elements.  NEON supports these directly.  They are
8798   // handled during DAG combining because type legalization will promote them
8799   // to 32-bit types and it is messy to recognize the operations after that.
8800   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8801     SDValue Vec = N0.getOperand(0);
8802     SDValue Lane = N0.getOperand(1);
8803     EVT VT = N->getValueType(0);
8804     EVT EltVT = N0.getValueType();
8805     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8806
8807     if (VT == MVT::i32 &&
8808         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8809         TLI.isTypeLegal(Vec.getValueType()) &&
8810         isa<ConstantSDNode>(Lane)) {
8811
8812       unsigned Opc = 0;
8813       switch (N->getOpcode()) {
8814       default: llvm_unreachable("unexpected opcode");
8815       case ISD::SIGN_EXTEND:
8816         Opc = ARMISD::VGETLANEs;
8817         break;
8818       case ISD::ZERO_EXTEND:
8819       case ISD::ANY_EXTEND:
8820         Opc = ARMISD::VGETLANEu;
8821         break;
8822       }
8823       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8824     }
8825   }
8826
8827   return SDValue();
8828 }
8829
8830 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8831 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8832 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8833                                        const ARMSubtarget *ST) {
8834   // If the target supports NEON, try to use vmax/vmin instructions for f32
8835   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8836   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8837   // a NaN; only do the transformation when it matches that behavior.
8838
8839   // For now only do this when using NEON for FP operations; if using VFP, it
8840   // is not obvious that the benefit outweighs the cost of switching to the
8841   // NEON pipeline.
8842   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8843       N->getValueType(0) != MVT::f32)
8844     return SDValue();
8845
8846   SDValue CondLHS = N->getOperand(0);
8847   SDValue CondRHS = N->getOperand(1);
8848   SDValue LHS = N->getOperand(2);
8849   SDValue RHS = N->getOperand(3);
8850   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8851
8852   unsigned Opcode = 0;
8853   bool IsReversed;
8854   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8855     IsReversed = false; // x CC y ? x : y
8856   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8857     IsReversed = true ; // x CC y ? y : x
8858   } else {
8859     return SDValue();
8860   }
8861
8862   bool IsUnordered;
8863   switch (CC) {
8864   default: break;
8865   case ISD::SETOLT:
8866   case ISD::SETOLE:
8867   case ISD::SETLT:
8868   case ISD::SETLE:
8869   case ISD::SETULT:
8870   case ISD::SETULE:
8871     // If LHS is NaN, an ordered comparison will be false and the result will
8872     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8873     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8874     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8875     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8876       break;
8877     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8878     // will return -0, so vmin can only be used for unsafe math or if one of
8879     // the operands is known to be nonzero.
8880     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8881         !DAG.getTarget().Options.UnsafeFPMath &&
8882         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8883       break;
8884     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8885     break;
8886
8887   case ISD::SETOGT:
8888   case ISD::SETOGE:
8889   case ISD::SETGT:
8890   case ISD::SETGE:
8891   case ISD::SETUGT:
8892   case ISD::SETUGE:
8893     // If LHS is NaN, an ordered comparison will be false and the result will
8894     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8895     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8896     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8897     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8898       break;
8899     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8900     // will return +0, so vmax can only be used for unsafe math or if one of
8901     // the operands is known to be nonzero.
8902     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8903         !DAG.getTarget().Options.UnsafeFPMath &&
8904         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8905       break;
8906     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8907     break;
8908   }
8909
8910   if (!Opcode)
8911     return SDValue();
8912   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8913 }
8914
8915 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8916 SDValue
8917 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8918   SDValue Cmp = N->getOperand(4);
8919   if (Cmp.getOpcode() != ARMISD::CMPZ)
8920     // Only looking at EQ and NE cases.
8921     return SDValue();
8922
8923   EVT VT = N->getValueType(0);
8924   DebugLoc dl = N->getDebugLoc();
8925   SDValue LHS = Cmp.getOperand(0);
8926   SDValue RHS = Cmp.getOperand(1);
8927   SDValue FalseVal = N->getOperand(0);
8928   SDValue TrueVal = N->getOperand(1);
8929   SDValue ARMcc = N->getOperand(2);
8930   ARMCC::CondCodes CC =
8931     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8932
8933   // Simplify
8934   //   mov     r1, r0
8935   //   cmp     r1, x
8936   //   mov     r0, y
8937   //   moveq   r0, x
8938   // to
8939   //   cmp     r0, x
8940   //   movne   r0, y
8941   //
8942   //   mov     r1, r0
8943   //   cmp     r1, x
8944   //   mov     r0, x
8945   //   movne   r0, y
8946   // to
8947   //   cmp     r0, x
8948   //   movne   r0, y
8949   /// FIXME: Turn this into a target neutral optimization?
8950   SDValue Res;
8951   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8952     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8953                       N->getOperand(3), Cmp);
8954   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8955     SDValue ARMcc;
8956     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8957     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8958                       N->getOperand(3), NewCmp);
8959   }
8960
8961   if (Res.getNode()) {
8962     APInt KnownZero, KnownOne;
8963     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8964     // Capture demanded bits information that would be otherwise lost.
8965     if (KnownZero == 0xfffffffe)
8966       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8967                         DAG.getValueType(MVT::i1));
8968     else if (KnownZero == 0xffffff00)
8969       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8970                         DAG.getValueType(MVT::i8));
8971     else if (KnownZero == 0xffff0000)
8972       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8973                         DAG.getValueType(MVT::i16));
8974   }
8975
8976   return Res;
8977 }
8978
8979 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8980                                              DAGCombinerInfo &DCI) const {
8981   switch (N->getOpcode()) {
8982   default: break;
8983   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
8984   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8985   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8986   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8987   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8988   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8989   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8990   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8991   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8992   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8993   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8994   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8995   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8996   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8997   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8998   case ISD::FP_TO_SINT:
8999   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9000   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9001   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9002   case ISD::SHL:
9003   case ISD::SRA:
9004   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9005   case ISD::SIGN_EXTEND:
9006   case ISD::ZERO_EXTEND:
9007   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9008   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9009   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9010   case ARMISD::VLD2DUP:
9011   case ARMISD::VLD3DUP:
9012   case ARMISD::VLD4DUP:
9013     return CombineBaseUpdate(N, DCI);
9014   case ISD::INTRINSIC_VOID:
9015   case ISD::INTRINSIC_W_CHAIN:
9016     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9017     case Intrinsic::arm_neon_vld1:
9018     case Intrinsic::arm_neon_vld2:
9019     case Intrinsic::arm_neon_vld3:
9020     case Intrinsic::arm_neon_vld4:
9021     case Intrinsic::arm_neon_vld2lane:
9022     case Intrinsic::arm_neon_vld3lane:
9023     case Intrinsic::arm_neon_vld4lane:
9024     case Intrinsic::arm_neon_vst1:
9025     case Intrinsic::arm_neon_vst2:
9026     case Intrinsic::arm_neon_vst3:
9027     case Intrinsic::arm_neon_vst4:
9028     case Intrinsic::arm_neon_vst2lane:
9029     case Intrinsic::arm_neon_vst3lane:
9030     case Intrinsic::arm_neon_vst4lane:
9031       return CombineBaseUpdate(N, DCI);
9032     default: break;
9033     }
9034     break;
9035   }
9036   return SDValue();
9037 }
9038
9039 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9040                                                           EVT VT) const {
9041   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9042 }
9043
9044 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9045   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9046   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9047
9048   switch (VT.getSimpleVT().SimpleTy) {
9049   default:
9050     return false;
9051   case MVT::i8:
9052   case MVT::i16:
9053   case MVT::i32:
9054     // Unaligned access can use (for example) LRDB, LRDH, LDR
9055     return AllowsUnaligned;
9056   case MVT::f64:
9057   case MVT::v2f64:
9058     // For any little-endian targets with neon, we can support unaligned ld/st
9059     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9060     // A big-endian target may also explictly support unaligned accesses
9061     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9062   }
9063 }
9064
9065 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9066                        unsigned AlignCheck) {
9067   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9068           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9069 }
9070
9071 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9072                                            unsigned DstAlign, unsigned SrcAlign,
9073                                            bool IsZeroVal,
9074                                            bool MemcpyStrSrc,
9075                                            MachineFunction &MF) const {
9076   const Function *F = MF.getFunction();
9077
9078   // See if we can use NEON instructions for this...
9079   if (IsZeroVal &&
9080       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat) &&
9081       Subtarget->hasNEON()) {
9082     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9083       return MVT::v4i32;
9084     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9085       return MVT::v2i32;
9086     }
9087   }
9088
9089   // Lowering to i32/i16 if the size permits.
9090   if (Size >= 4) {
9091     return MVT::i32;
9092   } else if (Size >= 2) {
9093     return MVT::i16;
9094   }
9095
9096   // Let the target-independent logic figure it out.
9097   return MVT::Other;
9098 }
9099
9100 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9101   if (V < 0)
9102     return false;
9103
9104   unsigned Scale = 1;
9105   switch (VT.getSimpleVT().SimpleTy) {
9106   default: return false;
9107   case MVT::i1:
9108   case MVT::i8:
9109     // Scale == 1;
9110     break;
9111   case MVT::i16:
9112     // Scale == 2;
9113     Scale = 2;
9114     break;
9115   case MVT::i32:
9116     // Scale == 4;
9117     Scale = 4;
9118     break;
9119   }
9120
9121   if ((V & (Scale - 1)) != 0)
9122     return false;
9123   V /= Scale;
9124   return V == (V & ((1LL << 5) - 1));
9125 }
9126
9127 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9128                                       const ARMSubtarget *Subtarget) {
9129   bool isNeg = false;
9130   if (V < 0) {
9131     isNeg = true;
9132     V = - V;
9133   }
9134
9135   switch (VT.getSimpleVT().SimpleTy) {
9136   default: return false;
9137   case MVT::i1:
9138   case MVT::i8:
9139   case MVT::i16:
9140   case MVT::i32:
9141     // + imm12 or - imm8
9142     if (isNeg)
9143       return V == (V & ((1LL << 8) - 1));
9144     return V == (V & ((1LL << 12) - 1));
9145   case MVT::f32:
9146   case MVT::f64:
9147     // Same as ARM mode. FIXME: NEON?
9148     if (!Subtarget->hasVFP2())
9149       return false;
9150     if ((V & 3) != 0)
9151       return false;
9152     V >>= 2;
9153     return V == (V & ((1LL << 8) - 1));
9154   }
9155 }
9156
9157 /// isLegalAddressImmediate - Return true if the integer value can be used
9158 /// as the offset of the target addressing mode for load / store of the
9159 /// given type.
9160 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9161                                     const ARMSubtarget *Subtarget) {
9162   if (V == 0)
9163     return true;
9164
9165   if (!VT.isSimple())
9166     return false;
9167
9168   if (Subtarget->isThumb1Only())
9169     return isLegalT1AddressImmediate(V, VT);
9170   else if (Subtarget->isThumb2())
9171     return isLegalT2AddressImmediate(V, VT, Subtarget);
9172
9173   // ARM mode.
9174   if (V < 0)
9175     V = - V;
9176   switch (VT.getSimpleVT().SimpleTy) {
9177   default: return false;
9178   case MVT::i1:
9179   case MVT::i8:
9180   case MVT::i32:
9181     // +- imm12
9182     return V == (V & ((1LL << 12) - 1));
9183   case MVT::i16:
9184     // +- imm8
9185     return V == (V & ((1LL << 8) - 1));
9186   case MVT::f32:
9187   case MVT::f64:
9188     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9189       return false;
9190     if ((V & 3) != 0)
9191       return false;
9192     V >>= 2;
9193     return V == (V & ((1LL << 8) - 1));
9194   }
9195 }
9196
9197 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9198                                                       EVT VT) const {
9199   int Scale = AM.Scale;
9200   if (Scale < 0)
9201     return false;
9202
9203   switch (VT.getSimpleVT().SimpleTy) {
9204   default: return false;
9205   case MVT::i1:
9206   case MVT::i8:
9207   case MVT::i16:
9208   case MVT::i32:
9209     if (Scale == 1)
9210       return true;
9211     // r + r << imm
9212     Scale = Scale & ~1;
9213     return Scale == 2 || Scale == 4 || Scale == 8;
9214   case MVT::i64:
9215     // r + r
9216     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9217       return true;
9218     return false;
9219   case MVT::isVoid:
9220     // Note, we allow "void" uses (basically, uses that aren't loads or
9221     // stores), because arm allows folding a scale into many arithmetic
9222     // operations.  This should be made more precise and revisited later.
9223
9224     // Allow r << imm, but the imm has to be a multiple of two.
9225     if (Scale & 1) return false;
9226     return isPowerOf2_32(Scale);
9227   }
9228 }
9229
9230 /// isLegalAddressingMode - Return true if the addressing mode represented
9231 /// by AM is legal for this target, for a load/store of the specified type.
9232 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9233                                               Type *Ty) const {
9234   EVT VT = getValueType(Ty, true);
9235   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9236     return false;
9237
9238   // Can never fold addr of global into load/store.
9239   if (AM.BaseGV)
9240     return false;
9241
9242   switch (AM.Scale) {
9243   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9244     break;
9245   case 1:
9246     if (Subtarget->isThumb1Only())
9247       return false;
9248     // FALL THROUGH.
9249   default:
9250     // ARM doesn't support any R+R*scale+imm addr modes.
9251     if (AM.BaseOffs)
9252       return false;
9253
9254     if (!VT.isSimple())
9255       return false;
9256
9257     if (Subtarget->isThumb2())
9258       return isLegalT2ScaledAddressingMode(AM, VT);
9259
9260     int Scale = AM.Scale;
9261     switch (VT.getSimpleVT().SimpleTy) {
9262     default: return false;
9263     case MVT::i1:
9264     case MVT::i8:
9265     case MVT::i32:
9266       if (Scale < 0) Scale = -Scale;
9267       if (Scale == 1)
9268         return true;
9269       // r + r << imm
9270       return isPowerOf2_32(Scale & ~1);
9271     case MVT::i16:
9272     case MVT::i64:
9273       // r + r
9274       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9275         return true;
9276       return false;
9277
9278     case MVT::isVoid:
9279       // Note, we allow "void" uses (basically, uses that aren't loads or
9280       // stores), because arm allows folding a scale into many arithmetic
9281       // operations.  This should be made more precise and revisited later.
9282
9283       // Allow r << imm, but the imm has to be a multiple of two.
9284       if (Scale & 1) return false;
9285       return isPowerOf2_32(Scale);
9286     }
9287   }
9288   return true;
9289 }
9290
9291 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9292 /// icmp immediate, that is the target has icmp instructions which can compare
9293 /// a register against the immediate without having to materialize the
9294 /// immediate into a register.
9295 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9296   // Thumb2 and ARM modes can use cmn for negative immediates.
9297   if (!Subtarget->isThumb())
9298     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9299   if (Subtarget->isThumb2())
9300     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9301   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9302   return Imm >= 0 && Imm <= 255;
9303 }
9304
9305 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9306 /// *or sub* immediate, that is the target has add or sub instructions which can
9307 /// add a register with the immediate without having to materialize the
9308 /// immediate into a register.
9309 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9310   // Same encoding for add/sub, just flip the sign.
9311   int64_t AbsImm = llvm::abs64(Imm);
9312   if (!Subtarget->isThumb())
9313     return ARM_AM::getSOImmVal(AbsImm) != -1;
9314   if (Subtarget->isThumb2())
9315     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9316   // Thumb1 only has 8-bit unsigned immediate.
9317   return AbsImm >= 0 && AbsImm <= 255;
9318 }
9319
9320 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9321                                       bool isSEXTLoad, SDValue &Base,
9322                                       SDValue &Offset, bool &isInc,
9323                                       SelectionDAG &DAG) {
9324   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9325     return false;
9326
9327   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9328     // AddressingMode 3
9329     Base = Ptr->getOperand(0);
9330     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9331       int RHSC = (int)RHS->getZExtValue();
9332       if (RHSC < 0 && RHSC > -256) {
9333         assert(Ptr->getOpcode() == ISD::ADD);
9334         isInc = false;
9335         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9336         return true;
9337       }
9338     }
9339     isInc = (Ptr->getOpcode() == ISD::ADD);
9340     Offset = Ptr->getOperand(1);
9341     return true;
9342   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9343     // AddressingMode 2
9344     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9345       int RHSC = (int)RHS->getZExtValue();
9346       if (RHSC < 0 && RHSC > -0x1000) {
9347         assert(Ptr->getOpcode() == ISD::ADD);
9348         isInc = false;
9349         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9350         Base = Ptr->getOperand(0);
9351         return true;
9352       }
9353     }
9354
9355     if (Ptr->getOpcode() == ISD::ADD) {
9356       isInc = true;
9357       ARM_AM::ShiftOpc ShOpcVal=
9358         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9359       if (ShOpcVal != ARM_AM::no_shift) {
9360         Base = Ptr->getOperand(1);
9361         Offset = Ptr->getOperand(0);
9362       } else {
9363         Base = Ptr->getOperand(0);
9364         Offset = Ptr->getOperand(1);
9365       }
9366       return true;
9367     }
9368
9369     isInc = (Ptr->getOpcode() == ISD::ADD);
9370     Base = Ptr->getOperand(0);
9371     Offset = Ptr->getOperand(1);
9372     return true;
9373   }
9374
9375   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9376   return false;
9377 }
9378
9379 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9380                                      bool isSEXTLoad, SDValue &Base,
9381                                      SDValue &Offset, bool &isInc,
9382                                      SelectionDAG &DAG) {
9383   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9384     return false;
9385
9386   Base = Ptr->getOperand(0);
9387   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9388     int RHSC = (int)RHS->getZExtValue();
9389     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9390       assert(Ptr->getOpcode() == ISD::ADD);
9391       isInc = false;
9392       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9393       return true;
9394     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9395       isInc = Ptr->getOpcode() == ISD::ADD;
9396       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9397       return true;
9398     }
9399   }
9400
9401   return false;
9402 }
9403
9404 /// getPreIndexedAddressParts - returns true by value, base pointer and
9405 /// offset pointer and addressing mode by reference if the node's address
9406 /// can be legally represented as pre-indexed load / store address.
9407 bool
9408 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9409                                              SDValue &Offset,
9410                                              ISD::MemIndexedMode &AM,
9411                                              SelectionDAG &DAG) const {
9412   if (Subtarget->isThumb1Only())
9413     return false;
9414
9415   EVT VT;
9416   SDValue Ptr;
9417   bool isSEXTLoad = false;
9418   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9419     Ptr = LD->getBasePtr();
9420     VT  = LD->getMemoryVT();
9421     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9422   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9423     Ptr = ST->getBasePtr();
9424     VT  = ST->getMemoryVT();
9425   } else
9426     return false;
9427
9428   bool isInc;
9429   bool isLegal = false;
9430   if (Subtarget->isThumb2())
9431     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9432                                        Offset, isInc, DAG);
9433   else
9434     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9435                                         Offset, isInc, DAG);
9436   if (!isLegal)
9437     return false;
9438
9439   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9440   return true;
9441 }
9442
9443 /// getPostIndexedAddressParts - returns true by value, base pointer and
9444 /// offset pointer and addressing mode by reference if this node can be
9445 /// combined with a load / store to form a post-indexed load / store.
9446 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9447                                                    SDValue &Base,
9448                                                    SDValue &Offset,
9449                                                    ISD::MemIndexedMode &AM,
9450                                                    SelectionDAG &DAG) const {
9451   if (Subtarget->isThumb1Only())
9452     return false;
9453
9454   EVT VT;
9455   SDValue Ptr;
9456   bool isSEXTLoad = false;
9457   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9458     VT  = LD->getMemoryVT();
9459     Ptr = LD->getBasePtr();
9460     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9461   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9462     VT  = ST->getMemoryVT();
9463     Ptr = ST->getBasePtr();
9464   } else
9465     return false;
9466
9467   bool isInc;
9468   bool isLegal = false;
9469   if (Subtarget->isThumb2())
9470     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9471                                        isInc, DAG);
9472   else
9473     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9474                                         isInc, DAG);
9475   if (!isLegal)
9476     return false;
9477
9478   if (Ptr != Base) {
9479     // Swap base ptr and offset to catch more post-index load / store when
9480     // it's legal. In Thumb2 mode, offset must be an immediate.
9481     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9482         !Subtarget->isThumb2())
9483       std::swap(Base, Offset);
9484
9485     // Post-indexed load / store update the base pointer.
9486     if (Ptr != Base)
9487       return false;
9488   }
9489
9490   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9491   return true;
9492 }
9493
9494 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9495                                                        APInt &KnownZero,
9496                                                        APInt &KnownOne,
9497                                                        const SelectionDAG &DAG,
9498                                                        unsigned Depth) const {
9499   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9500   switch (Op.getOpcode()) {
9501   default: break;
9502   case ARMISD::CMOV: {
9503     // Bits are known zero/one if known on the LHS and RHS.
9504     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9505     if (KnownZero == 0 && KnownOne == 0) return;
9506
9507     APInt KnownZeroRHS, KnownOneRHS;
9508     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9509     KnownZero &= KnownZeroRHS;
9510     KnownOne  &= KnownOneRHS;
9511     return;
9512   }
9513   }
9514 }
9515
9516 //===----------------------------------------------------------------------===//
9517 //                           ARM Inline Assembly Support
9518 //===----------------------------------------------------------------------===//
9519
9520 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9521   // Looking for "rev" which is V6+.
9522   if (!Subtarget->hasV6Ops())
9523     return false;
9524
9525   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9526   std::string AsmStr = IA->getAsmString();
9527   SmallVector<StringRef, 4> AsmPieces;
9528   SplitString(AsmStr, AsmPieces, ";\n");
9529
9530   switch (AsmPieces.size()) {
9531   default: return false;
9532   case 1:
9533     AsmStr = AsmPieces[0];
9534     AsmPieces.clear();
9535     SplitString(AsmStr, AsmPieces, " \t,");
9536
9537     // rev $0, $1
9538     if (AsmPieces.size() == 3 &&
9539         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9540         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9541       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9542       if (Ty && Ty->getBitWidth() == 32)
9543         return IntrinsicLowering::LowerToByteSwap(CI);
9544     }
9545     break;
9546   }
9547
9548   return false;
9549 }
9550
9551 /// getConstraintType - Given a constraint letter, return the type of
9552 /// constraint it is for this target.
9553 ARMTargetLowering::ConstraintType
9554 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9555   if (Constraint.size() == 1) {
9556     switch (Constraint[0]) {
9557     default:  break;
9558     case 'l': return C_RegisterClass;
9559     case 'w': return C_RegisterClass;
9560     case 'h': return C_RegisterClass;
9561     case 'x': return C_RegisterClass;
9562     case 't': return C_RegisterClass;
9563     case 'j': return C_Other; // Constant for movw.
9564       // An address with a single base register. Due to the way we
9565       // currently handle addresses it is the same as an 'r' memory constraint.
9566     case 'Q': return C_Memory;
9567     }
9568   } else if (Constraint.size() == 2) {
9569     switch (Constraint[0]) {
9570     default: break;
9571     // All 'U+' constraints are addresses.
9572     case 'U': return C_Memory;
9573     }
9574   }
9575   return TargetLowering::getConstraintType(Constraint);
9576 }
9577
9578 /// Examine constraint type and operand type and determine a weight value.
9579 /// This object must already have been set up with the operand type
9580 /// and the current alternative constraint selected.
9581 TargetLowering::ConstraintWeight
9582 ARMTargetLowering::getSingleConstraintMatchWeight(
9583     AsmOperandInfo &info, const char *constraint) const {
9584   ConstraintWeight weight = CW_Invalid;
9585   Value *CallOperandVal = info.CallOperandVal;
9586     // If we don't have a value, we can't do a match,
9587     // but allow it at the lowest weight.
9588   if (CallOperandVal == NULL)
9589     return CW_Default;
9590   Type *type = CallOperandVal->getType();
9591   // Look at the constraint type.
9592   switch (*constraint) {
9593   default:
9594     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9595     break;
9596   case 'l':
9597     if (type->isIntegerTy()) {
9598       if (Subtarget->isThumb())
9599         weight = CW_SpecificReg;
9600       else
9601         weight = CW_Register;
9602     }
9603     break;
9604   case 'w':
9605     if (type->isFloatingPointTy())
9606       weight = CW_Register;
9607     break;
9608   }
9609   return weight;
9610 }
9611
9612 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9613 RCPair
9614 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9615                                                 EVT VT) const {
9616   if (Constraint.size() == 1) {
9617     // GCC ARM Constraint Letters
9618     switch (Constraint[0]) {
9619     case 'l': // Low regs or general regs.
9620       if (Subtarget->isThumb())
9621         return RCPair(0U, &ARM::tGPRRegClass);
9622       return RCPair(0U, &ARM::GPRRegClass);
9623     case 'h': // High regs or no regs.
9624       if (Subtarget->isThumb())
9625         return RCPair(0U, &ARM::hGPRRegClass);
9626       break;
9627     case 'r':
9628       return RCPair(0U, &ARM::GPRRegClass);
9629     case 'w':
9630       if (VT == MVT::f32)
9631         return RCPair(0U, &ARM::SPRRegClass);
9632       if (VT.getSizeInBits() == 64)
9633         return RCPair(0U, &ARM::DPRRegClass);
9634       if (VT.getSizeInBits() == 128)
9635         return RCPair(0U, &ARM::QPRRegClass);
9636       break;
9637     case 'x':
9638       if (VT == MVT::f32)
9639         return RCPair(0U, &ARM::SPR_8RegClass);
9640       if (VT.getSizeInBits() == 64)
9641         return RCPair(0U, &ARM::DPR_8RegClass);
9642       if (VT.getSizeInBits() == 128)
9643         return RCPair(0U, &ARM::QPR_8RegClass);
9644       break;
9645     case 't':
9646       if (VT == MVT::f32)
9647         return RCPair(0U, &ARM::SPRRegClass);
9648       break;
9649     }
9650   }
9651   if (StringRef("{cc}").equals_lower(Constraint))
9652     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9653
9654   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9655 }
9656
9657 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9658 /// vector.  If it is invalid, don't add anything to Ops.
9659 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9660                                                      std::string &Constraint,
9661                                                      std::vector<SDValue>&Ops,
9662                                                      SelectionDAG &DAG) const {
9663   SDValue Result(0, 0);
9664
9665   // Currently only support length 1 constraints.
9666   if (Constraint.length() != 1) return;
9667
9668   char ConstraintLetter = Constraint[0];
9669   switch (ConstraintLetter) {
9670   default: break;
9671   case 'j':
9672   case 'I': case 'J': case 'K': case 'L':
9673   case 'M': case 'N': case 'O':
9674     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9675     if (!C)
9676       return;
9677
9678     int64_t CVal64 = C->getSExtValue();
9679     int CVal = (int) CVal64;
9680     // None of these constraints allow values larger than 32 bits.  Check
9681     // that the value fits in an int.
9682     if (CVal != CVal64)
9683       return;
9684
9685     switch (ConstraintLetter) {
9686       case 'j':
9687         // Constant suitable for movw, must be between 0 and
9688         // 65535.
9689         if (Subtarget->hasV6T2Ops())
9690           if (CVal >= 0 && CVal <= 65535)
9691             break;
9692         return;
9693       case 'I':
9694         if (Subtarget->isThumb1Only()) {
9695           // This must be a constant between 0 and 255, for ADD
9696           // immediates.
9697           if (CVal >= 0 && CVal <= 255)
9698             break;
9699         } else if (Subtarget->isThumb2()) {
9700           // A constant that can be used as an immediate value in a
9701           // data-processing instruction.
9702           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9703             break;
9704         } else {
9705           // A constant that can be used as an immediate value in a
9706           // data-processing instruction.
9707           if (ARM_AM::getSOImmVal(CVal) != -1)
9708             break;
9709         }
9710         return;
9711
9712       case 'J':
9713         if (Subtarget->isThumb()) {  // FIXME thumb2
9714           // This must be a constant between -255 and -1, for negated ADD
9715           // immediates. This can be used in GCC with an "n" modifier that
9716           // prints the negated value, for use with SUB instructions. It is
9717           // not useful otherwise but is implemented for compatibility.
9718           if (CVal >= -255 && CVal <= -1)
9719             break;
9720         } else {
9721           // This must be a constant between -4095 and 4095. It is not clear
9722           // what this constraint is intended for. Implemented for
9723           // compatibility with GCC.
9724           if (CVal >= -4095 && CVal <= 4095)
9725             break;
9726         }
9727         return;
9728
9729       case 'K':
9730         if (Subtarget->isThumb1Only()) {
9731           // A 32-bit value where only one byte has a nonzero value. Exclude
9732           // zero to match GCC. This constraint is used by GCC internally for
9733           // constants that can be loaded with a move/shift combination.
9734           // It is not useful otherwise but is implemented for compatibility.
9735           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9736             break;
9737         } else if (Subtarget->isThumb2()) {
9738           // A constant whose bitwise inverse can be used as an immediate
9739           // value in a data-processing instruction. This can be used in GCC
9740           // with a "B" modifier that prints the inverted value, for use with
9741           // BIC and MVN instructions. It is not useful otherwise but is
9742           // implemented for compatibility.
9743           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9744             break;
9745         } else {
9746           // A constant whose bitwise inverse can be used as an immediate
9747           // value in a data-processing instruction. This can be used in GCC
9748           // with a "B" modifier that prints the inverted value, for use with
9749           // BIC and MVN instructions. It is not useful otherwise but is
9750           // implemented for compatibility.
9751           if (ARM_AM::getSOImmVal(~CVal) != -1)
9752             break;
9753         }
9754         return;
9755
9756       case 'L':
9757         if (Subtarget->isThumb1Only()) {
9758           // This must be a constant between -7 and 7,
9759           // for 3-operand ADD/SUB immediate instructions.
9760           if (CVal >= -7 && CVal < 7)
9761             break;
9762         } else if (Subtarget->isThumb2()) {
9763           // A constant whose negation can be used as an immediate value in a
9764           // data-processing instruction. This can be used in GCC with an "n"
9765           // modifier that prints the negated value, for use with SUB
9766           // instructions. It is not useful otherwise but is implemented for
9767           // compatibility.
9768           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9769             break;
9770         } else {
9771           // A constant whose negation can be used as an immediate value in a
9772           // data-processing instruction. This can be used in GCC with an "n"
9773           // modifier that prints the negated value, for use with SUB
9774           // instructions. It is not useful otherwise but is implemented for
9775           // compatibility.
9776           if (ARM_AM::getSOImmVal(-CVal) != -1)
9777             break;
9778         }
9779         return;
9780
9781       case 'M':
9782         if (Subtarget->isThumb()) { // FIXME thumb2
9783           // This must be a multiple of 4 between 0 and 1020, for
9784           // ADD sp + immediate.
9785           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9786             break;
9787         } else {
9788           // A power of two or a constant between 0 and 32.  This is used in
9789           // GCC for the shift amount on shifted register operands, but it is
9790           // useful in general for any shift amounts.
9791           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9792             break;
9793         }
9794         return;
9795
9796       case 'N':
9797         if (Subtarget->isThumb()) {  // FIXME thumb2
9798           // This must be a constant between 0 and 31, for shift amounts.
9799           if (CVal >= 0 && CVal <= 31)
9800             break;
9801         }
9802         return;
9803
9804       case 'O':
9805         if (Subtarget->isThumb()) {  // FIXME thumb2
9806           // This must be a multiple of 4 between -508 and 508, for
9807           // ADD/SUB sp = sp + immediate.
9808           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9809             break;
9810         }
9811         return;
9812     }
9813     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9814     break;
9815   }
9816
9817   if (Result.getNode()) {
9818     Ops.push_back(Result);
9819     return;
9820   }
9821   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9822 }
9823
9824 bool
9825 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9826   // The ARM target isn't yet aware of offsets.
9827   return false;
9828 }
9829
9830 bool ARM::isBitFieldInvertedMask(unsigned v) {
9831   if (v == 0xffffffff)
9832     return 0;
9833   // there can be 1's on either or both "outsides", all the "inside"
9834   // bits must be 0's
9835   unsigned int lsb = 0, msb = 31;
9836   while (v & (1 << msb)) --msb;
9837   while (v & (1 << lsb)) ++lsb;
9838   for (unsigned int i = lsb; i <= msb; ++i) {
9839     if (v & (1 << i))
9840       return 0;
9841   }
9842   return 1;
9843 }
9844
9845 /// isFPImmLegal - Returns true if the target can instruction select the
9846 /// specified FP immediate natively. If false, the legalizer will
9847 /// materialize the FP immediate as a load from a constant pool.
9848 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9849   if (!Subtarget->hasVFP3())
9850     return false;
9851   if (VT == MVT::f32)
9852     return ARM_AM::getFP32Imm(Imm) != -1;
9853   if (VT == MVT::f64)
9854     return ARM_AM::getFP64Imm(Imm) != -1;
9855   return false;
9856 }
9857
9858 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9859 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9860 /// specified in the intrinsic calls.
9861 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9862                                            const CallInst &I,
9863                                            unsigned Intrinsic) const {
9864   switch (Intrinsic) {
9865   case Intrinsic::arm_neon_vld1:
9866   case Intrinsic::arm_neon_vld2:
9867   case Intrinsic::arm_neon_vld3:
9868   case Intrinsic::arm_neon_vld4:
9869   case Intrinsic::arm_neon_vld2lane:
9870   case Intrinsic::arm_neon_vld3lane:
9871   case Intrinsic::arm_neon_vld4lane: {
9872     Info.opc = ISD::INTRINSIC_W_CHAIN;
9873     // Conservatively set memVT to the entire set of vectors loaded.
9874     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
9875     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9876     Info.ptrVal = I.getArgOperand(0);
9877     Info.offset = 0;
9878     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9879     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9880     Info.vol = false; // volatile loads with NEON intrinsics not supported
9881     Info.readMem = true;
9882     Info.writeMem = false;
9883     return true;
9884   }
9885   case Intrinsic::arm_neon_vst1:
9886   case Intrinsic::arm_neon_vst2:
9887   case Intrinsic::arm_neon_vst3:
9888   case Intrinsic::arm_neon_vst4:
9889   case Intrinsic::arm_neon_vst2lane:
9890   case Intrinsic::arm_neon_vst3lane:
9891   case Intrinsic::arm_neon_vst4lane: {
9892     Info.opc = ISD::INTRINSIC_VOID;
9893     // Conservatively set memVT to the entire set of vectors stored.
9894     unsigned NumElts = 0;
9895     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9896       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9897       if (!ArgTy->isVectorTy())
9898         break;
9899       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
9900     }
9901     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9902     Info.ptrVal = I.getArgOperand(0);
9903     Info.offset = 0;
9904     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9905     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9906     Info.vol = false; // volatile stores with NEON intrinsics not supported
9907     Info.readMem = false;
9908     Info.writeMem = true;
9909     return true;
9910   }
9911   case Intrinsic::arm_strexd: {
9912     Info.opc = ISD::INTRINSIC_W_CHAIN;
9913     Info.memVT = MVT::i64;
9914     Info.ptrVal = I.getArgOperand(2);
9915     Info.offset = 0;
9916     Info.align = 8;
9917     Info.vol = true;
9918     Info.readMem = false;
9919     Info.writeMem = true;
9920     return true;
9921   }
9922   case Intrinsic::arm_ldrexd: {
9923     Info.opc = ISD::INTRINSIC_W_CHAIN;
9924     Info.memVT = MVT::i64;
9925     Info.ptrVal = I.getArgOperand(0);
9926     Info.offset = 0;
9927     Info.align = 8;
9928     Info.vol = true;
9929     Info.readMem = true;
9930     Info.writeMem = false;
9931     return true;
9932   }
9933   default:
9934     break;
9935   }
9936
9937   return false;
9938 }