Tidy up; no functional change.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507
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::FCEIL, MVT::v4f32, Expand);
519     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
520     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
521     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
523
524     // Neon does not support some operations on v1i64 and v2i64 types.
525     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
526     // Custom handling for some quad-vector types to detect VMULL.
527     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
528     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
529     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
530     // Custom handling for some vector types to avoid expensive expansions
531     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
534     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
535     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
536     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
537     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
538     // a destination type that is wider than the source, and nor does
539     // it have a FP_TO_[SU]INT instruction with a narrower destination than
540     // source.
541     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
542     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
543     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
544     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
545
546     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
547     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
548
549     // NEON does not have single instruction CTPOP for vectors with element
550     // types wider than 8-bits.  However, custom lowering can leverage the
551     // v8i8/v16i8 vcnt instruction.
552     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
554     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
555     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
556
557     // NEON only has FMA instructions as of VFP4.
558     if (!Subtarget->hasVFP4()) {
559       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
560       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
561     }
562
563     setTargetDAGCombine(ISD::INTRINSIC_VOID);
564     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
565     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
566     setTargetDAGCombine(ISD::SHL);
567     setTargetDAGCombine(ISD::SRL);
568     setTargetDAGCombine(ISD::SRA);
569     setTargetDAGCombine(ISD::SIGN_EXTEND);
570     setTargetDAGCombine(ISD::ZERO_EXTEND);
571     setTargetDAGCombine(ISD::ANY_EXTEND);
572     setTargetDAGCombine(ISD::SELECT_CC);
573     setTargetDAGCombine(ISD::BUILD_VECTOR);
574     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
575     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
576     setTargetDAGCombine(ISD::STORE);
577     setTargetDAGCombine(ISD::FP_TO_SINT);
578     setTargetDAGCombine(ISD::FP_TO_UINT);
579     setTargetDAGCombine(ISD::FDIV);
580
581     // It is legal to extload from v4i8 to v4i16 or v4i32.
582     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
583                   MVT::v4i16, MVT::v2i16,
584                   MVT::v2i32};
585     for (unsigned i = 0; i < 6; ++i) {
586       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
587       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
588       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
589     }
590   }
591
592   // ARM and Thumb2 support UMLAL/SMLAL.
593   if (!Subtarget->isThumb1Only())
594     setTargetDAGCombine(ISD::ADDC);
595
596
597   computeRegisterProperties();
598
599   // ARM does not have f32 extending load.
600   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
601
602   // ARM does not have i1 sign extending load.
603   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
604
605   // ARM supports all 4 flavors of integer indexed load / store.
606   if (!Subtarget->isThumb1Only()) {
607     for (unsigned im = (unsigned)ISD::PRE_INC;
608          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
609       setIndexedLoadAction(im,  MVT::i1,  Legal);
610       setIndexedLoadAction(im,  MVT::i8,  Legal);
611       setIndexedLoadAction(im,  MVT::i16, Legal);
612       setIndexedLoadAction(im,  MVT::i32, Legal);
613       setIndexedStoreAction(im, MVT::i1,  Legal);
614       setIndexedStoreAction(im, MVT::i8,  Legal);
615       setIndexedStoreAction(im, MVT::i16, Legal);
616       setIndexedStoreAction(im, MVT::i32, Legal);
617     }
618   }
619
620   // i64 operation support.
621   setOperationAction(ISD::MUL,     MVT::i64, Expand);
622   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
623   if (Subtarget->isThumb1Only()) {
624     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
625     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
626   }
627   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
628       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
629     setOperationAction(ISD::MULHS, MVT::i32, Expand);
630
631   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
632   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
633   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
634   setOperationAction(ISD::SRL,       MVT::i64, Custom);
635   setOperationAction(ISD::SRA,       MVT::i64, Custom);
636
637   if (!Subtarget->isThumb1Only()) {
638     // FIXME: We should do this for Thumb1 as well.
639     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
640     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
641     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
642     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
643   }
644
645   // ARM does not have ROTL.
646   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
647   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
648   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
649   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
650     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
651
652   // These just redirect to CTTZ and CTLZ on ARM.
653   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
654   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
655
656   // Only ARMv6 has BSWAP.
657   if (!Subtarget->hasV6Ops())
658     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
659
660   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
661       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
662     // These are expanded into libcalls if the cpu doesn't have HW divider.
663     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
664     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
665   }
666   setOperationAction(ISD::SREM,  MVT::i32, Expand);
667   setOperationAction(ISD::UREM,  MVT::i32, Expand);
668   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
669   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
670
671   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
672   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
673   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
674   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
675   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
676
677   setOperationAction(ISD::TRAP, MVT::Other, Legal);
678
679   // Use the default implementation.
680   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
681   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
682   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
683   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
684   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
685   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
686
687   if (!Subtarget->isTargetDarwin()) {
688     // Non-Darwin platforms may return values in these registers via the
689     // personality function.
690     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
691     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
692     setExceptionPointerRegister(ARM::R0);
693     setExceptionSelectorRegister(ARM::R1);
694   }
695
696   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
697   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
698   // the default expansion.
699   // FIXME: This should be checking for v6k, not just v6.
700   if (Subtarget->hasDataBarrier() ||
701       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
702     // membarrier needs custom lowering; the rest are legal and handled
703     // normally.
704     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
705     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
706     // Custom lowering for 64-bit ops
707     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
708     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
709     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
710     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
711     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
712     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
713     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
714     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
715     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
716     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
717     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
718     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
719     setInsertFencesForAtomic(true);
720   } else {
721     // Set them all for expansion, which will force libcalls.
722     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
723     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
724     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
725     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
726     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
727     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
728     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
729     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
730     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
731     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
732     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
733     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
734     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
735     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
736     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
737     // Unordered/Monotonic case.
738     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
739     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
740     // Since the libcalls include locking, fold in the fences
741     setShouldFoldAtomicFences(true);
742   }
743
744   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
745
746   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
747   if (!Subtarget->hasV6Ops()) {
748     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
749     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
750   }
751   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
752
753   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
754       !Subtarget->isThumb1Only()) {
755     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
756     // iff target supports vfp2.
757     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
758     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
759   }
760
761   // We want to custom lower some of our intrinsics.
762   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
763   if (Subtarget->isTargetDarwin()) {
764     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
765     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
766     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
767   }
768
769   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
770   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
771   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
772   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
773   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
774   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
775   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
776   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
777   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
778
779   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
780   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
781   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
782   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
783   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
784
785   // We don't support sin/cos/fmod/copysign/pow
786   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
787   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
788   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
789   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
790   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
791   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
792   setOperationAction(ISD::FREM,      MVT::f64, Expand);
793   setOperationAction(ISD::FREM,      MVT::f32, Expand);
794   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
795       !Subtarget->isThumb1Only()) {
796     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
797     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
798   }
799   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
800   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
801
802   if (!Subtarget->hasVFP4()) {
803     setOperationAction(ISD::FMA, MVT::f64, Expand);
804     setOperationAction(ISD::FMA, MVT::f32, Expand);
805   }
806
807   // Various VFP goodness
808   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
809     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
810     if (Subtarget->hasVFP2()) {
811       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
812       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
813       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
814       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
815     }
816     // Special handling for half-precision FP.
817     if (!Subtarget->hasFP16()) {
818       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
819       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
820     }
821   }
822
823   // We have target-specific dag combine patterns for the following nodes:
824   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
825   setTargetDAGCombine(ISD::ADD);
826   setTargetDAGCombine(ISD::SUB);
827   setTargetDAGCombine(ISD::MUL);
828   setTargetDAGCombine(ISD::AND);
829   setTargetDAGCombine(ISD::OR);
830   setTargetDAGCombine(ISD::XOR);
831
832   if (Subtarget->hasV6Ops())
833     setTargetDAGCombine(ISD::SRL);
834
835   setStackPointerRegisterToSaveRestore(ARM::SP);
836
837   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
838       !Subtarget->hasVFP2())
839     setSchedulingPreference(Sched::RegPressure);
840   else
841     setSchedulingPreference(Sched::Hybrid);
842
843   //// temporary - rewrite interface to use type
844   MaxStoresPerMemset = 8;
845   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
846   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
847   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
848   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
849   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
850
851   // On ARM arguments smaller than 4 bytes are extended, so all arguments
852   // are at least 4 bytes aligned.
853   setMinStackArgumentAlignment(4);
854
855   BenefitFromCodePlacementOpt = true;
856
857   // Prefer likely predicted branches to selects on out-of-order cores.
858   PredictableSelectIsExpensive = Subtarget->isLikeA9();
859
860   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
861 }
862
863 // FIXME: It might make sense to define the representative register class as the
864 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
865 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
866 // SPR's representative would be DPR_VFP2. This should work well if register
867 // pressure tracking were modified such that a register use would increment the
868 // pressure of the register class's representative and all of it's super
869 // classes' representatives transitively. We have not implemented this because
870 // of the difficulty prior to coalescing of modeling operand register classes
871 // due to the common occurrence of cross class copies and subregister insertions
872 // and extractions.
873 std::pair<const TargetRegisterClass*, uint8_t>
874 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
875   const TargetRegisterClass *RRC = 0;
876   uint8_t Cost = 1;
877   switch (VT.SimpleTy) {
878   default:
879     return TargetLowering::findRepresentativeClass(VT);
880   // Use DPR as representative register class for all floating point
881   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
882   // the cost is 1 for both f32 and f64.
883   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
884   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
885     RRC = &ARM::DPRRegClass;
886     // When NEON is used for SP, only half of the register file is available
887     // because operations that define both SP and DP results will be constrained
888     // to the VFP2 class (D0-D15). We currently model this constraint prior to
889     // coalescing by double-counting the SP regs. See the FIXME above.
890     if (Subtarget->useNEONForSinglePrecisionFP())
891       Cost = 2;
892     break;
893   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
894   case MVT::v4f32: case MVT::v2f64:
895     RRC = &ARM::DPRRegClass;
896     Cost = 2;
897     break;
898   case MVT::v4i64:
899     RRC = &ARM::DPRRegClass;
900     Cost = 4;
901     break;
902   case MVT::v8i64:
903     RRC = &ARM::DPRRegClass;
904     Cost = 8;
905     break;
906   }
907   return std::make_pair(RRC, Cost);
908 }
909
910 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
911   switch (Opcode) {
912   default: return 0;
913   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
914   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
915   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
916   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
917   case ARMISD::CALL:          return "ARMISD::CALL";
918   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
919   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
920   case ARMISD::tCALL:         return "ARMISD::tCALL";
921   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
922   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
923   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
924   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
925   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
926   case ARMISD::CMP:           return "ARMISD::CMP";
927   case ARMISD::CMN:           return "ARMISD::CMN";
928   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
929   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
930   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
931   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
932   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
933
934   case ARMISD::CMOV:          return "ARMISD::CMOV";
935
936   case ARMISD::RBIT:          return "ARMISD::RBIT";
937
938   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
939   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
940   case ARMISD::SITOF:         return "ARMISD::SITOF";
941   case ARMISD::UITOF:         return "ARMISD::UITOF";
942
943   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
944   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
945   case ARMISD::RRX:           return "ARMISD::RRX";
946
947   case ARMISD::ADDC:          return "ARMISD::ADDC";
948   case ARMISD::ADDE:          return "ARMISD::ADDE";
949   case ARMISD::SUBC:          return "ARMISD::SUBC";
950   case ARMISD::SUBE:          return "ARMISD::SUBE";
951
952   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
953   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
954
955   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
956   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
957
958   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
959
960   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
961
962   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
963
964   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
965   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
966
967   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
968
969   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
970   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
971   case ARMISD::VCGE:          return "ARMISD::VCGE";
972   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
973   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
974   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
975   case ARMISD::VCGT:          return "ARMISD::VCGT";
976   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
977   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
978   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
979   case ARMISD::VTST:          return "ARMISD::VTST";
980
981   case ARMISD::VSHL:          return "ARMISD::VSHL";
982   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
983   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
984   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
985   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
986   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
987   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
988   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
989   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
990   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
991   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
992   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
993   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
994   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
995   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
996   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
997   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
998   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
999   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1000   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1001   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1002   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1003   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1004   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1005   case ARMISD::VDUP:          return "ARMISD::VDUP";
1006   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1007   case ARMISD::VEXT:          return "ARMISD::VEXT";
1008   case ARMISD::VREV64:        return "ARMISD::VREV64";
1009   case ARMISD::VREV32:        return "ARMISD::VREV32";
1010   case ARMISD::VREV16:        return "ARMISD::VREV16";
1011   case ARMISD::VZIP:          return "ARMISD::VZIP";
1012   case ARMISD::VUZP:          return "ARMISD::VUZP";
1013   case ARMISD::VTRN:          return "ARMISD::VTRN";
1014   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1015   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1016   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1017   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1018   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1019   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1020   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1021   case ARMISD::FMAX:          return "ARMISD::FMAX";
1022   case ARMISD::FMIN:          return "ARMISD::FMIN";
1023   case ARMISD::BFI:           return "ARMISD::BFI";
1024   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1025   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1026   case ARMISD::VBSL:          return "ARMISD::VBSL";
1027   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1028   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1029   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1030   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1031   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1032   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1033   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1034   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1035   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1036   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1037   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1038   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1039   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1040   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1041   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1042   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1043   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1044   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1045   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1046   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1047   }
1048 }
1049
1050 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1051   if (!VT.isVector()) return getPointerTy();
1052   return VT.changeVectorElementTypeToInteger();
1053 }
1054
1055 /// getRegClassFor - Return the register class that should be used for the
1056 /// specified value type.
1057 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1058   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1059   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1060   // load / store 4 to 8 consecutive D registers.
1061   if (Subtarget->hasNEON()) {
1062     if (VT == MVT::v4i64)
1063       return &ARM::QQPRRegClass;
1064     if (VT == MVT::v8i64)
1065       return &ARM::QQQQPRRegClass;
1066   }
1067   return TargetLowering::getRegClassFor(VT);
1068 }
1069
1070 // Create a fast isel object.
1071 FastISel *
1072 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1073                                   const TargetLibraryInfo *libInfo) const {
1074   return ARM::createFastISel(funcInfo, libInfo);
1075 }
1076
1077 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1078 /// be used for loads / stores from the global.
1079 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1080   return (Subtarget->isThumb1Only() ? 127 : 4095);
1081 }
1082
1083 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1084   unsigned NumVals = N->getNumValues();
1085   if (!NumVals)
1086     return Sched::RegPressure;
1087
1088   for (unsigned i = 0; i != NumVals; ++i) {
1089     EVT VT = N->getValueType(i);
1090     if (VT == MVT::Glue || VT == MVT::Other)
1091       continue;
1092     if (VT.isFloatingPoint() || VT.isVector())
1093       return Sched::ILP;
1094   }
1095
1096   if (!N->isMachineOpcode())
1097     return Sched::RegPressure;
1098
1099   // Load are scheduled for latency even if there instruction itinerary
1100   // is not available.
1101   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1102   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1103
1104   if (MCID.getNumDefs() == 0)
1105     return Sched::RegPressure;
1106   if (!Itins->isEmpty() &&
1107       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1108     return Sched::ILP;
1109
1110   return Sched::RegPressure;
1111 }
1112
1113 //===----------------------------------------------------------------------===//
1114 // Lowering Code
1115 //===----------------------------------------------------------------------===//
1116
1117 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1118 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1119   switch (CC) {
1120   default: llvm_unreachable("Unknown condition code!");
1121   case ISD::SETNE:  return ARMCC::NE;
1122   case ISD::SETEQ:  return ARMCC::EQ;
1123   case ISD::SETGT:  return ARMCC::GT;
1124   case ISD::SETGE:  return ARMCC::GE;
1125   case ISD::SETLT:  return ARMCC::LT;
1126   case ISD::SETLE:  return ARMCC::LE;
1127   case ISD::SETUGT: return ARMCC::HI;
1128   case ISD::SETUGE: return ARMCC::HS;
1129   case ISD::SETULT: return ARMCC::LO;
1130   case ISD::SETULE: return ARMCC::LS;
1131   }
1132 }
1133
1134 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1135 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1136                         ARMCC::CondCodes &CondCode2) {
1137   CondCode2 = ARMCC::AL;
1138   switch (CC) {
1139   default: llvm_unreachable("Unknown FP condition!");
1140   case ISD::SETEQ:
1141   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1142   case ISD::SETGT:
1143   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1144   case ISD::SETGE:
1145   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1146   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1147   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1148   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1149   case ISD::SETO:   CondCode = ARMCC::VC; break;
1150   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1151   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1152   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1153   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1154   case ISD::SETLT:
1155   case ISD::SETULT: CondCode = ARMCC::LT; break;
1156   case ISD::SETLE:
1157   case ISD::SETULE: CondCode = ARMCC::LE; break;
1158   case ISD::SETNE:
1159   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1160   }
1161 }
1162
1163 //===----------------------------------------------------------------------===//
1164 //                      Calling Convention Implementation
1165 //===----------------------------------------------------------------------===//
1166
1167 #include "ARMGenCallingConv.inc"
1168
1169 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1170 /// given CallingConvention value.
1171 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1172                                                  bool Return,
1173                                                  bool isVarArg) const {
1174   switch (CC) {
1175   default:
1176     llvm_unreachable("Unsupported calling convention");
1177   case CallingConv::Fast:
1178     if (Subtarget->hasVFP2() && !isVarArg) {
1179       if (!Subtarget->isAAPCS_ABI())
1180         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1181       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1182       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1183     }
1184     // Fallthrough
1185   case CallingConv::C: {
1186     // Use target triple & subtarget features to do actual dispatch.
1187     if (!Subtarget->isAAPCS_ABI())
1188       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1189     else if (Subtarget->hasVFP2() &&
1190              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1191              !isVarArg)
1192       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1193     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1194   }
1195   case CallingConv::ARM_AAPCS_VFP:
1196     if (!isVarArg)
1197       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1198     // Fallthrough
1199   case CallingConv::ARM_AAPCS:
1200     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1201   case CallingConv::ARM_APCS:
1202     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1203   case CallingConv::GHC:
1204     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1205   }
1206 }
1207
1208 /// LowerCallResult - Lower the result values of a call into the
1209 /// appropriate copies out of appropriate physical registers.
1210 SDValue
1211 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1212                                    CallingConv::ID CallConv, bool isVarArg,
1213                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1214                                    DebugLoc dl, SelectionDAG &DAG,
1215                                    SmallVectorImpl<SDValue> &InVals) const {
1216
1217   // Assign locations to each value returned by this call.
1218   SmallVector<CCValAssign, 16> RVLocs;
1219   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1220                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1221   CCInfo.AnalyzeCallResult(Ins,
1222                            CCAssignFnForNode(CallConv, /* Return*/ true,
1223                                              isVarArg));
1224
1225   // Copy all of the result registers out of their specified physreg.
1226   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1227     CCValAssign VA = RVLocs[i];
1228
1229     SDValue Val;
1230     if (VA.needsCustom()) {
1231       // Handle f64 or half of a v2f64.
1232       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1233                                       InFlag);
1234       Chain = Lo.getValue(1);
1235       InFlag = Lo.getValue(2);
1236       VA = RVLocs[++i]; // skip ahead to next loc
1237       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1238                                       InFlag);
1239       Chain = Hi.getValue(1);
1240       InFlag = Hi.getValue(2);
1241       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1242
1243       if (VA.getLocVT() == MVT::v2f64) {
1244         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1245         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1246                           DAG.getConstant(0, MVT::i32));
1247
1248         VA = RVLocs[++i]; // skip ahead to next loc
1249         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1250         Chain = Lo.getValue(1);
1251         InFlag = Lo.getValue(2);
1252         VA = RVLocs[++i]; // skip ahead to next loc
1253         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1254         Chain = Hi.getValue(1);
1255         InFlag = Hi.getValue(2);
1256         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1257         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1258                           DAG.getConstant(1, MVT::i32));
1259       }
1260     } else {
1261       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1262                                InFlag);
1263       Chain = Val.getValue(1);
1264       InFlag = Val.getValue(2);
1265     }
1266
1267     switch (VA.getLocInfo()) {
1268     default: llvm_unreachable("Unknown loc info!");
1269     case CCValAssign::Full: break;
1270     case CCValAssign::BCvt:
1271       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1272       break;
1273     }
1274
1275     InVals.push_back(Val);
1276   }
1277
1278   return Chain;
1279 }
1280
1281 /// LowerMemOpCallTo - Store the argument to the stack.
1282 SDValue
1283 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1284                                     SDValue StackPtr, SDValue Arg,
1285                                     DebugLoc dl, SelectionDAG &DAG,
1286                                     const CCValAssign &VA,
1287                                     ISD::ArgFlagsTy Flags) const {
1288   unsigned LocMemOffset = VA.getLocMemOffset();
1289   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1290   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1291   return DAG.getStore(Chain, dl, Arg, PtrOff,
1292                       MachinePointerInfo::getStack(LocMemOffset),
1293                       false, false, 0);
1294 }
1295
1296 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1297                                          SDValue Chain, SDValue &Arg,
1298                                          RegsToPassVector &RegsToPass,
1299                                          CCValAssign &VA, CCValAssign &NextVA,
1300                                          SDValue &StackPtr,
1301                                          SmallVector<SDValue, 8> &MemOpChains,
1302                                          ISD::ArgFlagsTy Flags) const {
1303
1304   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1305                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1306   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1307
1308   if (NextVA.isRegLoc())
1309     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1310   else {
1311     assert(NextVA.isMemLoc());
1312     if (StackPtr.getNode() == 0)
1313       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1314
1315     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1316                                            dl, DAG, NextVA,
1317                                            Flags));
1318   }
1319 }
1320
1321 /// LowerCall - Lowering a call into a callseq_start <-
1322 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1323 /// nodes.
1324 SDValue
1325 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1326                              SmallVectorImpl<SDValue> &InVals) const {
1327   SelectionDAG &DAG                     = CLI.DAG;
1328   DebugLoc &dl                          = CLI.DL;
1329   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1330   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1331   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1332   SDValue Chain                         = CLI.Chain;
1333   SDValue Callee                        = CLI.Callee;
1334   bool &isTailCall                      = CLI.IsTailCall;
1335   CallingConv::ID CallConv              = CLI.CallConv;
1336   bool doesNotRet                       = CLI.DoesNotReturn;
1337   bool isVarArg                         = CLI.IsVarArg;
1338
1339   MachineFunction &MF = DAG.getMachineFunction();
1340   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1341   bool IsSibCall = false;
1342   // Disable tail calls if they're not supported.
1343   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1344     isTailCall = false;
1345   if (isTailCall) {
1346     // Check if it's really possible to do a tail call.
1347     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1348                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1349                                                    Outs, OutVals, Ins, DAG);
1350     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1351     // detected sibcalls.
1352     if (isTailCall) {
1353       ++NumTailCalls;
1354       IsSibCall = true;
1355     }
1356   }
1357
1358   // Analyze operands of the call, assigning locations to each operand.
1359   SmallVector<CCValAssign, 16> ArgLocs;
1360   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1361                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1362   CCInfo.AnalyzeCallOperands(Outs,
1363                              CCAssignFnForNode(CallConv, /* Return*/ false,
1364                                                isVarArg));
1365
1366   // Get a count of how many bytes are to be pushed on the stack.
1367   unsigned NumBytes = CCInfo.getNextStackOffset();
1368
1369   // For tail calls, memory operands are available in our caller's stack.
1370   if (IsSibCall)
1371     NumBytes = 0;
1372
1373   // Adjust the stack pointer for the new arguments...
1374   // These operations are automatically eliminated by the prolog/epilog pass
1375   if (!IsSibCall)
1376     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1377
1378   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1379
1380   RegsToPassVector RegsToPass;
1381   SmallVector<SDValue, 8> MemOpChains;
1382
1383   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1384   // of tail call optimization, arguments are handled later.
1385   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1386        i != e;
1387        ++i, ++realArgIdx) {
1388     CCValAssign &VA = ArgLocs[i];
1389     SDValue Arg = OutVals[realArgIdx];
1390     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1391     bool isByVal = Flags.isByVal();
1392
1393     // Promote the value if needed.
1394     switch (VA.getLocInfo()) {
1395     default: llvm_unreachable("Unknown loc info!");
1396     case CCValAssign::Full: break;
1397     case CCValAssign::SExt:
1398       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1399       break;
1400     case CCValAssign::ZExt:
1401       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1402       break;
1403     case CCValAssign::AExt:
1404       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1405       break;
1406     case CCValAssign::BCvt:
1407       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1408       break;
1409     }
1410
1411     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1412     if (VA.needsCustom()) {
1413       if (VA.getLocVT() == MVT::v2f64) {
1414         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1415                                   DAG.getConstant(0, MVT::i32));
1416         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1417                                   DAG.getConstant(1, MVT::i32));
1418
1419         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1420                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1421
1422         VA = ArgLocs[++i]; // skip ahead to next loc
1423         if (VA.isRegLoc()) {
1424           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1425                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1426         } else {
1427           assert(VA.isMemLoc());
1428
1429           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1430                                                  dl, DAG, VA, Flags));
1431         }
1432       } else {
1433         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1434                          StackPtr, MemOpChains, Flags);
1435       }
1436     } else if (VA.isRegLoc()) {
1437       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1438     } else if (isByVal) {
1439       assert(VA.isMemLoc());
1440       unsigned offset = 0;
1441
1442       // True if this byval aggregate will be split between registers
1443       // and memory.
1444       if (CCInfo.isFirstByValRegValid()) {
1445         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1446         unsigned int i, j;
1447         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1448           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1449           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1450           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1451                                      MachinePointerInfo(),
1452                                      false, false, false, 0);
1453           MemOpChains.push_back(Load.getValue(1));
1454           RegsToPass.push_back(std::make_pair(j, Load));
1455         }
1456         offset = ARM::R4 - CCInfo.getFirstByValReg();
1457         CCInfo.clearFirstByValReg();
1458       }
1459
1460       if (Flags.getByValSize() - 4*offset > 0) {
1461         unsigned LocMemOffset = VA.getLocMemOffset();
1462         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1463         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1464                                   StkPtrOff);
1465         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1466         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1467         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1468                                            MVT::i32);
1469         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1470
1471         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1472         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1473         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1474                                           Ops, array_lengthof(Ops)));
1475       }
1476     } else if (!IsSibCall) {
1477       assert(VA.isMemLoc());
1478
1479       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1480                                              dl, DAG, VA, Flags));
1481     }
1482   }
1483
1484   if (!MemOpChains.empty())
1485     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1486                         &MemOpChains[0], MemOpChains.size());
1487
1488   // Build a sequence of copy-to-reg nodes chained together with token chain
1489   // and flag operands which copy the outgoing args into the appropriate regs.
1490   SDValue InFlag;
1491   // Tail call byval lowering might overwrite argument registers so in case of
1492   // tail call optimization the copies to registers are lowered later.
1493   if (!isTailCall)
1494     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1495       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1496                                RegsToPass[i].second, InFlag);
1497       InFlag = Chain.getValue(1);
1498     }
1499
1500   // For tail calls lower the arguments to the 'real' stack slot.
1501   if (isTailCall) {
1502     // Force all the incoming stack arguments to be loaded from the stack
1503     // before any new outgoing arguments are stored to the stack, because the
1504     // outgoing stack slots may alias the incoming argument stack slots, and
1505     // the alias isn't otherwise explicit. This is slightly more conservative
1506     // than necessary, because it means that each store effectively depends
1507     // on every argument instead of just those arguments it would clobber.
1508
1509     // Do not flag preceding copytoreg stuff together with the following stuff.
1510     InFlag = SDValue();
1511     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1512       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1513                                RegsToPass[i].second, InFlag);
1514       InFlag = Chain.getValue(1);
1515     }
1516     InFlag =SDValue();
1517   }
1518
1519   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1520   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1521   // node so that legalize doesn't hack it.
1522   bool isDirect = false;
1523   bool isARMFunc = false;
1524   bool isLocalARMFunc = false;
1525   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1526
1527   if (EnableARMLongCalls) {
1528     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1529             && "long-calls with non-static relocation model!");
1530     // Handle a global address or an external symbol. If it's not one of
1531     // those, the target's already in a register, so we don't need to do
1532     // anything extra.
1533     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1534       const GlobalValue *GV = G->getGlobal();
1535       // Create a constant pool entry for the callee address
1536       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1537       ARMConstantPoolValue *CPV =
1538         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1539
1540       // Get the address of the callee into a register
1541       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1542       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1543       Callee = DAG.getLoad(getPointerTy(), dl,
1544                            DAG.getEntryNode(), CPAddr,
1545                            MachinePointerInfo::getConstantPool(),
1546                            false, false, false, 0);
1547     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1548       const char *Sym = S->getSymbol();
1549
1550       // Create a constant pool entry for the callee address
1551       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1552       ARMConstantPoolValue *CPV =
1553         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1554                                       ARMPCLabelIndex, 0);
1555       // Get the address of the callee into a register
1556       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1557       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1558       Callee = DAG.getLoad(getPointerTy(), dl,
1559                            DAG.getEntryNode(), CPAddr,
1560                            MachinePointerInfo::getConstantPool(),
1561                            false, false, false, 0);
1562     }
1563   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1564     const GlobalValue *GV = G->getGlobal();
1565     isDirect = true;
1566     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1567     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1568                    getTargetMachine().getRelocationModel() != Reloc::Static;
1569     isARMFunc = !Subtarget->isThumb() || isStub;
1570     // ARM call to a local ARM function is predicable.
1571     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1572     // tBX takes a register source operand.
1573     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1574       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1575       ARMConstantPoolValue *CPV =
1576         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1577       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1578       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1579       Callee = DAG.getLoad(getPointerTy(), dl,
1580                            DAG.getEntryNode(), CPAddr,
1581                            MachinePointerInfo::getConstantPool(),
1582                            false, false, false, 0);
1583       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1584       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1585                            getPointerTy(), Callee, PICLabel);
1586     } else {
1587       // On ELF targets for PIC code, direct calls should go through the PLT
1588       unsigned OpFlags = 0;
1589       if (Subtarget->isTargetELF() &&
1590           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1591         OpFlags = ARMII::MO_PLT;
1592       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1593     }
1594   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1595     isDirect = true;
1596     bool isStub = Subtarget->isTargetDarwin() &&
1597                   getTargetMachine().getRelocationModel() != Reloc::Static;
1598     isARMFunc = !Subtarget->isThumb() || isStub;
1599     // tBX takes a register source operand.
1600     const char *Sym = S->getSymbol();
1601     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1602       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1603       ARMConstantPoolValue *CPV =
1604         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1605                                       ARMPCLabelIndex, 4);
1606       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1607       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1608       Callee = DAG.getLoad(getPointerTy(), dl,
1609                            DAG.getEntryNode(), CPAddr,
1610                            MachinePointerInfo::getConstantPool(),
1611                            false, false, false, 0);
1612       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1613       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1614                            getPointerTy(), Callee, PICLabel);
1615     } else {
1616       unsigned OpFlags = 0;
1617       // On ELF targets for PIC code, direct calls should go through the PLT
1618       if (Subtarget->isTargetELF() &&
1619                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1620         OpFlags = ARMII::MO_PLT;
1621       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1622     }
1623   }
1624
1625   // FIXME: handle tail calls differently.
1626   unsigned CallOpc;
1627   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1628     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1629   if (Subtarget->isThumb()) {
1630     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1631       CallOpc = ARMISD::CALL_NOLINK;
1632     else
1633       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1634   } else {
1635     if (!isDirect && !Subtarget->hasV5TOps())
1636       CallOpc = ARMISD::CALL_NOLINK;
1637     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1638                // Emit regular call when code size is the priority
1639                !HasMinSizeAttr)
1640       // "mov lr, pc; b _foo" to avoid confusing the RSP
1641       CallOpc = ARMISD::CALL_NOLINK;
1642     else
1643       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1644   }
1645
1646   std::vector<SDValue> Ops;
1647   Ops.push_back(Chain);
1648   Ops.push_back(Callee);
1649
1650   // Add argument registers to the end of the list so that they are known live
1651   // into the call.
1652   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1653     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1654                                   RegsToPass[i].second.getValueType()));
1655
1656   // Add a register mask operand representing the call-preserved registers.
1657   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1658   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1659   assert(Mask && "Missing call preserved mask for calling convention");
1660   Ops.push_back(DAG.getRegisterMask(Mask));
1661
1662   if (InFlag.getNode())
1663     Ops.push_back(InFlag);
1664
1665   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1666   if (isTailCall)
1667     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1668
1669   // Returns a chain and a flag for retval copy to use.
1670   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1671   InFlag = Chain.getValue(1);
1672
1673   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1674                              DAG.getIntPtrConstant(0, true), InFlag);
1675   if (!Ins.empty())
1676     InFlag = Chain.getValue(1);
1677
1678   // Handle result values, copying them out of physregs into vregs that we
1679   // return.
1680   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1681                          dl, DAG, InVals);
1682 }
1683
1684 /// HandleByVal - Every parameter *after* a byval parameter is passed
1685 /// on the stack.  Remember the next parameter register to allocate,
1686 /// and then confiscate the rest of the parameter registers to insure
1687 /// this.
1688 void
1689 ARMTargetLowering::HandleByVal(
1690     CCState *State, unsigned &size, unsigned Align) const {
1691   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1692   assert((State->getCallOrPrologue() == Prologue ||
1693           State->getCallOrPrologue() == Call) &&
1694          "unhandled ParmContext");
1695   if ((!State->isFirstByValRegValid()) &&
1696       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1697     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1698       unsigned AlignInRegs = Align / 4;
1699       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1700       for (unsigned i = 0; i < Waste; ++i)
1701         reg = State->AllocateReg(GPRArgRegs, 4);
1702     }
1703     if (reg != 0) {
1704       State->setFirstByValReg(reg);
1705       // At a call site, a byval parameter that is split between
1706       // registers and memory needs its size truncated here.  In a
1707       // function prologue, such byval parameters are reassembled in
1708       // memory, and are not truncated.
1709       if (State->getCallOrPrologue() == Call) {
1710         unsigned excess = 4 * (ARM::R4 - reg);
1711         assert(size >= excess && "expected larger existing stack allocation");
1712         size -= excess;
1713       }
1714     }
1715   }
1716   // Confiscate any remaining parameter registers to preclude their
1717   // assignment to subsequent parameters.
1718   while (State->AllocateReg(GPRArgRegs, 4))
1719     ;
1720 }
1721
1722 /// MatchingStackOffset - Return true if the given stack call argument is
1723 /// already available in the same position (relatively) of the caller's
1724 /// incoming argument stack.
1725 static
1726 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1727                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1728                          const TargetInstrInfo *TII) {
1729   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1730   int FI = INT_MAX;
1731   if (Arg.getOpcode() == ISD::CopyFromReg) {
1732     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1733     if (!TargetRegisterInfo::isVirtualRegister(VR))
1734       return false;
1735     MachineInstr *Def = MRI->getVRegDef(VR);
1736     if (!Def)
1737       return false;
1738     if (!Flags.isByVal()) {
1739       if (!TII->isLoadFromStackSlot(Def, FI))
1740         return false;
1741     } else {
1742       return false;
1743     }
1744   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1745     if (Flags.isByVal())
1746       // ByVal argument is passed in as a pointer but it's now being
1747       // dereferenced. e.g.
1748       // define @foo(%struct.X* %A) {
1749       //   tail call @bar(%struct.X* byval %A)
1750       // }
1751       return false;
1752     SDValue Ptr = Ld->getBasePtr();
1753     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1754     if (!FINode)
1755       return false;
1756     FI = FINode->getIndex();
1757   } else
1758     return false;
1759
1760   assert(FI != INT_MAX);
1761   if (!MFI->isFixedObjectIndex(FI))
1762     return false;
1763   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1764 }
1765
1766 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1767 /// for tail call optimization. Targets which want to do tail call
1768 /// optimization should implement this function.
1769 bool
1770 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1771                                                      CallingConv::ID CalleeCC,
1772                                                      bool isVarArg,
1773                                                      bool isCalleeStructRet,
1774                                                      bool isCallerStructRet,
1775                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1776                                     const SmallVectorImpl<SDValue> &OutVals,
1777                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1778                                                      SelectionDAG& DAG) const {
1779   const Function *CallerF = DAG.getMachineFunction().getFunction();
1780   CallingConv::ID CallerCC = CallerF->getCallingConv();
1781   bool CCMatch = CallerCC == CalleeCC;
1782
1783   // Look for obvious safe cases to perform tail call optimization that do not
1784   // require ABI changes. This is what gcc calls sibcall.
1785
1786   // Do not sibcall optimize vararg calls unless the call site is not passing
1787   // any arguments.
1788   if (isVarArg && !Outs.empty())
1789     return false;
1790
1791   // Also avoid sibcall optimization if either caller or callee uses struct
1792   // return semantics.
1793   if (isCalleeStructRet || isCallerStructRet)
1794     return false;
1795
1796   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1797   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1798   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1799   // support in the assembler and linker to be used. This would need to be
1800   // fixed to fully support tail calls in Thumb1.
1801   //
1802   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1803   // LR.  This means if we need to reload LR, it takes an extra instructions,
1804   // which outweighs the value of the tail call; but here we don't know yet
1805   // whether LR is going to be used.  Probably the right approach is to
1806   // generate the tail call here and turn it back into CALL/RET in
1807   // emitEpilogue if LR is used.
1808
1809   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1810   // but we need to make sure there are enough registers; the only valid
1811   // registers are the 4 used for parameters.  We don't currently do this
1812   // case.
1813   if (Subtarget->isThumb1Only())
1814     return false;
1815
1816   // If the calling conventions do not match, then we'd better make sure the
1817   // results are returned in the same way as what the caller expects.
1818   if (!CCMatch) {
1819     SmallVector<CCValAssign, 16> RVLocs1;
1820     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1821                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1822     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1823
1824     SmallVector<CCValAssign, 16> RVLocs2;
1825     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1826                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1827     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1828
1829     if (RVLocs1.size() != RVLocs2.size())
1830       return false;
1831     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1832       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1833         return false;
1834       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1835         return false;
1836       if (RVLocs1[i].isRegLoc()) {
1837         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1838           return false;
1839       } else {
1840         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1841           return false;
1842       }
1843     }
1844   }
1845
1846   // If Caller's vararg or byval argument has been split between registers and
1847   // stack, do not perform tail call, since part of the argument is in caller's
1848   // local frame.
1849   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1850                                       getInfo<ARMFunctionInfo>();
1851   if (AFI_Caller->getVarArgsRegSaveSize())
1852     return false;
1853
1854   // If the callee takes no arguments then go on to check the results of the
1855   // call.
1856   if (!Outs.empty()) {
1857     // Check if stack adjustment is needed. For now, do not do this if any
1858     // argument is passed on the stack.
1859     SmallVector<CCValAssign, 16> ArgLocs;
1860     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1861                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1862     CCInfo.AnalyzeCallOperands(Outs,
1863                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1864     if (CCInfo.getNextStackOffset()) {
1865       MachineFunction &MF = DAG.getMachineFunction();
1866
1867       // Check if the arguments are already laid out in the right way as
1868       // the caller's fixed stack objects.
1869       MachineFrameInfo *MFI = MF.getFrameInfo();
1870       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1871       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1872       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1873            i != e;
1874            ++i, ++realArgIdx) {
1875         CCValAssign &VA = ArgLocs[i];
1876         EVT RegVT = VA.getLocVT();
1877         SDValue Arg = OutVals[realArgIdx];
1878         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1879         if (VA.getLocInfo() == CCValAssign::Indirect)
1880           return false;
1881         if (VA.needsCustom()) {
1882           // f64 and vector types are split into multiple registers or
1883           // register/stack-slot combinations.  The types will not match
1884           // the registers; give up on memory f64 refs until we figure
1885           // out what to do about this.
1886           if (!VA.isRegLoc())
1887             return false;
1888           if (!ArgLocs[++i].isRegLoc())
1889             return false;
1890           if (RegVT == MVT::v2f64) {
1891             if (!ArgLocs[++i].isRegLoc())
1892               return false;
1893             if (!ArgLocs[++i].isRegLoc())
1894               return false;
1895           }
1896         } else if (!VA.isRegLoc()) {
1897           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1898                                    MFI, MRI, TII))
1899             return false;
1900         }
1901       }
1902     }
1903   }
1904
1905   return true;
1906 }
1907
1908 bool
1909 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1910                                   MachineFunction &MF, bool isVarArg,
1911                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
1912                                   LLVMContext &Context) const {
1913   SmallVector<CCValAssign, 16> RVLocs;
1914   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1915   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1916                                                     isVarArg));
1917 }
1918
1919 SDValue
1920 ARMTargetLowering::LowerReturn(SDValue Chain,
1921                                CallingConv::ID CallConv, bool isVarArg,
1922                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1923                                const SmallVectorImpl<SDValue> &OutVals,
1924                                DebugLoc dl, SelectionDAG &DAG) const {
1925
1926   // CCValAssign - represent the assignment of the return value to a location.
1927   SmallVector<CCValAssign, 16> RVLocs;
1928
1929   // CCState - Info about the registers and stack slots.
1930   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1931                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1932
1933   // Analyze outgoing return values.
1934   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1935                                                isVarArg));
1936
1937   SDValue Flag;
1938   SmallVector<SDValue, 4> RetOps;
1939   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1940
1941   // Copy the result values into the output registers.
1942   for (unsigned i = 0, realRVLocIdx = 0;
1943        i != RVLocs.size();
1944        ++i, ++realRVLocIdx) {
1945     CCValAssign &VA = RVLocs[i];
1946     assert(VA.isRegLoc() && "Can only return in registers!");
1947
1948     SDValue Arg = OutVals[realRVLocIdx];
1949
1950     switch (VA.getLocInfo()) {
1951     default: llvm_unreachable("Unknown loc info!");
1952     case CCValAssign::Full: break;
1953     case CCValAssign::BCvt:
1954       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1955       break;
1956     }
1957
1958     if (VA.needsCustom()) {
1959       if (VA.getLocVT() == MVT::v2f64) {
1960         // Extract the first half and return it in two registers.
1961         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1962                                    DAG.getConstant(0, MVT::i32));
1963         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1964                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1965
1966         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1967         Flag = Chain.getValue(1);
1968         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1969         VA = RVLocs[++i]; // skip ahead to next loc
1970         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1971                                  HalfGPRs.getValue(1), Flag);
1972         Flag = Chain.getValue(1);
1973         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1974         VA = RVLocs[++i]; // skip ahead to next loc
1975
1976         // Extract the 2nd half and fall through to handle it as an f64 value.
1977         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1978                           DAG.getConstant(1, MVT::i32));
1979       }
1980       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1981       // available.
1982       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1983                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1984       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1985       Flag = Chain.getValue(1);
1986       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1987       VA = RVLocs[++i]; // skip ahead to next loc
1988       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1989                                Flag);
1990     } else
1991       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1992
1993     // Guarantee that all emitted copies are
1994     // stuck together, avoiding something bad.
1995     Flag = Chain.getValue(1);
1996     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1997   }
1998
1999   // Update chain and glue.
2000   RetOps[0] = Chain;
2001   if (Flag.getNode())
2002     RetOps.push_back(Flag);
2003
2004   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2005                      RetOps.data(), RetOps.size());
2006 }
2007
2008 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2009   if (N->getNumValues() != 1)
2010     return false;
2011   if (!N->hasNUsesOfValue(1, 0))
2012     return false;
2013
2014   SDValue TCChain = Chain;
2015   SDNode *Copy = *N->use_begin();
2016   if (Copy->getOpcode() == ISD::CopyToReg) {
2017     // If the copy has a glue operand, we conservatively assume it isn't safe to
2018     // perform a tail call.
2019     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2020       return false;
2021     TCChain = Copy->getOperand(0);
2022   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2023     SDNode *VMov = Copy;
2024     // f64 returned in a pair of GPRs.
2025     SmallPtrSet<SDNode*, 2> Copies;
2026     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2027          UI != UE; ++UI) {
2028       if (UI->getOpcode() != ISD::CopyToReg)
2029         return false;
2030       Copies.insert(*UI);
2031     }
2032     if (Copies.size() > 2)
2033       return false;
2034
2035     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2036          UI != UE; ++UI) {
2037       SDValue UseChain = UI->getOperand(0);
2038       if (Copies.count(UseChain.getNode()))
2039         // Second CopyToReg
2040         Copy = *UI;
2041       else
2042         // First CopyToReg
2043         TCChain = UseChain;
2044     }
2045   } else if (Copy->getOpcode() == ISD::BITCAST) {
2046     // f32 returned in a single GPR.
2047     if (!Copy->hasOneUse())
2048       return false;
2049     Copy = *Copy->use_begin();
2050     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2051       return false;
2052     Chain = Copy->getOperand(0);
2053   } else {
2054     return false;
2055   }
2056
2057   bool HasRet = false;
2058   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2059        UI != UE; ++UI) {
2060     if (UI->getOpcode() != ARMISD::RET_FLAG)
2061       return false;
2062     HasRet = true;
2063   }
2064
2065   if (!HasRet)
2066     return false;
2067
2068   Chain = TCChain;
2069   return true;
2070 }
2071
2072 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2073   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2074     return false;
2075
2076   if (!CI->isTailCall())
2077     return false;
2078
2079   return !Subtarget->isThumb1Only();
2080 }
2081
2082 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2083 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2084 // one of the above mentioned nodes. It has to be wrapped because otherwise
2085 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2086 // be used to form addressing mode. These wrapped nodes will be selected
2087 // into MOVi.
2088 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2089   EVT PtrVT = Op.getValueType();
2090   // FIXME there is no actual debug info here
2091   DebugLoc dl = Op.getDebugLoc();
2092   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2093   SDValue Res;
2094   if (CP->isMachineConstantPoolEntry())
2095     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2096                                     CP->getAlignment());
2097   else
2098     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2099                                     CP->getAlignment());
2100   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2101 }
2102
2103 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2104   return MachineJumpTableInfo::EK_Inline;
2105 }
2106
2107 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2108                                              SelectionDAG &DAG) const {
2109   MachineFunction &MF = DAG.getMachineFunction();
2110   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2111   unsigned ARMPCLabelIndex = 0;
2112   DebugLoc DL = Op.getDebugLoc();
2113   EVT PtrVT = getPointerTy();
2114   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2115   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2116   SDValue CPAddr;
2117   if (RelocM == Reloc::Static) {
2118     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2119   } else {
2120     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2121     ARMPCLabelIndex = AFI->createPICLabelUId();
2122     ARMConstantPoolValue *CPV =
2123       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2124                                       ARMCP::CPBlockAddress, PCAdj);
2125     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2126   }
2127   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2128   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2129                                MachinePointerInfo::getConstantPool(),
2130                                false, false, false, 0);
2131   if (RelocM == Reloc::Static)
2132     return Result;
2133   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2134   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2135 }
2136
2137 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2138 SDValue
2139 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2140                                                  SelectionDAG &DAG) const {
2141   DebugLoc dl = GA->getDebugLoc();
2142   EVT PtrVT = getPointerTy();
2143   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2144   MachineFunction &MF = DAG.getMachineFunction();
2145   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2146   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2147   ARMConstantPoolValue *CPV =
2148     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2149                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2150   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2151   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2152   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2153                          MachinePointerInfo::getConstantPool(),
2154                          false, false, false, 0);
2155   SDValue Chain = Argument.getValue(1);
2156
2157   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2158   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2159
2160   // call __tls_get_addr.
2161   ArgListTy Args;
2162   ArgListEntry Entry;
2163   Entry.Node = Argument;
2164   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2165   Args.push_back(Entry);
2166   // FIXME: is there useful debug info available here?
2167   TargetLowering::CallLoweringInfo CLI(Chain,
2168                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2169                 false, false, false, false,
2170                 0, CallingConv::C, /*isTailCall=*/false,
2171                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2172                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2173   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2174   return CallResult.first;
2175 }
2176
2177 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2178 // "local exec" model.
2179 SDValue
2180 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2181                                         SelectionDAG &DAG,
2182                                         TLSModel::Model model) const {
2183   const GlobalValue *GV = GA->getGlobal();
2184   DebugLoc dl = GA->getDebugLoc();
2185   SDValue Offset;
2186   SDValue Chain = DAG.getEntryNode();
2187   EVT PtrVT = getPointerTy();
2188   // Get the Thread Pointer
2189   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2190
2191   if (model == TLSModel::InitialExec) {
2192     MachineFunction &MF = DAG.getMachineFunction();
2193     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2194     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2195     // Initial exec model.
2196     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2197     ARMConstantPoolValue *CPV =
2198       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2199                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2200                                       true);
2201     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2202     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2203     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2204                          MachinePointerInfo::getConstantPool(),
2205                          false, false, false, 0);
2206     Chain = Offset.getValue(1);
2207
2208     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2209     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2210
2211     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2212                          MachinePointerInfo::getConstantPool(),
2213                          false, false, false, 0);
2214   } else {
2215     // local exec model
2216     assert(model == TLSModel::LocalExec);
2217     ARMConstantPoolValue *CPV =
2218       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2219     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2220     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2221     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2222                          MachinePointerInfo::getConstantPool(),
2223                          false, false, false, 0);
2224   }
2225
2226   // The address of the thread local variable is the add of the thread
2227   // pointer with the offset of the variable.
2228   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2229 }
2230
2231 SDValue
2232 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2233   // TODO: implement the "local dynamic" model
2234   assert(Subtarget->isTargetELF() &&
2235          "TLS not implemented for non-ELF targets");
2236   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2237
2238   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2239
2240   switch (model) {
2241     case TLSModel::GeneralDynamic:
2242     case TLSModel::LocalDynamic:
2243       return LowerToTLSGeneralDynamicModel(GA, DAG);
2244     case TLSModel::InitialExec:
2245     case TLSModel::LocalExec:
2246       return LowerToTLSExecModels(GA, DAG, model);
2247   }
2248   llvm_unreachable("bogus TLS model");
2249 }
2250
2251 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2252                                                  SelectionDAG &DAG) const {
2253   EVT PtrVT = getPointerTy();
2254   DebugLoc dl = Op.getDebugLoc();
2255   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2256   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2257     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2258     ARMConstantPoolValue *CPV =
2259       ARMConstantPoolConstant::Create(GV,
2260                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2261     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2262     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2263     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2264                                  CPAddr,
2265                                  MachinePointerInfo::getConstantPool(),
2266                                  false, false, false, 0);
2267     SDValue Chain = Result.getValue(1);
2268     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2269     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2270     if (!UseGOTOFF)
2271       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2272                            MachinePointerInfo::getGOT(),
2273                            false, false, false, 0);
2274     return Result;
2275   }
2276
2277   // If we have T2 ops, we can materialize the address directly via movt/movw
2278   // pair. This is always cheaper.
2279   if (Subtarget->useMovt()) {
2280     ++NumMovwMovt;
2281     // FIXME: Once remat is capable of dealing with instructions with register
2282     // operands, expand this into two nodes.
2283     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2284                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2285   } else {
2286     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2287     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2288     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2289                        MachinePointerInfo::getConstantPool(),
2290                        false, false, false, 0);
2291   }
2292 }
2293
2294 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2295                                                     SelectionDAG &DAG) const {
2296   EVT PtrVT = getPointerTy();
2297   DebugLoc dl = Op.getDebugLoc();
2298   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2299   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2300
2301   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2302   // update ARMFastISel::ARMMaterializeGV.
2303   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2304     ++NumMovwMovt;
2305     // FIXME: Once remat is capable of dealing with instructions with register
2306     // operands, expand this into two nodes.
2307     if (RelocM == Reloc::Static)
2308       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2309                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2310
2311     unsigned Wrapper = (RelocM == Reloc::PIC_)
2312       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2313     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2314                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2315     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2316       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2317                            MachinePointerInfo::getGOT(),
2318                            false, false, false, 0);
2319     return Result;
2320   }
2321
2322   unsigned ARMPCLabelIndex = 0;
2323   SDValue CPAddr;
2324   if (RelocM == Reloc::Static) {
2325     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2326   } else {
2327     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2328     ARMPCLabelIndex = AFI->createPICLabelUId();
2329     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2330     ARMConstantPoolValue *CPV =
2331       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2332                                       PCAdj);
2333     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2334   }
2335   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2336
2337   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2338                                MachinePointerInfo::getConstantPool(),
2339                                false, false, false, 0);
2340   SDValue Chain = Result.getValue(1);
2341
2342   if (RelocM == Reloc::PIC_) {
2343     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2344     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2345   }
2346
2347   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2348     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2349                          false, false, false, 0);
2350
2351   return Result;
2352 }
2353
2354 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2355                                                     SelectionDAG &DAG) const {
2356   assert(Subtarget->isTargetELF() &&
2357          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2358   MachineFunction &MF = DAG.getMachineFunction();
2359   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2360   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2361   EVT PtrVT = getPointerTy();
2362   DebugLoc dl = Op.getDebugLoc();
2363   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2364   ARMConstantPoolValue *CPV =
2365     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2366                                   ARMPCLabelIndex, PCAdj);
2367   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2369   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2370                                MachinePointerInfo::getConstantPool(),
2371                                false, false, false, 0);
2372   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2373   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2374 }
2375
2376 SDValue
2377 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2378   DebugLoc dl = Op.getDebugLoc();
2379   SDValue Val = DAG.getConstant(0, MVT::i32);
2380   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2381                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2382                      Op.getOperand(1), Val);
2383 }
2384
2385 SDValue
2386 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2387   DebugLoc dl = Op.getDebugLoc();
2388   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2389                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2390 }
2391
2392 SDValue
2393 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2394                                           const ARMSubtarget *Subtarget) const {
2395   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2396   DebugLoc dl = Op.getDebugLoc();
2397   switch (IntNo) {
2398   default: return SDValue();    // Don't custom lower most intrinsics.
2399   case Intrinsic::arm_thread_pointer: {
2400     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2401     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2402   }
2403   case Intrinsic::eh_sjlj_lsda: {
2404     MachineFunction &MF = DAG.getMachineFunction();
2405     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2406     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2407     EVT PtrVT = getPointerTy();
2408     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2409     SDValue CPAddr;
2410     unsigned PCAdj = (RelocM != Reloc::PIC_)
2411       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2412     ARMConstantPoolValue *CPV =
2413       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2414                                       ARMCP::CPLSDA, PCAdj);
2415     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2416     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2417     SDValue Result =
2418       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2419                   MachinePointerInfo::getConstantPool(),
2420                   false, false, false, 0);
2421
2422     if (RelocM == Reloc::PIC_) {
2423       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2424       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2425     }
2426     return Result;
2427   }
2428   case Intrinsic::arm_neon_vmulls:
2429   case Intrinsic::arm_neon_vmullu: {
2430     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2431       ? ARMISD::VMULLs : ARMISD::VMULLu;
2432     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2433                        Op.getOperand(1), Op.getOperand(2));
2434   }
2435   }
2436 }
2437
2438 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2439                                const ARMSubtarget *Subtarget) {
2440   DebugLoc dl = Op.getDebugLoc();
2441   if (!Subtarget->hasDataBarrier()) {
2442     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2443     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2444     // here.
2445     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2446            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2447     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2448                        DAG.getConstant(0, MVT::i32));
2449   }
2450
2451   SDValue Op5 = Op.getOperand(5);
2452   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2453   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2454   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2455   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2456
2457   ARM_MB::MemBOpt DMBOpt;
2458   if (isDeviceBarrier)
2459     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2460   else
2461     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2462   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2463                      DAG.getConstant(DMBOpt, MVT::i32));
2464 }
2465
2466
2467 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2468                                  const ARMSubtarget *Subtarget) {
2469   // FIXME: handle "fence singlethread" more efficiently.
2470   DebugLoc dl = Op.getDebugLoc();
2471   if (!Subtarget->hasDataBarrier()) {
2472     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2473     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2474     // here.
2475     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2476            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2477     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2478                        DAG.getConstant(0, MVT::i32));
2479   }
2480
2481   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2482                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2483 }
2484
2485 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2486                              const ARMSubtarget *Subtarget) {
2487   // ARM pre v5TE and Thumb1 does not have preload instructions.
2488   if (!(Subtarget->isThumb2() ||
2489         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2490     // Just preserve the chain.
2491     return Op.getOperand(0);
2492
2493   DebugLoc dl = Op.getDebugLoc();
2494   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2495   if (!isRead &&
2496       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2497     // ARMv7 with MP extension has PLDW.
2498     return Op.getOperand(0);
2499
2500   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2501   if (Subtarget->isThumb()) {
2502     // Invert the bits.
2503     isRead = ~isRead & 1;
2504     isData = ~isData & 1;
2505   }
2506
2507   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2508                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2509                      DAG.getConstant(isData, MVT::i32));
2510 }
2511
2512 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2513   MachineFunction &MF = DAG.getMachineFunction();
2514   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2515
2516   // vastart just stores the address of the VarArgsFrameIndex slot into the
2517   // memory location argument.
2518   DebugLoc dl = Op.getDebugLoc();
2519   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2520   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2521   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2522   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2523                       MachinePointerInfo(SV), false, false, 0);
2524 }
2525
2526 SDValue
2527 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2528                                         SDValue &Root, SelectionDAG &DAG,
2529                                         DebugLoc dl) const {
2530   MachineFunction &MF = DAG.getMachineFunction();
2531   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2532
2533   const TargetRegisterClass *RC;
2534   if (AFI->isThumb1OnlyFunction())
2535     RC = &ARM::tGPRRegClass;
2536   else
2537     RC = &ARM::GPRRegClass;
2538
2539   // Transform the arguments stored in physical registers into virtual ones.
2540   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2541   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2542
2543   SDValue ArgValue2;
2544   if (NextVA.isMemLoc()) {
2545     MachineFrameInfo *MFI = MF.getFrameInfo();
2546     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2547
2548     // Create load node to retrieve arguments from the stack.
2549     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2550     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2551                             MachinePointerInfo::getFixedStack(FI),
2552                             false, false, false, 0);
2553   } else {
2554     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2555     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2556   }
2557
2558   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2559 }
2560
2561 void
2562 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2563                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2564   const {
2565   unsigned NumGPRs;
2566   if (CCInfo.isFirstByValRegValid())
2567     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2568   else {
2569     unsigned int firstUnalloced;
2570     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2571                                                 sizeof(GPRArgRegs) /
2572                                                 sizeof(GPRArgRegs[0]));
2573     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2574   }
2575
2576   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2577   VARegSize = NumGPRs * 4;
2578   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2579 }
2580
2581 // The remaining GPRs hold either the beginning of variable-argument
2582 // data, or the beginning of an aggregate passed by value (usually
2583 // byval).  Either way, we allocate stack slots adjacent to the data
2584 // provided by our caller, and store the unallocated registers there.
2585 // If this is a variadic function, the va_list pointer will begin with
2586 // these values; otherwise, this reassembles a (byval) structure that
2587 // was split between registers and memory.
2588 void
2589 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2590                                         DebugLoc dl, SDValue &Chain,
2591                                         const Value *OrigArg,
2592                                         unsigned OffsetFromOrigArg,
2593                                         unsigned ArgOffset,
2594                                         bool ForceMutable) const {
2595   MachineFunction &MF = DAG.getMachineFunction();
2596   MachineFrameInfo *MFI = MF.getFrameInfo();
2597   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2598   unsigned firstRegToSaveIndex;
2599   if (CCInfo.isFirstByValRegValid())
2600     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2601   else {
2602     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2603       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2604   }
2605
2606   unsigned VARegSize, VARegSaveSize;
2607   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2608   if (VARegSaveSize) {
2609     // If this function is vararg, store any remaining integer argument regs
2610     // to their spots on the stack so that they may be loaded by deferencing
2611     // the result of va_next.
2612     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2613     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2614                                                      ArgOffset + VARegSaveSize
2615                                                      - VARegSize,
2616                                                      false));
2617     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2618                                     getPointerTy());
2619
2620     SmallVector<SDValue, 4> MemOps;
2621     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2622       const TargetRegisterClass *RC;
2623       if (AFI->isThumb1OnlyFunction())
2624         RC = &ARM::tGPRRegClass;
2625       else
2626         RC = &ARM::GPRRegClass;
2627
2628       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2629       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2630       SDValue Store =
2631         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2632                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2633                      false, false, 0);
2634       MemOps.push_back(Store);
2635       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2636                         DAG.getConstant(4, getPointerTy()));
2637     }
2638     if (!MemOps.empty())
2639       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2640                           &MemOps[0], MemOps.size());
2641   } else
2642     // This will point to the next argument passed via stack.
2643     AFI->setVarArgsFrameIndex(
2644         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2645 }
2646
2647 SDValue
2648 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2649                                         CallingConv::ID CallConv, bool isVarArg,
2650                                         const SmallVectorImpl<ISD::InputArg>
2651                                           &Ins,
2652                                         DebugLoc dl, SelectionDAG &DAG,
2653                                         SmallVectorImpl<SDValue> &InVals)
2654                                           const {
2655   MachineFunction &MF = DAG.getMachineFunction();
2656   MachineFrameInfo *MFI = MF.getFrameInfo();
2657
2658   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2659
2660   // Assign locations to all of the incoming arguments.
2661   SmallVector<CCValAssign, 16> ArgLocs;
2662   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2663                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2664   CCInfo.AnalyzeFormalArguments(Ins,
2665                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2666                                                   isVarArg));
2667   
2668   SmallVector<SDValue, 16> ArgValues;
2669   int lastInsIndex = -1;
2670   SDValue ArgValue;
2671   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2672   unsigned CurArgIdx = 0;
2673   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2674     CCValAssign &VA = ArgLocs[i];
2675     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2676     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2677     // Arguments stored in registers.
2678     if (VA.isRegLoc()) {
2679       EVT RegVT = VA.getLocVT();
2680
2681       if (VA.needsCustom()) {
2682         // f64 and vector types are split up into multiple registers or
2683         // combinations of registers and stack slots.
2684         if (VA.getLocVT() == MVT::v2f64) {
2685           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2686                                                    Chain, DAG, dl);
2687           VA = ArgLocs[++i]; // skip ahead to next loc
2688           SDValue ArgValue2;
2689           if (VA.isMemLoc()) {
2690             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2691             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2692             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2693                                     MachinePointerInfo::getFixedStack(FI),
2694                                     false, false, false, 0);
2695           } else {
2696             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2697                                              Chain, DAG, dl);
2698           }
2699           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2700           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2701                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2702           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2703                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2704         } else
2705           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2706
2707       } else {
2708         const TargetRegisterClass *RC;
2709
2710         if (RegVT == MVT::f32)
2711           RC = &ARM::SPRRegClass;
2712         else if (RegVT == MVT::f64)
2713           RC = &ARM::DPRRegClass;
2714         else if (RegVT == MVT::v2f64)
2715           RC = &ARM::QPRRegClass;
2716         else if (RegVT == MVT::i32)
2717           RC = AFI->isThumb1OnlyFunction() ?
2718             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2719             (const TargetRegisterClass*)&ARM::GPRRegClass;
2720         else
2721           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2722
2723         // Transform the arguments in physical registers into virtual ones.
2724         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2725         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2726       }
2727
2728       // If this is an 8 or 16-bit value, it is really passed promoted
2729       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2730       // truncate to the right size.
2731       switch (VA.getLocInfo()) {
2732       default: llvm_unreachable("Unknown loc info!");
2733       case CCValAssign::Full: break;
2734       case CCValAssign::BCvt:
2735         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2736         break;
2737       case CCValAssign::SExt:
2738         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2739                                DAG.getValueType(VA.getValVT()));
2740         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2741         break;
2742       case CCValAssign::ZExt:
2743         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2744                                DAG.getValueType(VA.getValVT()));
2745         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2746         break;
2747       }
2748
2749       InVals.push_back(ArgValue);
2750
2751     } else { // VA.isRegLoc()
2752
2753       // sanity check
2754       assert(VA.isMemLoc());
2755       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2756
2757       int index = ArgLocs[i].getValNo();
2758
2759       // Some Ins[] entries become multiple ArgLoc[] entries.
2760       // Process them only once.
2761       if (index != lastInsIndex)
2762         {
2763           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2764           // FIXME: For now, all byval parameter objects are marked mutable.
2765           // This can be changed with more analysis.
2766           // In case of tail call optimization mark all arguments mutable.
2767           // Since they could be overwritten by lowering of arguments in case of
2768           // a tail call.
2769           if (Flags.isByVal()) {
2770             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2771             if (!AFI->getVarArgsFrameIndex()) {
2772               VarArgStyleRegisters(CCInfo, DAG,
2773                                    dl, Chain, CurOrigArg,
2774                                    Ins[VA.getValNo()].PartOffset,
2775                                    VA.getLocMemOffset(),
2776                                    true /*force mutable frames*/);
2777               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2778               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2779             } else {
2780               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2781                                               VA.getLocMemOffset(), false);
2782               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2783             }
2784           } else {
2785             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2786                                             VA.getLocMemOffset(), true);
2787
2788             // Create load nodes to retrieve arguments from the stack.
2789             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2790             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2791                                          MachinePointerInfo::getFixedStack(FI),
2792                                          false, false, false, 0));
2793           }
2794           lastInsIndex = index;
2795         }
2796     }
2797   }
2798
2799   // varargs
2800   if (isVarArg)
2801     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2802                          CCInfo.getNextStackOffset());
2803
2804   return Chain;
2805 }
2806
2807 /// isFloatingPointZero - Return true if this is +0.0.
2808 static bool isFloatingPointZero(SDValue Op) {
2809   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2810     return CFP->getValueAPF().isPosZero();
2811   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2812     // Maybe this has already been legalized into the constant pool?
2813     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2814       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2815       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2816         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2817           return CFP->getValueAPF().isPosZero();
2818     }
2819   }
2820   return false;
2821 }
2822
2823 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2824 /// the given operands.
2825 SDValue
2826 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2827                              SDValue &ARMcc, SelectionDAG &DAG,
2828                              DebugLoc dl) const {
2829   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2830     unsigned C = RHSC->getZExtValue();
2831     if (!isLegalICmpImmediate(C)) {
2832       // Constant does not fit, try adjusting it by one?
2833       switch (CC) {
2834       default: break;
2835       case ISD::SETLT:
2836       case ISD::SETGE:
2837         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2838           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2839           RHS = DAG.getConstant(C-1, MVT::i32);
2840         }
2841         break;
2842       case ISD::SETULT:
2843       case ISD::SETUGE:
2844         if (C != 0 && isLegalICmpImmediate(C-1)) {
2845           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2846           RHS = DAG.getConstant(C-1, MVT::i32);
2847         }
2848         break;
2849       case ISD::SETLE:
2850       case ISD::SETGT:
2851         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2852           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2853           RHS = DAG.getConstant(C+1, MVT::i32);
2854         }
2855         break;
2856       case ISD::SETULE:
2857       case ISD::SETUGT:
2858         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2859           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2860           RHS = DAG.getConstant(C+1, MVT::i32);
2861         }
2862         break;
2863       }
2864     }
2865   }
2866
2867   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2868   ARMISD::NodeType CompareType;
2869   switch (CondCode) {
2870   default:
2871     CompareType = ARMISD::CMP;
2872     break;
2873   case ARMCC::EQ:
2874   case ARMCC::NE:
2875     // Uses only Z Flag
2876     CompareType = ARMISD::CMPZ;
2877     break;
2878   }
2879   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2880   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2881 }
2882
2883 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2884 SDValue
2885 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2886                              DebugLoc dl) const {
2887   SDValue Cmp;
2888   if (!isFloatingPointZero(RHS))
2889     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2890   else
2891     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2892   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2893 }
2894
2895 /// duplicateCmp - Glue values can have only one use, so this function
2896 /// duplicates a comparison node.
2897 SDValue
2898 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2899   unsigned Opc = Cmp.getOpcode();
2900   DebugLoc DL = Cmp.getDebugLoc();
2901   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2902     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2903
2904   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2905   Cmp = Cmp.getOperand(0);
2906   Opc = Cmp.getOpcode();
2907   if (Opc == ARMISD::CMPFP)
2908     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2909   else {
2910     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2911     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2912   }
2913   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2914 }
2915
2916 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2917   SDValue Cond = Op.getOperand(0);
2918   SDValue SelectTrue = Op.getOperand(1);
2919   SDValue SelectFalse = Op.getOperand(2);
2920   DebugLoc dl = Op.getDebugLoc();
2921
2922   // Convert:
2923   //
2924   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2925   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2926   //
2927   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2928     const ConstantSDNode *CMOVTrue =
2929       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2930     const ConstantSDNode *CMOVFalse =
2931       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2932
2933     if (CMOVTrue && CMOVFalse) {
2934       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2935       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2936
2937       SDValue True;
2938       SDValue False;
2939       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2940         True = SelectTrue;
2941         False = SelectFalse;
2942       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2943         True = SelectFalse;
2944         False = SelectTrue;
2945       }
2946
2947       if (True.getNode() && False.getNode()) {
2948         EVT VT = Op.getValueType();
2949         SDValue ARMcc = Cond.getOperand(2);
2950         SDValue CCR = Cond.getOperand(3);
2951         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2952         assert(True.getValueType() == VT);
2953         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2954       }
2955     }
2956   }
2957
2958   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2959   // undefined bits before doing a full-word comparison with zero.
2960   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2961                      DAG.getConstant(1, Cond.getValueType()));
2962
2963   return DAG.getSelectCC(dl, Cond,
2964                          DAG.getConstant(0, Cond.getValueType()),
2965                          SelectTrue, SelectFalse, ISD::SETNE);
2966 }
2967
2968 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2969   EVT VT = Op.getValueType();
2970   SDValue LHS = Op.getOperand(0);
2971   SDValue RHS = Op.getOperand(1);
2972   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2973   SDValue TrueVal = Op.getOperand(2);
2974   SDValue FalseVal = Op.getOperand(3);
2975   DebugLoc dl = Op.getDebugLoc();
2976
2977   if (LHS.getValueType() == MVT::i32) {
2978     SDValue ARMcc;
2979     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2980     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2981     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2982   }
2983
2984   ARMCC::CondCodes CondCode, CondCode2;
2985   FPCCToARMCC(CC, CondCode, CondCode2);
2986
2987   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2988   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2989   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2990   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2991                                ARMcc, CCR, Cmp);
2992   if (CondCode2 != ARMCC::AL) {
2993     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2994     // FIXME: Needs another CMP because flag can have but one use.
2995     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2996     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2997                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2998   }
2999   return Result;
3000 }
3001
3002 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3003 /// to morph to an integer compare sequence.
3004 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3005                            const ARMSubtarget *Subtarget) {
3006   SDNode *N = Op.getNode();
3007   if (!N->hasOneUse())
3008     // Otherwise it requires moving the value from fp to integer registers.
3009     return false;
3010   if (!N->getNumValues())
3011     return false;
3012   EVT VT = Op.getValueType();
3013   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3014     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3015     // vmrs are very slow, e.g. cortex-a8.
3016     return false;
3017
3018   if (isFloatingPointZero(Op)) {
3019     SeenZero = true;
3020     return true;
3021   }
3022   return ISD::isNormalLoad(N);
3023 }
3024
3025 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3026   if (isFloatingPointZero(Op))
3027     return DAG.getConstant(0, MVT::i32);
3028
3029   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3030     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3031                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3032                        Ld->isVolatile(), Ld->isNonTemporal(),
3033                        Ld->isInvariant(), Ld->getAlignment());
3034
3035   llvm_unreachable("Unknown VFP cmp argument!");
3036 }
3037
3038 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3039                            SDValue &RetVal1, SDValue &RetVal2) {
3040   if (isFloatingPointZero(Op)) {
3041     RetVal1 = DAG.getConstant(0, MVT::i32);
3042     RetVal2 = DAG.getConstant(0, MVT::i32);
3043     return;
3044   }
3045
3046   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3047     SDValue Ptr = Ld->getBasePtr();
3048     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3049                           Ld->getChain(), Ptr,
3050                           Ld->getPointerInfo(),
3051                           Ld->isVolatile(), Ld->isNonTemporal(),
3052                           Ld->isInvariant(), Ld->getAlignment());
3053
3054     EVT PtrType = Ptr.getValueType();
3055     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3056     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3057                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3058     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3059                           Ld->getChain(), NewPtr,
3060                           Ld->getPointerInfo().getWithOffset(4),
3061                           Ld->isVolatile(), Ld->isNonTemporal(),
3062                           Ld->isInvariant(), NewAlign);
3063     return;
3064   }
3065
3066   llvm_unreachable("Unknown VFP cmp argument!");
3067 }
3068
3069 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3070 /// f32 and even f64 comparisons to integer ones.
3071 SDValue
3072 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3073   SDValue Chain = Op.getOperand(0);
3074   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3075   SDValue LHS = Op.getOperand(2);
3076   SDValue RHS = Op.getOperand(3);
3077   SDValue Dest = Op.getOperand(4);
3078   DebugLoc dl = Op.getDebugLoc();
3079
3080   bool LHSSeenZero = false;
3081   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3082   bool RHSSeenZero = false;
3083   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3084   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3085     // If unsafe fp math optimization is enabled and there are no other uses of
3086     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3087     // to an integer comparison.
3088     if (CC == ISD::SETOEQ)
3089       CC = ISD::SETEQ;
3090     else if (CC == ISD::SETUNE)
3091       CC = ISD::SETNE;
3092
3093     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3094     SDValue ARMcc;
3095     if (LHS.getValueType() == MVT::f32) {
3096       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3097                         bitcastf32Toi32(LHS, DAG), Mask);
3098       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3099                         bitcastf32Toi32(RHS, DAG), Mask);
3100       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3101       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3102       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3103                          Chain, Dest, ARMcc, CCR, Cmp);
3104     }
3105
3106     SDValue LHS1, LHS2;
3107     SDValue RHS1, RHS2;
3108     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3109     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3110     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3111     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3112     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3113     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3114     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3115     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3116     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3117   }
3118
3119   return SDValue();
3120 }
3121
3122 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3123   SDValue Chain = Op.getOperand(0);
3124   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3125   SDValue LHS = Op.getOperand(2);
3126   SDValue RHS = Op.getOperand(3);
3127   SDValue Dest = Op.getOperand(4);
3128   DebugLoc dl = Op.getDebugLoc();
3129
3130   if (LHS.getValueType() == MVT::i32) {
3131     SDValue ARMcc;
3132     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3133     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3134     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3135                        Chain, Dest, ARMcc, CCR, Cmp);
3136   }
3137
3138   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3139
3140   if (getTargetMachine().Options.UnsafeFPMath &&
3141       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3142        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3143     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3144     if (Result.getNode())
3145       return Result;
3146   }
3147
3148   ARMCC::CondCodes CondCode, CondCode2;
3149   FPCCToARMCC(CC, CondCode, CondCode2);
3150
3151   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3152   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3153   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3154   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3155   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3156   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3157   if (CondCode2 != ARMCC::AL) {
3158     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3159     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3160     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3161   }
3162   return Res;
3163 }
3164
3165 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3166   SDValue Chain = Op.getOperand(0);
3167   SDValue Table = Op.getOperand(1);
3168   SDValue Index = Op.getOperand(2);
3169   DebugLoc dl = Op.getDebugLoc();
3170
3171   EVT PTy = getPointerTy();
3172   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3173   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3174   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3175   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3176   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3177   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3178   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3179   if (Subtarget->isThumb2()) {
3180     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3181     // which does another jump to the destination. This also makes it easier
3182     // to translate it to TBB / TBH later.
3183     // FIXME: This might not work if the function is extremely large.
3184     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3185                        Addr, Op.getOperand(2), JTI, UId);
3186   }
3187   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3188     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3189                        MachinePointerInfo::getJumpTable(),
3190                        false, false, false, 0);
3191     Chain = Addr.getValue(1);
3192     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3193     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3194   } else {
3195     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3196                        MachinePointerInfo::getJumpTable(),
3197                        false, false, false, 0);
3198     Chain = Addr.getValue(1);
3199     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3200   }
3201 }
3202
3203 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3204   EVT VT = Op.getValueType();
3205   DebugLoc dl = Op.getDebugLoc();
3206
3207   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3208     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3209       return Op;
3210     return DAG.UnrollVectorOp(Op.getNode());
3211   }
3212
3213   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3214          "Invalid type for custom lowering!");
3215   if (VT != MVT::v4i16)
3216     return DAG.UnrollVectorOp(Op.getNode());
3217
3218   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3219   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3220 }
3221
3222 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3223   EVT VT = Op.getValueType();
3224   if (VT.isVector())
3225     return LowerVectorFP_TO_INT(Op, DAG);
3226
3227   DebugLoc dl = Op.getDebugLoc();
3228   unsigned Opc;
3229
3230   switch (Op.getOpcode()) {
3231   default: llvm_unreachable("Invalid opcode!");
3232   case ISD::FP_TO_SINT:
3233     Opc = ARMISD::FTOSI;
3234     break;
3235   case ISD::FP_TO_UINT:
3236     Opc = ARMISD::FTOUI;
3237     break;
3238   }
3239   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3240   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3241 }
3242
3243 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3244   EVT VT = Op.getValueType();
3245   DebugLoc dl = Op.getDebugLoc();
3246
3247   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3248     if (VT.getVectorElementType() == MVT::f32)
3249       return Op;
3250     return DAG.UnrollVectorOp(Op.getNode());
3251   }
3252
3253   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3254          "Invalid type for custom lowering!");
3255   if (VT != MVT::v4f32)
3256     return DAG.UnrollVectorOp(Op.getNode());
3257
3258   unsigned CastOpc;
3259   unsigned Opc;
3260   switch (Op.getOpcode()) {
3261   default: llvm_unreachable("Invalid opcode!");
3262   case ISD::SINT_TO_FP:
3263     CastOpc = ISD::SIGN_EXTEND;
3264     Opc = ISD::SINT_TO_FP;
3265     break;
3266   case ISD::UINT_TO_FP:
3267     CastOpc = ISD::ZERO_EXTEND;
3268     Opc = ISD::UINT_TO_FP;
3269     break;
3270   }
3271
3272   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3273   return DAG.getNode(Opc, dl, VT, Op);
3274 }
3275
3276 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3277   EVT VT = Op.getValueType();
3278   if (VT.isVector())
3279     return LowerVectorINT_TO_FP(Op, DAG);
3280
3281   DebugLoc dl = Op.getDebugLoc();
3282   unsigned Opc;
3283
3284   switch (Op.getOpcode()) {
3285   default: llvm_unreachable("Invalid opcode!");
3286   case ISD::SINT_TO_FP:
3287     Opc = ARMISD::SITOF;
3288     break;
3289   case ISD::UINT_TO_FP:
3290     Opc = ARMISD::UITOF;
3291     break;
3292   }
3293
3294   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3295   return DAG.getNode(Opc, dl, VT, Op);
3296 }
3297
3298 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3299   // Implement fcopysign with a fabs and a conditional fneg.
3300   SDValue Tmp0 = Op.getOperand(0);
3301   SDValue Tmp1 = Op.getOperand(1);
3302   DebugLoc dl = Op.getDebugLoc();
3303   EVT VT = Op.getValueType();
3304   EVT SrcVT = Tmp1.getValueType();
3305   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3306     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3307   bool UseNEON = !InGPR && Subtarget->hasNEON();
3308
3309   if (UseNEON) {
3310     // Use VBSL to copy the sign bit.
3311     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3312     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3313                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3314     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3315     if (VT == MVT::f64)
3316       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3317                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3318                          DAG.getConstant(32, MVT::i32));
3319     else /*if (VT == MVT::f32)*/
3320       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3321     if (SrcVT == MVT::f32) {
3322       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3323       if (VT == MVT::f64)
3324         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3325                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3326                            DAG.getConstant(32, MVT::i32));
3327     } else if (VT == MVT::f32)
3328       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3329                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3330                          DAG.getConstant(32, MVT::i32));
3331     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3332     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3333
3334     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3335                                             MVT::i32);
3336     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3337     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3338                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3339
3340     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3341                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3342                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3343     if (VT == MVT::f32) {
3344       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3345       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3346                         DAG.getConstant(0, MVT::i32));
3347     } else {
3348       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3349     }
3350
3351     return Res;
3352   }
3353
3354   // Bitcast operand 1 to i32.
3355   if (SrcVT == MVT::f64)
3356     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3357                        &Tmp1, 1).getValue(1);
3358   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3359
3360   // Or in the signbit with integer operations.
3361   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3362   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3363   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3364   if (VT == MVT::f32) {
3365     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3366                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3367     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3368                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3369   }
3370
3371   // f64: Or the high part with signbit and then combine two parts.
3372   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3373                      &Tmp0, 1);
3374   SDValue Lo = Tmp0.getValue(0);
3375   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3376   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3377   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3378 }
3379
3380 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3381   MachineFunction &MF = DAG.getMachineFunction();
3382   MachineFrameInfo *MFI = MF.getFrameInfo();
3383   MFI->setReturnAddressIsTaken(true);
3384
3385   EVT VT = Op.getValueType();
3386   DebugLoc dl = Op.getDebugLoc();
3387   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3388   if (Depth) {
3389     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3390     SDValue Offset = DAG.getConstant(4, MVT::i32);
3391     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3392                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3393                        MachinePointerInfo(), false, false, false, 0);
3394   }
3395
3396   // Return LR, which contains the return address. Mark it an implicit live-in.
3397   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3398   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3399 }
3400
3401 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3402   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3403   MFI->setFrameAddressIsTaken(true);
3404
3405   EVT VT = Op.getValueType();
3406   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3407   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3408   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3409     ? ARM::R7 : ARM::R11;
3410   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3411   while (Depth--)
3412     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3413                             MachinePointerInfo(),
3414                             false, false, false, 0);
3415   return FrameAddr;
3416 }
3417
3418 /// ExpandBITCAST - If the target supports VFP, this function is called to
3419 /// expand a bit convert where either the source or destination type is i64 to
3420 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3421 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3422 /// vectors), since the legalizer won't know what to do with that.
3423 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3425   DebugLoc dl = N->getDebugLoc();
3426   SDValue Op = N->getOperand(0);
3427
3428   // This function is only supposed to be called for i64 types, either as the
3429   // source or destination of the bit convert.
3430   EVT SrcVT = Op.getValueType();
3431   EVT DstVT = N->getValueType(0);
3432   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3433          "ExpandBITCAST called for non-i64 type");
3434
3435   // Turn i64->f64 into VMOVDRR.
3436   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3437     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3438                              DAG.getConstant(0, MVT::i32));
3439     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3440                              DAG.getConstant(1, MVT::i32));
3441     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3442                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3443   }
3444
3445   // Turn f64->i64 into VMOVRRD.
3446   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3447     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3448                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3449     // Merge the pieces into a single i64 value.
3450     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3451   }
3452
3453   return SDValue();
3454 }
3455
3456 /// getZeroVector - Returns a vector of specified type with all zero elements.
3457 /// Zero vectors are used to represent vector negation and in those cases
3458 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3459 /// not support i64 elements, so sometimes the zero vectors will need to be
3460 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3461 /// zero vector.
3462 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3463   assert(VT.isVector() && "Expected a vector type");
3464   // The canonical modified immediate encoding of a zero vector is....0!
3465   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3466   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3467   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3468   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3469 }
3470
3471 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3472 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3473 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3474                                                 SelectionDAG &DAG) const {
3475   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3476   EVT VT = Op.getValueType();
3477   unsigned VTBits = VT.getSizeInBits();
3478   DebugLoc dl = Op.getDebugLoc();
3479   SDValue ShOpLo = Op.getOperand(0);
3480   SDValue ShOpHi = Op.getOperand(1);
3481   SDValue ShAmt  = Op.getOperand(2);
3482   SDValue ARMcc;
3483   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3484
3485   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3486
3487   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3488                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3489   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3490   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3491                                    DAG.getConstant(VTBits, MVT::i32));
3492   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3493   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3494   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3495
3496   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3497   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3498                           ARMcc, DAG, dl);
3499   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3500   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3501                            CCR, Cmp);
3502
3503   SDValue Ops[2] = { Lo, Hi };
3504   return DAG.getMergeValues(Ops, 2, dl);
3505 }
3506
3507 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3508 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3509 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3510                                                SelectionDAG &DAG) const {
3511   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3512   EVT VT = Op.getValueType();
3513   unsigned VTBits = VT.getSizeInBits();
3514   DebugLoc dl = Op.getDebugLoc();
3515   SDValue ShOpLo = Op.getOperand(0);
3516   SDValue ShOpHi = Op.getOperand(1);
3517   SDValue ShAmt  = Op.getOperand(2);
3518   SDValue ARMcc;
3519
3520   assert(Op.getOpcode() == ISD::SHL_PARTS);
3521   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3522                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3523   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3524   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3525                                    DAG.getConstant(VTBits, MVT::i32));
3526   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3527   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3528
3529   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3530   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3531   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3532                           ARMcc, DAG, dl);
3533   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3534   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3535                            CCR, Cmp);
3536
3537   SDValue Ops[2] = { Lo, Hi };
3538   return DAG.getMergeValues(Ops, 2, dl);
3539 }
3540
3541 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3542                                             SelectionDAG &DAG) const {
3543   // The rounding mode is in bits 23:22 of the FPSCR.
3544   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3545   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3546   // so that the shift + and get folded into a bitfield extract.
3547   DebugLoc dl = Op.getDebugLoc();
3548   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3549                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3550                                               MVT::i32));
3551   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3552                                   DAG.getConstant(1U << 22, MVT::i32));
3553   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3554                               DAG.getConstant(22, MVT::i32));
3555   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3556                      DAG.getConstant(3, MVT::i32));
3557 }
3558
3559 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3560                          const ARMSubtarget *ST) {
3561   EVT VT = N->getValueType(0);
3562   DebugLoc dl = N->getDebugLoc();
3563
3564   if (!ST->hasV6T2Ops())
3565     return SDValue();
3566
3567   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3568   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3569 }
3570
3571 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3572 /// for each 16-bit element from operand, repeated.  The basic idea is to
3573 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3574 ///
3575 /// Trace for v4i16:
3576 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3577 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3578 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3579 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 
3580 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3581 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3582 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3583 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3584 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3585   EVT VT = N->getValueType(0);
3586   DebugLoc DL = N->getDebugLoc();
3587
3588   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3589   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3590   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3591   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3592   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3593   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3594 }
3595
3596 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3597 /// bit-count for each 16-bit element from the operand.  We need slightly
3598 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3599 /// 64/128-bit registers.
3600 /// 
3601 /// Trace for v4i16:
3602 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3603 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3604 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3605 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3606 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3607   EVT VT = N->getValueType(0);
3608   DebugLoc DL = N->getDebugLoc();
3609
3610   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3611   if (VT.is64BitVector()) {
3612     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3613     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3614                        DAG.getIntPtrConstant(0));
3615   } else {
3616     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3617                                     BitCounts, DAG.getIntPtrConstant(0));
3618     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3619   }
3620 }
3621
3622 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3623 /// bit-count for each 32-bit element from the operand.  The idea here is
3624 /// to split the vector into 16-bit elements, leverage the 16-bit count
3625 /// routine, and then combine the results.
3626 ///
3627 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3628 /// input    = [v0    v1    ] (vi: 32-bit elements)
3629 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3630 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3631 /// vrev: N0 = [k1 k0 k3 k2 ] 
3632 ///            [k0 k1 k2 k3 ]
3633 ///       N1 =+[k1 k0 k3 k2 ]
3634 ///            [k0 k2 k1 k3 ]
3635 ///       N2 =+[k1 k3 k0 k2 ]
3636 ///            [k0    k2    k1    k3    ]
3637 /// Extended =+[k1    k3    k0    k2    ]
3638 ///            [k0    k2    ]
3639 /// Extracted=+[k1    k3    ]
3640 ///
3641 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3642   EVT VT = N->getValueType(0);
3643   DebugLoc DL = N->getDebugLoc();
3644
3645   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3646
3647   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3648   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3649   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3650   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3651   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3652
3653   if (VT.is64BitVector()) {
3654     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3655     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3656                        DAG.getIntPtrConstant(0));
3657   } else {
3658     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3659                                     DAG.getIntPtrConstant(0));
3660     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3661   }
3662 }
3663
3664 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3665                           const ARMSubtarget *ST) {
3666   EVT VT = N->getValueType(0);
3667
3668   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3669   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3670           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3671          "Unexpected type for custom ctpop lowering");
3672
3673   if (VT.getVectorElementType() == MVT::i32)
3674     return lowerCTPOP32BitElements(N, DAG);
3675   else
3676     return lowerCTPOP16BitElements(N, DAG);
3677 }
3678
3679 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3680                           const ARMSubtarget *ST) {
3681   EVT VT = N->getValueType(0);
3682   DebugLoc dl = N->getDebugLoc();
3683
3684   if (!VT.isVector())
3685     return SDValue();
3686
3687   // Lower vector shifts on NEON to use VSHL.
3688   assert(ST->hasNEON() && "unexpected vector shift");
3689
3690   // Left shifts translate directly to the vshiftu intrinsic.
3691   if (N->getOpcode() == ISD::SHL)
3692     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3693                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3694                        N->getOperand(0), N->getOperand(1));
3695
3696   assert((N->getOpcode() == ISD::SRA ||
3697           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3698
3699   // NEON uses the same intrinsics for both left and right shifts.  For
3700   // right shifts, the shift amounts are negative, so negate the vector of
3701   // shift amounts.
3702   EVT ShiftVT = N->getOperand(1).getValueType();
3703   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3704                                      getZeroVector(ShiftVT, DAG, dl),
3705                                      N->getOperand(1));
3706   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3707                              Intrinsic::arm_neon_vshifts :
3708                              Intrinsic::arm_neon_vshiftu);
3709   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3710                      DAG.getConstant(vshiftInt, MVT::i32),
3711                      N->getOperand(0), NegatedCount);
3712 }
3713
3714 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3715                                 const ARMSubtarget *ST) {
3716   EVT VT = N->getValueType(0);
3717   DebugLoc dl = N->getDebugLoc();
3718
3719   // We can get here for a node like i32 = ISD::SHL i32, i64
3720   if (VT != MVT::i64)
3721     return SDValue();
3722
3723   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3724          "Unknown shift to lower!");
3725
3726   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3727   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3728       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3729     return SDValue();
3730
3731   // If we are in thumb mode, we don't have RRX.
3732   if (ST->isThumb1Only()) return SDValue();
3733
3734   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3735   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3736                            DAG.getConstant(0, MVT::i32));
3737   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3738                            DAG.getConstant(1, MVT::i32));
3739
3740   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3741   // captures the result into a carry flag.
3742   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3743   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3744
3745   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3746   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3747
3748   // Merge the pieces into a single i64 value.
3749  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3750 }
3751
3752 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3753   SDValue TmpOp0, TmpOp1;
3754   bool Invert = false;
3755   bool Swap = false;
3756   unsigned Opc = 0;
3757
3758   SDValue Op0 = Op.getOperand(0);
3759   SDValue Op1 = Op.getOperand(1);
3760   SDValue CC = Op.getOperand(2);
3761   EVT VT = Op.getValueType();
3762   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3763   DebugLoc dl = Op.getDebugLoc();
3764
3765   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3766     switch (SetCCOpcode) {
3767     default: llvm_unreachable("Illegal FP comparison");
3768     case ISD::SETUNE:
3769     case ISD::SETNE:  Invert = true; // Fallthrough
3770     case ISD::SETOEQ:
3771     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3772     case ISD::SETOLT:
3773     case ISD::SETLT: Swap = true; // Fallthrough
3774     case ISD::SETOGT:
3775     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3776     case ISD::SETOLE:
3777     case ISD::SETLE:  Swap = true; // Fallthrough
3778     case ISD::SETOGE:
3779     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3780     case ISD::SETUGE: Swap = true; // Fallthrough
3781     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3782     case ISD::SETUGT: Swap = true; // Fallthrough
3783     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3784     case ISD::SETUEQ: Invert = true; // Fallthrough
3785     case ISD::SETONE:
3786       // Expand this to (OLT | OGT).
3787       TmpOp0 = Op0;
3788       TmpOp1 = Op1;
3789       Opc = ISD::OR;
3790       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3791       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3792       break;
3793     case ISD::SETUO: Invert = true; // Fallthrough
3794     case ISD::SETO:
3795       // Expand this to (OLT | OGE).
3796       TmpOp0 = Op0;
3797       TmpOp1 = Op1;
3798       Opc = ISD::OR;
3799       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3800       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3801       break;
3802     }
3803   } else {
3804     // Integer comparisons.
3805     switch (SetCCOpcode) {
3806     default: llvm_unreachable("Illegal integer comparison");
3807     case ISD::SETNE:  Invert = true;
3808     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3809     case ISD::SETLT:  Swap = true;
3810     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3811     case ISD::SETLE:  Swap = true;
3812     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3813     case ISD::SETULT: Swap = true;
3814     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3815     case ISD::SETULE: Swap = true;
3816     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3817     }
3818
3819     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3820     if (Opc == ARMISD::VCEQ) {
3821
3822       SDValue AndOp;
3823       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3824         AndOp = Op0;
3825       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3826         AndOp = Op1;
3827
3828       // Ignore bitconvert.
3829       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3830         AndOp = AndOp.getOperand(0);
3831
3832       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3833         Opc = ARMISD::VTST;
3834         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3835         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3836         Invert = !Invert;
3837       }
3838     }
3839   }
3840
3841   if (Swap)
3842     std::swap(Op0, Op1);
3843
3844   // If one of the operands is a constant vector zero, attempt to fold the
3845   // comparison to a specialized compare-against-zero form.
3846   SDValue SingleOp;
3847   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3848     SingleOp = Op0;
3849   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3850     if (Opc == ARMISD::VCGE)
3851       Opc = ARMISD::VCLEZ;
3852     else if (Opc == ARMISD::VCGT)
3853       Opc = ARMISD::VCLTZ;
3854     SingleOp = Op1;
3855   }
3856
3857   SDValue Result;
3858   if (SingleOp.getNode()) {
3859     switch (Opc) {
3860     case ARMISD::VCEQ:
3861       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3862     case ARMISD::VCGE:
3863       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3864     case ARMISD::VCLEZ:
3865       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3866     case ARMISD::VCGT:
3867       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3868     case ARMISD::VCLTZ:
3869       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3870     default:
3871       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3872     }
3873   } else {
3874      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3875   }
3876
3877   if (Invert)
3878     Result = DAG.getNOT(dl, Result, VT);
3879
3880   return Result;
3881 }
3882
3883 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3884 /// valid vector constant for a NEON instruction with a "modified immediate"
3885 /// operand (e.g., VMOV).  If so, return the encoded value.
3886 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3887                                  unsigned SplatBitSize, SelectionDAG &DAG,
3888                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3889   unsigned OpCmode, Imm;
3890
3891   // SplatBitSize is set to the smallest size that splats the vector, so a
3892   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3893   // immediate instructions others than VMOV do not support the 8-bit encoding
3894   // of a zero vector, and the default encoding of zero is supposed to be the
3895   // 32-bit version.
3896   if (SplatBits == 0)
3897     SplatBitSize = 32;
3898
3899   switch (SplatBitSize) {
3900   case 8:
3901     if (type != VMOVModImm)
3902       return SDValue();
3903     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3904     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3905     OpCmode = 0xe;
3906     Imm = SplatBits;
3907     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3908     break;
3909
3910   case 16:
3911     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3912     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3913     if ((SplatBits & ~0xff) == 0) {
3914       // Value = 0x00nn: Op=x, Cmode=100x.
3915       OpCmode = 0x8;
3916       Imm = SplatBits;
3917       break;
3918     }
3919     if ((SplatBits & ~0xff00) == 0) {
3920       // Value = 0xnn00: Op=x, Cmode=101x.
3921       OpCmode = 0xa;
3922       Imm = SplatBits >> 8;
3923       break;
3924     }
3925     return SDValue();
3926
3927   case 32:
3928     // NEON's 32-bit VMOV supports splat values where:
3929     // * only one byte is nonzero, or
3930     // * the least significant byte is 0xff and the second byte is nonzero, or
3931     // * the least significant 2 bytes are 0xff and the third is nonzero.
3932     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3933     if ((SplatBits & ~0xff) == 0) {
3934       // Value = 0x000000nn: Op=x, Cmode=000x.
3935       OpCmode = 0;
3936       Imm = SplatBits;
3937       break;
3938     }
3939     if ((SplatBits & ~0xff00) == 0) {
3940       // Value = 0x0000nn00: Op=x, Cmode=001x.
3941       OpCmode = 0x2;
3942       Imm = SplatBits >> 8;
3943       break;
3944     }
3945     if ((SplatBits & ~0xff0000) == 0) {
3946       // Value = 0x00nn0000: Op=x, Cmode=010x.
3947       OpCmode = 0x4;
3948       Imm = SplatBits >> 16;
3949       break;
3950     }
3951     if ((SplatBits & ~0xff000000) == 0) {
3952       // Value = 0xnn000000: Op=x, Cmode=011x.
3953       OpCmode = 0x6;
3954       Imm = SplatBits >> 24;
3955       break;
3956     }
3957
3958     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3959     if (type == OtherModImm) return SDValue();
3960
3961     if ((SplatBits & ~0xffff) == 0 &&
3962         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3963       // Value = 0x0000nnff: Op=x, Cmode=1100.
3964       OpCmode = 0xc;
3965       Imm = SplatBits >> 8;
3966       SplatBits |= 0xff;
3967       break;
3968     }
3969
3970     if ((SplatBits & ~0xffffff) == 0 &&
3971         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3972       // Value = 0x00nnffff: Op=x, Cmode=1101.
3973       OpCmode = 0xd;
3974       Imm = SplatBits >> 16;
3975       SplatBits |= 0xffff;
3976       break;
3977     }
3978
3979     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3980     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3981     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3982     // and fall through here to test for a valid 64-bit splat.  But, then the
3983     // caller would also need to check and handle the change in size.
3984     return SDValue();
3985
3986   case 64: {
3987     if (type != VMOVModImm)
3988       return SDValue();
3989     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3990     uint64_t BitMask = 0xff;
3991     uint64_t Val = 0;
3992     unsigned ImmMask = 1;
3993     Imm = 0;
3994     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3995       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3996         Val |= BitMask;
3997         Imm |= ImmMask;
3998       } else if ((SplatBits & BitMask) != 0) {
3999         return SDValue();
4000       }
4001       BitMask <<= 8;
4002       ImmMask <<= 1;
4003     }
4004     // Op=1, Cmode=1110.
4005     OpCmode = 0x1e;
4006     SplatBits = Val;
4007     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4008     break;
4009   }
4010
4011   default:
4012     llvm_unreachable("unexpected size for isNEONModifiedImm");
4013   }
4014
4015   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4016   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4017 }
4018
4019 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4020                                            const ARMSubtarget *ST) const {
4021   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4022     return SDValue();
4023
4024   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4025   assert(Op.getValueType() == MVT::f32 &&
4026          "ConstantFP custom lowering should only occur for f32.");
4027
4028   // Try splatting with a VMOV.f32...
4029   APFloat FPVal = CFP->getValueAPF();
4030   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4031   if (ImmVal != -1) {
4032     DebugLoc DL = Op.getDebugLoc();
4033     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4034     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4035                                       NewVal);
4036     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4037                        DAG.getConstant(0, MVT::i32));
4038   }
4039
4040   // If that fails, try a VMOV.i32
4041   EVT VMovVT;
4042   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4043   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4044                                      VMOVModImm);
4045   if (NewVal != SDValue()) {
4046     DebugLoc DL = Op.getDebugLoc();
4047     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4048                                       NewVal);
4049     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4050                                        VecConstant);
4051     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4052                        DAG.getConstant(0, MVT::i32));
4053   }
4054
4055   // Finally, try a VMVN.i32
4056   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4057                              VMVNModImm);
4058   if (NewVal != SDValue()) {
4059     DebugLoc DL = Op.getDebugLoc();
4060     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4061     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4062                                        VecConstant);
4063     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4064                        DAG.getConstant(0, MVT::i32));
4065   }
4066
4067   return SDValue();
4068 }
4069
4070 // check if an VEXT instruction can handle the shuffle mask when the
4071 // vector sources of the shuffle are the same.
4072 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4073   unsigned NumElts = VT.getVectorNumElements();
4074
4075   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4076   if (M[0] < 0)
4077     return false;
4078
4079   Imm = M[0];
4080
4081   // If this is a VEXT shuffle, the immediate value is the index of the first
4082   // element.  The other shuffle indices must be the successive elements after
4083   // the first one.
4084   unsigned ExpectedElt = Imm;
4085   for (unsigned i = 1; i < NumElts; ++i) {
4086     // Increment the expected index.  If it wraps around, just follow it
4087     // back to index zero and keep going.
4088     ++ExpectedElt;
4089     if (ExpectedElt == NumElts)
4090       ExpectedElt = 0;
4091
4092     if (M[i] < 0) continue; // ignore UNDEF indices
4093     if (ExpectedElt != static_cast<unsigned>(M[i]))
4094       return false;
4095   }
4096
4097   return true;
4098 }
4099
4100
4101 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4102                        bool &ReverseVEXT, unsigned &Imm) {
4103   unsigned NumElts = VT.getVectorNumElements();
4104   ReverseVEXT = false;
4105
4106   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4107   if (M[0] < 0)
4108     return false;
4109
4110   Imm = M[0];
4111
4112   // If this is a VEXT shuffle, the immediate value is the index of the first
4113   // element.  The other shuffle indices must be the successive elements after
4114   // the first one.
4115   unsigned ExpectedElt = Imm;
4116   for (unsigned i = 1; i < NumElts; ++i) {
4117     // Increment the expected index.  If it wraps around, it may still be
4118     // a VEXT but the source vectors must be swapped.
4119     ExpectedElt += 1;
4120     if (ExpectedElt == NumElts * 2) {
4121       ExpectedElt = 0;
4122       ReverseVEXT = true;
4123     }
4124
4125     if (M[i] < 0) continue; // ignore UNDEF indices
4126     if (ExpectedElt != static_cast<unsigned>(M[i]))
4127       return false;
4128   }
4129
4130   // Adjust the index value if the source operands will be swapped.
4131   if (ReverseVEXT)
4132     Imm -= NumElts;
4133
4134   return true;
4135 }
4136
4137 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4138 /// instruction with the specified blocksize.  (The order of the elements
4139 /// within each block of the vector is reversed.)
4140 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4141   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4142          "Only possible block sizes for VREV are: 16, 32, 64");
4143
4144   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4145   if (EltSz == 64)
4146     return false;
4147
4148   unsigned NumElts = VT.getVectorNumElements();
4149   unsigned BlockElts = M[0] + 1;
4150   // If the first shuffle index is UNDEF, be optimistic.
4151   if (M[0] < 0)
4152     BlockElts = BlockSize / EltSz;
4153
4154   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4155     return false;
4156
4157   for (unsigned i = 0; i < NumElts; ++i) {
4158     if (M[i] < 0) continue; // ignore UNDEF indices
4159     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4160       return false;
4161   }
4162
4163   return true;
4164 }
4165
4166 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4167   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4168   // range, then 0 is placed into the resulting vector. So pretty much any mask
4169   // of 8 elements can work here.
4170   return VT == MVT::v8i8 && M.size() == 8;
4171 }
4172
4173 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4174   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4175   if (EltSz == 64)
4176     return false;
4177
4178   unsigned NumElts = VT.getVectorNumElements();
4179   WhichResult = (M[0] == 0 ? 0 : 1);
4180   for (unsigned i = 0; i < NumElts; i += 2) {
4181     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4182         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4183       return false;
4184   }
4185   return true;
4186 }
4187
4188 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4189 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4190 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4191 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4192   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4193   if (EltSz == 64)
4194     return false;
4195
4196   unsigned NumElts = VT.getVectorNumElements();
4197   WhichResult = (M[0] == 0 ? 0 : 1);
4198   for (unsigned i = 0; i < NumElts; i += 2) {
4199     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4200         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4201       return false;
4202   }
4203   return true;
4204 }
4205
4206 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4207   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4208   if (EltSz == 64)
4209     return false;
4210
4211   unsigned NumElts = VT.getVectorNumElements();
4212   WhichResult = (M[0] == 0 ? 0 : 1);
4213   for (unsigned i = 0; i != NumElts; ++i) {
4214     if (M[i] < 0) continue; // ignore UNDEF indices
4215     if ((unsigned) M[i] != 2 * i + WhichResult)
4216       return false;
4217   }
4218
4219   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4220   if (VT.is64BitVector() && EltSz == 32)
4221     return false;
4222
4223   return true;
4224 }
4225
4226 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4227 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4228 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4229 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4230   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4231   if (EltSz == 64)
4232     return false;
4233
4234   unsigned Half = VT.getVectorNumElements() / 2;
4235   WhichResult = (M[0] == 0 ? 0 : 1);
4236   for (unsigned j = 0; j != 2; ++j) {
4237     unsigned Idx = WhichResult;
4238     for (unsigned i = 0; i != Half; ++i) {
4239       int MIdx = M[i + j * Half];
4240       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4241         return false;
4242       Idx += 2;
4243     }
4244   }
4245
4246   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4247   if (VT.is64BitVector() && EltSz == 32)
4248     return false;
4249
4250   return true;
4251 }
4252
4253 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4254   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4255   if (EltSz == 64)
4256     return false;
4257
4258   unsigned NumElts = VT.getVectorNumElements();
4259   WhichResult = (M[0] == 0 ? 0 : 1);
4260   unsigned Idx = WhichResult * NumElts / 2;
4261   for (unsigned i = 0; i != NumElts; i += 2) {
4262     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4263         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4264       return false;
4265     Idx += 1;
4266   }
4267
4268   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4269   if (VT.is64BitVector() && EltSz == 32)
4270     return false;
4271
4272   return true;
4273 }
4274
4275 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4276 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4277 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4278 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4279   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4280   if (EltSz == 64)
4281     return false;
4282
4283   unsigned NumElts = VT.getVectorNumElements();
4284   WhichResult = (M[0] == 0 ? 0 : 1);
4285   unsigned Idx = WhichResult * NumElts / 2;
4286   for (unsigned i = 0; i != NumElts; i += 2) {
4287     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4288         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4289       return false;
4290     Idx += 1;
4291   }
4292
4293   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4294   if (VT.is64BitVector() && EltSz == 32)
4295     return false;
4296
4297   return true;
4298 }
4299
4300 /// \return true if this is a reverse operation on an vector.
4301 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4302   unsigned NumElts = VT.getVectorNumElements();
4303   // Make sure the mask has the right size.
4304   if (NumElts != M.size())
4305       return false;
4306
4307   // Look for <15, ..., 3, -1, 1, 0>.
4308   for (unsigned i = 0; i != NumElts; ++i)
4309     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4310       return false;
4311
4312   return true;
4313 }
4314
4315 // If N is an integer constant that can be moved into a register in one
4316 // instruction, return an SDValue of such a constant (will become a MOV
4317 // instruction).  Otherwise return null.
4318 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4319                                      const ARMSubtarget *ST, DebugLoc dl) {
4320   uint64_t Val;
4321   if (!isa<ConstantSDNode>(N))
4322     return SDValue();
4323   Val = cast<ConstantSDNode>(N)->getZExtValue();
4324
4325   if (ST->isThumb1Only()) {
4326     if (Val <= 255 || ~Val <= 255)
4327       return DAG.getConstant(Val, MVT::i32);
4328   } else {
4329     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4330       return DAG.getConstant(Val, MVT::i32);
4331   }
4332   return SDValue();
4333 }
4334
4335 // If this is a case we can't handle, return null and let the default
4336 // expansion code take care of it.
4337 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4338                                              const ARMSubtarget *ST) const {
4339   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4340   DebugLoc dl = Op.getDebugLoc();
4341   EVT VT = Op.getValueType();
4342
4343   APInt SplatBits, SplatUndef;
4344   unsigned SplatBitSize;
4345   bool HasAnyUndefs;
4346   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4347     if (SplatBitSize <= 64) {
4348       // Check if an immediate VMOV works.
4349       EVT VmovVT;
4350       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4351                                       SplatUndef.getZExtValue(), SplatBitSize,
4352                                       DAG, VmovVT, VT.is128BitVector(),
4353                                       VMOVModImm);
4354       if (Val.getNode()) {
4355         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4356         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4357       }
4358
4359       // Try an immediate VMVN.
4360       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4361       Val = isNEONModifiedImm(NegatedImm,
4362                                       SplatUndef.getZExtValue(), SplatBitSize,
4363                                       DAG, VmovVT, VT.is128BitVector(),
4364                                       VMVNModImm);
4365       if (Val.getNode()) {
4366         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4367         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4368       }
4369
4370       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4371       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4372         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4373         if (ImmVal != -1) {
4374           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4375           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4376         }
4377       }
4378     }
4379   }
4380
4381   // Scan through the operands to see if only one value is used.
4382   //
4383   // As an optimisation, even if more than one value is used it may be more
4384   // profitable to splat with one value then change some lanes.
4385   //
4386   // Heuristically we decide to do this if the vector has a "dominant" value,
4387   // defined as splatted to more than half of the lanes.
4388   unsigned NumElts = VT.getVectorNumElements();
4389   bool isOnlyLowElement = true;
4390   bool usesOnlyOneValue = true;
4391   bool hasDominantValue = false;
4392   bool isConstant = true;
4393
4394   // Map of the number of times a particular SDValue appears in the
4395   // element list.
4396   DenseMap<SDValue, unsigned> ValueCounts;
4397   SDValue Value;
4398   for (unsigned i = 0; i < NumElts; ++i) {
4399     SDValue V = Op.getOperand(i);
4400     if (V.getOpcode() == ISD::UNDEF)
4401       continue;
4402     if (i > 0)
4403       isOnlyLowElement = false;
4404     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4405       isConstant = false;
4406
4407     ValueCounts.insert(std::make_pair(V, 0));
4408     unsigned &Count = ValueCounts[V];
4409     
4410     // Is this value dominant? (takes up more than half of the lanes)
4411     if (++Count > (NumElts / 2)) {
4412       hasDominantValue = true;
4413       Value = V;
4414     }
4415   }
4416   if (ValueCounts.size() != 1)
4417     usesOnlyOneValue = false;
4418   if (!Value.getNode() && ValueCounts.size() > 0)
4419     Value = ValueCounts.begin()->first;
4420
4421   if (ValueCounts.size() == 0)
4422     return DAG.getUNDEF(VT);
4423
4424   if (isOnlyLowElement)
4425     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4426
4427   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4428
4429   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4430   // i32 and try again.
4431   if (hasDominantValue && EltSize <= 32) {
4432     if (!isConstant) {
4433       SDValue N;
4434
4435       // If we are VDUPing a value that comes directly from a vector, that will
4436       // cause an unnecessary move to and from a GPR, where instead we could
4437       // just use VDUPLANE.
4438       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4439         // We need to create a new undef vector to use for the VDUPLANE if the
4440         // size of the vector from which we get the value is different than the
4441         // size of the vector that we need to create. We will insert the element
4442         // such that the register coalescer will remove unnecessary copies.
4443         if (VT != Value->getOperand(0).getValueType()) {
4444           ConstantSDNode *constIndex;
4445           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4446           assert(constIndex && "The index is not a constant!");
4447           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4448                              VT.getVectorNumElements();
4449           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4450                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4451                         Value, DAG.getConstant(index, MVT::i32)),
4452                            DAG.getConstant(index, MVT::i32));
4453         } else {
4454           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4455                         Value->getOperand(0), Value->getOperand(1));
4456         }
4457       }
4458       else
4459         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4460
4461       if (!usesOnlyOneValue) {
4462         // The dominant value was splatted as 'N', but we now have to insert
4463         // all differing elements.
4464         for (unsigned I = 0; I < NumElts; ++I) {
4465           if (Op.getOperand(I) == Value)
4466             continue;
4467           SmallVector<SDValue, 3> Ops;
4468           Ops.push_back(N);
4469           Ops.push_back(Op.getOperand(I));
4470           Ops.push_back(DAG.getConstant(I, MVT::i32));
4471           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4472         }
4473       }
4474       return N;
4475     }
4476     if (VT.getVectorElementType().isFloatingPoint()) {
4477       SmallVector<SDValue, 8> Ops;
4478       for (unsigned i = 0; i < NumElts; ++i)
4479         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4480                                   Op.getOperand(i)));
4481       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4482       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4483       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4484       if (Val.getNode())
4485         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4486     }
4487     if (usesOnlyOneValue) {
4488       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4489       if (isConstant && Val.getNode())
4490         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4491     }
4492   }
4493
4494   // If all elements are constants and the case above didn't get hit, fall back
4495   // to the default expansion, which will generate a load from the constant
4496   // pool.
4497   if (isConstant)
4498     return SDValue();
4499
4500   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4501   if (NumElts >= 4) {
4502     SDValue shuffle = ReconstructShuffle(Op, DAG);
4503     if (shuffle != SDValue())
4504       return shuffle;
4505   }
4506
4507   // Vectors with 32- or 64-bit elements can be built by directly assigning
4508   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4509   // will be legalized.
4510   if (EltSize >= 32) {
4511     // Do the expansion with floating-point types, since that is what the VFP
4512     // registers are defined to use, and since i64 is not legal.
4513     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4514     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4515     SmallVector<SDValue, 8> Ops;
4516     for (unsigned i = 0; i < NumElts; ++i)
4517       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4518     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4519     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4520   }
4521
4522   return SDValue();
4523 }
4524
4525 // Gather data to see if the operation can be modelled as a
4526 // shuffle in combination with VEXTs.
4527 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4528                                               SelectionDAG &DAG) const {
4529   DebugLoc dl = Op.getDebugLoc();
4530   EVT VT = Op.getValueType();
4531   unsigned NumElts = VT.getVectorNumElements();
4532
4533   SmallVector<SDValue, 2> SourceVecs;
4534   SmallVector<unsigned, 2> MinElts;
4535   SmallVector<unsigned, 2> MaxElts;
4536
4537   for (unsigned i = 0; i < NumElts; ++i) {
4538     SDValue V = Op.getOperand(i);
4539     if (V.getOpcode() == ISD::UNDEF)
4540       continue;
4541     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4542       // A shuffle can only come from building a vector from various
4543       // elements of other vectors.
4544       return SDValue();
4545     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4546                VT.getVectorElementType()) {
4547       // This code doesn't know how to handle shuffles where the vector
4548       // element types do not match (this happens because type legalization
4549       // promotes the return type of EXTRACT_VECTOR_ELT).
4550       // FIXME: It might be appropriate to extend this code to handle
4551       // mismatched types.
4552       return SDValue();
4553     }
4554
4555     // Record this extraction against the appropriate vector if possible...
4556     SDValue SourceVec = V.getOperand(0);
4557     // If the element number isn't a constant, we can't effectively
4558     // analyze what's going on.
4559     if (!isa<ConstantSDNode>(V.getOperand(1)))
4560       return SDValue();
4561     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4562     bool FoundSource = false;
4563     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4564       if (SourceVecs[j] == SourceVec) {
4565         if (MinElts[j] > EltNo)
4566           MinElts[j] = EltNo;
4567         if (MaxElts[j] < EltNo)
4568           MaxElts[j] = EltNo;
4569         FoundSource = true;
4570         break;
4571       }
4572     }
4573
4574     // Or record a new source if not...
4575     if (!FoundSource) {
4576       SourceVecs.push_back(SourceVec);
4577       MinElts.push_back(EltNo);
4578       MaxElts.push_back(EltNo);
4579     }
4580   }
4581
4582   // Currently only do something sane when at most two source vectors
4583   // involved.
4584   if (SourceVecs.size() > 2)
4585     return SDValue();
4586
4587   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4588   int VEXTOffsets[2] = {0, 0};
4589
4590   // This loop extracts the usage patterns of the source vectors
4591   // and prepares appropriate SDValues for a shuffle if possible.
4592   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4593     if (SourceVecs[i].getValueType() == VT) {
4594       // No VEXT necessary
4595       ShuffleSrcs[i] = SourceVecs[i];
4596       VEXTOffsets[i] = 0;
4597       continue;
4598     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4599       // It probably isn't worth padding out a smaller vector just to
4600       // break it down again in a shuffle.
4601       return SDValue();
4602     }
4603
4604     // Since only 64-bit and 128-bit vectors are legal on ARM and
4605     // we've eliminated the other cases...
4606     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4607            "unexpected vector sizes in ReconstructShuffle");
4608
4609     if (MaxElts[i] - MinElts[i] >= NumElts) {
4610       // Span too large for a VEXT to cope
4611       return SDValue();
4612     }
4613
4614     if (MinElts[i] >= NumElts) {
4615       // The extraction can just take the second half
4616       VEXTOffsets[i] = NumElts;
4617       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4618                                    SourceVecs[i],
4619                                    DAG.getIntPtrConstant(NumElts));
4620     } else if (MaxElts[i] < NumElts) {
4621       // The extraction can just take the first half
4622       VEXTOffsets[i] = 0;
4623       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4624                                    SourceVecs[i],
4625                                    DAG.getIntPtrConstant(0));
4626     } else {
4627       // An actual VEXT is needed
4628       VEXTOffsets[i] = MinElts[i];
4629       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4630                                      SourceVecs[i],
4631                                      DAG.getIntPtrConstant(0));
4632       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4633                                      SourceVecs[i],
4634                                      DAG.getIntPtrConstant(NumElts));
4635       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4636                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4637     }
4638   }
4639
4640   SmallVector<int, 8> Mask;
4641
4642   for (unsigned i = 0; i < NumElts; ++i) {
4643     SDValue Entry = Op.getOperand(i);
4644     if (Entry.getOpcode() == ISD::UNDEF) {
4645       Mask.push_back(-1);
4646       continue;
4647     }
4648
4649     SDValue ExtractVec = Entry.getOperand(0);
4650     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4651                                           .getOperand(1))->getSExtValue();
4652     if (ExtractVec == SourceVecs[0]) {
4653       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4654     } else {
4655       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4656     }
4657   }
4658
4659   // Final check before we try to produce nonsense...
4660   if (isShuffleMaskLegal(Mask, VT))
4661     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4662                                 &Mask[0]);
4663
4664   return SDValue();
4665 }
4666
4667 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4668 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4669 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4670 /// are assumed to be legal.
4671 bool
4672 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4673                                       EVT VT) const {
4674   if (VT.getVectorNumElements() == 4 &&
4675       (VT.is128BitVector() || VT.is64BitVector())) {
4676     unsigned PFIndexes[4];
4677     for (unsigned i = 0; i != 4; ++i) {
4678       if (M[i] < 0)
4679         PFIndexes[i] = 8;
4680       else
4681         PFIndexes[i] = M[i];
4682     }
4683
4684     // Compute the index in the perfect shuffle table.
4685     unsigned PFTableIndex =
4686       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4687     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4688     unsigned Cost = (PFEntry >> 30);
4689
4690     if (Cost <= 4)
4691       return true;
4692   }
4693
4694   bool ReverseVEXT;
4695   unsigned Imm, WhichResult;
4696
4697   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4698   return (EltSize >= 32 ||
4699           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4700           isVREVMask(M, VT, 64) ||
4701           isVREVMask(M, VT, 32) ||
4702           isVREVMask(M, VT, 16) ||
4703           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4704           isVTBLMask(M, VT) ||
4705           isVTRNMask(M, VT, WhichResult) ||
4706           isVUZPMask(M, VT, WhichResult) ||
4707           isVZIPMask(M, VT, WhichResult) ||
4708           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4709           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4710           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4711           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4712 }
4713
4714 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4715 /// the specified operations to build the shuffle.
4716 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4717                                       SDValue RHS, SelectionDAG &DAG,
4718                                       DebugLoc dl) {
4719   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4720   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4721   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4722
4723   enum {
4724     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4725     OP_VREV,
4726     OP_VDUP0,
4727     OP_VDUP1,
4728     OP_VDUP2,
4729     OP_VDUP3,
4730     OP_VEXT1,
4731     OP_VEXT2,
4732     OP_VEXT3,
4733     OP_VUZPL, // VUZP, left result
4734     OP_VUZPR, // VUZP, right result
4735     OP_VZIPL, // VZIP, left result
4736     OP_VZIPR, // VZIP, right result
4737     OP_VTRNL, // VTRN, left result
4738     OP_VTRNR  // VTRN, right result
4739   };
4740
4741   if (OpNum == OP_COPY) {
4742     if (LHSID == (1*9+2)*9+3) return LHS;
4743     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4744     return RHS;
4745   }
4746
4747   SDValue OpLHS, OpRHS;
4748   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4749   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4750   EVT VT = OpLHS.getValueType();
4751
4752   switch (OpNum) {
4753   default: llvm_unreachable("Unknown shuffle opcode!");
4754   case OP_VREV:
4755     // VREV divides the vector in half and swaps within the half.
4756     if (VT.getVectorElementType() == MVT::i32 ||
4757         VT.getVectorElementType() == MVT::f32)
4758       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4759     // vrev <4 x i16> -> VREV32
4760     if (VT.getVectorElementType() == MVT::i16)
4761       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4762     // vrev <4 x i8> -> VREV16
4763     assert(VT.getVectorElementType() == MVT::i8);
4764     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4765   case OP_VDUP0:
4766   case OP_VDUP1:
4767   case OP_VDUP2:
4768   case OP_VDUP3:
4769     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4770                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4771   case OP_VEXT1:
4772   case OP_VEXT2:
4773   case OP_VEXT3:
4774     return DAG.getNode(ARMISD::VEXT, dl, VT,
4775                        OpLHS, OpRHS,
4776                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4777   case OP_VUZPL:
4778   case OP_VUZPR:
4779     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4780                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4781   case OP_VZIPL:
4782   case OP_VZIPR:
4783     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4784                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4785   case OP_VTRNL:
4786   case OP_VTRNR:
4787     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4788                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4789   }
4790 }
4791
4792 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4793                                        ArrayRef<int> ShuffleMask,
4794                                        SelectionDAG &DAG) {
4795   // Check to see if we can use the VTBL instruction.
4796   SDValue V1 = Op.getOperand(0);
4797   SDValue V2 = Op.getOperand(1);
4798   DebugLoc DL = Op.getDebugLoc();
4799
4800   SmallVector<SDValue, 8> VTBLMask;
4801   for (ArrayRef<int>::iterator
4802          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4803     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4804
4805   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4806     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4807                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4808                                    &VTBLMask[0], 8));
4809
4810   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4811                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4812                                  &VTBLMask[0], 8));
4813 }
4814
4815 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4816                                                       SelectionDAG &DAG) {
4817   DebugLoc DL = Op.getDebugLoc();
4818   SDValue OpLHS = Op.getOperand(0);
4819   EVT VT = OpLHS.getValueType();
4820
4821   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4822          "Expect an v8i16/v16i8 type");
4823   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4824   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4825   // extract the first 8 bytes into the top double word and the last 8 bytes
4826   // into the bottom double word. The v8i16 case is similar.
4827   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4828   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4829                      DAG.getConstant(ExtractNum, MVT::i32));
4830 }
4831
4832 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4833   SDValue V1 = Op.getOperand(0);
4834   SDValue V2 = Op.getOperand(1);
4835   DebugLoc dl = Op.getDebugLoc();
4836   EVT VT = Op.getValueType();
4837   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4838
4839   // Convert shuffles that are directly supported on NEON to target-specific
4840   // DAG nodes, instead of keeping them as shuffles and matching them again
4841   // during code selection.  This is more efficient and avoids the possibility
4842   // of inconsistencies between legalization and selection.
4843   // FIXME: floating-point vectors should be canonicalized to integer vectors
4844   // of the same time so that they get CSEd properly.
4845   ArrayRef<int> ShuffleMask = SVN->getMask();
4846
4847   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4848   if (EltSize <= 32) {
4849     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4850       int Lane = SVN->getSplatIndex();
4851       // If this is undef splat, generate it via "just" vdup, if possible.
4852       if (Lane == -1) Lane = 0;
4853
4854       // Test if V1 is a SCALAR_TO_VECTOR.
4855       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4856         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4857       }
4858       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4859       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4860       // reaches it).
4861       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4862           !isa<ConstantSDNode>(V1.getOperand(0))) {
4863         bool IsScalarToVector = true;
4864         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4865           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4866             IsScalarToVector = false;
4867             break;
4868           }
4869         if (IsScalarToVector)
4870           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4871       }
4872       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4873                          DAG.getConstant(Lane, MVT::i32));
4874     }
4875
4876     bool ReverseVEXT;
4877     unsigned Imm;
4878     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4879       if (ReverseVEXT)
4880         std::swap(V1, V2);
4881       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4882                          DAG.getConstant(Imm, MVT::i32));
4883     }
4884
4885     if (isVREVMask(ShuffleMask, VT, 64))
4886       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4887     if (isVREVMask(ShuffleMask, VT, 32))
4888       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4889     if (isVREVMask(ShuffleMask, VT, 16))
4890       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4891
4892     if (V2->getOpcode() == ISD::UNDEF &&
4893         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4894       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4895                          DAG.getConstant(Imm, MVT::i32));
4896     }
4897
4898     // Check for Neon shuffles that modify both input vectors in place.
4899     // If both results are used, i.e., if there are two shuffles with the same
4900     // source operands and with masks corresponding to both results of one of
4901     // these operations, DAG memoization will ensure that a single node is
4902     // used for both shuffles.
4903     unsigned WhichResult;
4904     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4905       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4906                          V1, V2).getValue(WhichResult);
4907     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4908       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4909                          V1, V2).getValue(WhichResult);
4910     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4911       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4912                          V1, V2).getValue(WhichResult);
4913
4914     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4915       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4916                          V1, V1).getValue(WhichResult);
4917     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4918       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4919                          V1, V1).getValue(WhichResult);
4920     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4921       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4922                          V1, V1).getValue(WhichResult);
4923   }
4924
4925   // If the shuffle is not directly supported and it has 4 elements, use
4926   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4927   unsigned NumElts = VT.getVectorNumElements();
4928   if (NumElts == 4) {
4929     unsigned PFIndexes[4];
4930     for (unsigned i = 0; i != 4; ++i) {
4931       if (ShuffleMask[i] < 0)
4932         PFIndexes[i] = 8;
4933       else
4934         PFIndexes[i] = ShuffleMask[i];
4935     }
4936
4937     // Compute the index in the perfect shuffle table.
4938     unsigned PFTableIndex =
4939       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4940     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4941     unsigned Cost = (PFEntry >> 30);
4942
4943     if (Cost <= 4)
4944       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4945   }
4946
4947   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4948   if (EltSize >= 32) {
4949     // Do the expansion with floating-point types, since that is what the VFP
4950     // registers are defined to use, and since i64 is not legal.
4951     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4952     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4953     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4954     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4955     SmallVector<SDValue, 8> Ops;
4956     for (unsigned i = 0; i < NumElts; ++i) {
4957       if (ShuffleMask[i] < 0)
4958         Ops.push_back(DAG.getUNDEF(EltVT));
4959       else
4960         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4961                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4962                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4963                                                   MVT::i32)));
4964     }
4965     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4966     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4967   }
4968
4969   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
4970     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
4971
4972   if (VT == MVT::v8i8) {
4973     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4974     if (NewOp.getNode())
4975       return NewOp;
4976   }
4977
4978   return SDValue();
4979 }
4980
4981 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4982   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4983   SDValue Lane = Op.getOperand(2);
4984   if (!isa<ConstantSDNode>(Lane))
4985     return SDValue();
4986
4987   return Op;
4988 }
4989
4990 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4991   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4992   SDValue Lane = Op.getOperand(1);
4993   if (!isa<ConstantSDNode>(Lane))
4994     return SDValue();
4995
4996   SDValue Vec = Op.getOperand(0);
4997   if (Op.getValueType() == MVT::i32 &&
4998       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4999     DebugLoc dl = Op.getDebugLoc();
5000     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5001   }
5002
5003   return Op;
5004 }
5005
5006 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5007   // The only time a CONCAT_VECTORS operation can have legal types is when
5008   // two 64-bit vectors are concatenated to a 128-bit vector.
5009   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5010          "unexpected CONCAT_VECTORS");
5011   DebugLoc dl = Op.getDebugLoc();
5012   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5013   SDValue Op0 = Op.getOperand(0);
5014   SDValue Op1 = Op.getOperand(1);
5015   if (Op0.getOpcode() != ISD::UNDEF)
5016     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5017                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5018                       DAG.getIntPtrConstant(0));
5019   if (Op1.getOpcode() != ISD::UNDEF)
5020     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5021                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5022                       DAG.getIntPtrConstant(1));
5023   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5024 }
5025
5026 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5027 /// element has been zero/sign-extended, depending on the isSigned parameter,
5028 /// from an integer type half its size.
5029 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5030                                    bool isSigned) {
5031   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5032   EVT VT = N->getValueType(0);
5033   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5034     SDNode *BVN = N->getOperand(0).getNode();
5035     if (BVN->getValueType(0) != MVT::v4i32 ||
5036         BVN->getOpcode() != ISD::BUILD_VECTOR)
5037       return false;
5038     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5039     unsigned HiElt = 1 - LoElt;
5040     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5041     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5042     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5043     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5044     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5045       return false;
5046     if (isSigned) {
5047       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5048           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5049         return true;
5050     } else {
5051       if (Hi0->isNullValue() && Hi1->isNullValue())
5052         return true;
5053     }
5054     return false;
5055   }
5056
5057   if (N->getOpcode() != ISD::BUILD_VECTOR)
5058     return false;
5059
5060   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5061     SDNode *Elt = N->getOperand(i).getNode();
5062     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5063       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5064       unsigned HalfSize = EltSize / 2;
5065       if (isSigned) {
5066         if (!isIntN(HalfSize, C->getSExtValue()))
5067           return false;
5068       } else {
5069         if (!isUIntN(HalfSize, C->getZExtValue()))
5070           return false;
5071       }
5072       continue;
5073     }
5074     return false;
5075   }
5076
5077   return true;
5078 }
5079
5080 /// isSignExtended - Check if a node is a vector value that is sign-extended
5081 /// or a constant BUILD_VECTOR with sign-extended elements.
5082 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5083   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5084     return true;
5085   if (isExtendedBUILD_VECTOR(N, DAG, true))
5086     return true;
5087   return false;
5088 }
5089
5090 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5091 /// or a constant BUILD_VECTOR with zero-extended elements.
5092 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5093   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5094     return true;
5095   if (isExtendedBUILD_VECTOR(N, DAG, false))
5096     return true;
5097   return false;
5098 }
5099
5100 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5101 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5102 /// We insert the required extension here to get the vector to fill a D register.
5103 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5104                                             const EVT &OrigTy,
5105                                             const EVT &ExtTy,
5106                                             unsigned ExtOpcode) {
5107   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5108   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5109   // 64-bits we need to insert a new extension so that it will be 64-bits.
5110   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5111   if (OrigTy.getSizeInBits() >= 64)
5112     return N;
5113
5114   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5115   MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5116   EVT NewVT;
5117   switch (OrigSimpleTy) {
5118   default: llvm_unreachable("Unexpected Orig Vector Type");
5119   case MVT::v2i8:
5120   case MVT::v2i16:
5121     NewVT = MVT::v2i32;
5122     break;
5123   case MVT::v4i8:
5124     NewVT = MVT::v4i16;
5125     break;
5126   }
5127   return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5128 }
5129
5130 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5131 /// does not do any sign/zero extension. If the original vector is less
5132 /// than 64 bits, an appropriate extension will be added after the load to
5133 /// reach a total size of 64 bits. We have to add the extension separately
5134 /// because ARM does not have a sign/zero extending load for vectors.
5135 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5136   SDValue NonExtendingLoad =
5137     DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5138                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5139                 LD->isNonTemporal(), LD->isInvariant(),
5140                 LD->getAlignment());
5141   unsigned ExtOp = 0;
5142   switch (LD->getExtensionType()) {
5143   default: llvm_unreachable("Unexpected LoadExtType");
5144   case ISD::EXTLOAD:
5145   case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5146   case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5147   }
5148   MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5149   MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5150   return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5151                                       MemType, ExtType, ExtOp);
5152 }
5153
5154 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5155 /// extending load, or BUILD_VECTOR with extended elements, return the
5156 /// unextended value. The unextended vector should be 64 bits so that it can
5157 /// be used as an operand to a VMULL instruction. If the original vector size
5158 /// before extension is less than 64 bits we add a an extension to resize
5159 /// the vector to 64 bits.
5160 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5161   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5162     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5163                                         N->getOperand(0)->getValueType(0),
5164                                         N->getValueType(0),
5165                                         N->getOpcode());
5166
5167   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5168     return SkipLoadExtensionForVMULL(LD, DAG);
5169
5170   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5171   // have been legalized as a BITCAST from v4i32.
5172   if (N->getOpcode() == ISD::BITCAST) {
5173     SDNode *BVN = N->getOperand(0).getNode();
5174     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5175            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5176     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5177     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5178                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5179   }
5180   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5181   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5182   EVT VT = N->getValueType(0);
5183   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5184   unsigned NumElts = VT.getVectorNumElements();
5185   MVT TruncVT = MVT::getIntegerVT(EltSize);
5186   SmallVector<SDValue, 8> Ops;
5187   for (unsigned i = 0; i != NumElts; ++i) {
5188     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5189     const APInt &CInt = C->getAPIntValue();
5190     // Element types smaller than 32 bits are not legal, so use i32 elements.
5191     // The values are implicitly truncated so sext vs. zext doesn't matter.
5192     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5193   }
5194   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5195                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5196 }
5197
5198 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5199   unsigned Opcode = N->getOpcode();
5200   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5201     SDNode *N0 = N->getOperand(0).getNode();
5202     SDNode *N1 = N->getOperand(1).getNode();
5203     return N0->hasOneUse() && N1->hasOneUse() &&
5204       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5205   }
5206   return false;
5207 }
5208
5209 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5210   unsigned Opcode = N->getOpcode();
5211   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5212     SDNode *N0 = N->getOperand(0).getNode();
5213     SDNode *N1 = N->getOperand(1).getNode();
5214     return N0->hasOneUse() && N1->hasOneUse() &&
5215       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5216   }
5217   return false;
5218 }
5219
5220 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5221   // Multiplications are only custom-lowered for 128-bit vectors so that
5222   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5223   EVT VT = Op.getValueType();
5224   assert(VT.is128BitVector() && VT.isInteger() &&
5225          "unexpected type for custom-lowering ISD::MUL");
5226   SDNode *N0 = Op.getOperand(0).getNode();
5227   SDNode *N1 = Op.getOperand(1).getNode();
5228   unsigned NewOpc = 0;
5229   bool isMLA = false;
5230   bool isN0SExt = isSignExtended(N0, DAG);
5231   bool isN1SExt = isSignExtended(N1, DAG);
5232   if (isN0SExt && isN1SExt)
5233     NewOpc = ARMISD::VMULLs;
5234   else {
5235     bool isN0ZExt = isZeroExtended(N0, DAG);
5236     bool isN1ZExt = isZeroExtended(N1, DAG);
5237     if (isN0ZExt && isN1ZExt)
5238       NewOpc = ARMISD::VMULLu;
5239     else if (isN1SExt || isN1ZExt) {
5240       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5241       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5242       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5243         NewOpc = ARMISD::VMULLs;
5244         isMLA = true;
5245       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5246         NewOpc = ARMISD::VMULLu;
5247         isMLA = true;
5248       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5249         std::swap(N0, N1);
5250         NewOpc = ARMISD::VMULLu;
5251         isMLA = true;
5252       }
5253     }
5254
5255     if (!NewOpc) {
5256       if (VT == MVT::v2i64)
5257         // Fall through to expand this.  It is not legal.
5258         return SDValue();
5259       else
5260         // Other vector multiplications are legal.
5261         return Op;
5262     }
5263   }
5264
5265   // Legalize to a VMULL instruction.
5266   DebugLoc DL = Op.getDebugLoc();
5267   SDValue Op0;
5268   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5269   if (!isMLA) {
5270     Op0 = SkipExtensionForVMULL(N0, DAG);
5271     assert(Op0.getValueType().is64BitVector() &&
5272            Op1.getValueType().is64BitVector() &&
5273            "unexpected types for extended operands to VMULL");
5274     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5275   }
5276
5277   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5278   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5279   //   vmull q0, d4, d6
5280   //   vmlal q0, d5, d6
5281   // is faster than
5282   //   vaddl q0, d4, d5
5283   //   vmovl q1, d6
5284   //   vmul  q0, q0, q1
5285   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5286   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5287   EVT Op1VT = Op1.getValueType();
5288   return DAG.getNode(N0->getOpcode(), DL, VT,
5289                      DAG.getNode(NewOpc, DL, VT,
5290                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5291                      DAG.getNode(NewOpc, DL, VT,
5292                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5293 }
5294
5295 static SDValue
5296 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5297   // Convert to float
5298   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5299   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5300   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5301   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5302   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5303   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5304   // Get reciprocal estimate.
5305   // float4 recip = vrecpeq_f32(yf);
5306   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5307                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5308   // Because char has a smaller range than uchar, we can actually get away
5309   // without any newton steps.  This requires that we use a weird bias
5310   // of 0xb000, however (again, this has been exhaustively tested).
5311   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5312   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5313   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5314   Y = DAG.getConstant(0xb000, MVT::i32);
5315   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5316   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5317   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5318   // Convert back to short.
5319   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5320   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5321   return X;
5322 }
5323
5324 static SDValue
5325 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5326   SDValue N2;
5327   // Convert to float.
5328   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5329   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5330   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5331   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5332   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5333   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5334
5335   // Use reciprocal estimate and one refinement step.
5336   // float4 recip = vrecpeq_f32(yf);
5337   // recip *= vrecpsq_f32(yf, recip);
5338   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5339                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5340   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5341                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5342                    N1, N2);
5343   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5344   // Because short has a smaller range than ushort, we can actually get away
5345   // with only a single newton step.  This requires that we use a weird bias
5346   // of 89, however (again, this has been exhaustively tested).
5347   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5348   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5349   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5350   N1 = DAG.getConstant(0x89, MVT::i32);
5351   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5352   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5353   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5354   // Convert back to integer and return.
5355   // return vmovn_s32(vcvt_s32_f32(result));
5356   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5357   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5358   return N0;
5359 }
5360
5361 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5362   EVT VT = Op.getValueType();
5363   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5364          "unexpected type for custom-lowering ISD::SDIV");
5365
5366   DebugLoc dl = Op.getDebugLoc();
5367   SDValue N0 = Op.getOperand(0);
5368   SDValue N1 = Op.getOperand(1);
5369   SDValue N2, N3;
5370
5371   if (VT == MVT::v8i8) {
5372     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5373     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5374
5375     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5376                      DAG.getIntPtrConstant(4));
5377     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5378                      DAG.getIntPtrConstant(4));
5379     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5380                      DAG.getIntPtrConstant(0));
5381     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5382                      DAG.getIntPtrConstant(0));
5383
5384     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5385     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5386
5387     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5388     N0 = LowerCONCAT_VECTORS(N0, DAG);
5389
5390     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5391     return N0;
5392   }
5393   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5394 }
5395
5396 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5397   EVT VT = Op.getValueType();
5398   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5399          "unexpected type for custom-lowering ISD::UDIV");
5400
5401   DebugLoc dl = Op.getDebugLoc();
5402   SDValue N0 = Op.getOperand(0);
5403   SDValue N1 = Op.getOperand(1);
5404   SDValue N2, N3;
5405
5406   if (VT == MVT::v8i8) {
5407     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5408     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5409
5410     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5411                      DAG.getIntPtrConstant(4));
5412     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5413                      DAG.getIntPtrConstant(4));
5414     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5415                      DAG.getIntPtrConstant(0));
5416     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5417                      DAG.getIntPtrConstant(0));
5418
5419     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5420     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5421
5422     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5423     N0 = LowerCONCAT_VECTORS(N0, DAG);
5424
5425     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5426                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5427                      N0);
5428     return N0;
5429   }
5430
5431   // v4i16 sdiv ... Convert to float.
5432   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5433   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5434   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5435   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5436   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5437   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5438
5439   // Use reciprocal estimate and two refinement steps.
5440   // float4 recip = vrecpeq_f32(yf);
5441   // recip *= vrecpsq_f32(yf, recip);
5442   // recip *= vrecpsq_f32(yf, recip);
5443   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5444                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5445   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5446                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5447                    BN1, N2);
5448   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5449   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5450                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5451                    BN1, N2);
5452   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5453   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5454   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5455   // and that it will never cause us to return an answer too large).
5456   // float4 result = as_float4(as_int4(xf*recip) + 2);
5457   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5458   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5459   N1 = DAG.getConstant(2, MVT::i32);
5460   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5461   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5462   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5463   // Convert back to integer and return.
5464   // return vmovn_u32(vcvt_s32_f32(result));
5465   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5466   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5467   return N0;
5468 }
5469
5470 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5471   EVT VT = Op.getNode()->getValueType(0);
5472   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5473
5474   unsigned Opc;
5475   bool ExtraOp = false;
5476   switch (Op.getOpcode()) {
5477   default: llvm_unreachable("Invalid code");
5478   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5479   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5480   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5481   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5482   }
5483
5484   if (!ExtraOp)
5485     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5486                        Op.getOperand(1));
5487   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5488                      Op.getOperand(1), Op.getOperand(2));
5489 }
5490
5491 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5492   // Monotonic load/store is legal for all targets
5493   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5494     return Op;
5495
5496   // Aquire/Release load/store is not legal for targets without a
5497   // dmb or equivalent available.
5498   return SDValue();
5499 }
5500
5501
5502 static void
5503 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5504                     SelectionDAG &DAG, unsigned NewOp) {
5505   DebugLoc dl = Node->getDebugLoc();
5506   assert (Node->getValueType(0) == MVT::i64 &&
5507           "Only know how to expand i64 atomics");
5508
5509   SmallVector<SDValue, 6> Ops;
5510   Ops.push_back(Node->getOperand(0)); // Chain
5511   Ops.push_back(Node->getOperand(1)); // Ptr
5512   // Low part of Val1
5513   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5514                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5515   // High part of Val1
5516   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5517                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5518   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5519     // High part of Val1
5520     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5521                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5522     // High part of Val2
5523     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5524                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5525   }
5526   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5527   SDValue Result =
5528     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5529                             cast<MemSDNode>(Node)->getMemOperand());
5530   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5531   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5532   Results.push_back(Result.getValue(2));
5533 }
5534
5535 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5536   switch (Op.getOpcode()) {
5537   default: llvm_unreachable("Don't know how to custom lower this!");
5538   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5539   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5540   case ISD::GlobalAddress:
5541     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5542       LowerGlobalAddressELF(Op, DAG);
5543   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5544   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5545   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5546   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5547   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5548   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5549   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5550   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5551   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5552   case ISD::SINT_TO_FP:
5553   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5554   case ISD::FP_TO_SINT:
5555   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5556   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5557   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5558   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5559   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5560   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5561   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5562   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5563                                                                Subtarget);
5564   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5565   case ISD::SHL:
5566   case ISD::SRL:
5567   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5568   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5569   case ISD::SRL_PARTS:
5570   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5571   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5572   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5573   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5574   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5575   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5576   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5577   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5578   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5579   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5580   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5581   case ISD::MUL:           return LowerMUL(Op, DAG);
5582   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5583   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5584   case ISD::ADDC:
5585   case ISD::ADDE:
5586   case ISD::SUBC:
5587   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5588   case ISD::ATOMIC_LOAD:
5589   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5590   }
5591 }
5592
5593 /// ReplaceNodeResults - Replace the results of node with an illegal result
5594 /// type with new values built out of custom code.
5595 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5596                                            SmallVectorImpl<SDValue>&Results,
5597                                            SelectionDAG &DAG) const {
5598   SDValue Res;
5599   switch (N->getOpcode()) {
5600   default:
5601     llvm_unreachable("Don't know how to custom expand this!");
5602   case ISD::BITCAST:
5603     Res = ExpandBITCAST(N, DAG);
5604     break;
5605   case ISD::SRL:
5606   case ISD::SRA:
5607     Res = Expand64BitShift(N, DAG, Subtarget);
5608     break;
5609   case ISD::ATOMIC_LOAD_ADD:
5610     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5611     return;
5612   case ISD::ATOMIC_LOAD_AND:
5613     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5614     return;
5615   case ISD::ATOMIC_LOAD_NAND:
5616     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5617     return;
5618   case ISD::ATOMIC_LOAD_OR:
5619     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5620     return;
5621   case ISD::ATOMIC_LOAD_SUB:
5622     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5623     return;
5624   case ISD::ATOMIC_LOAD_XOR:
5625     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5626     return;
5627   case ISD::ATOMIC_SWAP:
5628     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5629     return;
5630   case ISD::ATOMIC_CMP_SWAP:
5631     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5632     return;
5633   case ISD::ATOMIC_LOAD_MIN:
5634     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5635     return;
5636   case ISD::ATOMIC_LOAD_UMIN:
5637     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5638     return;
5639   case ISD::ATOMIC_LOAD_MAX:
5640     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5641     return;
5642   case ISD::ATOMIC_LOAD_UMAX:
5643     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5644     return;
5645   }
5646   if (Res.getNode())
5647     Results.push_back(Res);
5648 }
5649
5650 //===----------------------------------------------------------------------===//
5651 //                           ARM Scheduler Hooks
5652 //===----------------------------------------------------------------------===//
5653
5654 MachineBasicBlock *
5655 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5656                                      MachineBasicBlock *BB,
5657                                      unsigned Size) const {
5658   unsigned dest    = MI->getOperand(0).getReg();
5659   unsigned ptr     = MI->getOperand(1).getReg();
5660   unsigned oldval  = MI->getOperand(2).getReg();
5661   unsigned newval  = MI->getOperand(3).getReg();
5662   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5663   DebugLoc dl = MI->getDebugLoc();
5664   bool isThumb2 = Subtarget->isThumb2();
5665
5666   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5667   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5668     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5669     (const TargetRegisterClass*)&ARM::GPRRegClass);
5670
5671   if (isThumb2) {
5672     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5673     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5674     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5675   }
5676
5677   unsigned ldrOpc, strOpc;
5678   switch (Size) {
5679   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5680   case 1:
5681     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5682     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5683     break;
5684   case 2:
5685     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5686     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5687     break;
5688   case 4:
5689     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5690     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5691     break;
5692   }
5693
5694   MachineFunction *MF = BB->getParent();
5695   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5696   MachineFunction::iterator It = BB;
5697   ++It; // insert the new blocks after the current block
5698
5699   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5700   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5701   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5702   MF->insert(It, loop1MBB);
5703   MF->insert(It, loop2MBB);
5704   MF->insert(It, exitMBB);
5705
5706   // Transfer the remainder of BB and its successor edges to exitMBB.
5707   exitMBB->splice(exitMBB->begin(), BB,
5708                   llvm::next(MachineBasicBlock::iterator(MI)),
5709                   BB->end());
5710   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5711
5712   //  thisMBB:
5713   //   ...
5714   //   fallthrough --> loop1MBB
5715   BB->addSuccessor(loop1MBB);
5716
5717   // loop1MBB:
5718   //   ldrex dest, [ptr]
5719   //   cmp dest, oldval
5720   //   bne exitMBB
5721   BB = loop1MBB;
5722   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5723   if (ldrOpc == ARM::t2LDREX)
5724     MIB.addImm(0);
5725   AddDefaultPred(MIB);
5726   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5727                  .addReg(dest).addReg(oldval));
5728   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5729     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5730   BB->addSuccessor(loop2MBB);
5731   BB->addSuccessor(exitMBB);
5732
5733   // loop2MBB:
5734   //   strex scratch, newval, [ptr]
5735   //   cmp scratch, #0
5736   //   bne loop1MBB
5737   BB = loop2MBB;
5738   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5739   if (strOpc == ARM::t2STREX)
5740     MIB.addImm(0);
5741   AddDefaultPred(MIB);
5742   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5743                  .addReg(scratch).addImm(0));
5744   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5745     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5746   BB->addSuccessor(loop1MBB);
5747   BB->addSuccessor(exitMBB);
5748
5749   //  exitMBB:
5750   //   ...
5751   BB = exitMBB;
5752
5753   MI->eraseFromParent();   // The instruction is gone now.
5754
5755   return BB;
5756 }
5757
5758 MachineBasicBlock *
5759 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5760                                     unsigned Size, unsigned BinOpcode) const {
5761   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5762   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5763
5764   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5765   MachineFunction *MF = BB->getParent();
5766   MachineFunction::iterator It = BB;
5767   ++It;
5768
5769   unsigned dest = MI->getOperand(0).getReg();
5770   unsigned ptr = MI->getOperand(1).getReg();
5771   unsigned incr = MI->getOperand(2).getReg();
5772   DebugLoc dl = MI->getDebugLoc();
5773   bool isThumb2 = Subtarget->isThumb2();
5774
5775   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5776   if (isThumb2) {
5777     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5778     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5779   }
5780
5781   unsigned ldrOpc, strOpc;
5782   switch (Size) {
5783   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5784   case 1:
5785     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5786     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5787     break;
5788   case 2:
5789     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5790     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5791     break;
5792   case 4:
5793     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5794     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5795     break;
5796   }
5797
5798   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5799   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5800   MF->insert(It, loopMBB);
5801   MF->insert(It, exitMBB);
5802
5803   // Transfer the remainder of BB and its successor edges to exitMBB.
5804   exitMBB->splice(exitMBB->begin(), BB,
5805                   llvm::next(MachineBasicBlock::iterator(MI)),
5806                   BB->end());
5807   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5808
5809   const TargetRegisterClass *TRC = isThumb2 ?
5810     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5811     (const TargetRegisterClass*)&ARM::GPRRegClass;
5812   unsigned scratch = MRI.createVirtualRegister(TRC);
5813   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5814
5815   //  thisMBB:
5816   //   ...
5817   //   fallthrough --> loopMBB
5818   BB->addSuccessor(loopMBB);
5819
5820   //  loopMBB:
5821   //   ldrex dest, ptr
5822   //   <binop> scratch2, dest, incr
5823   //   strex scratch, scratch2, ptr
5824   //   cmp scratch, #0
5825   //   bne- loopMBB
5826   //   fallthrough --> exitMBB
5827   BB = loopMBB;
5828   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5829   if (ldrOpc == ARM::t2LDREX)
5830     MIB.addImm(0);
5831   AddDefaultPred(MIB);
5832   if (BinOpcode) {
5833     // operand order needs to go the other way for NAND
5834     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5835       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5836                      addReg(incr).addReg(dest)).addReg(0);
5837     else
5838       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5839                      addReg(dest).addReg(incr)).addReg(0);
5840   }
5841
5842   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5843   if (strOpc == ARM::t2STREX)
5844     MIB.addImm(0);
5845   AddDefaultPred(MIB);
5846   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5847                  .addReg(scratch).addImm(0));
5848   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5849     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5850
5851   BB->addSuccessor(loopMBB);
5852   BB->addSuccessor(exitMBB);
5853
5854   //  exitMBB:
5855   //   ...
5856   BB = exitMBB;
5857
5858   MI->eraseFromParent();   // The instruction is gone now.
5859
5860   return BB;
5861 }
5862
5863 MachineBasicBlock *
5864 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5865                                           MachineBasicBlock *BB,
5866                                           unsigned Size,
5867                                           bool signExtend,
5868                                           ARMCC::CondCodes Cond) const {
5869   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5870
5871   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5872   MachineFunction *MF = BB->getParent();
5873   MachineFunction::iterator It = BB;
5874   ++It;
5875
5876   unsigned dest = MI->getOperand(0).getReg();
5877   unsigned ptr = MI->getOperand(1).getReg();
5878   unsigned incr = MI->getOperand(2).getReg();
5879   unsigned oldval = dest;
5880   DebugLoc dl = MI->getDebugLoc();
5881   bool isThumb2 = Subtarget->isThumb2();
5882
5883   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5884   if (isThumb2) {
5885     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5886     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5887   }
5888
5889   unsigned ldrOpc, strOpc, extendOpc;
5890   switch (Size) {
5891   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5892   case 1:
5893     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5894     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5895     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5896     break;
5897   case 2:
5898     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5899     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5900     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5901     break;
5902   case 4:
5903     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5904     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5905     extendOpc = 0;
5906     break;
5907   }
5908
5909   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5910   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5911   MF->insert(It, loopMBB);
5912   MF->insert(It, exitMBB);
5913
5914   // Transfer the remainder of BB and its successor edges to exitMBB.
5915   exitMBB->splice(exitMBB->begin(), BB,
5916                   llvm::next(MachineBasicBlock::iterator(MI)),
5917                   BB->end());
5918   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5919
5920   const TargetRegisterClass *TRC = isThumb2 ?
5921     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5922     (const TargetRegisterClass*)&ARM::GPRRegClass;
5923   unsigned scratch = MRI.createVirtualRegister(TRC);
5924   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5925
5926   //  thisMBB:
5927   //   ...
5928   //   fallthrough --> loopMBB
5929   BB->addSuccessor(loopMBB);
5930
5931   //  loopMBB:
5932   //   ldrex dest, ptr
5933   //   (sign extend dest, if required)
5934   //   cmp dest, incr
5935   //   cmov.cond scratch2, incr, dest
5936   //   strex scratch, scratch2, ptr
5937   //   cmp scratch, #0
5938   //   bne- loopMBB
5939   //   fallthrough --> exitMBB
5940   BB = loopMBB;
5941   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5942   if (ldrOpc == ARM::t2LDREX)
5943     MIB.addImm(0);
5944   AddDefaultPred(MIB);
5945
5946   // Sign extend the value, if necessary.
5947   if (signExtend && extendOpc) {
5948     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5949     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5950                      .addReg(dest)
5951                      .addImm(0));
5952   }
5953
5954   // Build compare and cmov instructions.
5955   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5956                  .addReg(oldval).addReg(incr));
5957   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5958          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5959
5960   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5961   if (strOpc == ARM::t2STREX)
5962     MIB.addImm(0);
5963   AddDefaultPred(MIB);
5964   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5965                  .addReg(scratch).addImm(0));
5966   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5967     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5968
5969   BB->addSuccessor(loopMBB);
5970   BB->addSuccessor(exitMBB);
5971
5972   //  exitMBB:
5973   //   ...
5974   BB = exitMBB;
5975
5976   MI->eraseFromParent();   // The instruction is gone now.
5977
5978   return BB;
5979 }
5980
5981 MachineBasicBlock *
5982 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5983                                       unsigned Op1, unsigned Op2,
5984                                       bool NeedsCarry, bool IsCmpxchg,
5985                                       bool IsMinMax, ARMCC::CondCodes CC) const {
5986   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5987   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5988
5989   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5990   MachineFunction *MF = BB->getParent();
5991   MachineFunction::iterator It = BB;
5992   ++It;
5993
5994   unsigned destlo = MI->getOperand(0).getReg();
5995   unsigned desthi = MI->getOperand(1).getReg();
5996   unsigned ptr = MI->getOperand(2).getReg();
5997   unsigned vallo = MI->getOperand(3).getReg();
5998   unsigned valhi = MI->getOperand(4).getReg();
5999   DebugLoc dl = MI->getDebugLoc();
6000   bool isThumb2 = Subtarget->isThumb2();
6001
6002   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6003   if (isThumb2) {
6004     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6005     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6006     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6007   }
6008
6009   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6010   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6011   if (IsCmpxchg || IsMinMax)
6012     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6013   if (IsCmpxchg)
6014     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6015   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6016
6017   MF->insert(It, loopMBB);
6018   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6019   if (IsCmpxchg) MF->insert(It, cont2BB);
6020   MF->insert(It, exitMBB);
6021
6022   // Transfer the remainder of BB and its successor edges to exitMBB.
6023   exitMBB->splice(exitMBB->begin(), BB,
6024                   llvm::next(MachineBasicBlock::iterator(MI)),
6025                   BB->end());
6026   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6027
6028   const TargetRegisterClass *TRC = isThumb2 ?
6029     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6030     (const TargetRegisterClass*)&ARM::GPRRegClass;
6031   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6032
6033   //  thisMBB:
6034   //   ...
6035   //   fallthrough --> loopMBB
6036   BB->addSuccessor(loopMBB);
6037
6038   //  loopMBB:
6039   //   ldrexd r2, r3, ptr
6040   //   <binopa> r0, r2, incr
6041   //   <binopb> r1, r3, incr
6042   //   strexd storesuccess, r0, r1, ptr
6043   //   cmp storesuccess, #0
6044   //   bne- loopMBB
6045   //   fallthrough --> exitMBB
6046   BB = loopMBB;
6047
6048   // Load
6049   if (isThumb2) {
6050     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6051                    .addReg(destlo, RegState::Define)
6052                    .addReg(desthi, RegState::Define)
6053                    .addReg(ptr));
6054   } else {
6055     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6056     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6057                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6058     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6059     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6060       .addReg(GPRPair0, 0, ARM::gsub_0);
6061     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6062       .addReg(GPRPair0, 0, ARM::gsub_1);
6063   }
6064
6065   unsigned StoreLo, StoreHi;
6066   if (IsCmpxchg) {
6067     // Add early exit
6068     for (unsigned i = 0; i < 2; i++) {
6069       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6070                                                          ARM::CMPrr))
6071                      .addReg(i == 0 ? destlo : desthi)
6072                      .addReg(i == 0 ? vallo : valhi));
6073       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6074         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6075       BB->addSuccessor(exitMBB);
6076       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6077       BB = (i == 0 ? contBB : cont2BB);
6078     }
6079
6080     // Copy to physregs for strexd
6081     StoreLo = MI->getOperand(5).getReg();
6082     StoreHi = MI->getOperand(6).getReg();
6083   } else if (Op1) {
6084     // Perform binary operation
6085     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6086     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6087                    .addReg(destlo).addReg(vallo))
6088         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6089     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6090     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6091                    .addReg(desthi).addReg(valhi))
6092         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6093
6094     StoreLo = tmpRegLo;
6095     StoreHi = tmpRegHi;
6096   } else {
6097     // Copy to physregs for strexd
6098     StoreLo = vallo;
6099     StoreHi = valhi;
6100   }
6101   if (IsMinMax) {
6102     // Compare and branch to exit block.
6103     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6104       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6105     BB->addSuccessor(exitMBB);
6106     BB->addSuccessor(contBB);
6107     BB = contBB;
6108     StoreLo = vallo;
6109     StoreHi = valhi;
6110   }
6111
6112   // Store
6113   if (isThumb2) {
6114     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6115                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6116   } else {
6117     // Marshal a pair...
6118     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6119     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6120     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6121     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6122     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6123       .addReg(UndefPair)
6124       .addReg(StoreLo)
6125       .addImm(ARM::gsub_0);
6126     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6127       .addReg(r1)
6128       .addReg(StoreHi)
6129       .addImm(ARM::gsub_1);
6130
6131     // ...and store it
6132     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6133                    .addReg(StorePair).addReg(ptr));
6134   }
6135   // Cmp+jump
6136   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6137                  .addReg(storesuccess).addImm(0));
6138   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6139     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6140
6141   BB->addSuccessor(loopMBB);
6142   BB->addSuccessor(exitMBB);
6143
6144   //  exitMBB:
6145   //   ...
6146   BB = exitMBB;
6147
6148   MI->eraseFromParent();   // The instruction is gone now.
6149
6150   return BB;
6151 }
6152
6153 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6154 /// registers the function context.
6155 void ARMTargetLowering::
6156 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6157                        MachineBasicBlock *DispatchBB, int FI) const {
6158   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6159   DebugLoc dl = MI->getDebugLoc();
6160   MachineFunction *MF = MBB->getParent();
6161   MachineRegisterInfo *MRI = &MF->getRegInfo();
6162   MachineConstantPool *MCP = MF->getConstantPool();
6163   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6164   const Function *F = MF->getFunction();
6165
6166   bool isThumb = Subtarget->isThumb();
6167   bool isThumb2 = Subtarget->isThumb2();
6168
6169   unsigned PCLabelId = AFI->createPICLabelUId();
6170   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6171   ARMConstantPoolValue *CPV =
6172     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6173   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6174
6175   const TargetRegisterClass *TRC = isThumb ?
6176     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6177     (const TargetRegisterClass*)&ARM::GPRRegClass;
6178
6179   // Grab constant pool and fixed stack memory operands.
6180   MachineMemOperand *CPMMO =
6181     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6182                              MachineMemOperand::MOLoad, 4, 4);
6183
6184   MachineMemOperand *FIMMOSt =
6185     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6186                              MachineMemOperand::MOStore, 4, 4);
6187
6188   // Load the address of the dispatch MBB into the jump buffer.
6189   if (isThumb2) {
6190     // Incoming value: jbuf
6191     //   ldr.n  r5, LCPI1_1
6192     //   orr    r5, r5, #1
6193     //   add    r5, pc
6194     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6195     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6196     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6197                    .addConstantPoolIndex(CPI)
6198                    .addMemOperand(CPMMO));
6199     // Set the low bit because of thumb mode.
6200     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6201     AddDefaultCC(
6202       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6203                      .addReg(NewVReg1, RegState::Kill)
6204                      .addImm(0x01)));
6205     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6206     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6207       .addReg(NewVReg2, RegState::Kill)
6208       .addImm(PCLabelId);
6209     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6210                    .addReg(NewVReg3, RegState::Kill)
6211                    .addFrameIndex(FI)
6212                    .addImm(36)  // &jbuf[1] :: pc
6213                    .addMemOperand(FIMMOSt));
6214   } else if (isThumb) {
6215     // Incoming value: jbuf
6216     //   ldr.n  r1, LCPI1_4
6217     //   add    r1, pc
6218     //   mov    r2, #1
6219     //   orrs   r1, r2
6220     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6221     //   str    r1, [r2]
6222     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6223     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6224                    .addConstantPoolIndex(CPI)
6225                    .addMemOperand(CPMMO));
6226     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6227     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6228       .addReg(NewVReg1, RegState::Kill)
6229       .addImm(PCLabelId);
6230     // Set the low bit because of thumb mode.
6231     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6232     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6233                    .addReg(ARM::CPSR, RegState::Define)
6234                    .addImm(1));
6235     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6236     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6237                    .addReg(ARM::CPSR, RegState::Define)
6238                    .addReg(NewVReg2, RegState::Kill)
6239                    .addReg(NewVReg3, RegState::Kill));
6240     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6241     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6242                    .addFrameIndex(FI)
6243                    .addImm(36)); // &jbuf[1] :: pc
6244     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6245                    .addReg(NewVReg4, RegState::Kill)
6246                    .addReg(NewVReg5, RegState::Kill)
6247                    .addImm(0)
6248                    .addMemOperand(FIMMOSt));
6249   } else {
6250     // Incoming value: jbuf
6251     //   ldr  r1, LCPI1_1
6252     //   add  r1, pc, r1
6253     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6254     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6255     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6256                    .addConstantPoolIndex(CPI)
6257                    .addImm(0)
6258                    .addMemOperand(CPMMO));
6259     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6260     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6261                    .addReg(NewVReg1, RegState::Kill)
6262                    .addImm(PCLabelId));
6263     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6264                    .addReg(NewVReg2, RegState::Kill)
6265                    .addFrameIndex(FI)
6266                    .addImm(36)  // &jbuf[1] :: pc
6267                    .addMemOperand(FIMMOSt));
6268   }
6269 }
6270
6271 MachineBasicBlock *ARMTargetLowering::
6272 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6273   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6274   DebugLoc dl = MI->getDebugLoc();
6275   MachineFunction *MF = MBB->getParent();
6276   MachineRegisterInfo *MRI = &MF->getRegInfo();
6277   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6278   MachineFrameInfo *MFI = MF->getFrameInfo();
6279   int FI = MFI->getFunctionContextIndex();
6280
6281   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6282     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6283     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6284
6285   // Get a mapping of the call site numbers to all of the landing pads they're
6286   // associated with.
6287   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6288   unsigned MaxCSNum = 0;
6289   MachineModuleInfo &MMI = MF->getMMI();
6290   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6291        ++BB) {
6292     if (!BB->isLandingPad()) continue;
6293
6294     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6295     // pad.
6296     for (MachineBasicBlock::iterator
6297            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6298       if (!II->isEHLabel()) continue;
6299
6300       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6301       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6302
6303       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6304       for (SmallVectorImpl<unsigned>::iterator
6305              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6306            CSI != CSE; ++CSI) {
6307         CallSiteNumToLPad[*CSI].push_back(BB);
6308         MaxCSNum = std::max(MaxCSNum, *CSI);
6309       }
6310       break;
6311     }
6312   }
6313
6314   // Get an ordered list of the machine basic blocks for the jump table.
6315   std::vector<MachineBasicBlock*> LPadList;
6316   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6317   LPadList.reserve(CallSiteNumToLPad.size());
6318   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6319     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6320     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6321            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6322       LPadList.push_back(*II);
6323       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6324     }
6325   }
6326
6327   assert(!LPadList.empty() &&
6328          "No landing pad destinations for the dispatch jump table!");
6329
6330   // Create the jump table and associated information.
6331   MachineJumpTableInfo *JTI =
6332     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6333   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6334   unsigned UId = AFI->createJumpTableUId();
6335
6336   // Create the MBBs for the dispatch code.
6337
6338   // Shove the dispatch's address into the return slot in the function context.
6339   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6340   DispatchBB->setIsLandingPad();
6341
6342   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6343   unsigned trap_opcode;
6344   if (Subtarget->isThumb())
6345     trap_opcode = ARM::tTRAP;
6346   else
6347     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6348
6349   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6350   DispatchBB->addSuccessor(TrapBB);
6351
6352   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6353   DispatchBB->addSuccessor(DispContBB);
6354
6355   // Insert and MBBs.
6356   MF->insert(MF->end(), DispatchBB);
6357   MF->insert(MF->end(), DispContBB);
6358   MF->insert(MF->end(), TrapBB);
6359
6360   // Insert code into the entry block that creates and registers the function
6361   // context.
6362   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6363
6364   MachineMemOperand *FIMMOLd =
6365     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6366                              MachineMemOperand::MOLoad |
6367                              MachineMemOperand::MOVolatile, 4, 4);
6368
6369   MachineInstrBuilder MIB;
6370   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6371
6372   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6373   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6374
6375   // Add a register mask with no preserved registers.  This results in all
6376   // registers being marked as clobbered.
6377   MIB.addRegMask(RI.getNoPreservedMask());
6378
6379   unsigned NumLPads = LPadList.size();
6380   if (Subtarget->isThumb2()) {
6381     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6382     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6383                    .addFrameIndex(FI)
6384                    .addImm(4)
6385                    .addMemOperand(FIMMOLd));
6386
6387     if (NumLPads < 256) {
6388       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6389                      .addReg(NewVReg1)
6390                      .addImm(LPadList.size()));
6391     } else {
6392       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6393       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6394                      .addImm(NumLPads & 0xFFFF));
6395
6396       unsigned VReg2 = VReg1;
6397       if ((NumLPads & 0xFFFF0000) != 0) {
6398         VReg2 = MRI->createVirtualRegister(TRC);
6399         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6400                        .addReg(VReg1)
6401                        .addImm(NumLPads >> 16));
6402       }
6403
6404       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6405                      .addReg(NewVReg1)
6406                      .addReg(VReg2));
6407     }
6408
6409     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6410       .addMBB(TrapBB)
6411       .addImm(ARMCC::HI)
6412       .addReg(ARM::CPSR);
6413
6414     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6415     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6416                    .addJumpTableIndex(MJTI)
6417                    .addImm(UId));
6418
6419     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6420     AddDefaultCC(
6421       AddDefaultPred(
6422         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6423         .addReg(NewVReg3, RegState::Kill)
6424         .addReg(NewVReg1)
6425         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6426
6427     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6428       .addReg(NewVReg4, RegState::Kill)
6429       .addReg(NewVReg1)
6430       .addJumpTableIndex(MJTI)
6431       .addImm(UId);
6432   } else if (Subtarget->isThumb()) {
6433     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6434     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6435                    .addFrameIndex(FI)
6436                    .addImm(1)
6437                    .addMemOperand(FIMMOLd));
6438
6439     if (NumLPads < 256) {
6440       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6441                      .addReg(NewVReg1)
6442                      .addImm(NumLPads));
6443     } else {
6444       MachineConstantPool *ConstantPool = MF->getConstantPool();
6445       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6446       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6447
6448       // MachineConstantPool wants an explicit alignment.
6449       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6450       if (Align == 0)
6451         Align = getDataLayout()->getTypeAllocSize(C->getType());
6452       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6453
6454       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6455       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6456                      .addReg(VReg1, RegState::Define)
6457                      .addConstantPoolIndex(Idx));
6458       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6459                      .addReg(NewVReg1)
6460                      .addReg(VReg1));
6461     }
6462
6463     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6464       .addMBB(TrapBB)
6465       .addImm(ARMCC::HI)
6466       .addReg(ARM::CPSR);
6467
6468     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6469     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6470                    .addReg(ARM::CPSR, RegState::Define)
6471                    .addReg(NewVReg1)
6472                    .addImm(2));
6473
6474     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6475     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6476                    .addJumpTableIndex(MJTI)
6477                    .addImm(UId));
6478
6479     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6480     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6481                    .addReg(ARM::CPSR, RegState::Define)
6482                    .addReg(NewVReg2, RegState::Kill)
6483                    .addReg(NewVReg3));
6484
6485     MachineMemOperand *JTMMOLd =
6486       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6487                                MachineMemOperand::MOLoad, 4, 4);
6488
6489     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6490     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6491                    .addReg(NewVReg4, RegState::Kill)
6492                    .addImm(0)
6493                    .addMemOperand(JTMMOLd));
6494
6495     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6496     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6497                    .addReg(ARM::CPSR, RegState::Define)
6498                    .addReg(NewVReg5, RegState::Kill)
6499                    .addReg(NewVReg3));
6500
6501     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6502       .addReg(NewVReg6, RegState::Kill)
6503       .addJumpTableIndex(MJTI)
6504       .addImm(UId);
6505   } else {
6506     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6507     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6508                    .addFrameIndex(FI)
6509                    .addImm(4)
6510                    .addMemOperand(FIMMOLd));
6511
6512     if (NumLPads < 256) {
6513       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6514                      .addReg(NewVReg1)
6515                      .addImm(NumLPads));
6516     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6517       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6518       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6519                      .addImm(NumLPads & 0xFFFF));
6520
6521       unsigned VReg2 = VReg1;
6522       if ((NumLPads & 0xFFFF0000) != 0) {
6523         VReg2 = MRI->createVirtualRegister(TRC);
6524         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6525                        .addReg(VReg1)
6526                        .addImm(NumLPads >> 16));
6527       }
6528
6529       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6530                      .addReg(NewVReg1)
6531                      .addReg(VReg2));
6532     } else {
6533       MachineConstantPool *ConstantPool = MF->getConstantPool();
6534       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6535       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6536
6537       // MachineConstantPool wants an explicit alignment.
6538       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6539       if (Align == 0)
6540         Align = getDataLayout()->getTypeAllocSize(C->getType());
6541       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6542
6543       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6544       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6545                      .addReg(VReg1, RegState::Define)
6546                      .addConstantPoolIndex(Idx)
6547                      .addImm(0));
6548       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6549                      .addReg(NewVReg1)
6550                      .addReg(VReg1, RegState::Kill));
6551     }
6552
6553     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6554       .addMBB(TrapBB)
6555       .addImm(ARMCC::HI)
6556       .addReg(ARM::CPSR);
6557
6558     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6559     AddDefaultCC(
6560       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6561                      .addReg(NewVReg1)
6562                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6563     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6564     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6565                    .addJumpTableIndex(MJTI)
6566                    .addImm(UId));
6567
6568     MachineMemOperand *JTMMOLd =
6569       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6570                                MachineMemOperand::MOLoad, 4, 4);
6571     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6572     AddDefaultPred(
6573       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6574       .addReg(NewVReg3, RegState::Kill)
6575       .addReg(NewVReg4)
6576       .addImm(0)
6577       .addMemOperand(JTMMOLd));
6578
6579     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6580       .addReg(NewVReg5, RegState::Kill)
6581       .addReg(NewVReg4)
6582       .addJumpTableIndex(MJTI)
6583       .addImm(UId);
6584   }
6585
6586   // Add the jump table entries as successors to the MBB.
6587   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6588   for (std::vector<MachineBasicBlock*>::iterator
6589          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6590     MachineBasicBlock *CurMBB = *I;
6591     if (SeenMBBs.insert(CurMBB))
6592       DispContBB->addSuccessor(CurMBB);
6593   }
6594
6595   // N.B. the order the invoke BBs are processed in doesn't matter here.
6596   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6597   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6598   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6599          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6600     MachineBasicBlock *BB = *I;
6601
6602     // Remove the landing pad successor from the invoke block and replace it
6603     // with the new dispatch block.
6604     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6605                                                   BB->succ_end());
6606     while (!Successors.empty()) {
6607       MachineBasicBlock *SMBB = Successors.pop_back_val();
6608       if (SMBB->isLandingPad()) {
6609         BB->removeSuccessor(SMBB);
6610         MBBLPads.push_back(SMBB);
6611       }
6612     }
6613
6614     BB->addSuccessor(DispatchBB);
6615
6616     // Find the invoke call and mark all of the callee-saved registers as
6617     // 'implicit defined' so that they're spilled. This prevents code from
6618     // moving instructions to before the EH block, where they will never be
6619     // executed.
6620     for (MachineBasicBlock::reverse_iterator
6621            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6622       if (!II->isCall()) continue;
6623
6624       DenseMap<unsigned, bool> DefRegs;
6625       for (MachineInstr::mop_iterator
6626              OI = II->operands_begin(), OE = II->operands_end();
6627            OI != OE; ++OI) {
6628         if (!OI->isReg()) continue;
6629         DefRegs[OI->getReg()] = true;
6630       }
6631
6632       MachineInstrBuilder MIB(*MF, &*II);
6633
6634       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6635         unsigned Reg = SavedRegs[i];
6636         if (Subtarget->isThumb2() &&
6637             !ARM::tGPRRegClass.contains(Reg) &&
6638             !ARM::hGPRRegClass.contains(Reg))
6639           continue;
6640         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6641           continue;
6642         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6643           continue;
6644         if (!DefRegs[Reg])
6645           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6646       }
6647
6648       break;
6649     }
6650   }
6651
6652   // Mark all former landing pads as non-landing pads. The dispatch is the only
6653   // landing pad now.
6654   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6655          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6656     (*I)->setIsLandingPad(false);
6657
6658   // The instruction is gone now.
6659   MI->eraseFromParent();
6660
6661   return MBB;
6662 }
6663
6664 static
6665 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6666   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6667        E = MBB->succ_end(); I != E; ++I)
6668     if (*I != Succ)
6669       return *I;
6670   llvm_unreachable("Expecting a BB with two successors!");
6671 }
6672
6673 MachineBasicBlock *ARMTargetLowering::
6674 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6675   // This pseudo instruction has 3 operands: dst, src, size
6676   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6677   // Otherwise, we will generate unrolled scalar copies.
6678   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6679   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6680   MachineFunction::iterator It = BB;
6681   ++It;
6682
6683   unsigned dest = MI->getOperand(0).getReg();
6684   unsigned src = MI->getOperand(1).getReg();
6685   unsigned SizeVal = MI->getOperand(2).getImm();
6686   unsigned Align = MI->getOperand(3).getImm();
6687   DebugLoc dl = MI->getDebugLoc();
6688
6689   bool isThumb2 = Subtarget->isThumb2();
6690   MachineFunction *MF = BB->getParent();
6691   MachineRegisterInfo &MRI = MF->getRegInfo();
6692   unsigned ldrOpc, strOpc, UnitSize = 0;
6693
6694   const TargetRegisterClass *TRC = isThumb2 ?
6695     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6696     (const TargetRegisterClass*)&ARM::GPRRegClass;
6697   const TargetRegisterClass *TRC_Vec = 0;
6698
6699   if (Align & 1) {
6700     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6701     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6702     UnitSize = 1;
6703   } else if (Align & 2) {
6704     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6705     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6706     UnitSize = 2;
6707   } else {
6708     // Check whether we can use NEON instructions.
6709     if (!MF->getFunction()->getAttributes().
6710           hasAttribute(AttributeSet::FunctionIndex,
6711                        Attribute::NoImplicitFloat) &&
6712         Subtarget->hasNEON()) {
6713       if ((Align % 16 == 0) && SizeVal >= 16) {
6714         ldrOpc = ARM::VLD1q32wb_fixed;
6715         strOpc = ARM::VST1q32wb_fixed;
6716         UnitSize = 16;
6717         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6718       }
6719       else if ((Align % 8 == 0) && SizeVal >= 8) {
6720         ldrOpc = ARM::VLD1d32wb_fixed;
6721         strOpc = ARM::VST1d32wb_fixed;
6722         UnitSize = 8;
6723         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6724       }
6725     }
6726     // Can't use NEON instructions.
6727     if (UnitSize == 0) {
6728       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6729       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6730       UnitSize = 4;
6731     }
6732   }
6733
6734   unsigned BytesLeft = SizeVal % UnitSize;
6735   unsigned LoopSize = SizeVal - BytesLeft;
6736
6737   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6738     // Use LDR and STR to copy.
6739     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6740     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6741     unsigned srcIn = src;
6742     unsigned destIn = dest;
6743     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6744       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6745       unsigned srcOut = MRI.createVirtualRegister(TRC);
6746       unsigned destOut = MRI.createVirtualRegister(TRC);
6747       if (UnitSize >= 8) {
6748         AddDefaultPred(BuildMI(*BB, MI, dl,
6749           TII->get(ldrOpc), scratch)
6750           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6751
6752         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6753           .addReg(destIn).addImm(0).addReg(scratch));
6754       } else if (isThumb2) {
6755         AddDefaultPred(BuildMI(*BB, MI, dl,
6756           TII->get(ldrOpc), scratch)
6757           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6758
6759         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6760           .addReg(scratch).addReg(destIn)
6761           .addImm(UnitSize));
6762       } else {
6763         AddDefaultPred(BuildMI(*BB, MI, dl,
6764           TII->get(ldrOpc), scratch)
6765           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6766           .addImm(UnitSize));
6767
6768         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6769           .addReg(scratch).addReg(destIn)
6770           .addReg(0).addImm(UnitSize));
6771       }
6772       srcIn = srcOut;
6773       destIn = destOut;
6774     }
6775
6776     // Handle the leftover bytes with LDRB and STRB.
6777     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6778     // [destOut] = STRB_POST(scratch, destIn, 1)
6779     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6780     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6781     for (unsigned i = 0; i < BytesLeft; i++) {
6782       unsigned scratch = MRI.createVirtualRegister(TRC);
6783       unsigned srcOut = MRI.createVirtualRegister(TRC);
6784       unsigned destOut = MRI.createVirtualRegister(TRC);
6785       if (isThumb2) {
6786         AddDefaultPred(BuildMI(*BB, MI, dl,
6787           TII->get(ldrOpc),scratch)
6788           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6789
6790         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6791           .addReg(scratch).addReg(destIn)
6792           .addReg(0).addImm(1));
6793       } else {
6794         AddDefaultPred(BuildMI(*BB, MI, dl,
6795           TII->get(ldrOpc),scratch)
6796           .addReg(srcOut, RegState::Define).addReg(srcIn)
6797           .addReg(0).addImm(1));
6798
6799         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6800           .addReg(scratch).addReg(destIn)
6801           .addReg(0).addImm(1));
6802       }
6803       srcIn = srcOut;
6804       destIn = destOut;
6805     }
6806     MI->eraseFromParent();   // The instruction is gone now.
6807     return BB;
6808   }
6809
6810   // Expand the pseudo op to a loop.
6811   // thisMBB:
6812   //   ...
6813   //   movw varEnd, # --> with thumb2
6814   //   movt varEnd, #
6815   //   ldrcp varEnd, idx --> without thumb2
6816   //   fallthrough --> loopMBB
6817   // loopMBB:
6818   //   PHI varPhi, varEnd, varLoop
6819   //   PHI srcPhi, src, srcLoop
6820   //   PHI destPhi, dst, destLoop
6821   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6822   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6823   //   subs varLoop, varPhi, #UnitSize
6824   //   bne loopMBB
6825   //   fallthrough --> exitMBB
6826   // exitMBB:
6827   //   epilogue to handle left-over bytes
6828   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6829   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6830   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6831   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6832   MF->insert(It, loopMBB);
6833   MF->insert(It, exitMBB);
6834
6835   // Transfer the remainder of BB and its successor edges to exitMBB.
6836   exitMBB->splice(exitMBB->begin(), BB,
6837                   llvm::next(MachineBasicBlock::iterator(MI)),
6838                   BB->end());
6839   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6840
6841   // Load an immediate to varEnd.
6842   unsigned varEnd = MRI.createVirtualRegister(TRC);
6843   if (isThumb2) {
6844     unsigned VReg1 = varEnd;
6845     if ((LoopSize & 0xFFFF0000) != 0)
6846       VReg1 = MRI.createVirtualRegister(TRC);
6847     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6848                    .addImm(LoopSize & 0xFFFF));
6849
6850     if ((LoopSize & 0xFFFF0000) != 0)
6851       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6852                      .addReg(VReg1)
6853                      .addImm(LoopSize >> 16));
6854   } else {
6855     MachineConstantPool *ConstantPool = MF->getConstantPool();
6856     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6857     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6858
6859     // MachineConstantPool wants an explicit alignment.
6860     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6861     if (Align == 0)
6862       Align = getDataLayout()->getTypeAllocSize(C->getType());
6863     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6864
6865     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6866                    .addReg(varEnd, RegState::Define)
6867                    .addConstantPoolIndex(Idx)
6868                    .addImm(0));
6869   }
6870   BB->addSuccessor(loopMBB);
6871
6872   // Generate the loop body:
6873   //   varPhi = PHI(varLoop, varEnd)
6874   //   srcPhi = PHI(srcLoop, src)
6875   //   destPhi = PHI(destLoop, dst)
6876   MachineBasicBlock *entryBB = BB;
6877   BB = loopMBB;
6878   unsigned varLoop = MRI.createVirtualRegister(TRC);
6879   unsigned varPhi = MRI.createVirtualRegister(TRC);
6880   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6881   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6882   unsigned destLoop = MRI.createVirtualRegister(TRC);
6883   unsigned destPhi = MRI.createVirtualRegister(TRC);
6884
6885   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6886     .addReg(varLoop).addMBB(loopMBB)
6887     .addReg(varEnd).addMBB(entryBB);
6888   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6889     .addReg(srcLoop).addMBB(loopMBB)
6890     .addReg(src).addMBB(entryBB);
6891   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6892     .addReg(destLoop).addMBB(loopMBB)
6893     .addReg(dest).addMBB(entryBB);
6894
6895   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6896   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6897   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6898   if (UnitSize >= 8) {
6899     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6900       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6901
6902     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6903       .addReg(destPhi).addImm(0).addReg(scratch));
6904   } else if (isThumb2) {
6905     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6906       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6907
6908     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6909       .addReg(scratch).addReg(destPhi)
6910       .addImm(UnitSize));
6911   } else {
6912     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6913       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6914       .addImm(UnitSize));
6915
6916     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6917       .addReg(scratch).addReg(destPhi)
6918       .addReg(0).addImm(UnitSize));
6919   }
6920
6921   // Decrement loop variable by UnitSize.
6922   MachineInstrBuilder MIB = BuildMI(BB, dl,
6923     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6924   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6925   MIB->getOperand(5).setReg(ARM::CPSR);
6926   MIB->getOperand(5).setIsDef(true);
6927
6928   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6929     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6930
6931   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6932   BB->addSuccessor(loopMBB);
6933   BB->addSuccessor(exitMBB);
6934
6935   // Add epilogue to handle BytesLeft.
6936   BB = exitMBB;
6937   MachineInstr *StartOfExit = exitMBB->begin();
6938   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6939   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6940
6941   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6942   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6943   unsigned srcIn = srcLoop;
6944   unsigned destIn = destLoop;
6945   for (unsigned i = 0; i < BytesLeft; i++) {
6946     unsigned scratch = MRI.createVirtualRegister(TRC);
6947     unsigned srcOut = MRI.createVirtualRegister(TRC);
6948     unsigned destOut = MRI.createVirtualRegister(TRC);
6949     if (isThumb2) {
6950       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6951         TII->get(ldrOpc),scratch)
6952         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6953
6954       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6955         .addReg(scratch).addReg(destIn)
6956         .addImm(1));
6957     } else {
6958       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6959         TII->get(ldrOpc),scratch)
6960         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6961
6962       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6963         .addReg(scratch).addReg(destIn)
6964         .addReg(0).addImm(1));
6965     }
6966     srcIn = srcOut;
6967     destIn = destOut;
6968   }
6969
6970   MI->eraseFromParent();   // The instruction is gone now.
6971   return BB;
6972 }
6973
6974 MachineBasicBlock *
6975 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6976                                                MachineBasicBlock *BB) const {
6977   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6978   DebugLoc dl = MI->getDebugLoc();
6979   bool isThumb2 = Subtarget->isThumb2();
6980   switch (MI->getOpcode()) {
6981   default: {
6982     MI->dump();
6983     llvm_unreachable("Unexpected instr type to insert");
6984   }
6985   // The Thumb2 pre-indexed stores have the same MI operands, they just
6986   // define them differently in the .td files from the isel patterns, so
6987   // they need pseudos.
6988   case ARM::t2STR_preidx:
6989     MI->setDesc(TII->get(ARM::t2STR_PRE));
6990     return BB;
6991   case ARM::t2STRB_preidx:
6992     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6993     return BB;
6994   case ARM::t2STRH_preidx:
6995     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6996     return BB;
6997
6998   case ARM::STRi_preidx:
6999   case ARM::STRBi_preidx: {
7000     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7001       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7002     // Decode the offset.
7003     unsigned Offset = MI->getOperand(4).getImm();
7004     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7005     Offset = ARM_AM::getAM2Offset(Offset);
7006     if (isSub)
7007       Offset = -Offset;
7008
7009     MachineMemOperand *MMO = *MI->memoperands_begin();
7010     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7011       .addOperand(MI->getOperand(0))  // Rn_wb
7012       .addOperand(MI->getOperand(1))  // Rt
7013       .addOperand(MI->getOperand(2))  // Rn
7014       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7015       .addOperand(MI->getOperand(5))  // pred
7016       .addOperand(MI->getOperand(6))
7017       .addMemOperand(MMO);
7018     MI->eraseFromParent();
7019     return BB;
7020   }
7021   case ARM::STRr_preidx:
7022   case ARM::STRBr_preidx:
7023   case ARM::STRH_preidx: {
7024     unsigned NewOpc;
7025     switch (MI->getOpcode()) {
7026     default: llvm_unreachable("unexpected opcode!");
7027     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7028     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7029     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7030     }
7031     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7032     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7033       MIB.addOperand(MI->getOperand(i));
7034     MI->eraseFromParent();
7035     return BB;
7036   }
7037   case ARM::ATOMIC_LOAD_ADD_I8:
7038      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7039   case ARM::ATOMIC_LOAD_ADD_I16:
7040      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7041   case ARM::ATOMIC_LOAD_ADD_I32:
7042      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7043
7044   case ARM::ATOMIC_LOAD_AND_I8:
7045      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7046   case ARM::ATOMIC_LOAD_AND_I16:
7047      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7048   case ARM::ATOMIC_LOAD_AND_I32:
7049      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7050
7051   case ARM::ATOMIC_LOAD_OR_I8:
7052      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7053   case ARM::ATOMIC_LOAD_OR_I16:
7054      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7055   case ARM::ATOMIC_LOAD_OR_I32:
7056      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7057
7058   case ARM::ATOMIC_LOAD_XOR_I8:
7059      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7060   case ARM::ATOMIC_LOAD_XOR_I16:
7061      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7062   case ARM::ATOMIC_LOAD_XOR_I32:
7063      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7064
7065   case ARM::ATOMIC_LOAD_NAND_I8:
7066      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7067   case ARM::ATOMIC_LOAD_NAND_I16:
7068      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7069   case ARM::ATOMIC_LOAD_NAND_I32:
7070      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7071
7072   case ARM::ATOMIC_LOAD_SUB_I8:
7073      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7074   case ARM::ATOMIC_LOAD_SUB_I16:
7075      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7076   case ARM::ATOMIC_LOAD_SUB_I32:
7077      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7078
7079   case ARM::ATOMIC_LOAD_MIN_I8:
7080      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7081   case ARM::ATOMIC_LOAD_MIN_I16:
7082      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7083   case ARM::ATOMIC_LOAD_MIN_I32:
7084      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7085
7086   case ARM::ATOMIC_LOAD_MAX_I8:
7087      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7088   case ARM::ATOMIC_LOAD_MAX_I16:
7089      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7090   case ARM::ATOMIC_LOAD_MAX_I32:
7091      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7092
7093   case ARM::ATOMIC_LOAD_UMIN_I8:
7094      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7095   case ARM::ATOMIC_LOAD_UMIN_I16:
7096      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7097   case ARM::ATOMIC_LOAD_UMIN_I32:
7098      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7099
7100   case ARM::ATOMIC_LOAD_UMAX_I8:
7101      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7102   case ARM::ATOMIC_LOAD_UMAX_I16:
7103      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7104   case ARM::ATOMIC_LOAD_UMAX_I32:
7105      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7106
7107   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7108   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7109   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7110
7111   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7112   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7113   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7114
7115
7116   case ARM::ATOMADD6432:
7117     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7118                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7119                               /*NeedsCarry*/ true);
7120   case ARM::ATOMSUB6432:
7121     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7122                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7123                               /*NeedsCarry*/ true);
7124   case ARM::ATOMOR6432:
7125     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7126                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7127   case ARM::ATOMXOR6432:
7128     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7129                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7130   case ARM::ATOMAND6432:
7131     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7132                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7133   case ARM::ATOMSWAP6432:
7134     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7135   case ARM::ATOMCMPXCHG6432:
7136     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7137                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7138                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7139   case ARM::ATOMMIN6432:
7140     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7141                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7142                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7143                               /*IsMinMax*/ true, ARMCC::LT);
7144   case ARM::ATOMMAX6432:
7145     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7146                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7147                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7148                               /*IsMinMax*/ true, ARMCC::GE);
7149   case ARM::ATOMUMIN6432:
7150     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7151                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7152                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7153                               /*IsMinMax*/ true, ARMCC::LO);
7154   case ARM::ATOMUMAX6432:
7155     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7156                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7157                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7158                               /*IsMinMax*/ true, ARMCC::HS);
7159
7160   case ARM::tMOVCCr_pseudo: {
7161     // To "insert" a SELECT_CC instruction, we actually have to insert the
7162     // diamond control-flow pattern.  The incoming instruction knows the
7163     // destination vreg to set, the condition code register to branch on, the
7164     // true/false values to select between, and a branch opcode to use.
7165     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7166     MachineFunction::iterator It = BB;
7167     ++It;
7168
7169     //  thisMBB:
7170     //  ...
7171     //   TrueVal = ...
7172     //   cmpTY ccX, r1, r2
7173     //   bCC copy1MBB
7174     //   fallthrough --> copy0MBB
7175     MachineBasicBlock *thisMBB  = BB;
7176     MachineFunction *F = BB->getParent();
7177     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7178     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7179     F->insert(It, copy0MBB);
7180     F->insert(It, sinkMBB);
7181
7182     // Transfer the remainder of BB and its successor edges to sinkMBB.
7183     sinkMBB->splice(sinkMBB->begin(), BB,
7184                     llvm::next(MachineBasicBlock::iterator(MI)),
7185                     BB->end());
7186     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7187
7188     BB->addSuccessor(copy0MBB);
7189     BB->addSuccessor(sinkMBB);
7190
7191     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7192       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7193
7194     //  copy0MBB:
7195     //   %FalseValue = ...
7196     //   # fallthrough to sinkMBB
7197     BB = copy0MBB;
7198
7199     // Update machine-CFG edges
7200     BB->addSuccessor(sinkMBB);
7201
7202     //  sinkMBB:
7203     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7204     //  ...
7205     BB = sinkMBB;
7206     BuildMI(*BB, BB->begin(), dl,
7207             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7208       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7209       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7210
7211     MI->eraseFromParent();   // The pseudo instruction is gone now.
7212     return BB;
7213   }
7214
7215   case ARM::BCCi64:
7216   case ARM::BCCZi64: {
7217     // If there is an unconditional branch to the other successor, remove it.
7218     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7219
7220     // Compare both parts that make up the double comparison separately for
7221     // equality.
7222     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7223
7224     unsigned LHS1 = MI->getOperand(1).getReg();
7225     unsigned LHS2 = MI->getOperand(2).getReg();
7226     if (RHSisZero) {
7227       AddDefaultPred(BuildMI(BB, dl,
7228                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7229                      .addReg(LHS1).addImm(0));
7230       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7231         .addReg(LHS2).addImm(0)
7232         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7233     } else {
7234       unsigned RHS1 = MI->getOperand(3).getReg();
7235       unsigned RHS2 = MI->getOperand(4).getReg();
7236       AddDefaultPred(BuildMI(BB, dl,
7237                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7238                      .addReg(LHS1).addReg(RHS1));
7239       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7240         .addReg(LHS2).addReg(RHS2)
7241         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7242     }
7243
7244     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7245     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7246     if (MI->getOperand(0).getImm() == ARMCC::NE)
7247       std::swap(destMBB, exitMBB);
7248
7249     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7250       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7251     if (isThumb2)
7252       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7253     else
7254       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7255
7256     MI->eraseFromParent();   // The pseudo instruction is gone now.
7257     return BB;
7258   }
7259
7260   case ARM::Int_eh_sjlj_setjmp:
7261   case ARM::Int_eh_sjlj_setjmp_nofp:
7262   case ARM::tInt_eh_sjlj_setjmp:
7263   case ARM::t2Int_eh_sjlj_setjmp:
7264   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7265     EmitSjLjDispatchBlock(MI, BB);
7266     return BB;
7267
7268   case ARM::ABS:
7269   case ARM::t2ABS: {
7270     // To insert an ABS instruction, we have to insert the
7271     // diamond control-flow pattern.  The incoming instruction knows the
7272     // source vreg to test against 0, the destination vreg to set,
7273     // the condition code register to branch on, the
7274     // true/false values to select between, and a branch opcode to use.
7275     // It transforms
7276     //     V1 = ABS V0
7277     // into
7278     //     V2 = MOVS V0
7279     //     BCC                      (branch to SinkBB if V0 >= 0)
7280     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7281     //     SinkBB: V1 = PHI(V2, V3)
7282     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7283     MachineFunction::iterator BBI = BB;
7284     ++BBI;
7285     MachineFunction *Fn = BB->getParent();
7286     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7287     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7288     Fn->insert(BBI, RSBBB);
7289     Fn->insert(BBI, SinkBB);
7290
7291     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7292     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7293     bool isThumb2 = Subtarget->isThumb2();
7294     MachineRegisterInfo &MRI = Fn->getRegInfo();
7295     // In Thumb mode S must not be specified if source register is the SP or
7296     // PC and if destination register is the SP, so restrict register class
7297     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7298       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7299       (const TargetRegisterClass*)&ARM::GPRRegClass);
7300
7301     // Transfer the remainder of BB and its successor edges to sinkMBB.
7302     SinkBB->splice(SinkBB->begin(), BB,
7303       llvm::next(MachineBasicBlock::iterator(MI)),
7304       BB->end());
7305     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7306
7307     BB->addSuccessor(RSBBB);
7308     BB->addSuccessor(SinkBB);
7309
7310     // fall through to SinkMBB
7311     RSBBB->addSuccessor(SinkBB);
7312
7313     // insert a cmp at the end of BB
7314     AddDefaultPred(BuildMI(BB, dl,
7315                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7316                    .addReg(ABSSrcReg).addImm(0));
7317
7318     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7319     BuildMI(BB, dl,
7320       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7321       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7322
7323     // insert rsbri in RSBBB
7324     // Note: BCC and rsbri will be converted into predicated rsbmi
7325     // by if-conversion pass
7326     BuildMI(*RSBBB, RSBBB->begin(), dl,
7327       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7328       .addReg(ABSSrcReg, RegState::Kill)
7329       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7330
7331     // insert PHI in SinkBB,
7332     // reuse ABSDstReg to not change uses of ABS instruction
7333     BuildMI(*SinkBB, SinkBB->begin(), dl,
7334       TII->get(ARM::PHI), ABSDstReg)
7335       .addReg(NewRsbDstReg).addMBB(RSBBB)
7336       .addReg(ABSSrcReg).addMBB(BB);
7337
7338     // remove ABS instruction
7339     MI->eraseFromParent();
7340
7341     // return last added BB
7342     return SinkBB;
7343   }
7344   case ARM::COPY_STRUCT_BYVAL_I32:
7345     ++NumLoopByVals;
7346     return EmitStructByval(MI, BB);
7347   }
7348 }
7349
7350 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7351                                                       SDNode *Node) const {
7352   if (!MI->hasPostISelHook()) {
7353     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7354            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7355     return;
7356   }
7357
7358   const MCInstrDesc *MCID = &MI->getDesc();
7359   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7360   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7361   // operand is still set to noreg. If needed, set the optional operand's
7362   // register to CPSR, and remove the redundant implicit def.
7363   //
7364   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7365
7366   // Rename pseudo opcodes.
7367   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7368   if (NewOpc) {
7369     const ARMBaseInstrInfo *TII =
7370       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7371     MCID = &TII->get(NewOpc);
7372
7373     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7374            "converted opcode should be the same except for cc_out");
7375
7376     MI->setDesc(*MCID);
7377
7378     // Add the optional cc_out operand
7379     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7380   }
7381   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7382
7383   // Any ARM instruction that sets the 's' bit should specify an optional
7384   // "cc_out" operand in the last operand position.
7385   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7386     assert(!NewOpc && "Optional cc_out operand required");
7387     return;
7388   }
7389   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7390   // since we already have an optional CPSR def.
7391   bool definesCPSR = false;
7392   bool deadCPSR = false;
7393   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7394        i != e; ++i) {
7395     const MachineOperand &MO = MI->getOperand(i);
7396     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7397       definesCPSR = true;
7398       if (MO.isDead())
7399         deadCPSR = true;
7400       MI->RemoveOperand(i);
7401       break;
7402     }
7403   }
7404   if (!definesCPSR) {
7405     assert(!NewOpc && "Optional cc_out operand required");
7406     return;
7407   }
7408   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7409   if (deadCPSR) {
7410     assert(!MI->getOperand(ccOutIdx).getReg() &&
7411            "expect uninitialized optional cc_out operand");
7412     return;
7413   }
7414
7415   // If this instruction was defined with an optional CPSR def and its dag node
7416   // had a live implicit CPSR def, then activate the optional CPSR def.
7417   MachineOperand &MO = MI->getOperand(ccOutIdx);
7418   MO.setReg(ARM::CPSR);
7419   MO.setIsDef(true);
7420 }
7421
7422 //===----------------------------------------------------------------------===//
7423 //                           ARM Optimization Hooks
7424 //===----------------------------------------------------------------------===//
7425
7426 // Helper function that checks if N is a null or all ones constant.
7427 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7428   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7429   if (!C)
7430     return false;
7431   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7432 }
7433
7434 // Return true if N is conditionally 0 or all ones.
7435 // Detects these expressions where cc is an i1 value:
7436 //
7437 //   (select cc 0, y)   [AllOnes=0]
7438 //   (select cc y, 0)   [AllOnes=0]
7439 //   (zext cc)          [AllOnes=0]
7440 //   (sext cc)          [AllOnes=0/1]
7441 //   (select cc -1, y)  [AllOnes=1]
7442 //   (select cc y, -1)  [AllOnes=1]
7443 //
7444 // Invert is set when N is the null/all ones constant when CC is false.
7445 // OtherOp is set to the alternative value of N.
7446 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7447                                        SDValue &CC, bool &Invert,
7448                                        SDValue &OtherOp,
7449                                        SelectionDAG &DAG) {
7450   switch (N->getOpcode()) {
7451   default: return false;
7452   case ISD::SELECT: {
7453     CC = N->getOperand(0);
7454     SDValue N1 = N->getOperand(1);
7455     SDValue N2 = N->getOperand(2);
7456     if (isZeroOrAllOnes(N1, AllOnes)) {
7457       Invert = false;
7458       OtherOp = N2;
7459       return true;
7460     }
7461     if (isZeroOrAllOnes(N2, AllOnes)) {
7462       Invert = true;
7463       OtherOp = N1;
7464       return true;
7465     }
7466     return false;
7467   }
7468   case ISD::ZERO_EXTEND:
7469     // (zext cc) can never be the all ones value.
7470     if (AllOnes)
7471       return false;
7472     // Fall through.
7473   case ISD::SIGN_EXTEND: {
7474     EVT VT = N->getValueType(0);
7475     CC = N->getOperand(0);
7476     if (CC.getValueType() != MVT::i1)
7477       return false;
7478     Invert = !AllOnes;
7479     if (AllOnes)
7480       // When looking for an AllOnes constant, N is an sext, and the 'other'
7481       // value is 0.
7482       OtherOp = DAG.getConstant(0, VT);
7483     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7484       // When looking for a 0 constant, N can be zext or sext.
7485       OtherOp = DAG.getConstant(1, VT);
7486     else
7487       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7488     return true;
7489   }
7490   }
7491 }
7492
7493 // Combine a constant select operand into its use:
7494 //
7495 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7496 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7497 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7498 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7499 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7500 //
7501 // The transform is rejected if the select doesn't have a constant operand that
7502 // is null, or all ones when AllOnes is set.
7503 //
7504 // Also recognize sext/zext from i1:
7505 //
7506 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7507 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7508 //
7509 // These transformations eventually create predicated instructions.
7510 //
7511 // @param N       The node to transform.
7512 // @param Slct    The N operand that is a select.
7513 // @param OtherOp The other N operand (x above).
7514 // @param DCI     Context.
7515 // @param AllOnes Require the select constant to be all ones instead of null.
7516 // @returns The new node, or SDValue() on failure.
7517 static
7518 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7519                             TargetLowering::DAGCombinerInfo &DCI,
7520                             bool AllOnes = false) {
7521   SelectionDAG &DAG = DCI.DAG;
7522   EVT VT = N->getValueType(0);
7523   SDValue NonConstantVal;
7524   SDValue CCOp;
7525   bool SwapSelectOps;
7526   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7527                                   NonConstantVal, DAG))
7528     return SDValue();
7529
7530   // Slct is now know to be the desired identity constant when CC is true.
7531   SDValue TrueVal = OtherOp;
7532   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7533                                  OtherOp, NonConstantVal);
7534   // Unless SwapSelectOps says CC should be false.
7535   if (SwapSelectOps)
7536     std::swap(TrueVal, FalseVal);
7537
7538   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7539                      CCOp, TrueVal, FalseVal);
7540 }
7541
7542 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7543 static
7544 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7545                                        TargetLowering::DAGCombinerInfo &DCI) {
7546   SDValue N0 = N->getOperand(0);
7547   SDValue N1 = N->getOperand(1);
7548   if (N0.getNode()->hasOneUse()) {
7549     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7550     if (Result.getNode())
7551       return Result;
7552   }
7553   if (N1.getNode()->hasOneUse()) {
7554     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7555     if (Result.getNode())
7556       return Result;
7557   }
7558   return SDValue();
7559 }
7560
7561 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7562 // (only after legalization).
7563 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7564                                  TargetLowering::DAGCombinerInfo &DCI,
7565                                  const ARMSubtarget *Subtarget) {
7566
7567   // Only perform optimization if after legalize, and if NEON is available. We
7568   // also expected both operands to be BUILD_VECTORs.
7569   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7570       || N0.getOpcode() != ISD::BUILD_VECTOR
7571       || N1.getOpcode() != ISD::BUILD_VECTOR)
7572     return SDValue();
7573
7574   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7575   EVT VT = N->getValueType(0);
7576   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7577     return SDValue();
7578
7579   // Check that the vector operands are of the right form.
7580   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7581   // operands, where N is the size of the formed vector.
7582   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7583   // index such that we have a pair wise add pattern.
7584
7585   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7586   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7587     return SDValue();
7588   SDValue Vec = N0->getOperand(0)->getOperand(0);
7589   SDNode *V = Vec.getNode();
7590   unsigned nextIndex = 0;
7591
7592   // For each operands to the ADD which are BUILD_VECTORs,
7593   // check to see if each of their operands are an EXTRACT_VECTOR with
7594   // the same vector and appropriate index.
7595   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7596     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7597         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7598
7599       SDValue ExtVec0 = N0->getOperand(i);
7600       SDValue ExtVec1 = N1->getOperand(i);
7601
7602       // First operand is the vector, verify its the same.
7603       if (V != ExtVec0->getOperand(0).getNode() ||
7604           V != ExtVec1->getOperand(0).getNode())
7605         return SDValue();
7606
7607       // Second is the constant, verify its correct.
7608       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7609       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7610
7611       // For the constant, we want to see all the even or all the odd.
7612       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7613           || C1->getZExtValue() != nextIndex+1)
7614         return SDValue();
7615
7616       // Increment index.
7617       nextIndex+=2;
7618     } else
7619       return SDValue();
7620   }
7621
7622   // Create VPADDL node.
7623   SelectionDAG &DAG = DCI.DAG;
7624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7625
7626   // Build operand list.
7627   SmallVector<SDValue, 8> Ops;
7628   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7629                                 TLI.getPointerTy()));
7630
7631   // Input is the vector.
7632   Ops.push_back(Vec);
7633
7634   // Get widened type and narrowed type.
7635   MVT widenType;
7636   unsigned numElem = VT.getVectorNumElements();
7637   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7638     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7639     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7640     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7641     default:
7642       llvm_unreachable("Invalid vector element type for padd optimization.");
7643   }
7644
7645   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7646                             widenType, &Ops[0], Ops.size());
7647   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7648 }
7649
7650 static SDValue findMUL_LOHI(SDValue V) {
7651   if (V->getOpcode() == ISD::UMUL_LOHI ||
7652       V->getOpcode() == ISD::SMUL_LOHI)
7653     return V;
7654   return SDValue();
7655 }
7656
7657 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7658                                      TargetLowering::DAGCombinerInfo &DCI,
7659                                      const ARMSubtarget *Subtarget) {
7660
7661   if (Subtarget->isThumb1Only()) return SDValue();
7662
7663   // Only perform the checks after legalize when the pattern is available.
7664   if (DCI.isBeforeLegalize()) return SDValue();
7665
7666   // Look for multiply add opportunities.
7667   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7668   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7669   // a glue link from the first add to the second add.
7670   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7671   // a S/UMLAL instruction.
7672   //          loAdd   UMUL_LOHI
7673   //            \    / :lo    \ :hi
7674   //             \  /          \          [no multiline comment]
7675   //              ADDC         |  hiAdd
7676   //                 \ :glue  /  /
7677   //                  \      /  /
7678   //                    ADDE
7679   //
7680   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7681   SDValue AddcOp0 = AddcNode->getOperand(0);
7682   SDValue AddcOp1 = AddcNode->getOperand(1);
7683
7684   // Check if the two operands are from the same mul_lohi node.
7685   if (AddcOp0.getNode() == AddcOp1.getNode())
7686     return SDValue();
7687
7688   assert(AddcNode->getNumValues() == 2 &&
7689          AddcNode->getValueType(0) == MVT::i32 &&
7690          AddcNode->getValueType(1) == MVT::Glue &&
7691          "Expect ADDC with two result values: i32, glue");
7692
7693   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7694   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7695       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7696       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7697       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7698     return SDValue();
7699
7700   // Look for the glued ADDE.
7701   SDNode* AddeNode = AddcNode->getGluedUser();
7702   if (AddeNode == NULL)
7703     return SDValue();
7704
7705   // Make sure it is really an ADDE.
7706   if (AddeNode->getOpcode() != ISD::ADDE)
7707     return SDValue();
7708
7709   assert(AddeNode->getNumOperands() == 3 &&
7710          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7711          "ADDE node has the wrong inputs");
7712
7713   // Check for the triangle shape.
7714   SDValue AddeOp0 = AddeNode->getOperand(0);
7715   SDValue AddeOp1 = AddeNode->getOperand(1);
7716
7717   // Make sure that the ADDE operands are not coming from the same node.
7718   if (AddeOp0.getNode() == AddeOp1.getNode())
7719     return SDValue();
7720
7721   // Find the MUL_LOHI node walking up ADDE's operands.
7722   bool IsLeftOperandMUL = false;
7723   SDValue MULOp = findMUL_LOHI(AddeOp0);
7724   if (MULOp == SDValue())
7725    MULOp = findMUL_LOHI(AddeOp1);
7726   else
7727     IsLeftOperandMUL = true;
7728   if (MULOp == SDValue())
7729      return SDValue();
7730
7731   // Figure out the right opcode.
7732   unsigned Opc = MULOp->getOpcode();
7733   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7734
7735   // Figure out the high and low input values to the MLAL node.
7736   SDValue* HiMul = &MULOp;
7737   SDValue* HiAdd = NULL;
7738   SDValue* LoMul = NULL;
7739   SDValue* LowAdd = NULL;
7740
7741   if (IsLeftOperandMUL)
7742     HiAdd = &AddeOp1;
7743   else
7744     HiAdd = &AddeOp0;
7745
7746
7747   if (AddcOp0->getOpcode() == Opc) {
7748     LoMul = &AddcOp0;
7749     LowAdd = &AddcOp1;
7750   }
7751   if (AddcOp1->getOpcode() == Opc) {
7752     LoMul = &AddcOp1;
7753     LowAdd = &AddcOp0;
7754   }
7755
7756   if (LoMul == NULL)
7757     return SDValue();
7758
7759   if (LoMul->getNode() != HiMul->getNode())
7760     return SDValue();
7761
7762   // Create the merged node.
7763   SelectionDAG &DAG = DCI.DAG;
7764
7765   // Build operand list.
7766   SmallVector<SDValue, 8> Ops;
7767   Ops.push_back(LoMul->getOperand(0));
7768   Ops.push_back(LoMul->getOperand(1));
7769   Ops.push_back(*LowAdd);
7770   Ops.push_back(*HiAdd);
7771
7772   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7773                                  DAG.getVTList(MVT::i32, MVT::i32),
7774                                  &Ops[0], Ops.size());
7775
7776   // Replace the ADDs' nodes uses by the MLA node's values.
7777   SDValue HiMLALResult(MLALNode.getNode(), 1);
7778   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7779
7780   SDValue LoMLALResult(MLALNode.getNode(), 0);
7781   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7782
7783   // Return original node to notify the driver to stop replacing.
7784   SDValue resNode(AddcNode, 0);
7785   return resNode;
7786 }
7787
7788 /// PerformADDCCombine - Target-specific dag combine transform from
7789 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7790 static SDValue PerformADDCCombine(SDNode *N,
7791                                  TargetLowering::DAGCombinerInfo &DCI,
7792                                  const ARMSubtarget *Subtarget) {
7793
7794   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7795
7796 }
7797
7798 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7799 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7800 /// called with the default operands, and if that fails, with commuted
7801 /// operands.
7802 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7803                                           TargetLowering::DAGCombinerInfo &DCI,
7804                                           const ARMSubtarget *Subtarget){
7805
7806   // Attempt to create vpaddl for this add.
7807   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7808   if (Result.getNode())
7809     return Result;
7810
7811   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7812   if (N0.getNode()->hasOneUse()) {
7813     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7814     if (Result.getNode()) return Result;
7815   }
7816   return SDValue();
7817 }
7818
7819 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7820 ///
7821 static SDValue PerformADDCombine(SDNode *N,
7822                                  TargetLowering::DAGCombinerInfo &DCI,
7823                                  const ARMSubtarget *Subtarget) {
7824   SDValue N0 = N->getOperand(0);
7825   SDValue N1 = N->getOperand(1);
7826
7827   // First try with the default operand order.
7828   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7829   if (Result.getNode())
7830     return Result;
7831
7832   // If that didn't work, try again with the operands commuted.
7833   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7834 }
7835
7836 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7837 ///
7838 static SDValue PerformSUBCombine(SDNode *N,
7839                                  TargetLowering::DAGCombinerInfo &DCI) {
7840   SDValue N0 = N->getOperand(0);
7841   SDValue N1 = N->getOperand(1);
7842
7843   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7844   if (N1.getNode()->hasOneUse()) {
7845     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7846     if (Result.getNode()) return Result;
7847   }
7848
7849   return SDValue();
7850 }
7851
7852 /// PerformVMULCombine
7853 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7854 /// special multiplier accumulator forwarding.
7855 ///   vmul d3, d0, d2
7856 ///   vmla d3, d1, d2
7857 /// is faster than
7858 ///   vadd d3, d0, d1
7859 ///   vmul d3, d3, d2
7860 static SDValue PerformVMULCombine(SDNode *N,
7861                                   TargetLowering::DAGCombinerInfo &DCI,
7862                                   const ARMSubtarget *Subtarget) {
7863   if (!Subtarget->hasVMLxForwarding())
7864     return SDValue();
7865
7866   SelectionDAG &DAG = DCI.DAG;
7867   SDValue N0 = N->getOperand(0);
7868   SDValue N1 = N->getOperand(1);
7869   unsigned Opcode = N0.getOpcode();
7870   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7871       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7872     Opcode = N1.getOpcode();
7873     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7874         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7875       return SDValue();
7876     std::swap(N0, N1);
7877   }
7878
7879   EVT VT = N->getValueType(0);
7880   DebugLoc DL = N->getDebugLoc();
7881   SDValue N00 = N0->getOperand(0);
7882   SDValue N01 = N0->getOperand(1);
7883   return DAG.getNode(Opcode, DL, VT,
7884                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7885                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7886 }
7887
7888 static SDValue PerformMULCombine(SDNode *N,
7889                                  TargetLowering::DAGCombinerInfo &DCI,
7890                                  const ARMSubtarget *Subtarget) {
7891   SelectionDAG &DAG = DCI.DAG;
7892
7893   if (Subtarget->isThumb1Only())
7894     return SDValue();
7895
7896   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7897     return SDValue();
7898
7899   EVT VT = N->getValueType(0);
7900   if (VT.is64BitVector() || VT.is128BitVector())
7901     return PerformVMULCombine(N, DCI, Subtarget);
7902   if (VT != MVT::i32)
7903     return SDValue();
7904
7905   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7906   if (!C)
7907     return SDValue();
7908
7909   int64_t MulAmt = C->getSExtValue();
7910   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7911
7912   ShiftAmt = ShiftAmt & (32 - 1);
7913   SDValue V = N->getOperand(0);
7914   DebugLoc DL = N->getDebugLoc();
7915
7916   SDValue Res;
7917   MulAmt >>= ShiftAmt;
7918
7919   if (MulAmt >= 0) {
7920     if (isPowerOf2_32(MulAmt - 1)) {
7921       // (mul x, 2^N + 1) => (add (shl x, N), x)
7922       Res = DAG.getNode(ISD::ADD, DL, VT,
7923                         V,
7924                         DAG.getNode(ISD::SHL, DL, VT,
7925                                     V,
7926                                     DAG.getConstant(Log2_32(MulAmt - 1),
7927                                                     MVT::i32)));
7928     } else if (isPowerOf2_32(MulAmt + 1)) {
7929       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7930       Res = DAG.getNode(ISD::SUB, DL, VT,
7931                         DAG.getNode(ISD::SHL, DL, VT,
7932                                     V,
7933                                     DAG.getConstant(Log2_32(MulAmt + 1),
7934                                                     MVT::i32)),
7935                         V);
7936     } else
7937       return SDValue();
7938   } else {
7939     uint64_t MulAmtAbs = -MulAmt;
7940     if (isPowerOf2_32(MulAmtAbs + 1)) {
7941       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7942       Res = DAG.getNode(ISD::SUB, DL, VT,
7943                         V,
7944                         DAG.getNode(ISD::SHL, DL, VT,
7945                                     V,
7946                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7947                                                     MVT::i32)));
7948     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7949       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7950       Res = DAG.getNode(ISD::ADD, DL, VT,
7951                         V,
7952                         DAG.getNode(ISD::SHL, DL, VT,
7953                                     V,
7954                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7955                                                     MVT::i32)));
7956       Res = DAG.getNode(ISD::SUB, DL, VT,
7957                         DAG.getConstant(0, MVT::i32),Res);
7958
7959     } else
7960       return SDValue();
7961   }
7962
7963   if (ShiftAmt != 0)
7964     Res = DAG.getNode(ISD::SHL, DL, VT,
7965                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7966
7967   // Do not add new nodes to DAG combiner worklist.
7968   DCI.CombineTo(N, Res, false);
7969   return SDValue();
7970 }
7971
7972 static SDValue PerformANDCombine(SDNode *N,
7973                                  TargetLowering::DAGCombinerInfo &DCI,
7974                                  const ARMSubtarget *Subtarget) {
7975
7976   // Attempt to use immediate-form VBIC
7977   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7978   DebugLoc dl = N->getDebugLoc();
7979   EVT VT = N->getValueType(0);
7980   SelectionDAG &DAG = DCI.DAG;
7981
7982   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7983     return SDValue();
7984
7985   APInt SplatBits, SplatUndef;
7986   unsigned SplatBitSize;
7987   bool HasAnyUndefs;
7988   if (BVN &&
7989       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7990     if (SplatBitSize <= 64) {
7991       EVT VbicVT;
7992       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7993                                       SplatUndef.getZExtValue(), SplatBitSize,
7994                                       DAG, VbicVT, VT.is128BitVector(),
7995                                       OtherModImm);
7996       if (Val.getNode()) {
7997         SDValue Input =
7998           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7999         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8000         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8001       }
8002     }
8003   }
8004
8005   if (!Subtarget->isThumb1Only()) {
8006     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8007     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8008     if (Result.getNode())
8009       return Result;
8010   }
8011
8012   return SDValue();
8013 }
8014
8015 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8016 static SDValue PerformORCombine(SDNode *N,
8017                                 TargetLowering::DAGCombinerInfo &DCI,
8018                                 const ARMSubtarget *Subtarget) {
8019   // Attempt to use immediate-form VORR
8020   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8021   DebugLoc dl = N->getDebugLoc();
8022   EVT VT = N->getValueType(0);
8023   SelectionDAG &DAG = DCI.DAG;
8024
8025   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8026     return SDValue();
8027
8028   APInt SplatBits, SplatUndef;
8029   unsigned SplatBitSize;
8030   bool HasAnyUndefs;
8031   if (BVN && Subtarget->hasNEON() &&
8032       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8033     if (SplatBitSize <= 64) {
8034       EVT VorrVT;
8035       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8036                                       SplatUndef.getZExtValue(), SplatBitSize,
8037                                       DAG, VorrVT, VT.is128BitVector(),
8038                                       OtherModImm);
8039       if (Val.getNode()) {
8040         SDValue Input =
8041           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8042         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8043         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8044       }
8045     }
8046   }
8047
8048   if (!Subtarget->isThumb1Only()) {
8049     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8050     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8051     if (Result.getNode())
8052       return Result;
8053   }
8054
8055   // The code below optimizes (or (and X, Y), Z).
8056   // The AND operand needs to have a single user to make these optimizations
8057   // profitable.
8058   SDValue N0 = N->getOperand(0);
8059   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8060     return SDValue();
8061   SDValue N1 = N->getOperand(1);
8062
8063   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8064   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8065       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8066     APInt SplatUndef;
8067     unsigned SplatBitSize;
8068     bool HasAnyUndefs;
8069
8070     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8071     APInt SplatBits0;
8072     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8073                                   HasAnyUndefs) && !HasAnyUndefs) {
8074       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8075       APInt SplatBits1;
8076       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8077                                     HasAnyUndefs) && !HasAnyUndefs &&
8078           SplatBits0 == ~SplatBits1) {
8079         // Canonicalize the vector type to make instruction selection simpler.
8080         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8081         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8082                                      N0->getOperand(1), N0->getOperand(0),
8083                                      N1->getOperand(0));
8084         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8085       }
8086     }
8087   }
8088
8089   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8090   // reasonable.
8091
8092   // BFI is only available on V6T2+
8093   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8094     return SDValue();
8095
8096   DebugLoc DL = N->getDebugLoc();
8097   // 1) or (and A, mask), val => ARMbfi A, val, mask
8098   //      iff (val & mask) == val
8099   //
8100   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8101   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8102   //          && mask == ~mask2
8103   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8104   //          && ~mask == mask2
8105   //  (i.e., copy a bitfield value into another bitfield of the same width)
8106
8107   if (VT != MVT::i32)
8108     return SDValue();
8109
8110   SDValue N00 = N0.getOperand(0);
8111
8112   // The value and the mask need to be constants so we can verify this is
8113   // actually a bitfield set. If the mask is 0xffff, we can do better
8114   // via a movt instruction, so don't use BFI in that case.
8115   SDValue MaskOp = N0.getOperand(1);
8116   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8117   if (!MaskC)
8118     return SDValue();
8119   unsigned Mask = MaskC->getZExtValue();
8120   if (Mask == 0xffff)
8121     return SDValue();
8122   SDValue Res;
8123   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8124   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8125   if (N1C) {
8126     unsigned Val = N1C->getZExtValue();
8127     if ((Val & ~Mask) != Val)
8128       return SDValue();
8129
8130     if (ARM::isBitFieldInvertedMask(Mask)) {
8131       Val >>= CountTrailingZeros_32(~Mask);
8132
8133       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8134                         DAG.getConstant(Val, MVT::i32),
8135                         DAG.getConstant(Mask, MVT::i32));
8136
8137       // Do not add new nodes to DAG combiner worklist.
8138       DCI.CombineTo(N, Res, false);
8139       return SDValue();
8140     }
8141   } else if (N1.getOpcode() == ISD::AND) {
8142     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8143     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8144     if (!N11C)
8145       return SDValue();
8146     unsigned Mask2 = N11C->getZExtValue();
8147
8148     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8149     // as is to match.
8150     if (ARM::isBitFieldInvertedMask(Mask) &&
8151         (Mask == ~Mask2)) {
8152       // The pack halfword instruction works better for masks that fit it,
8153       // so use that when it's available.
8154       if (Subtarget->hasT2ExtractPack() &&
8155           (Mask == 0xffff || Mask == 0xffff0000))
8156         return SDValue();
8157       // 2a
8158       unsigned amt = CountTrailingZeros_32(Mask2);
8159       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8160                         DAG.getConstant(amt, MVT::i32));
8161       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8162                         DAG.getConstant(Mask, MVT::i32));
8163       // Do not add new nodes to DAG combiner worklist.
8164       DCI.CombineTo(N, Res, false);
8165       return SDValue();
8166     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8167                (~Mask == Mask2)) {
8168       // The pack halfword instruction works better for masks that fit it,
8169       // so use that when it's available.
8170       if (Subtarget->hasT2ExtractPack() &&
8171           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8172         return SDValue();
8173       // 2b
8174       unsigned lsb = CountTrailingZeros_32(Mask);
8175       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8176                         DAG.getConstant(lsb, MVT::i32));
8177       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8178                         DAG.getConstant(Mask2, MVT::i32));
8179       // Do not add new nodes to DAG combiner worklist.
8180       DCI.CombineTo(N, Res, false);
8181       return SDValue();
8182     }
8183   }
8184
8185   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8186       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8187       ARM::isBitFieldInvertedMask(~Mask)) {
8188     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8189     // where lsb(mask) == #shamt and masked bits of B are known zero.
8190     SDValue ShAmt = N00.getOperand(1);
8191     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8192     unsigned LSB = CountTrailingZeros_32(Mask);
8193     if (ShAmtC != LSB)
8194       return SDValue();
8195
8196     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8197                       DAG.getConstant(~Mask, MVT::i32));
8198
8199     // Do not add new nodes to DAG combiner worklist.
8200     DCI.CombineTo(N, Res, false);
8201   }
8202
8203   return SDValue();
8204 }
8205
8206 static SDValue PerformXORCombine(SDNode *N,
8207                                  TargetLowering::DAGCombinerInfo &DCI,
8208                                  const ARMSubtarget *Subtarget) {
8209   EVT VT = N->getValueType(0);
8210   SelectionDAG &DAG = DCI.DAG;
8211
8212   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8213     return SDValue();
8214
8215   if (!Subtarget->isThumb1Only()) {
8216     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8217     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8218     if (Result.getNode())
8219       return Result;
8220   }
8221
8222   return SDValue();
8223 }
8224
8225 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8226 /// the bits being cleared by the AND are not demanded by the BFI.
8227 static SDValue PerformBFICombine(SDNode *N,
8228                                  TargetLowering::DAGCombinerInfo &DCI) {
8229   SDValue N1 = N->getOperand(1);
8230   if (N1.getOpcode() == ISD::AND) {
8231     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8232     if (!N11C)
8233       return SDValue();
8234     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8235     unsigned LSB = CountTrailingZeros_32(~InvMask);
8236     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8237     unsigned Mask = (1 << Width)-1;
8238     unsigned Mask2 = N11C->getZExtValue();
8239     if ((Mask & (~Mask2)) == 0)
8240       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8241                              N->getOperand(0), N1.getOperand(0),
8242                              N->getOperand(2));
8243   }
8244   return SDValue();
8245 }
8246
8247 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8248 /// ARMISD::VMOVRRD.
8249 static SDValue PerformVMOVRRDCombine(SDNode *N,
8250                                      TargetLowering::DAGCombinerInfo &DCI) {
8251   // vmovrrd(vmovdrr x, y) -> x,y
8252   SDValue InDouble = N->getOperand(0);
8253   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8254     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8255
8256   // vmovrrd(load f64) -> (load i32), (load i32)
8257   SDNode *InNode = InDouble.getNode();
8258   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8259       InNode->getValueType(0) == MVT::f64 &&
8260       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8261       !cast<LoadSDNode>(InNode)->isVolatile()) {
8262     // TODO: Should this be done for non-FrameIndex operands?
8263     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8264
8265     SelectionDAG &DAG = DCI.DAG;
8266     DebugLoc DL = LD->getDebugLoc();
8267     SDValue BasePtr = LD->getBasePtr();
8268     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8269                                  LD->getPointerInfo(), LD->isVolatile(),
8270                                  LD->isNonTemporal(), LD->isInvariant(),
8271                                  LD->getAlignment());
8272
8273     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8274                                     DAG.getConstant(4, MVT::i32));
8275     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8276                                  LD->getPointerInfo(), LD->isVolatile(),
8277                                  LD->isNonTemporal(), LD->isInvariant(),
8278                                  std::min(4U, LD->getAlignment() / 2));
8279
8280     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8281     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8282     DCI.RemoveFromWorklist(LD);
8283     DAG.DeleteNode(LD);
8284     return Result;
8285   }
8286
8287   return SDValue();
8288 }
8289
8290 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8291 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8292 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8293   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8294   SDValue Op0 = N->getOperand(0);
8295   SDValue Op1 = N->getOperand(1);
8296   if (Op0.getOpcode() == ISD::BITCAST)
8297     Op0 = Op0.getOperand(0);
8298   if (Op1.getOpcode() == ISD::BITCAST)
8299     Op1 = Op1.getOperand(0);
8300   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8301       Op0.getNode() == Op1.getNode() &&
8302       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8303     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8304                        N->getValueType(0), Op0.getOperand(0));
8305   return SDValue();
8306 }
8307
8308 /// PerformSTORECombine - Target-specific dag combine xforms for
8309 /// ISD::STORE.
8310 static SDValue PerformSTORECombine(SDNode *N,
8311                                    TargetLowering::DAGCombinerInfo &DCI) {
8312   StoreSDNode *St = cast<StoreSDNode>(N);
8313   if (St->isVolatile())
8314     return SDValue();
8315
8316   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8317   // pack all of the elements in one place.  Next, store to memory in fewer
8318   // chunks.
8319   SDValue StVal = St->getValue();
8320   EVT VT = StVal.getValueType();
8321   if (St->isTruncatingStore() && VT.isVector()) {
8322     SelectionDAG &DAG = DCI.DAG;
8323     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8324     EVT StVT = St->getMemoryVT();
8325     unsigned NumElems = VT.getVectorNumElements();
8326     assert(StVT != VT && "Cannot truncate to the same type");
8327     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8328     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8329
8330     // From, To sizes and ElemCount must be pow of two
8331     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8332
8333     // We are going to use the original vector elt for storing.
8334     // Accumulated smaller vector elements must be a multiple of the store size.
8335     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8336
8337     unsigned SizeRatio  = FromEltSz / ToEltSz;
8338     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8339
8340     // Create a type on which we perform the shuffle.
8341     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8342                                      NumElems*SizeRatio);
8343     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8344
8345     DebugLoc DL = St->getDebugLoc();
8346     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8347     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8348     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8349
8350     // Can't shuffle using an illegal type.
8351     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8352
8353     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8354                                 DAG.getUNDEF(WideVec.getValueType()),
8355                                 ShuffleVec.data());
8356     // At this point all of the data is stored at the bottom of the
8357     // register. We now need to save it to mem.
8358
8359     // Find the largest store unit
8360     MVT StoreType = MVT::i8;
8361     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8362          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8363       MVT Tp = (MVT::SimpleValueType)tp;
8364       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8365         StoreType = Tp;
8366     }
8367     // Didn't find a legal store type.
8368     if (!TLI.isTypeLegal(StoreType))
8369       return SDValue();
8370
8371     // Bitcast the original vector into a vector of store-size units
8372     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8373             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8374     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8375     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8376     SmallVector<SDValue, 8> Chains;
8377     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8378                                         TLI.getPointerTy());
8379     SDValue BasePtr = St->getBasePtr();
8380
8381     // Perform one or more big stores into memory.
8382     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8383     for (unsigned I = 0; I < E; I++) {
8384       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8385                                    StoreType, ShuffWide,
8386                                    DAG.getIntPtrConstant(I));
8387       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8388                                 St->getPointerInfo(), St->isVolatile(),
8389                                 St->isNonTemporal(), St->getAlignment());
8390       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8391                             Increment);
8392       Chains.push_back(Ch);
8393     }
8394     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8395                        Chains.size());
8396   }
8397
8398   if (!ISD::isNormalStore(St))
8399     return SDValue();
8400
8401   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8402   // ARM stores of arguments in the same cache line.
8403   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8404       StVal.getNode()->hasOneUse()) {
8405     SelectionDAG  &DAG = DCI.DAG;
8406     DebugLoc DL = St->getDebugLoc();
8407     SDValue BasePtr = St->getBasePtr();
8408     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8409                                   StVal.getNode()->getOperand(0), BasePtr,
8410                                   St->getPointerInfo(), St->isVolatile(),
8411                                   St->isNonTemporal(), St->getAlignment());
8412
8413     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8414                                     DAG.getConstant(4, MVT::i32));
8415     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8416                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8417                         St->isNonTemporal(),
8418                         std::min(4U, St->getAlignment() / 2));
8419   }
8420
8421   if (StVal.getValueType() != MVT::i64 ||
8422       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8423     return SDValue();
8424
8425   // Bitcast an i64 store extracted from a vector to f64.
8426   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8427   SelectionDAG &DAG = DCI.DAG;
8428   DebugLoc dl = StVal.getDebugLoc();
8429   SDValue IntVec = StVal.getOperand(0);
8430   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8431                                  IntVec.getValueType().getVectorNumElements());
8432   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8433   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8434                                Vec, StVal.getOperand(1));
8435   dl = N->getDebugLoc();
8436   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8437   // Make the DAGCombiner fold the bitcasts.
8438   DCI.AddToWorklist(Vec.getNode());
8439   DCI.AddToWorklist(ExtElt.getNode());
8440   DCI.AddToWorklist(V.getNode());
8441   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8442                       St->getPointerInfo(), St->isVolatile(),
8443                       St->isNonTemporal(), St->getAlignment(),
8444                       St->getTBAAInfo());
8445 }
8446
8447 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8448 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8449 /// i64 vector to have f64 elements, since the value can then be loaded
8450 /// directly into a VFP register.
8451 static bool hasNormalLoadOperand(SDNode *N) {
8452   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8453   for (unsigned i = 0; i < NumElts; ++i) {
8454     SDNode *Elt = N->getOperand(i).getNode();
8455     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8456       return true;
8457   }
8458   return false;
8459 }
8460
8461 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8462 /// ISD::BUILD_VECTOR.
8463 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8464                                           TargetLowering::DAGCombinerInfo &DCI){
8465   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8466   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8467   // into a pair of GPRs, which is fine when the value is used as a scalar,
8468   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8469   SelectionDAG &DAG = DCI.DAG;
8470   if (N->getNumOperands() == 2) {
8471     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8472     if (RV.getNode())
8473       return RV;
8474   }
8475
8476   // Load i64 elements as f64 values so that type legalization does not split
8477   // them up into i32 values.
8478   EVT VT = N->getValueType(0);
8479   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8480     return SDValue();
8481   DebugLoc dl = N->getDebugLoc();
8482   SmallVector<SDValue, 8> Ops;
8483   unsigned NumElts = VT.getVectorNumElements();
8484   for (unsigned i = 0; i < NumElts; ++i) {
8485     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8486     Ops.push_back(V);
8487     // Make the DAGCombiner fold the bitcast.
8488     DCI.AddToWorklist(V.getNode());
8489   }
8490   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8491   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8492   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8493 }
8494
8495 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8496 /// ISD::INSERT_VECTOR_ELT.
8497 static SDValue PerformInsertEltCombine(SDNode *N,
8498                                        TargetLowering::DAGCombinerInfo &DCI) {
8499   // Bitcast an i64 load inserted into a vector to f64.
8500   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8501   EVT VT = N->getValueType(0);
8502   SDNode *Elt = N->getOperand(1).getNode();
8503   if (VT.getVectorElementType() != MVT::i64 ||
8504       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8505     return SDValue();
8506
8507   SelectionDAG &DAG = DCI.DAG;
8508   DebugLoc dl = N->getDebugLoc();
8509   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8510                                  VT.getVectorNumElements());
8511   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8512   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8513   // Make the DAGCombiner fold the bitcasts.
8514   DCI.AddToWorklist(Vec.getNode());
8515   DCI.AddToWorklist(V.getNode());
8516   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8517                                Vec, V, N->getOperand(2));
8518   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8519 }
8520
8521 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8522 /// ISD::VECTOR_SHUFFLE.
8523 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8524   // The LLVM shufflevector instruction does not require the shuffle mask
8525   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8526   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8527   // operands do not match the mask length, they are extended by concatenating
8528   // them with undef vectors.  That is probably the right thing for other
8529   // targets, but for NEON it is better to concatenate two double-register
8530   // size vector operands into a single quad-register size vector.  Do that
8531   // transformation here:
8532   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8533   //   shuffle(concat(v1, v2), undef)
8534   SDValue Op0 = N->getOperand(0);
8535   SDValue Op1 = N->getOperand(1);
8536   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8537       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8538       Op0.getNumOperands() != 2 ||
8539       Op1.getNumOperands() != 2)
8540     return SDValue();
8541   SDValue Concat0Op1 = Op0.getOperand(1);
8542   SDValue Concat1Op1 = Op1.getOperand(1);
8543   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8544       Concat1Op1.getOpcode() != ISD::UNDEF)
8545     return SDValue();
8546   // Skip the transformation if any of the types are illegal.
8547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8548   EVT VT = N->getValueType(0);
8549   if (!TLI.isTypeLegal(VT) ||
8550       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8551       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8552     return SDValue();
8553
8554   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8555                                   Op0.getOperand(0), Op1.getOperand(0));
8556   // Translate the shuffle mask.
8557   SmallVector<int, 16> NewMask;
8558   unsigned NumElts = VT.getVectorNumElements();
8559   unsigned HalfElts = NumElts/2;
8560   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8561   for (unsigned n = 0; n < NumElts; ++n) {
8562     int MaskElt = SVN->getMaskElt(n);
8563     int NewElt = -1;
8564     if (MaskElt < (int)HalfElts)
8565       NewElt = MaskElt;
8566     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8567       NewElt = HalfElts + MaskElt - NumElts;
8568     NewMask.push_back(NewElt);
8569   }
8570   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8571                               DAG.getUNDEF(VT), NewMask.data());
8572 }
8573
8574 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8575 /// NEON load/store intrinsics to merge base address updates.
8576 static SDValue CombineBaseUpdate(SDNode *N,
8577                                  TargetLowering::DAGCombinerInfo &DCI) {
8578   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8579     return SDValue();
8580
8581   SelectionDAG &DAG = DCI.DAG;
8582   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8583                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8584   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8585   SDValue Addr = N->getOperand(AddrOpIdx);
8586
8587   // Search for a use of the address operand that is an increment.
8588   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8589          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8590     SDNode *User = *UI;
8591     if (User->getOpcode() != ISD::ADD ||
8592         UI.getUse().getResNo() != Addr.getResNo())
8593       continue;
8594
8595     // Check that the add is independent of the load/store.  Otherwise, folding
8596     // it would create a cycle.
8597     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8598       continue;
8599
8600     // Find the new opcode for the updating load/store.
8601     bool isLoad = true;
8602     bool isLaneOp = false;
8603     unsigned NewOpc = 0;
8604     unsigned NumVecs = 0;
8605     if (isIntrinsic) {
8606       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8607       switch (IntNo) {
8608       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8609       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8610         NumVecs = 1; break;
8611       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8612         NumVecs = 2; break;
8613       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8614         NumVecs = 3; break;
8615       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8616         NumVecs = 4; break;
8617       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8618         NumVecs = 2; isLaneOp = true; break;
8619       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8620         NumVecs = 3; isLaneOp = true; break;
8621       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8622         NumVecs = 4; isLaneOp = true; break;
8623       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8624         NumVecs = 1; isLoad = false; break;
8625       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8626         NumVecs = 2; isLoad = false; break;
8627       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8628         NumVecs = 3; isLoad = false; break;
8629       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8630         NumVecs = 4; isLoad = false; break;
8631       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8632         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8633       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8634         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8635       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8636         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8637       }
8638     } else {
8639       isLaneOp = true;
8640       switch (N->getOpcode()) {
8641       default: llvm_unreachable("unexpected opcode for Neon base update");
8642       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8643       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8644       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8645       }
8646     }
8647
8648     // Find the size of memory referenced by the load/store.
8649     EVT VecTy;
8650     if (isLoad)
8651       VecTy = N->getValueType(0);
8652     else
8653       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8654     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8655     if (isLaneOp)
8656       NumBytes /= VecTy.getVectorNumElements();
8657
8658     // If the increment is a constant, it must match the memory ref size.
8659     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8660     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8661       uint64_t IncVal = CInc->getZExtValue();
8662       if (IncVal != NumBytes)
8663         continue;
8664     } else if (NumBytes >= 3 * 16) {
8665       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8666       // separate instructions that make it harder to use a non-constant update.
8667       continue;
8668     }
8669
8670     // Create the new updating load/store node.
8671     EVT Tys[6];
8672     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8673     unsigned n;
8674     for (n = 0; n < NumResultVecs; ++n)
8675       Tys[n] = VecTy;
8676     Tys[n++] = MVT::i32;
8677     Tys[n] = MVT::Other;
8678     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8679     SmallVector<SDValue, 8> Ops;
8680     Ops.push_back(N->getOperand(0)); // incoming chain
8681     Ops.push_back(N->getOperand(AddrOpIdx));
8682     Ops.push_back(Inc);
8683     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8684       Ops.push_back(N->getOperand(i));
8685     }
8686     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8687     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8688                                            Ops.data(), Ops.size(),
8689                                            MemInt->getMemoryVT(),
8690                                            MemInt->getMemOperand());
8691
8692     // Update the uses.
8693     std::vector<SDValue> NewResults;
8694     for (unsigned i = 0; i < NumResultVecs; ++i) {
8695       NewResults.push_back(SDValue(UpdN.getNode(), i));
8696     }
8697     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8698     DCI.CombineTo(N, NewResults);
8699     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8700
8701     break;
8702   }
8703   return SDValue();
8704 }
8705
8706 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8707 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8708 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8709 /// return true.
8710 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8711   SelectionDAG &DAG = DCI.DAG;
8712   EVT VT = N->getValueType(0);
8713   // vldN-dup instructions only support 64-bit vectors for N > 1.
8714   if (!VT.is64BitVector())
8715     return false;
8716
8717   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8718   SDNode *VLD = N->getOperand(0).getNode();
8719   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8720     return false;
8721   unsigned NumVecs = 0;
8722   unsigned NewOpc = 0;
8723   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8724   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8725     NumVecs = 2;
8726     NewOpc = ARMISD::VLD2DUP;
8727   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8728     NumVecs = 3;
8729     NewOpc = ARMISD::VLD3DUP;
8730   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8731     NumVecs = 4;
8732     NewOpc = ARMISD::VLD4DUP;
8733   } else {
8734     return false;
8735   }
8736
8737   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8738   // numbers match the load.
8739   unsigned VLDLaneNo =
8740     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8741   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8742        UI != UE; ++UI) {
8743     // Ignore uses of the chain result.
8744     if (UI.getUse().getResNo() == NumVecs)
8745       continue;
8746     SDNode *User = *UI;
8747     if (User->getOpcode() != ARMISD::VDUPLANE ||
8748         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8749       return false;
8750   }
8751
8752   // Create the vldN-dup node.
8753   EVT Tys[5];
8754   unsigned n;
8755   for (n = 0; n < NumVecs; ++n)
8756     Tys[n] = VT;
8757   Tys[n] = MVT::Other;
8758   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8759   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8760   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8761   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8762                                            Ops, 2, VLDMemInt->getMemoryVT(),
8763                                            VLDMemInt->getMemOperand());
8764
8765   // Update the uses.
8766   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8767        UI != UE; ++UI) {
8768     unsigned ResNo = UI.getUse().getResNo();
8769     // Ignore uses of the chain result.
8770     if (ResNo == NumVecs)
8771       continue;
8772     SDNode *User = *UI;
8773     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8774   }
8775
8776   // Now the vldN-lane intrinsic is dead except for its chain result.
8777   // Update uses of the chain.
8778   std::vector<SDValue> VLDDupResults;
8779   for (unsigned n = 0; n < NumVecs; ++n)
8780     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8781   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8782   DCI.CombineTo(VLD, VLDDupResults);
8783
8784   return true;
8785 }
8786
8787 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8788 /// ARMISD::VDUPLANE.
8789 static SDValue PerformVDUPLANECombine(SDNode *N,
8790                                       TargetLowering::DAGCombinerInfo &DCI) {
8791   SDValue Op = N->getOperand(0);
8792
8793   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8794   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8795   if (CombineVLDDUP(N, DCI))
8796     return SDValue(N, 0);
8797
8798   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8799   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8800   while (Op.getOpcode() == ISD::BITCAST)
8801     Op = Op.getOperand(0);
8802   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8803     return SDValue();
8804
8805   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8806   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8807   // The canonical VMOV for a zero vector uses a 32-bit element size.
8808   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8809   unsigned EltBits;
8810   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8811     EltSize = 8;
8812   EVT VT = N->getValueType(0);
8813   if (EltSize > VT.getVectorElementType().getSizeInBits())
8814     return SDValue();
8815
8816   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8817 }
8818
8819 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8820 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8821 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8822 {
8823   integerPart cN;
8824   integerPart c0 = 0;
8825   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8826        I != E; I++) {
8827     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8828     if (!C)
8829       return false;
8830
8831     bool isExact;
8832     APFloat APF = C->getValueAPF();
8833     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8834         != APFloat::opOK || !isExact)
8835       return false;
8836
8837     c0 = (I == 0) ? cN : c0;
8838     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8839       return false;
8840   }
8841   C = c0;
8842   return true;
8843 }
8844
8845 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8846 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8847 /// when the VMUL has a constant operand that is a power of 2.
8848 ///
8849 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8850 ///  vmul.f32        d16, d17, d16
8851 ///  vcvt.s32.f32    d16, d16
8852 /// becomes:
8853 ///  vcvt.s32.f32    d16, d16, #3
8854 static SDValue PerformVCVTCombine(SDNode *N,
8855                                   TargetLowering::DAGCombinerInfo &DCI,
8856                                   const ARMSubtarget *Subtarget) {
8857   SelectionDAG &DAG = DCI.DAG;
8858   SDValue Op = N->getOperand(0);
8859
8860   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8861       Op.getOpcode() != ISD::FMUL)
8862     return SDValue();
8863
8864   uint64_t C;
8865   SDValue N0 = Op->getOperand(0);
8866   SDValue ConstVec = Op->getOperand(1);
8867   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8868
8869   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8870       !isConstVecPow2(ConstVec, isSigned, C))
8871     return SDValue();
8872
8873   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8874     Intrinsic::arm_neon_vcvtfp2fxu;
8875   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8876                      N->getValueType(0),
8877                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8878                      DAG.getConstant(Log2_64(C), MVT::i32));
8879 }
8880
8881 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8882 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8883 /// when the VDIV has a constant operand that is a power of 2.
8884 ///
8885 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8886 ///  vcvt.f32.s32    d16, d16
8887 ///  vdiv.f32        d16, d17, d16
8888 /// becomes:
8889 ///  vcvt.f32.s32    d16, d16, #3
8890 static SDValue PerformVDIVCombine(SDNode *N,
8891                                   TargetLowering::DAGCombinerInfo &DCI,
8892                                   const ARMSubtarget *Subtarget) {
8893   SelectionDAG &DAG = DCI.DAG;
8894   SDValue Op = N->getOperand(0);
8895   unsigned OpOpcode = Op.getNode()->getOpcode();
8896
8897   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8898       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8899     return SDValue();
8900
8901   uint64_t C;
8902   SDValue ConstVec = N->getOperand(1);
8903   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8904
8905   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8906       !isConstVecPow2(ConstVec, isSigned, C))
8907     return SDValue();
8908
8909   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8910     Intrinsic::arm_neon_vcvtfxu2fp;
8911   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8912                      Op.getValueType(),
8913                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8914                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8915 }
8916
8917 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8918 /// operand of a vector shift operation, where all the elements of the
8919 /// build_vector must have the same constant integer value.
8920 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8921   // Ignore bit_converts.
8922   while (Op.getOpcode() == ISD::BITCAST)
8923     Op = Op.getOperand(0);
8924   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8925   APInt SplatBits, SplatUndef;
8926   unsigned SplatBitSize;
8927   bool HasAnyUndefs;
8928   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8929                                       HasAnyUndefs, ElementBits) ||
8930       SplatBitSize > ElementBits)
8931     return false;
8932   Cnt = SplatBits.getSExtValue();
8933   return true;
8934 }
8935
8936 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8937 /// operand of a vector shift left operation.  That value must be in the range:
8938 ///   0 <= Value < ElementBits for a left shift; or
8939 ///   0 <= Value <= ElementBits for a long left shift.
8940 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8941   assert(VT.isVector() && "vector shift count is not a vector type");
8942   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8943   if (! getVShiftImm(Op, ElementBits, Cnt))
8944     return false;
8945   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8946 }
8947
8948 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8949 /// operand of a vector shift right operation.  For a shift opcode, the value
8950 /// is positive, but for an intrinsic the value count must be negative. The
8951 /// absolute value must be in the range:
8952 ///   1 <= |Value| <= ElementBits for a right shift; or
8953 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8954 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8955                          int64_t &Cnt) {
8956   assert(VT.isVector() && "vector shift count is not a vector type");
8957   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8958   if (! getVShiftImm(Op, ElementBits, Cnt))
8959     return false;
8960   if (isIntrinsic)
8961     Cnt = -Cnt;
8962   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8963 }
8964
8965 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8966 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8967   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8968   switch (IntNo) {
8969   default:
8970     // Don't do anything for most intrinsics.
8971     break;
8972
8973   // Vector shifts: check for immediate versions and lower them.
8974   // Note: This is done during DAG combining instead of DAG legalizing because
8975   // the build_vectors for 64-bit vector element shift counts are generally
8976   // not legal, and it is hard to see their values after they get legalized to
8977   // loads from a constant pool.
8978   case Intrinsic::arm_neon_vshifts:
8979   case Intrinsic::arm_neon_vshiftu:
8980   case Intrinsic::arm_neon_vshiftls:
8981   case Intrinsic::arm_neon_vshiftlu:
8982   case Intrinsic::arm_neon_vshiftn:
8983   case Intrinsic::arm_neon_vrshifts:
8984   case Intrinsic::arm_neon_vrshiftu:
8985   case Intrinsic::arm_neon_vrshiftn:
8986   case Intrinsic::arm_neon_vqshifts:
8987   case Intrinsic::arm_neon_vqshiftu:
8988   case Intrinsic::arm_neon_vqshiftsu:
8989   case Intrinsic::arm_neon_vqshiftns:
8990   case Intrinsic::arm_neon_vqshiftnu:
8991   case Intrinsic::arm_neon_vqshiftnsu:
8992   case Intrinsic::arm_neon_vqrshiftns:
8993   case Intrinsic::arm_neon_vqrshiftnu:
8994   case Intrinsic::arm_neon_vqrshiftnsu: {
8995     EVT VT = N->getOperand(1).getValueType();
8996     int64_t Cnt;
8997     unsigned VShiftOpc = 0;
8998
8999     switch (IntNo) {
9000     case Intrinsic::arm_neon_vshifts:
9001     case Intrinsic::arm_neon_vshiftu:
9002       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9003         VShiftOpc = ARMISD::VSHL;
9004         break;
9005       }
9006       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9007         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9008                      ARMISD::VSHRs : ARMISD::VSHRu);
9009         break;
9010       }
9011       return SDValue();
9012
9013     case Intrinsic::arm_neon_vshiftls:
9014     case Intrinsic::arm_neon_vshiftlu:
9015       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9016         break;
9017       llvm_unreachable("invalid shift count for vshll intrinsic");
9018
9019     case Intrinsic::arm_neon_vrshifts:
9020     case Intrinsic::arm_neon_vrshiftu:
9021       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9022         break;
9023       return SDValue();
9024
9025     case Intrinsic::arm_neon_vqshifts:
9026     case Intrinsic::arm_neon_vqshiftu:
9027       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9028         break;
9029       return SDValue();
9030
9031     case Intrinsic::arm_neon_vqshiftsu:
9032       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9033         break;
9034       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9035
9036     case Intrinsic::arm_neon_vshiftn:
9037     case Intrinsic::arm_neon_vrshiftn:
9038     case Intrinsic::arm_neon_vqshiftns:
9039     case Intrinsic::arm_neon_vqshiftnu:
9040     case Intrinsic::arm_neon_vqshiftnsu:
9041     case Intrinsic::arm_neon_vqrshiftns:
9042     case Intrinsic::arm_neon_vqrshiftnu:
9043     case Intrinsic::arm_neon_vqrshiftnsu:
9044       // Narrowing shifts require an immediate right shift.
9045       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9046         break;
9047       llvm_unreachable("invalid shift count for narrowing vector shift "
9048                        "intrinsic");
9049
9050     default:
9051       llvm_unreachable("unhandled vector shift");
9052     }
9053
9054     switch (IntNo) {
9055     case Intrinsic::arm_neon_vshifts:
9056     case Intrinsic::arm_neon_vshiftu:
9057       // Opcode already set above.
9058       break;
9059     case Intrinsic::arm_neon_vshiftls:
9060     case Intrinsic::arm_neon_vshiftlu:
9061       if (Cnt == VT.getVectorElementType().getSizeInBits())
9062         VShiftOpc = ARMISD::VSHLLi;
9063       else
9064         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9065                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9066       break;
9067     case Intrinsic::arm_neon_vshiftn:
9068       VShiftOpc = ARMISD::VSHRN; break;
9069     case Intrinsic::arm_neon_vrshifts:
9070       VShiftOpc = ARMISD::VRSHRs; break;
9071     case Intrinsic::arm_neon_vrshiftu:
9072       VShiftOpc = ARMISD::VRSHRu; break;
9073     case Intrinsic::arm_neon_vrshiftn:
9074       VShiftOpc = ARMISD::VRSHRN; break;
9075     case Intrinsic::arm_neon_vqshifts:
9076       VShiftOpc = ARMISD::VQSHLs; break;
9077     case Intrinsic::arm_neon_vqshiftu:
9078       VShiftOpc = ARMISD::VQSHLu; break;
9079     case Intrinsic::arm_neon_vqshiftsu:
9080       VShiftOpc = ARMISD::VQSHLsu; break;
9081     case Intrinsic::arm_neon_vqshiftns:
9082       VShiftOpc = ARMISD::VQSHRNs; break;
9083     case Intrinsic::arm_neon_vqshiftnu:
9084       VShiftOpc = ARMISD::VQSHRNu; break;
9085     case Intrinsic::arm_neon_vqshiftnsu:
9086       VShiftOpc = ARMISD::VQSHRNsu; break;
9087     case Intrinsic::arm_neon_vqrshiftns:
9088       VShiftOpc = ARMISD::VQRSHRNs; break;
9089     case Intrinsic::arm_neon_vqrshiftnu:
9090       VShiftOpc = ARMISD::VQRSHRNu; break;
9091     case Intrinsic::arm_neon_vqrshiftnsu:
9092       VShiftOpc = ARMISD::VQRSHRNsu; break;
9093     }
9094
9095     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9096                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9097   }
9098
9099   case Intrinsic::arm_neon_vshiftins: {
9100     EVT VT = N->getOperand(1).getValueType();
9101     int64_t Cnt;
9102     unsigned VShiftOpc = 0;
9103
9104     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9105       VShiftOpc = ARMISD::VSLI;
9106     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9107       VShiftOpc = ARMISD::VSRI;
9108     else {
9109       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9110     }
9111
9112     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9113                        N->getOperand(1), N->getOperand(2),
9114                        DAG.getConstant(Cnt, MVT::i32));
9115   }
9116
9117   case Intrinsic::arm_neon_vqrshifts:
9118   case Intrinsic::arm_neon_vqrshiftu:
9119     // No immediate versions of these to check for.
9120     break;
9121   }
9122
9123   return SDValue();
9124 }
9125
9126 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9127 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9128 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9129 /// vector element shift counts are generally not legal, and it is hard to see
9130 /// their values after they get legalized to loads from a constant pool.
9131 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9132                                    const ARMSubtarget *ST) {
9133   EVT VT = N->getValueType(0);
9134   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9135     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9136     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9137     SDValue N1 = N->getOperand(1);
9138     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9139       SDValue N0 = N->getOperand(0);
9140       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9141           DAG.MaskedValueIsZero(N0.getOperand(0),
9142                                 APInt::getHighBitsSet(32, 16)))
9143         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9144     }
9145   }
9146
9147   // Nothing to be done for scalar shifts.
9148   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9149   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9150     return SDValue();
9151
9152   assert(ST->hasNEON() && "unexpected vector shift");
9153   int64_t Cnt;
9154
9155   switch (N->getOpcode()) {
9156   default: llvm_unreachable("unexpected shift opcode");
9157
9158   case ISD::SHL:
9159     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9160       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9161                          DAG.getConstant(Cnt, MVT::i32));
9162     break;
9163
9164   case ISD::SRA:
9165   case ISD::SRL:
9166     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9167       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9168                             ARMISD::VSHRs : ARMISD::VSHRu);
9169       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9170                          DAG.getConstant(Cnt, MVT::i32));
9171     }
9172   }
9173   return SDValue();
9174 }
9175
9176 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9177 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9178 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9179                                     const ARMSubtarget *ST) {
9180   SDValue N0 = N->getOperand(0);
9181
9182   // Check for sign- and zero-extensions of vector extract operations of 8-
9183   // and 16-bit vector elements.  NEON supports these directly.  They are
9184   // handled during DAG combining because type legalization will promote them
9185   // to 32-bit types and it is messy to recognize the operations after that.
9186   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9187     SDValue Vec = N0.getOperand(0);
9188     SDValue Lane = N0.getOperand(1);
9189     EVT VT = N->getValueType(0);
9190     EVT EltVT = N0.getValueType();
9191     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9192
9193     if (VT == MVT::i32 &&
9194         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9195         TLI.isTypeLegal(Vec.getValueType()) &&
9196         isa<ConstantSDNode>(Lane)) {
9197
9198       unsigned Opc = 0;
9199       switch (N->getOpcode()) {
9200       default: llvm_unreachable("unexpected opcode");
9201       case ISD::SIGN_EXTEND:
9202         Opc = ARMISD::VGETLANEs;
9203         break;
9204       case ISD::ZERO_EXTEND:
9205       case ISD::ANY_EXTEND:
9206         Opc = ARMISD::VGETLANEu;
9207         break;
9208       }
9209       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9210     }
9211   }
9212
9213   return SDValue();
9214 }
9215
9216 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9217 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9218 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9219                                        const ARMSubtarget *ST) {
9220   // If the target supports NEON, try to use vmax/vmin instructions for f32
9221   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9222   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9223   // a NaN; only do the transformation when it matches that behavior.
9224
9225   // For now only do this when using NEON for FP operations; if using VFP, it
9226   // is not obvious that the benefit outweighs the cost of switching to the
9227   // NEON pipeline.
9228   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9229       N->getValueType(0) != MVT::f32)
9230     return SDValue();
9231
9232   SDValue CondLHS = N->getOperand(0);
9233   SDValue CondRHS = N->getOperand(1);
9234   SDValue LHS = N->getOperand(2);
9235   SDValue RHS = N->getOperand(3);
9236   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9237
9238   unsigned Opcode = 0;
9239   bool IsReversed;
9240   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9241     IsReversed = false; // x CC y ? x : y
9242   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9243     IsReversed = true ; // x CC y ? y : x
9244   } else {
9245     return SDValue();
9246   }
9247
9248   bool IsUnordered;
9249   switch (CC) {
9250   default: break;
9251   case ISD::SETOLT:
9252   case ISD::SETOLE:
9253   case ISD::SETLT:
9254   case ISD::SETLE:
9255   case ISD::SETULT:
9256   case ISD::SETULE:
9257     // If LHS is NaN, an ordered comparison will be false and the result will
9258     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9259     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9260     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9261     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9262       break;
9263     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9264     // will return -0, so vmin can only be used for unsafe math or if one of
9265     // the operands is known to be nonzero.
9266     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9267         !DAG.getTarget().Options.UnsafeFPMath &&
9268         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9269       break;
9270     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9271     break;
9272
9273   case ISD::SETOGT:
9274   case ISD::SETOGE:
9275   case ISD::SETGT:
9276   case ISD::SETGE:
9277   case ISD::SETUGT:
9278   case ISD::SETUGE:
9279     // If LHS is NaN, an ordered comparison will be false and the result will
9280     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9281     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9282     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9283     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9284       break;
9285     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9286     // will return +0, so vmax can only be used for unsafe math or if one of
9287     // the operands is known to be nonzero.
9288     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9289         !DAG.getTarget().Options.UnsafeFPMath &&
9290         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9291       break;
9292     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9293     break;
9294   }
9295
9296   if (!Opcode)
9297     return SDValue();
9298   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9299 }
9300
9301 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9302 SDValue
9303 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9304   SDValue Cmp = N->getOperand(4);
9305   if (Cmp.getOpcode() != ARMISD::CMPZ)
9306     // Only looking at EQ and NE cases.
9307     return SDValue();
9308
9309   EVT VT = N->getValueType(0);
9310   DebugLoc dl = N->getDebugLoc();
9311   SDValue LHS = Cmp.getOperand(0);
9312   SDValue RHS = Cmp.getOperand(1);
9313   SDValue FalseVal = N->getOperand(0);
9314   SDValue TrueVal = N->getOperand(1);
9315   SDValue ARMcc = N->getOperand(2);
9316   ARMCC::CondCodes CC =
9317     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9318
9319   // Simplify
9320   //   mov     r1, r0
9321   //   cmp     r1, x
9322   //   mov     r0, y
9323   //   moveq   r0, x
9324   // to
9325   //   cmp     r0, x
9326   //   movne   r0, y
9327   //
9328   //   mov     r1, r0
9329   //   cmp     r1, x
9330   //   mov     r0, x
9331   //   movne   r0, y
9332   // to
9333   //   cmp     r0, x
9334   //   movne   r0, y
9335   /// FIXME: Turn this into a target neutral optimization?
9336   SDValue Res;
9337   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9338     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9339                       N->getOperand(3), Cmp);
9340   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9341     SDValue ARMcc;
9342     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9343     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9344                       N->getOperand(3), NewCmp);
9345   }
9346
9347   if (Res.getNode()) {
9348     APInt KnownZero, KnownOne;
9349     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9350     // Capture demanded bits information that would be otherwise lost.
9351     if (KnownZero == 0xfffffffe)
9352       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9353                         DAG.getValueType(MVT::i1));
9354     else if (KnownZero == 0xffffff00)
9355       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9356                         DAG.getValueType(MVT::i8));
9357     else if (KnownZero == 0xffff0000)
9358       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9359                         DAG.getValueType(MVT::i16));
9360   }
9361
9362   return Res;
9363 }
9364
9365 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9366                                              DAGCombinerInfo &DCI) const {
9367   switch (N->getOpcode()) {
9368   default: break;
9369   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9370   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9371   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9372   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9373   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9374   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9375   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9376   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9377   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9378   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9379   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9380   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9381   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9382   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9383   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9384   case ISD::FP_TO_SINT:
9385   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9386   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9387   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9388   case ISD::SHL:
9389   case ISD::SRA:
9390   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9391   case ISD::SIGN_EXTEND:
9392   case ISD::ZERO_EXTEND:
9393   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9394   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9395   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9396   case ARMISD::VLD2DUP:
9397   case ARMISD::VLD3DUP:
9398   case ARMISD::VLD4DUP:
9399     return CombineBaseUpdate(N, DCI);
9400   case ISD::INTRINSIC_VOID:
9401   case ISD::INTRINSIC_W_CHAIN:
9402     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9403     case Intrinsic::arm_neon_vld1:
9404     case Intrinsic::arm_neon_vld2:
9405     case Intrinsic::arm_neon_vld3:
9406     case Intrinsic::arm_neon_vld4:
9407     case Intrinsic::arm_neon_vld2lane:
9408     case Intrinsic::arm_neon_vld3lane:
9409     case Intrinsic::arm_neon_vld4lane:
9410     case Intrinsic::arm_neon_vst1:
9411     case Intrinsic::arm_neon_vst2:
9412     case Intrinsic::arm_neon_vst3:
9413     case Intrinsic::arm_neon_vst4:
9414     case Intrinsic::arm_neon_vst2lane:
9415     case Intrinsic::arm_neon_vst3lane:
9416     case Intrinsic::arm_neon_vst4lane:
9417       return CombineBaseUpdate(N, DCI);
9418     default: break;
9419     }
9420     break;
9421   }
9422   return SDValue();
9423 }
9424
9425 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9426                                                           EVT VT) const {
9427   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9428 }
9429
9430 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9431   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9432   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9433
9434   switch (VT.getSimpleVT().SimpleTy) {
9435   default:
9436     return false;
9437   case MVT::i8:
9438   case MVT::i16:
9439   case MVT::i32: {
9440     // Unaligned access can use (for example) LRDB, LRDH, LDR
9441     if (AllowsUnaligned) {
9442       if (Fast)
9443         *Fast = Subtarget->hasV7Ops();
9444       return true;
9445     }
9446     return false;
9447   }
9448   case MVT::f64:
9449   case MVT::v2f64: {
9450     // For any little-endian targets with neon, we can support unaligned ld/st
9451     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9452     // A big-endian target may also explictly support unaligned accesses
9453     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9454       if (Fast)
9455         *Fast = true;
9456       return true;
9457     }
9458     return false;
9459   }
9460   }
9461 }
9462
9463 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9464                        unsigned AlignCheck) {
9465   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9466           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9467 }
9468
9469 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9470                                            unsigned DstAlign, unsigned SrcAlign,
9471                                            bool IsMemset, bool ZeroMemset,
9472                                            bool MemcpyStrSrc,
9473                                            MachineFunction &MF) const {
9474   const Function *F = MF.getFunction();
9475
9476   // See if we can use NEON instructions for this...
9477   if ((!IsMemset || ZeroMemset) &&
9478       Subtarget->hasNEON() &&
9479       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9480                                        Attribute::NoImplicitFloat)) {
9481     bool Fast;
9482     if (Size >= 16 &&
9483         (memOpAlign(SrcAlign, DstAlign, 16) ||
9484          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9485       return MVT::v2f64;
9486     } else if (Size >= 8 &&
9487                (memOpAlign(SrcAlign, DstAlign, 8) ||
9488                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9489       return MVT::f64;
9490     }
9491   }
9492
9493   // Lowering to i32/i16 if the size permits.
9494   if (Size >= 4)
9495     return MVT::i32;
9496   else if (Size >= 2)
9497     return MVT::i16;
9498
9499   // Let the target-independent logic figure it out.
9500   return MVT::Other;
9501 }
9502
9503 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9504   if (Val.getOpcode() != ISD::LOAD)
9505     return false;
9506
9507   EVT VT1 = Val.getValueType();
9508   if (!VT1.isSimple() || !VT1.isInteger() ||
9509       !VT2.isSimple() || !VT2.isInteger())
9510     return false;
9511
9512   switch (VT1.getSimpleVT().SimpleTy) {
9513   default: break;
9514   case MVT::i1:
9515   case MVT::i8:
9516   case MVT::i16:
9517     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9518     return true;
9519   }
9520
9521   return false;
9522 }
9523
9524 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9525   if (V < 0)
9526     return false;
9527
9528   unsigned Scale = 1;
9529   switch (VT.getSimpleVT().SimpleTy) {
9530   default: return false;
9531   case MVT::i1:
9532   case MVT::i8:
9533     // Scale == 1;
9534     break;
9535   case MVT::i16:
9536     // Scale == 2;
9537     Scale = 2;
9538     break;
9539   case MVT::i32:
9540     // Scale == 4;
9541     Scale = 4;
9542     break;
9543   }
9544
9545   if ((V & (Scale - 1)) != 0)
9546     return false;
9547   V /= Scale;
9548   return V == (V & ((1LL << 5) - 1));
9549 }
9550
9551 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9552                                       const ARMSubtarget *Subtarget) {
9553   bool isNeg = false;
9554   if (V < 0) {
9555     isNeg = true;
9556     V = - V;
9557   }
9558
9559   switch (VT.getSimpleVT().SimpleTy) {
9560   default: return false;
9561   case MVT::i1:
9562   case MVT::i8:
9563   case MVT::i16:
9564   case MVT::i32:
9565     // + imm12 or - imm8
9566     if (isNeg)
9567       return V == (V & ((1LL << 8) - 1));
9568     return V == (V & ((1LL << 12) - 1));
9569   case MVT::f32:
9570   case MVT::f64:
9571     // Same as ARM mode. FIXME: NEON?
9572     if (!Subtarget->hasVFP2())
9573       return false;
9574     if ((V & 3) != 0)
9575       return false;
9576     V >>= 2;
9577     return V == (V & ((1LL << 8) - 1));
9578   }
9579 }
9580
9581 /// isLegalAddressImmediate - Return true if the integer value can be used
9582 /// as the offset of the target addressing mode for load / store of the
9583 /// given type.
9584 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9585                                     const ARMSubtarget *Subtarget) {
9586   if (V == 0)
9587     return true;
9588
9589   if (!VT.isSimple())
9590     return false;
9591
9592   if (Subtarget->isThumb1Only())
9593     return isLegalT1AddressImmediate(V, VT);
9594   else if (Subtarget->isThumb2())
9595     return isLegalT2AddressImmediate(V, VT, Subtarget);
9596
9597   // ARM mode.
9598   if (V < 0)
9599     V = - V;
9600   switch (VT.getSimpleVT().SimpleTy) {
9601   default: return false;
9602   case MVT::i1:
9603   case MVT::i8:
9604   case MVT::i32:
9605     // +- imm12
9606     return V == (V & ((1LL << 12) - 1));
9607   case MVT::i16:
9608     // +- imm8
9609     return V == (V & ((1LL << 8) - 1));
9610   case MVT::f32:
9611   case MVT::f64:
9612     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9613       return false;
9614     if ((V & 3) != 0)
9615       return false;
9616     V >>= 2;
9617     return V == (V & ((1LL << 8) - 1));
9618   }
9619 }
9620
9621 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9622                                                       EVT VT) const {
9623   int Scale = AM.Scale;
9624   if (Scale < 0)
9625     return false;
9626
9627   switch (VT.getSimpleVT().SimpleTy) {
9628   default: return false;
9629   case MVT::i1:
9630   case MVT::i8:
9631   case MVT::i16:
9632   case MVT::i32:
9633     if (Scale == 1)
9634       return true;
9635     // r + r << imm
9636     Scale = Scale & ~1;
9637     return Scale == 2 || Scale == 4 || Scale == 8;
9638   case MVT::i64:
9639     // r + r
9640     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9641       return true;
9642     return false;
9643   case MVT::isVoid:
9644     // Note, we allow "void" uses (basically, uses that aren't loads or
9645     // stores), because arm allows folding a scale into many arithmetic
9646     // operations.  This should be made more precise and revisited later.
9647
9648     // Allow r << imm, but the imm has to be a multiple of two.
9649     if (Scale & 1) return false;
9650     return isPowerOf2_32(Scale);
9651   }
9652 }
9653
9654 /// isLegalAddressingMode - Return true if the addressing mode represented
9655 /// by AM is legal for this target, for a load/store of the specified type.
9656 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9657                                               Type *Ty) const {
9658   EVT VT = getValueType(Ty, true);
9659   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9660     return false;
9661
9662   // Can never fold addr of global into load/store.
9663   if (AM.BaseGV)
9664     return false;
9665
9666   switch (AM.Scale) {
9667   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9668     break;
9669   case 1:
9670     if (Subtarget->isThumb1Only())
9671       return false;
9672     // FALL THROUGH.
9673   default:
9674     // ARM doesn't support any R+R*scale+imm addr modes.
9675     if (AM.BaseOffs)
9676       return false;
9677
9678     if (!VT.isSimple())
9679       return false;
9680
9681     if (Subtarget->isThumb2())
9682       return isLegalT2ScaledAddressingMode(AM, VT);
9683
9684     int Scale = AM.Scale;
9685     switch (VT.getSimpleVT().SimpleTy) {
9686     default: return false;
9687     case MVT::i1:
9688     case MVT::i8:
9689     case MVT::i32:
9690       if (Scale < 0) Scale = -Scale;
9691       if (Scale == 1)
9692         return true;
9693       // r + r << imm
9694       return isPowerOf2_32(Scale & ~1);
9695     case MVT::i16:
9696     case MVT::i64:
9697       // r + r
9698       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9699         return true;
9700       return false;
9701
9702     case MVT::isVoid:
9703       // Note, we allow "void" uses (basically, uses that aren't loads or
9704       // stores), because arm allows folding a scale into many arithmetic
9705       // operations.  This should be made more precise and revisited later.
9706
9707       // Allow r << imm, but the imm has to be a multiple of two.
9708       if (Scale & 1) return false;
9709       return isPowerOf2_32(Scale);
9710     }
9711   }
9712   return true;
9713 }
9714
9715 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9716 /// icmp immediate, that is the target has icmp instructions which can compare
9717 /// a register against the immediate without having to materialize the
9718 /// immediate into a register.
9719 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9720   // Thumb2 and ARM modes can use cmn for negative immediates.
9721   if (!Subtarget->isThumb())
9722     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9723   if (Subtarget->isThumb2())
9724     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9725   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9726   return Imm >= 0 && Imm <= 255;
9727 }
9728
9729 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9730 /// *or sub* immediate, that is the target has add or sub instructions which can
9731 /// add a register with the immediate without having to materialize the
9732 /// immediate into a register.
9733 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9734   // Same encoding for add/sub, just flip the sign.
9735   int64_t AbsImm = llvm::abs64(Imm);
9736   if (!Subtarget->isThumb())
9737     return ARM_AM::getSOImmVal(AbsImm) != -1;
9738   if (Subtarget->isThumb2())
9739     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9740   // Thumb1 only has 8-bit unsigned immediate.
9741   return AbsImm >= 0 && AbsImm <= 255;
9742 }
9743
9744 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9745                                       bool isSEXTLoad, SDValue &Base,
9746                                       SDValue &Offset, bool &isInc,
9747                                       SelectionDAG &DAG) {
9748   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9749     return false;
9750
9751   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9752     // AddressingMode 3
9753     Base = Ptr->getOperand(0);
9754     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9755       int RHSC = (int)RHS->getZExtValue();
9756       if (RHSC < 0 && RHSC > -256) {
9757         assert(Ptr->getOpcode() == ISD::ADD);
9758         isInc = false;
9759         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9760         return true;
9761       }
9762     }
9763     isInc = (Ptr->getOpcode() == ISD::ADD);
9764     Offset = Ptr->getOperand(1);
9765     return true;
9766   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9767     // AddressingMode 2
9768     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9769       int RHSC = (int)RHS->getZExtValue();
9770       if (RHSC < 0 && RHSC > -0x1000) {
9771         assert(Ptr->getOpcode() == ISD::ADD);
9772         isInc = false;
9773         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9774         Base = Ptr->getOperand(0);
9775         return true;
9776       }
9777     }
9778
9779     if (Ptr->getOpcode() == ISD::ADD) {
9780       isInc = true;
9781       ARM_AM::ShiftOpc ShOpcVal=
9782         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9783       if (ShOpcVal != ARM_AM::no_shift) {
9784         Base = Ptr->getOperand(1);
9785         Offset = Ptr->getOperand(0);
9786       } else {
9787         Base = Ptr->getOperand(0);
9788         Offset = Ptr->getOperand(1);
9789       }
9790       return true;
9791     }
9792
9793     isInc = (Ptr->getOpcode() == ISD::ADD);
9794     Base = Ptr->getOperand(0);
9795     Offset = Ptr->getOperand(1);
9796     return true;
9797   }
9798
9799   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9800   return false;
9801 }
9802
9803 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9804                                      bool isSEXTLoad, SDValue &Base,
9805                                      SDValue &Offset, bool &isInc,
9806                                      SelectionDAG &DAG) {
9807   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9808     return false;
9809
9810   Base = Ptr->getOperand(0);
9811   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9812     int RHSC = (int)RHS->getZExtValue();
9813     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9814       assert(Ptr->getOpcode() == ISD::ADD);
9815       isInc = false;
9816       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9817       return true;
9818     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9819       isInc = Ptr->getOpcode() == ISD::ADD;
9820       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9821       return true;
9822     }
9823   }
9824
9825   return false;
9826 }
9827
9828 /// getPreIndexedAddressParts - returns true by value, base pointer and
9829 /// offset pointer and addressing mode by reference if the node's address
9830 /// can be legally represented as pre-indexed load / store address.
9831 bool
9832 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9833                                              SDValue &Offset,
9834                                              ISD::MemIndexedMode &AM,
9835                                              SelectionDAG &DAG) const {
9836   if (Subtarget->isThumb1Only())
9837     return false;
9838
9839   EVT VT;
9840   SDValue Ptr;
9841   bool isSEXTLoad = false;
9842   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9843     Ptr = LD->getBasePtr();
9844     VT  = LD->getMemoryVT();
9845     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9846   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9847     Ptr = ST->getBasePtr();
9848     VT  = ST->getMemoryVT();
9849   } else
9850     return false;
9851
9852   bool isInc;
9853   bool isLegal = false;
9854   if (Subtarget->isThumb2())
9855     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9856                                        Offset, isInc, DAG);
9857   else
9858     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9859                                         Offset, isInc, DAG);
9860   if (!isLegal)
9861     return false;
9862
9863   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9864   return true;
9865 }
9866
9867 /// getPostIndexedAddressParts - returns true by value, base pointer and
9868 /// offset pointer and addressing mode by reference if this node can be
9869 /// combined with a load / store to form a post-indexed load / store.
9870 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9871                                                    SDValue &Base,
9872                                                    SDValue &Offset,
9873                                                    ISD::MemIndexedMode &AM,
9874                                                    SelectionDAG &DAG) const {
9875   if (Subtarget->isThumb1Only())
9876     return false;
9877
9878   EVT VT;
9879   SDValue Ptr;
9880   bool isSEXTLoad = false;
9881   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9882     VT  = LD->getMemoryVT();
9883     Ptr = LD->getBasePtr();
9884     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9885   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9886     VT  = ST->getMemoryVT();
9887     Ptr = ST->getBasePtr();
9888   } else
9889     return false;
9890
9891   bool isInc;
9892   bool isLegal = false;
9893   if (Subtarget->isThumb2())
9894     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9895                                        isInc, DAG);
9896   else
9897     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9898                                         isInc, DAG);
9899   if (!isLegal)
9900     return false;
9901
9902   if (Ptr != Base) {
9903     // Swap base ptr and offset to catch more post-index load / store when
9904     // it's legal. In Thumb2 mode, offset must be an immediate.
9905     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9906         !Subtarget->isThumb2())
9907       std::swap(Base, Offset);
9908
9909     // Post-indexed load / store update the base pointer.
9910     if (Ptr != Base)
9911       return false;
9912   }
9913
9914   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9915   return true;
9916 }
9917
9918 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9919                                                        APInt &KnownZero,
9920                                                        APInt &KnownOne,
9921                                                        const SelectionDAG &DAG,
9922                                                        unsigned Depth) const {
9923   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9924   switch (Op.getOpcode()) {
9925   default: break;
9926   case ARMISD::CMOV: {
9927     // Bits are known zero/one if known on the LHS and RHS.
9928     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9929     if (KnownZero == 0 && KnownOne == 0) return;
9930
9931     APInt KnownZeroRHS, KnownOneRHS;
9932     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9933     KnownZero &= KnownZeroRHS;
9934     KnownOne  &= KnownOneRHS;
9935     return;
9936   }
9937   }
9938 }
9939
9940 //===----------------------------------------------------------------------===//
9941 //                           ARM Inline Assembly Support
9942 //===----------------------------------------------------------------------===//
9943
9944 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9945   // Looking for "rev" which is V6+.
9946   if (!Subtarget->hasV6Ops())
9947     return false;
9948
9949   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9950   std::string AsmStr = IA->getAsmString();
9951   SmallVector<StringRef, 4> AsmPieces;
9952   SplitString(AsmStr, AsmPieces, ";\n");
9953
9954   switch (AsmPieces.size()) {
9955   default: return false;
9956   case 1:
9957     AsmStr = AsmPieces[0];
9958     AsmPieces.clear();
9959     SplitString(AsmStr, AsmPieces, " \t,");
9960
9961     // rev $0, $1
9962     if (AsmPieces.size() == 3 &&
9963         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9964         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9965       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9966       if (Ty && Ty->getBitWidth() == 32)
9967         return IntrinsicLowering::LowerToByteSwap(CI);
9968     }
9969     break;
9970   }
9971
9972   return false;
9973 }
9974
9975 /// getConstraintType - Given a constraint letter, return the type of
9976 /// constraint it is for this target.
9977 ARMTargetLowering::ConstraintType
9978 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9979   if (Constraint.size() == 1) {
9980     switch (Constraint[0]) {
9981     default:  break;
9982     case 'l': return C_RegisterClass;
9983     case 'w': return C_RegisterClass;
9984     case 'h': return C_RegisterClass;
9985     case 'x': return C_RegisterClass;
9986     case 't': return C_RegisterClass;
9987     case 'j': return C_Other; // Constant for movw.
9988       // An address with a single base register. Due to the way we
9989       // currently handle addresses it is the same as an 'r' memory constraint.
9990     case 'Q': return C_Memory;
9991     }
9992   } else if (Constraint.size() == 2) {
9993     switch (Constraint[0]) {
9994     default: break;
9995     // All 'U+' constraints are addresses.
9996     case 'U': return C_Memory;
9997     }
9998   }
9999   return TargetLowering::getConstraintType(Constraint);
10000 }
10001
10002 /// Examine constraint type and operand type and determine a weight value.
10003 /// This object must already have been set up with the operand type
10004 /// and the current alternative constraint selected.
10005 TargetLowering::ConstraintWeight
10006 ARMTargetLowering::getSingleConstraintMatchWeight(
10007     AsmOperandInfo &info, const char *constraint) const {
10008   ConstraintWeight weight = CW_Invalid;
10009   Value *CallOperandVal = info.CallOperandVal;
10010     // If we don't have a value, we can't do a match,
10011     // but allow it at the lowest weight.
10012   if (CallOperandVal == NULL)
10013     return CW_Default;
10014   Type *type = CallOperandVal->getType();
10015   // Look at the constraint type.
10016   switch (*constraint) {
10017   default:
10018     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10019     break;
10020   case 'l':
10021     if (type->isIntegerTy()) {
10022       if (Subtarget->isThumb())
10023         weight = CW_SpecificReg;
10024       else
10025         weight = CW_Register;
10026     }
10027     break;
10028   case 'w':
10029     if (type->isFloatingPointTy())
10030       weight = CW_Register;
10031     break;
10032   }
10033   return weight;
10034 }
10035
10036 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10037 RCPair
10038 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10039                                                 EVT VT) const {
10040   if (Constraint.size() == 1) {
10041     // GCC ARM Constraint Letters
10042     switch (Constraint[0]) {
10043     case 'l': // Low regs or general regs.
10044       if (Subtarget->isThumb())
10045         return RCPair(0U, &ARM::tGPRRegClass);
10046       return RCPair(0U, &ARM::GPRRegClass);
10047     case 'h': // High regs or no regs.
10048       if (Subtarget->isThumb())
10049         return RCPair(0U, &ARM::hGPRRegClass);
10050       break;
10051     case 'r':
10052       return RCPair(0U, &ARM::GPRRegClass);
10053     case 'w':
10054       if (VT == MVT::f32)
10055         return RCPair(0U, &ARM::SPRRegClass);
10056       if (VT.getSizeInBits() == 64)
10057         return RCPair(0U, &ARM::DPRRegClass);
10058       if (VT.getSizeInBits() == 128)
10059         return RCPair(0U, &ARM::QPRRegClass);
10060       break;
10061     case 'x':
10062       if (VT == MVT::f32)
10063         return RCPair(0U, &ARM::SPR_8RegClass);
10064       if (VT.getSizeInBits() == 64)
10065         return RCPair(0U, &ARM::DPR_8RegClass);
10066       if (VT.getSizeInBits() == 128)
10067         return RCPair(0U, &ARM::QPR_8RegClass);
10068       break;
10069     case 't':
10070       if (VT == MVT::f32)
10071         return RCPair(0U, &ARM::SPRRegClass);
10072       break;
10073     }
10074   }
10075   if (StringRef("{cc}").equals_lower(Constraint))
10076     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10077
10078   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10079 }
10080
10081 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10082 /// vector.  If it is invalid, don't add anything to Ops.
10083 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10084                                                      std::string &Constraint,
10085                                                      std::vector<SDValue>&Ops,
10086                                                      SelectionDAG &DAG) const {
10087   SDValue Result(0, 0);
10088
10089   // Currently only support length 1 constraints.
10090   if (Constraint.length() != 1) return;
10091
10092   char ConstraintLetter = Constraint[0];
10093   switch (ConstraintLetter) {
10094   default: break;
10095   case 'j':
10096   case 'I': case 'J': case 'K': case 'L':
10097   case 'M': case 'N': case 'O':
10098     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10099     if (!C)
10100       return;
10101
10102     int64_t CVal64 = C->getSExtValue();
10103     int CVal = (int) CVal64;
10104     // None of these constraints allow values larger than 32 bits.  Check
10105     // that the value fits in an int.
10106     if (CVal != CVal64)
10107       return;
10108
10109     switch (ConstraintLetter) {
10110       case 'j':
10111         // Constant suitable for movw, must be between 0 and
10112         // 65535.
10113         if (Subtarget->hasV6T2Ops())
10114           if (CVal >= 0 && CVal <= 65535)
10115             break;
10116         return;
10117       case 'I':
10118         if (Subtarget->isThumb1Only()) {
10119           // This must be a constant between 0 and 255, for ADD
10120           // immediates.
10121           if (CVal >= 0 && CVal <= 255)
10122             break;
10123         } else if (Subtarget->isThumb2()) {
10124           // A constant that can be used as an immediate value in a
10125           // data-processing instruction.
10126           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10127             break;
10128         } else {
10129           // A constant that can be used as an immediate value in a
10130           // data-processing instruction.
10131           if (ARM_AM::getSOImmVal(CVal) != -1)
10132             break;
10133         }
10134         return;
10135
10136       case 'J':
10137         if (Subtarget->isThumb()) {  // FIXME thumb2
10138           // This must be a constant between -255 and -1, for negated ADD
10139           // immediates. This can be used in GCC with an "n" modifier that
10140           // prints the negated value, for use with SUB instructions. It is
10141           // not useful otherwise but is implemented for compatibility.
10142           if (CVal >= -255 && CVal <= -1)
10143             break;
10144         } else {
10145           // This must be a constant between -4095 and 4095. It is not clear
10146           // what this constraint is intended for. Implemented for
10147           // compatibility with GCC.
10148           if (CVal >= -4095 && CVal <= 4095)
10149             break;
10150         }
10151         return;
10152
10153       case 'K':
10154         if (Subtarget->isThumb1Only()) {
10155           // A 32-bit value where only one byte has a nonzero value. Exclude
10156           // zero to match GCC. This constraint is used by GCC internally for
10157           // constants that can be loaded with a move/shift combination.
10158           // It is not useful otherwise but is implemented for compatibility.
10159           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10160             break;
10161         } else if (Subtarget->isThumb2()) {
10162           // A constant whose bitwise inverse can be used as an immediate
10163           // value in a data-processing instruction. This can be used in GCC
10164           // with a "B" modifier that prints the inverted value, for use with
10165           // BIC and MVN instructions. It is not useful otherwise but is
10166           // implemented for compatibility.
10167           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10168             break;
10169         } else {
10170           // A constant whose bitwise inverse can be used as an immediate
10171           // value in a data-processing instruction. This can be used in GCC
10172           // with a "B" modifier that prints the inverted value, for use with
10173           // BIC and MVN instructions. It is not useful otherwise but is
10174           // implemented for compatibility.
10175           if (ARM_AM::getSOImmVal(~CVal) != -1)
10176             break;
10177         }
10178         return;
10179
10180       case 'L':
10181         if (Subtarget->isThumb1Only()) {
10182           // This must be a constant between -7 and 7,
10183           // for 3-operand ADD/SUB immediate instructions.
10184           if (CVal >= -7 && CVal < 7)
10185             break;
10186         } else if (Subtarget->isThumb2()) {
10187           // A constant whose negation can be used as an immediate value in a
10188           // data-processing instruction. This can be used in GCC with an "n"
10189           // modifier that prints the negated value, for use with SUB
10190           // instructions. It is not useful otherwise but is implemented for
10191           // compatibility.
10192           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10193             break;
10194         } else {
10195           // A constant whose negation can be used as an immediate value in a
10196           // data-processing instruction. This can be used in GCC with an "n"
10197           // modifier that prints the negated value, for use with SUB
10198           // instructions. It is not useful otherwise but is implemented for
10199           // compatibility.
10200           if (ARM_AM::getSOImmVal(-CVal) != -1)
10201             break;
10202         }
10203         return;
10204
10205       case 'M':
10206         if (Subtarget->isThumb()) { // FIXME thumb2
10207           // This must be a multiple of 4 between 0 and 1020, for
10208           // ADD sp + immediate.
10209           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10210             break;
10211         } else {
10212           // A power of two or a constant between 0 and 32.  This is used in
10213           // GCC for the shift amount on shifted register operands, but it is
10214           // useful in general for any shift amounts.
10215           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10216             break;
10217         }
10218         return;
10219
10220       case 'N':
10221         if (Subtarget->isThumb()) {  // FIXME thumb2
10222           // This must be a constant between 0 and 31, for shift amounts.
10223           if (CVal >= 0 && CVal <= 31)
10224             break;
10225         }
10226         return;
10227
10228       case 'O':
10229         if (Subtarget->isThumb()) {  // FIXME thumb2
10230           // This must be a multiple of 4 between -508 and 508, for
10231           // ADD/SUB sp = sp + immediate.
10232           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10233             break;
10234         }
10235         return;
10236     }
10237     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10238     break;
10239   }
10240
10241   if (Result.getNode()) {
10242     Ops.push_back(Result);
10243     return;
10244   }
10245   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10246 }
10247
10248 bool
10249 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10250   // The ARM target isn't yet aware of offsets.
10251   return false;
10252 }
10253
10254 bool ARM::isBitFieldInvertedMask(unsigned v) {
10255   if (v == 0xffffffff)
10256     return 0;
10257   // there can be 1's on either or both "outsides", all the "inside"
10258   // bits must be 0's
10259   unsigned int lsb = 0, msb = 31;
10260   while (v & (1 << msb)) --msb;
10261   while (v & (1 << lsb)) ++lsb;
10262   for (unsigned int i = lsb; i <= msb; ++i) {
10263     if (v & (1 << i))
10264       return 0;
10265   }
10266   return 1;
10267 }
10268
10269 /// isFPImmLegal - Returns true if the target can instruction select the
10270 /// specified FP immediate natively. If false, the legalizer will
10271 /// materialize the FP immediate as a load from a constant pool.
10272 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10273   if (!Subtarget->hasVFP3())
10274     return false;
10275   if (VT == MVT::f32)
10276     return ARM_AM::getFP32Imm(Imm) != -1;
10277   if (VT == MVT::f64)
10278     return ARM_AM::getFP64Imm(Imm) != -1;
10279   return false;
10280 }
10281
10282 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10283 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10284 /// specified in the intrinsic calls.
10285 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10286                                            const CallInst &I,
10287                                            unsigned Intrinsic) const {
10288   switch (Intrinsic) {
10289   case Intrinsic::arm_neon_vld1:
10290   case Intrinsic::arm_neon_vld2:
10291   case Intrinsic::arm_neon_vld3:
10292   case Intrinsic::arm_neon_vld4:
10293   case Intrinsic::arm_neon_vld2lane:
10294   case Intrinsic::arm_neon_vld3lane:
10295   case Intrinsic::arm_neon_vld4lane: {
10296     Info.opc = ISD::INTRINSIC_W_CHAIN;
10297     // Conservatively set memVT to the entire set of vectors loaded.
10298     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10299     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10300     Info.ptrVal = I.getArgOperand(0);
10301     Info.offset = 0;
10302     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10303     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10304     Info.vol = false; // volatile loads with NEON intrinsics not supported
10305     Info.readMem = true;
10306     Info.writeMem = false;
10307     return true;
10308   }
10309   case Intrinsic::arm_neon_vst1:
10310   case Intrinsic::arm_neon_vst2:
10311   case Intrinsic::arm_neon_vst3:
10312   case Intrinsic::arm_neon_vst4:
10313   case Intrinsic::arm_neon_vst2lane:
10314   case Intrinsic::arm_neon_vst3lane:
10315   case Intrinsic::arm_neon_vst4lane: {
10316     Info.opc = ISD::INTRINSIC_VOID;
10317     // Conservatively set memVT to the entire set of vectors stored.
10318     unsigned NumElts = 0;
10319     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10320       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10321       if (!ArgTy->isVectorTy())
10322         break;
10323       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10324     }
10325     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10326     Info.ptrVal = I.getArgOperand(0);
10327     Info.offset = 0;
10328     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10329     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10330     Info.vol = false; // volatile stores with NEON intrinsics not supported
10331     Info.readMem = false;
10332     Info.writeMem = true;
10333     return true;
10334   }
10335   case Intrinsic::arm_strexd: {
10336     Info.opc = ISD::INTRINSIC_W_CHAIN;
10337     Info.memVT = MVT::i64;
10338     Info.ptrVal = I.getArgOperand(2);
10339     Info.offset = 0;
10340     Info.align = 8;
10341     Info.vol = true;
10342     Info.readMem = false;
10343     Info.writeMem = true;
10344     return true;
10345   }
10346   case Intrinsic::arm_ldrexd: {
10347     Info.opc = ISD::INTRINSIC_W_CHAIN;
10348     Info.memVT = MVT::i64;
10349     Info.ptrVal = I.getArgOperand(0);
10350     Info.offset = 0;
10351     Info.align = 8;
10352     Info.vol = true;
10353     Info.readMem = true;
10354     Info.writeMem = false;
10355     return true;
10356   }
10357   default:
10358     break;
10359   }
10360
10361   return false;
10362 }