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