abf229b3c405ba26c79245c501074df3f04f57c1
[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 #include <utility>
52 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 // This option should go away when tail calls fully work.
59 static cl::opt<bool>
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
62   cl::init(false));
63
64 cl::opt<bool>
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66   cl::desc("Generate calls via indirect call instructions"),
67   cl::init(false));
68
69 static cl::opt<bool>
70 ARMInterworking("arm-interworking", cl::Hidden,
71   cl::desc("Enable / disable ARM interworking (for debugging only)"),
72   cl::init(true));
73
74 namespace {
75   class ARMCCState : public CCState {
76   public:
77     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
79                LLVMContext &C, ParmContext PC)
80         : CCState(CC, isVarArg, MF, TM, locs, C) {
81       assert(((PC == Call) || (PC == Prologue)) &&
82              "ARMCCState users must specify whether their context is call"
83              "or prologue generation.");
84       CallOrPrologue = PC;
85     }
86   };
87 }
88
89 // The APCS parameter registers.
90 static const uint16_t GPRArgRegs[] = {
91   ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 };
93
94 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
95                                        MVT PromotedBitwiseVT) {
96   if (VT != PromotedLdStVT) {
97     setOperationAction(ISD::LOAD, VT, Promote);
98     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99
100     setOperationAction(ISD::STORE, VT, Promote);
101     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
102   }
103
104   MVT ElemTy = VT.getVectorElementType();
105   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106     setOperationAction(ISD::SETCC, VT, Custom);
107   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
108   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
109   if (ElemTy == MVT::i32) {
110     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
112     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
113     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114   } else {
115     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
117     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
118     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119   }
120   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
121   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
122   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
123   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
124   setOperationAction(ISD::SELECT,            VT, Expand);
125   setOperationAction(ISD::SELECT_CC,         VT, Expand);
126   setOperationAction(ISD::VSELECT,           VT, Expand);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
128   if (VT.isInteger()) {
129     setOperationAction(ISD::SHL, VT, Custom);
130     setOperationAction(ISD::SRA, VT, Custom);
131     setOperationAction(ISD::SRL, VT, Custom);
132   }
133
134   // Promote all bit-wise operations.
135   if (VT.isInteger() && VT != PromotedBitwiseVT) {
136     setOperationAction(ISD::AND, VT, Promote);
137     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
138     setOperationAction(ISD::OR,  VT, Promote);
139     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
140     setOperationAction(ISD::XOR, VT, Promote);
141     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142   }
143
144   // Neon does not support vector divide/remainder operations.
145   setOperationAction(ISD::SDIV, VT, Expand);
146   setOperationAction(ISD::UDIV, VT, Expand);
147   setOperationAction(ISD::FDIV, VT, Expand);
148   setOperationAction(ISD::SREM, VT, Expand);
149   setOperationAction(ISD::UREM, VT, Expand);
150   setOperationAction(ISD::FREM, VT, Expand);
151 }
152
153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPRRegClass);
155   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 }
157
158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
159   addRegisterClass(VT, &ARM::DPairRegClass);
160   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 }
162
163 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
164   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
165     return new TargetLoweringObjectFileMachO();
166
167   return new ARMElfTargetObjectFile();
168 }
169
170 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
171     : TargetLowering(TM, createTLOF(TM)) {
172   Subtarget = &TM.getSubtarget<ARMSubtarget>();
173   RegInfo = TM.getRegisterInfo();
174   Itins = TM.getInstrItineraryData();
175
176   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177
178   if (Subtarget->isTargetMachO()) {
179     // Uses VFP for Thumb libfuncs if available.
180     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
181         Subtarget->hasARMOps()) {
182       // Single-precision floating-point arithmetic.
183       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
184       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
185       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
186       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
187
188       // Double-precision floating-point arithmetic.
189       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
190       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
191       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
192       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
193
194       // Single-precision comparisons.
195       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
196       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
197       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
198       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
199       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
200       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
201       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
202       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
203
204       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
211       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
212
213       // Double-precision comparisons.
214       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
215       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
216       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
217       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
218       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
219       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
220       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
221       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
222
223       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
230       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
231
232       // Floating-point to integer conversions.
233       // i64 conversions are done via library routines even when generating VFP
234       // instructions, so use the same ones.
235       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
237       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
238       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
239
240       // Conversions between floating types.
241       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
242       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
243
244       // Integer to floating-point conversions.
245       // i64 conversions are done via library routines even when generating VFP
246       // instructions, so use the same ones.
247       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
248       // e.g., __floatunsidf vs. __floatunssidfvfp.
249       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
251       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
252       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253     }
254   }
255
256   // These libcalls are not available in 32-bit.
257   setLibcallName(RTLIB::SHL_I128, 0);
258   setLibcallName(RTLIB::SRL_I128, 0);
259   setLibcallName(RTLIB::SRA_I128, 0);
260
261   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO()) {
262     // Double-precision floating-point arithmetic helper functions
263     // RTABI chapter 4.1.2, Table 2
264     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
265     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
266     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
267     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
268     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
270     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
272
273     // Double-precision floating-point comparison helper functions
274     // RTABI chapter 4.1.2, Table 3
275     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
277     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
278     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
279     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
280     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
282     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
284     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
285     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
286     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
287     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
289     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
290     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
291     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
299
300     // Single-precision floating-point arithmetic helper functions
301     // RTABI chapter 4.1.2, Table 4
302     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
303     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
304     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
305     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
306     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
308     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
310
311     // Single-precision floating-point comparison helper functions
312     // RTABI chapter 4.1.2, Table 5
313     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
315     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
316     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
317     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
318     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
320     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
322     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
323     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
324     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
325     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
327     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
328     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
329     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
337
338     // Floating-point to integer conversions.
339     // RTABI chapter 4.1.2, Table 6
340     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
342     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
343     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
346     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
347     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
356
357     // Conversions between floating types.
358     // RTABI chapter 4.1.2, Table 7
359     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
360     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
361     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
362     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
363
364     // Integer to floating-point conversions.
365     // RTABI chapter 4.1.2, Table 8
366     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
367     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
368     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
369     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
370     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
371     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
372     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
373     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
374     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382
383     // Long long helper functions
384     // RTABI chapter 4.2, Table 9
385     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
386     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
387     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
388     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
389     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
395
396     // Integer division functions
397     // RTABI chapter 4.3.1
398     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
400     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
401     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
402     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
404     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
405     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
406     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414
415     // Memory operations
416     // RTABI chapter 4.3.4
417     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
418     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
419     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
420     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
421     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
422     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423   }
424
425   // Use divmod compiler-rt calls for iOS 5.0 and later.
426   if (Subtarget->getTargetTriple().isiOS() &&
427       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
428     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
429     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430   }
431
432   if (Subtarget->isThumb1Only())
433     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
434   else
435     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
436   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
437       !Subtarget->isThumb1Only()) {
438     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
439     if (!Subtarget->isFPOnlySP())
440       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
441
442     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443   }
444
445   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
447     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
449       setTruncStoreAction((MVT::SimpleValueType)VT,
450                           (MVT::SimpleValueType)InnerVT, Expand);
451     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
452     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454   }
455
456   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
511
512     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
527
528     // Mark v2f32 intrinsics.
529     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
544
545     // Neon does not support some operations on v1i64 and v2i64 types.
546     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547     // Custom handling for some quad-vector types to detect VMULL.
548     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551     // Custom handling for some vector types to avoid expensive expansions
552     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559     // a destination type that is wider than the source, and nor does
560     // it have a FP_TO_[SU]INT instruction with a narrower destination than
561     // source.
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
566
567     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
568     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
569
570     // NEON does not have single instruction CTPOP for vectors with element
571     // types wider than 8-bits.  However, custom lowering can leverage the
572     // v8i8/v16i8 vcnt instruction.
573     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
574     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
575     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
576     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
577
578     // NEON only has FMA instructions as of VFP4.
579     if (!Subtarget->hasVFP4()) {
580       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
582     }
583
584     setTargetDAGCombine(ISD::INTRINSIC_VOID);
585     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587     setTargetDAGCombine(ISD::SHL);
588     setTargetDAGCombine(ISD::SRL);
589     setTargetDAGCombine(ISD::SRA);
590     setTargetDAGCombine(ISD::SIGN_EXTEND);
591     setTargetDAGCombine(ISD::ZERO_EXTEND);
592     setTargetDAGCombine(ISD::ANY_EXTEND);
593     setTargetDAGCombine(ISD::SELECT_CC);
594     setTargetDAGCombine(ISD::BUILD_VECTOR);
595     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597     setTargetDAGCombine(ISD::STORE);
598     setTargetDAGCombine(ISD::FP_TO_SINT);
599     setTargetDAGCombine(ISD::FP_TO_UINT);
600     setTargetDAGCombine(ISD::FDIV);
601
602     // It is legal to extload from v4i8 to v4i16 or v4i32.
603     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604                   MVT::v4i16, MVT::v2i16,
605                   MVT::v2i32};
606     for (unsigned i = 0; i < 6; ++i) {
607       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
610     }
611   }
612
613   // ARM and Thumb2 support UMLAL/SMLAL.
614   if (!Subtarget->isThumb1Only())
615     setTargetDAGCombine(ISD::ADDC);
616
617
618   computeRegisterProperties();
619
620   // ARM does not have f32 extending load.
621   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
622
623   // ARM does not have i1 sign extending load.
624   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
625
626   // ARM supports all 4 flavors of integer indexed load / store.
627   if (!Subtarget->isThumb1Only()) {
628     for (unsigned im = (unsigned)ISD::PRE_INC;
629          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630       setIndexedLoadAction(im,  MVT::i1,  Legal);
631       setIndexedLoadAction(im,  MVT::i8,  Legal);
632       setIndexedLoadAction(im,  MVT::i16, Legal);
633       setIndexedLoadAction(im,  MVT::i32, Legal);
634       setIndexedStoreAction(im, MVT::i1,  Legal);
635       setIndexedStoreAction(im, MVT::i8,  Legal);
636       setIndexedStoreAction(im, MVT::i16, Legal);
637       setIndexedStoreAction(im, MVT::i32, Legal);
638     }
639   }
640
641   // i64 operation support.
642   setOperationAction(ISD::MUL,     MVT::i64, Expand);
643   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
644   if (Subtarget->isThumb1Only()) {
645     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
647   }
648   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650     setOperationAction(ISD::MULHS, MVT::i32, Expand);
651
652   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655   setOperationAction(ISD::SRL,       MVT::i64, Custom);
656   setOperationAction(ISD::SRA,       MVT::i64, Custom);
657
658   if (!Subtarget->isThumb1Only()) {
659     // FIXME: We should do this for Thumb1 as well.
660     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
661     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
662     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
663     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
664   }
665
666   // ARM does not have ROTL.
667   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
668   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
669   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
672
673   // These just redirect to CTTZ and CTLZ on ARM.
674   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
675   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
676
677   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
678
679   // Only ARMv6 has BSWAP.
680   if (!Subtarget->hasV6Ops())
681     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
682
683   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685     // These are expanded into libcalls if the cpu doesn't have HW divider.
686     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
687     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
688   }
689
690   // FIXME: Also set divmod for SREM on EABI
691   setOperationAction(ISD::SREM,  MVT::i32, Expand);
692   setOperationAction(ISD::UREM,  MVT::i32, Expand);
693   // Register based DivRem for AEABI (RTABI 4.2)
694   if (Subtarget->isTargetAEABI()) {
695     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
696     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
700     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
703
704     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
712
713     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
715   } else {
716     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
718   }
719
720   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
721   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
722   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
725
726   setOperationAction(ISD::TRAP, MVT::Other, Legal);
727
728   // Use the default implementation.
729   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
730   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
731   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
732   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
733   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
734   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
735
736   if (!Subtarget->isTargetMachO()) {
737     // Non-MachO platforms may return values in these registers via the
738     // personality function.
739     setExceptionPointerRegister(ARM::R0);
740     setExceptionSelectorRegister(ARM::R1);
741   }
742
743   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745   // the default expansion.
746   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747     // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
748     // handled normally.
749     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
750     // Custom lowering for 64-bit ops
751     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
752     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
753     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
754     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
755     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
756     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
757     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
758     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
759     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
760     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
761     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
762     // On v8, we have particularly efficient implementations of atomic fences
763     // if they can be combined with nearby atomic loads and stores.
764     if (!Subtarget->hasV8Ops()) {
765       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
766       setInsertFencesForAtomic(true);
767     }
768     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
769   } else {
770     // If there's anything we can use as a barrier, go through custom lowering
771     // for ATOMIC_FENCE.
772     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
773                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
774
775     // Set them all for expansion, which will force libcalls.
776     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
777     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
782     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
783     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
784     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
785     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
788     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
789     // Unordered/Monotonic case.
790     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
791     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
792   }
793
794   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
795
796   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
797   if (!Subtarget->hasV6Ops()) {
798     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
799     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
800   }
801   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
802
803   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
804       !Subtarget->isThumb1Only()) {
805     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
806     // iff target supports vfp2.
807     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
808     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
809   }
810
811   // We want to custom lower some of our intrinsics.
812   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813   if (Subtarget->isTargetDarwin()) {
814     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
815     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
816     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
817   }
818
819   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
820   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
821   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
822   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
823   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
824   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
825   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
826   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
827   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
828
829   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
830   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
831   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
832   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
833   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
834
835   // We don't support sin/cos/fmod/copysign/pow
836   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
837   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
838   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
839   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
840   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
841   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
842   setOperationAction(ISD::FREM,      MVT::f64, Expand);
843   setOperationAction(ISD::FREM,      MVT::f32, Expand);
844   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
845       !Subtarget->isThumb1Only()) {
846     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
847     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
848   }
849   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
850   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
851
852   if (!Subtarget->hasVFP4()) {
853     setOperationAction(ISD::FMA, MVT::f64, Expand);
854     setOperationAction(ISD::FMA, MVT::f32, Expand);
855   }
856
857   // Various VFP goodness
858   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
859     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
860     if (Subtarget->hasVFP2()) {
861       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
862       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
863       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
864       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
865     }
866     // Special handling for half-precision FP.
867     if (!Subtarget->hasFP16()) {
868       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
869       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
870     }
871   }
872       
873   // Combine sin / cos into one node or libcall if possible.
874   if (Subtarget->hasSinCos()) {
875     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
876     setLibcallName(RTLIB::SINCOS_F64, "sincos");
877     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
878       // For iOS, we don't want to the normal expansion of a libcall to
879       // sincos. We want to issue a libcall to __sincos_stret.
880       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
881       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
882     }
883   }
884
885   // We have target-specific dag combine patterns for the following nodes:
886   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
887   setTargetDAGCombine(ISD::ADD);
888   setTargetDAGCombine(ISD::SUB);
889   setTargetDAGCombine(ISD::MUL);
890   setTargetDAGCombine(ISD::AND);
891   setTargetDAGCombine(ISD::OR);
892   setTargetDAGCombine(ISD::XOR);
893
894   if (Subtarget->hasV6Ops())
895     setTargetDAGCombine(ISD::SRL);
896
897   setStackPointerRegisterToSaveRestore(ARM::SP);
898
899   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
900       !Subtarget->hasVFP2())
901     setSchedulingPreference(Sched::RegPressure);
902   else
903     setSchedulingPreference(Sched::Hybrid);
904
905   //// temporary - rewrite interface to use type
906   MaxStoresPerMemset = 8;
907   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
908   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
909   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
910   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
911   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
912
913   // On ARM arguments smaller than 4 bytes are extended, so all arguments
914   // are at least 4 bytes aligned.
915   setMinStackArgumentAlignment(4);
916
917   // Prefer likely predicted branches to selects on out-of-order cores.
918   PredictableSelectIsExpensive = Subtarget->isLikeA9();
919
920   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
921 }
922
923 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
924                                   bool isThumb2, unsigned &LdrOpc,
925                                   unsigned &StrOpc) {
926   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
927                                             {ARM::LDREXH, ARM::t2LDREXH},
928                                             {ARM::LDREX,  ARM::t2LDREX},
929                                             {ARM::LDREXD, ARM::t2LDREXD}};
930   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
931                                             {ARM::LDAEXH, ARM::t2LDAEXH},
932                                             {ARM::LDAEX,  ARM::t2LDAEX},
933                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
934   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
935                                             {ARM::STREXH, ARM::t2STREXH},
936                                             {ARM::STREX,  ARM::t2STREX},
937                                             {ARM::STREXD, ARM::t2STREXD}};
938   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
939                                             {ARM::STLEXH, ARM::t2STLEXH},
940                                             {ARM::STLEX,  ARM::t2STLEX},
941                                             {ARM::STLEXD, ARM::t2STLEXD}};
942
943   const unsigned (*LoadOps)[2], (*StoreOps)[2];
944   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
945     LoadOps = LoadAcqs;
946   else
947     LoadOps = LoadBares;
948
949   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
950     StoreOps = StoreRels;
951   else
952     StoreOps = StoreBares;
953
954   assert(isPowerOf2_32(Size) && Size <= 8 &&
955          "unsupported size for atomic binary op!");
956
957   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
958   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
959 }
960
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
970 // and extractions.
971 std::pair<const TargetRegisterClass*, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
973   const TargetRegisterClass *RRC = 0;
974   uint8_t Cost = 1;
975   switch (VT.SimpleTy) {
976   default:
977     return TargetLowering::findRepresentativeClass(VT);
978   // Use DPR as representative register class for all floating point
979   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
980   // the cost is 1 for both f32 and f64.
981   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
982   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
983     RRC = &ARM::DPRRegClass;
984     // When NEON is used for SP, only half of the register file is available
985     // because operations that define both SP and DP results will be constrained
986     // to the VFP2 class (D0-D15). We currently model this constraint prior to
987     // coalescing by double-counting the SP regs. See the FIXME above.
988     if (Subtarget->useNEONForSinglePrecisionFP())
989       Cost = 2;
990     break;
991   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
992   case MVT::v4f32: case MVT::v2f64:
993     RRC = &ARM::DPRRegClass;
994     Cost = 2;
995     break;
996   case MVT::v4i64:
997     RRC = &ARM::DPRRegClass;
998     Cost = 4;
999     break;
1000   case MVT::v8i64:
1001     RRC = &ARM::DPRRegClass;
1002     Cost = 8;
1003     break;
1004   }
1005   return std::make_pair(RRC, Cost);
1006 }
1007
1008 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009   switch (Opcode) {
1010   default: return 0;
1011   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1012   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1013   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1014   case ARMISD::CALL:          return "ARMISD::CALL";
1015   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1016   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1017   case ARMISD::tCALL:         return "ARMISD::tCALL";
1018   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1019   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1020   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1021   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1022   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1023   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1024   case ARMISD::CMP:           return "ARMISD::CMP";
1025   case ARMISD::CMN:           return "ARMISD::CMN";
1026   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1027   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1028   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1029   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1030   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1031
1032   case ARMISD::CMOV:          return "ARMISD::CMOV";
1033
1034   case ARMISD::RBIT:          return "ARMISD::RBIT";
1035
1036   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1037   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1038   case ARMISD::SITOF:         return "ARMISD::SITOF";
1039   case ARMISD::UITOF:         return "ARMISD::UITOF";
1040
1041   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1042   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1043   case ARMISD::RRX:           return "ARMISD::RRX";
1044
1045   case ARMISD::ADDC:          return "ARMISD::ADDC";
1046   case ARMISD::ADDE:          return "ARMISD::ADDE";
1047   case ARMISD::SUBC:          return "ARMISD::SUBC";
1048   case ARMISD::SUBE:          return "ARMISD::SUBE";
1049
1050   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1051   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1052
1053   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1054   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055
1056   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1057
1058   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059
1060   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1061
1062   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063
1064   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1065
1066   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1067   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1068   case ARMISD::VCGE:          return "ARMISD::VCGE";
1069   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1070   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1071   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1072   case ARMISD::VCGT:          return "ARMISD::VCGT";
1073   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1074   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1075   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1076   case ARMISD::VTST:          return "ARMISD::VTST";
1077
1078   case ARMISD::VSHL:          return "ARMISD::VSHL";
1079   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1080   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1197   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1198
1199   if (MCID.getNumDefs() == 0)
1200     return Sched::RegPressure;
1201   if (!Itins->isEmpty() &&
1202       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1203     return Sched::ILP;
1204
1205   return Sched::RegPressure;
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Lowering Code
1210 //===----------------------------------------------------------------------===//
1211
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1214   switch (CC) {
1215   default: llvm_unreachable("Unknown condition code!");
1216   case ISD::SETNE:  return ARMCC::NE;
1217   case ISD::SETEQ:  return ARMCC::EQ;
1218   case ISD::SETGT:  return ARMCC::GT;
1219   case ISD::SETGE:  return ARMCC::GE;
1220   case ISD::SETLT:  return ARMCC::LT;
1221   case ISD::SETLE:  return ARMCC::LE;
1222   case ISD::SETUGT: return ARMCC::HI;
1223   case ISD::SETUGE: return ARMCC::HS;
1224   case ISD::SETULT: return ARMCC::LO;
1225   case ISD::SETULE: return ARMCC::LS;
1226   }
1227 }
1228
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231                         ARMCC::CondCodes &CondCode2) {
1232   CondCode2 = ARMCC::AL;
1233   switch (CC) {
1234   default: llvm_unreachable("Unknown FP condition!");
1235   case ISD::SETEQ:
1236   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1237   case ISD::SETGT:
1238   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1239   case ISD::SETGE:
1240   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244   case ISD::SETO:   CondCode = ARMCC::VC; break;
1245   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1246   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1249   case ISD::SETLT:
1250   case ISD::SETULT: CondCode = ARMCC::LT; break;
1251   case ISD::SETLE:
1252   case ISD::SETULE: CondCode = ARMCC::LE; break;
1253   case ISD::SETNE:
1254   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255   }
1256 }
1257
1258 //===----------------------------------------------------------------------===//
1259 //                      Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1261
1262 #include "ARMGenCallingConv.inc"
1263
1264 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1265 /// given CallingConvention value.
1266 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1267                                                  bool Return,
1268                                                  bool isVarArg) const {
1269   switch (CC) {
1270   default:
1271     llvm_unreachable("Unsupported calling convention");
1272   case CallingConv::Fast:
1273     if (Subtarget->hasVFP2() && !isVarArg) {
1274       if (!Subtarget->isAAPCS_ABI())
1275         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1276       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1277       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1278     }
1279     // Fallthrough
1280   case CallingConv::C: {
1281     // Use target triple & subtarget features to do actual dispatch.
1282     if (!Subtarget->isAAPCS_ABI())
1283       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1284     else if (Subtarget->hasVFP2() &&
1285              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1286              !isVarArg)
1287       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1288     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1289   }
1290   case CallingConv::ARM_AAPCS_VFP:
1291     if (!isVarArg)
1292       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293     // Fallthrough
1294   case CallingConv::ARM_AAPCS:
1295     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1296   case CallingConv::ARM_APCS:
1297     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1298   case CallingConv::GHC:
1299     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1300   }
1301 }
1302
1303 /// LowerCallResult - Lower the result values of a call into the
1304 /// appropriate copies out of appropriate physical registers.
1305 SDValue
1306 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1307                                    CallingConv::ID CallConv, bool isVarArg,
1308                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1309                                    SDLoc dl, SelectionDAG &DAG,
1310                                    SmallVectorImpl<SDValue> &InVals,
1311                                    bool isThisReturn, SDValue ThisVal) const {
1312
1313   // Assign locations to each value returned by this call.
1314   SmallVector<CCValAssign, 16> RVLocs;
1315   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1316                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1317   CCInfo.AnalyzeCallResult(Ins,
1318                            CCAssignFnForNode(CallConv, /* Return*/ true,
1319                                              isVarArg));
1320
1321   // Copy all of the result registers out of their specified physreg.
1322   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1323     CCValAssign VA = RVLocs[i];
1324
1325     // Pass 'this' value directly from the argument to return value, to avoid
1326     // reg unit interference
1327     if (i == 0 && isThisReturn) {
1328       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1329              "unexpected return calling convention register assignment");
1330       InVals.push_back(ThisVal);
1331       continue;
1332     }
1333
1334     SDValue Val;
1335     if (VA.needsCustom()) {
1336       // Handle f64 or half of a v2f64.
1337       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1338                                       InFlag);
1339       Chain = Lo.getValue(1);
1340       InFlag = Lo.getValue(2);
1341       VA = RVLocs[++i]; // skip ahead to next loc
1342       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1343                                       InFlag);
1344       Chain = Hi.getValue(1);
1345       InFlag = Hi.getValue(2);
1346       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1347
1348       if (VA.getLocVT() == MVT::v2f64) {
1349         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1350         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1351                           DAG.getConstant(0, MVT::i32));
1352
1353         VA = RVLocs[++i]; // skip ahead to next loc
1354         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1355         Chain = Lo.getValue(1);
1356         InFlag = Lo.getValue(2);
1357         VA = RVLocs[++i]; // skip ahead to next loc
1358         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1359         Chain = Hi.getValue(1);
1360         InFlag = Hi.getValue(2);
1361         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1362         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1363                           DAG.getConstant(1, MVT::i32));
1364       }
1365     } else {
1366       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1367                                InFlag);
1368       Chain = Val.getValue(1);
1369       InFlag = Val.getValue(2);
1370     }
1371
1372     switch (VA.getLocInfo()) {
1373     default: llvm_unreachable("Unknown loc info!");
1374     case CCValAssign::Full: break;
1375     case CCValAssign::BCvt:
1376       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1377       break;
1378     }
1379
1380     InVals.push_back(Val);
1381   }
1382
1383   return Chain;
1384 }
1385
1386 /// LowerMemOpCallTo - Store the argument to the stack.
1387 SDValue
1388 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1389                                     SDValue StackPtr, SDValue Arg,
1390                                     SDLoc dl, SelectionDAG &DAG,
1391                                     const CCValAssign &VA,
1392                                     ISD::ArgFlagsTy Flags) const {
1393   unsigned LocMemOffset = VA.getLocMemOffset();
1394   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1395   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1396   return DAG.getStore(Chain, dl, Arg, PtrOff,
1397                       MachinePointerInfo::getStack(LocMemOffset),
1398                       false, false, 0);
1399 }
1400
1401 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1402                                          SDValue Chain, SDValue &Arg,
1403                                          RegsToPassVector &RegsToPass,
1404                                          CCValAssign &VA, CCValAssign &NextVA,
1405                                          SDValue &StackPtr,
1406                                          SmallVectorImpl<SDValue> &MemOpChains,
1407                                          ISD::ArgFlagsTy Flags) const {
1408
1409   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1410                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1411   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1412
1413   if (NextVA.isRegLoc())
1414     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1415   else {
1416     assert(NextVA.isMemLoc());
1417     if (StackPtr.getNode() == 0)
1418       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1419
1420     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1421                                            dl, DAG, NextVA,
1422                                            Flags));
1423   }
1424 }
1425
1426 /// LowerCall - Lowering a call into a callseq_start <-
1427 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1428 /// nodes.
1429 SDValue
1430 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1431                              SmallVectorImpl<SDValue> &InVals) const {
1432   SelectionDAG &DAG                     = CLI.DAG;
1433   SDLoc &dl                          = CLI.DL;
1434   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1435   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1436   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1437   SDValue Chain                         = CLI.Chain;
1438   SDValue Callee                        = CLI.Callee;
1439   bool &isTailCall                      = CLI.IsTailCall;
1440   CallingConv::ID CallConv              = CLI.CallConv;
1441   bool doesNotRet                       = CLI.DoesNotReturn;
1442   bool isVarArg                         = CLI.IsVarArg;
1443
1444   MachineFunction &MF = DAG.getMachineFunction();
1445   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1446   bool isThisReturn   = false;
1447   bool isSibCall      = false;
1448   // Disable tail calls if they're not supported.
1449   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1450     isTailCall = false;
1451   if (isTailCall) {
1452     // Check if it's really possible to do a tail call.
1453     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1454                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1455                                                    Outs, OutVals, Ins, DAG);
1456     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1457     // detected sibcalls.
1458     if (isTailCall) {
1459       ++NumTailCalls;
1460       isSibCall = true;
1461     }
1462   }
1463
1464   // Analyze operands of the call, assigning locations to each operand.
1465   SmallVector<CCValAssign, 16> ArgLocs;
1466   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1467                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1468   CCInfo.AnalyzeCallOperands(Outs,
1469                              CCAssignFnForNode(CallConv, /* Return*/ false,
1470                                                isVarArg));
1471
1472   // Get a count of how many bytes are to be pushed on the stack.
1473   unsigned NumBytes = CCInfo.getNextStackOffset();
1474
1475   // For tail calls, memory operands are available in our caller's stack.
1476   if (isSibCall)
1477     NumBytes = 0;
1478
1479   // Adjust the stack pointer for the new arguments...
1480   // These operations are automatically eliminated by the prolog/epilog pass
1481   if (!isSibCall)
1482     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1483                                  dl);
1484
1485   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1486
1487   RegsToPassVector RegsToPass;
1488   SmallVector<SDValue, 8> MemOpChains;
1489
1490   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1491   // of tail call optimization, arguments are handled later.
1492   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1493        i != e;
1494        ++i, ++realArgIdx) {
1495     CCValAssign &VA = ArgLocs[i];
1496     SDValue Arg = OutVals[realArgIdx];
1497     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1498     bool isByVal = Flags.isByVal();
1499
1500     // Promote the value if needed.
1501     switch (VA.getLocInfo()) {
1502     default: llvm_unreachable("Unknown loc info!");
1503     case CCValAssign::Full: break;
1504     case CCValAssign::SExt:
1505       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1506       break;
1507     case CCValAssign::ZExt:
1508       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1509       break;
1510     case CCValAssign::AExt:
1511       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1512       break;
1513     case CCValAssign::BCvt:
1514       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1515       break;
1516     }
1517
1518     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1519     if (VA.needsCustom()) {
1520       if (VA.getLocVT() == MVT::v2f64) {
1521         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1522                                   DAG.getConstant(0, MVT::i32));
1523         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1524                                   DAG.getConstant(1, MVT::i32));
1525
1526         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1527                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1528
1529         VA = ArgLocs[++i]; // skip ahead to next loc
1530         if (VA.isRegLoc()) {
1531           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1532                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1533         } else {
1534           assert(VA.isMemLoc());
1535
1536           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1537                                                  dl, DAG, VA, Flags));
1538         }
1539       } else {
1540         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1541                          StackPtr, MemOpChains, Flags);
1542       }
1543     } else if (VA.isRegLoc()) {
1544       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1545         assert(VA.getLocVT() == MVT::i32 &&
1546                "unexpected calling convention register assignment");
1547         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1548                "unexpected use of 'returned'");
1549         isThisReturn = true;
1550       }
1551       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1552     } else if (isByVal) {
1553       assert(VA.isMemLoc());
1554       unsigned offset = 0;
1555
1556       // True if this byval aggregate will be split between registers
1557       // and memory.
1558       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1559       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1560
1561       if (CurByValIdx < ByValArgsCount) {
1562
1563         unsigned RegBegin, RegEnd;
1564         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1565
1566         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1567         unsigned int i, j;
1568         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1569           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1570           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1571           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1572                                      MachinePointerInfo(),
1573                                      false, false, false,
1574                                      DAG.InferPtrAlignment(AddArg));
1575           MemOpChains.push_back(Load.getValue(1));
1576           RegsToPass.push_back(std::make_pair(j, Load));
1577         }
1578
1579         // If parameter size outsides register area, "offset" value
1580         // helps us to calculate stack slot for remained part properly.
1581         offset = RegEnd - RegBegin;
1582
1583         CCInfo.nextInRegsParam();
1584       }
1585
1586       if (Flags.getByValSize() > 4*offset) {
1587         unsigned LocMemOffset = VA.getLocMemOffset();
1588         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1589         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1590                                   StkPtrOff);
1591         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1592         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1593         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1594                                            MVT::i32);
1595         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1596
1597         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1598         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1599         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1600                                           Ops, array_lengthof(Ops)));
1601       }
1602     } else if (!isSibCall) {
1603       assert(VA.isMemLoc());
1604
1605       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1606                                              dl, DAG, VA, Flags));
1607     }
1608   }
1609
1610   if (!MemOpChains.empty())
1611     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1612                         &MemOpChains[0], MemOpChains.size());
1613
1614   // Build a sequence of copy-to-reg nodes chained together with token chain
1615   // and flag operands which copy the outgoing args into the appropriate regs.
1616   SDValue InFlag;
1617   // Tail call byval lowering might overwrite argument registers so in case of
1618   // tail call optimization the copies to registers are lowered later.
1619   if (!isTailCall)
1620     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1621       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1622                                RegsToPass[i].second, InFlag);
1623       InFlag = Chain.getValue(1);
1624     }
1625
1626   // For tail calls lower the arguments to the 'real' stack slot.
1627   if (isTailCall) {
1628     // Force all the incoming stack arguments to be loaded from the stack
1629     // before any new outgoing arguments are stored to the stack, because the
1630     // outgoing stack slots may alias the incoming argument stack slots, and
1631     // the alias isn't otherwise explicit. This is slightly more conservative
1632     // than necessary, because it means that each store effectively depends
1633     // on every argument instead of just those arguments it would clobber.
1634
1635     // Do not flag preceding copytoreg stuff together with the following stuff.
1636     InFlag = SDValue();
1637     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1638       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1639                                RegsToPass[i].second, InFlag);
1640       InFlag = Chain.getValue(1);
1641     }
1642     InFlag = SDValue();
1643   }
1644
1645   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1646   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1647   // node so that legalize doesn't hack it.
1648   bool isDirect = false;
1649   bool isARMFunc = false;
1650   bool isLocalARMFunc = false;
1651   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1652
1653   if (EnableARMLongCalls) {
1654     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1655             && "long-calls with non-static relocation model!");
1656     // Handle a global address or an external symbol. If it's not one of
1657     // those, the target's already in a register, so we don't need to do
1658     // anything extra.
1659     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1660       const GlobalValue *GV = G->getGlobal();
1661       // Create a constant pool entry for the callee address
1662       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1663       ARMConstantPoolValue *CPV =
1664         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1665
1666       // Get the address of the callee into a register
1667       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1668       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1669       Callee = DAG.getLoad(getPointerTy(), dl,
1670                            DAG.getEntryNode(), CPAddr,
1671                            MachinePointerInfo::getConstantPool(),
1672                            false, false, false, 0);
1673     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1674       const char *Sym = S->getSymbol();
1675
1676       // Create a constant pool entry for the callee address
1677       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1678       ARMConstantPoolValue *CPV =
1679         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1680                                       ARMPCLabelIndex, 0);
1681       // Get the address of the callee into a register
1682       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1683       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1684       Callee = DAG.getLoad(getPointerTy(), dl,
1685                            DAG.getEntryNode(), CPAddr,
1686                            MachinePointerInfo::getConstantPool(),
1687                            false, false, false, 0);
1688     }
1689   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1690     const GlobalValue *GV = G->getGlobal();
1691     isDirect = true;
1692     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1693     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1694                    getTargetMachine().getRelocationModel() != Reloc::Static;
1695     isARMFunc = !Subtarget->isThumb() || isStub;
1696     // ARM call to a local ARM function is predicable.
1697     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1698     // tBX takes a register source operand.
1699     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1700       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1701       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1702                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1703     } else {
1704       // On ELF targets for PIC code, direct calls should go through the PLT
1705       unsigned OpFlags = 0;
1706       if (Subtarget->isTargetELF() &&
1707           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1708         OpFlags = ARMII::MO_PLT;
1709       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1710     }
1711   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1712     isDirect = true;
1713     bool isStub = Subtarget->isTargetMachO() &&
1714                   getTargetMachine().getRelocationModel() != Reloc::Static;
1715     isARMFunc = !Subtarget->isThumb() || isStub;
1716     // tBX takes a register source operand.
1717     const char *Sym = S->getSymbol();
1718     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1719       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1720       ARMConstantPoolValue *CPV =
1721         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1722                                       ARMPCLabelIndex, 4);
1723       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1724       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1725       Callee = DAG.getLoad(getPointerTy(), dl,
1726                            DAG.getEntryNode(), CPAddr,
1727                            MachinePointerInfo::getConstantPool(),
1728                            false, false, false, 0);
1729       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1730       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1731                            getPointerTy(), Callee, PICLabel);
1732     } else {
1733       unsigned OpFlags = 0;
1734       // On ELF targets for PIC code, direct calls should go through the PLT
1735       if (Subtarget->isTargetELF() &&
1736                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1737         OpFlags = ARMII::MO_PLT;
1738       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1739     }
1740   }
1741
1742   // FIXME: handle tail calls differently.
1743   unsigned CallOpc;
1744   bool HasMinSizeAttr = Subtarget->isMinSize();
1745   if (Subtarget->isThumb()) {
1746     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1747       CallOpc = ARMISD::CALL_NOLINK;
1748     else
1749       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1750   } else {
1751     if (!isDirect && !Subtarget->hasV5TOps())
1752       CallOpc = ARMISD::CALL_NOLINK;
1753     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1754                // Emit regular call when code size is the priority
1755                !HasMinSizeAttr)
1756       // "mov lr, pc; b _foo" to avoid confusing the RSP
1757       CallOpc = ARMISD::CALL_NOLINK;
1758     else
1759       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1760   }
1761
1762   std::vector<SDValue> Ops;
1763   Ops.push_back(Chain);
1764   Ops.push_back(Callee);
1765
1766   // Add argument registers to the end of the list so that they are known live
1767   // into the call.
1768   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1769     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1770                                   RegsToPass[i].second.getValueType()));
1771
1772   // Add a register mask operand representing the call-preserved registers.
1773   if (!isTailCall) {
1774     const uint32_t *Mask;
1775     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1776     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1777     if (isThisReturn) {
1778       // For 'this' returns, use the R0-preserving mask if applicable
1779       Mask = ARI->getThisReturnPreservedMask(CallConv);
1780       if (!Mask) {
1781         // Set isThisReturn to false if the calling convention is not one that
1782         // allows 'returned' to be modeled in this way, so LowerCallResult does
1783         // not try to pass 'this' straight through
1784         isThisReturn = false;
1785         Mask = ARI->getCallPreservedMask(CallConv);
1786       }
1787     } else
1788       Mask = ARI->getCallPreservedMask(CallConv);
1789
1790     assert(Mask && "Missing call preserved mask for calling convention");
1791     Ops.push_back(DAG.getRegisterMask(Mask));
1792   }
1793
1794   if (InFlag.getNode())
1795     Ops.push_back(InFlag);
1796
1797   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1798   if (isTailCall)
1799     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1800
1801   // Returns a chain and a flag for retval copy to use.
1802   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1803   InFlag = Chain.getValue(1);
1804
1805   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1806                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1807   if (!Ins.empty())
1808     InFlag = Chain.getValue(1);
1809
1810   // Handle result values, copying them out of physregs into vregs that we
1811   // return.
1812   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1813                          InVals, isThisReturn,
1814                          isThisReturn ? OutVals[0] : SDValue());
1815 }
1816
1817 /// HandleByVal - Every parameter *after* a byval parameter is passed
1818 /// on the stack.  Remember the next parameter register to allocate,
1819 /// and then confiscate the rest of the parameter registers to insure
1820 /// this.
1821 void
1822 ARMTargetLowering::HandleByVal(
1823     CCState *State, unsigned &size, unsigned Align) const {
1824   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1825   assert((State->getCallOrPrologue() == Prologue ||
1826           State->getCallOrPrologue() == Call) &&
1827          "unhandled ParmContext");
1828
1829   // For in-prologue parameters handling, we also introduce stack offset
1830   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1831   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1832   // NSAA should be evaluted (NSAA means "next stacked argument address").
1833   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1834   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1835   unsigned NSAAOffset = State->getNextStackOffset();
1836   if (State->getCallOrPrologue() != Call) {
1837     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1838       unsigned RB, RE;
1839       State->getInRegsParamInfo(i, RB, RE);
1840       assert(NSAAOffset >= (RE-RB)*4 &&
1841              "Stack offset for byval regs doesn't introduced anymore?");
1842       NSAAOffset -= (RE-RB)*4;
1843     }
1844   }
1845   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1846     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1847       unsigned AlignInRegs = Align / 4;
1848       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1849       for (unsigned i = 0; i < Waste; ++i)
1850         reg = State->AllocateReg(GPRArgRegs, 4);
1851     }
1852     if (reg != 0) {
1853       unsigned excess = 4 * (ARM::R4 - reg);
1854
1855       // Special case when NSAA != SP and parameter size greater than size of
1856       // all remained GPR regs. In that case we can't split parameter, we must
1857       // send it to stack. We also must set NCRN to R4, so waste all
1858       // remained registers.
1859       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1860         while (State->AllocateReg(GPRArgRegs, 4))
1861           ;
1862         return;
1863       }
1864
1865       // First register for byval parameter is the first register that wasn't
1866       // allocated before this method call, so it would be "reg".
1867       // If parameter is small enough to be saved in range [reg, r4), then
1868       // the end (first after last) register would be reg + param-size-in-regs,
1869       // else parameter would be splitted between registers and stack,
1870       // end register would be r4 in this case.
1871       unsigned ByValRegBegin = reg;
1872       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1873       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1874       // Note, first register is allocated in the beginning of function already,
1875       // allocate remained amount of registers we need.
1876       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1877         State->AllocateReg(GPRArgRegs, 4);
1878       // At a call site, a byval parameter that is split between
1879       // registers and memory needs its size truncated here.  In a
1880       // function prologue, such byval parameters are reassembled in
1881       // memory, and are not truncated.
1882       if (State->getCallOrPrologue() == Call) {
1883         // Make remained size equal to 0 in case, when
1884         // the whole structure may be stored into registers.
1885         if (size < excess)
1886           size = 0;
1887         else
1888           size -= excess;
1889       }
1890     }
1891   }
1892 }
1893
1894 /// MatchingStackOffset - Return true if the given stack call argument is
1895 /// already available in the same position (relatively) of the caller's
1896 /// incoming argument stack.
1897 static
1898 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1899                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1900                          const TargetInstrInfo *TII) {
1901   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1902   int FI = INT_MAX;
1903   if (Arg.getOpcode() == ISD::CopyFromReg) {
1904     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1905     if (!TargetRegisterInfo::isVirtualRegister(VR))
1906       return false;
1907     MachineInstr *Def = MRI->getVRegDef(VR);
1908     if (!Def)
1909       return false;
1910     if (!Flags.isByVal()) {
1911       if (!TII->isLoadFromStackSlot(Def, FI))
1912         return false;
1913     } else {
1914       return false;
1915     }
1916   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1917     if (Flags.isByVal())
1918       // ByVal argument is passed in as a pointer but it's now being
1919       // dereferenced. e.g.
1920       // define @foo(%struct.X* %A) {
1921       //   tail call @bar(%struct.X* byval %A)
1922       // }
1923       return false;
1924     SDValue Ptr = Ld->getBasePtr();
1925     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1926     if (!FINode)
1927       return false;
1928     FI = FINode->getIndex();
1929   } else
1930     return false;
1931
1932   assert(FI != INT_MAX);
1933   if (!MFI->isFixedObjectIndex(FI))
1934     return false;
1935   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1936 }
1937
1938 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1939 /// for tail call optimization. Targets which want to do tail call
1940 /// optimization should implement this function.
1941 bool
1942 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1943                                                      CallingConv::ID CalleeCC,
1944                                                      bool isVarArg,
1945                                                      bool isCalleeStructRet,
1946                                                      bool isCallerStructRet,
1947                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1948                                     const SmallVectorImpl<SDValue> &OutVals,
1949                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1950                                                      SelectionDAG& DAG) const {
1951   const Function *CallerF = DAG.getMachineFunction().getFunction();
1952   CallingConv::ID CallerCC = CallerF->getCallingConv();
1953   bool CCMatch = CallerCC == CalleeCC;
1954
1955   // Look for obvious safe cases to perform tail call optimization that do not
1956   // require ABI changes. This is what gcc calls sibcall.
1957
1958   // Do not sibcall optimize vararg calls unless the call site is not passing
1959   // any arguments.
1960   if (isVarArg && !Outs.empty())
1961     return false;
1962
1963   // Exception-handling functions need a special set of instructions to indicate
1964   // a return to the hardware. Tail-calling another function would probably
1965   // break this.
1966   if (CallerF->hasFnAttribute("interrupt"))
1967     return false;
1968
1969   // Also avoid sibcall optimization if either caller or callee uses struct
1970   // return semantics.
1971   if (isCalleeStructRet || isCallerStructRet)
1972     return false;
1973
1974   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1975   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1976   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1977   // support in the assembler and linker to be used. This would need to be
1978   // fixed to fully support tail calls in Thumb1.
1979   //
1980   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1981   // LR.  This means if we need to reload LR, it takes an extra instructions,
1982   // which outweighs the value of the tail call; but here we don't know yet
1983   // whether LR is going to be used.  Probably the right approach is to
1984   // generate the tail call here and turn it back into CALL/RET in
1985   // emitEpilogue if LR is used.
1986
1987   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1988   // but we need to make sure there are enough registers; the only valid
1989   // registers are the 4 used for parameters.  We don't currently do this
1990   // case.
1991   if (Subtarget->isThumb1Only())
1992     return false;
1993
1994   // If the calling conventions do not match, then we'd better make sure the
1995   // results are returned in the same way as what the caller expects.
1996   if (!CCMatch) {
1997     SmallVector<CCValAssign, 16> RVLocs1;
1998     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1999                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2000     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2001
2002     SmallVector<CCValAssign, 16> RVLocs2;
2003     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2004                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2005     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2006
2007     if (RVLocs1.size() != RVLocs2.size())
2008       return false;
2009     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2010       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2011         return false;
2012       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2013         return false;
2014       if (RVLocs1[i].isRegLoc()) {
2015         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2016           return false;
2017       } else {
2018         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2019           return false;
2020       }
2021     }
2022   }
2023
2024   // If Caller's vararg or byval argument has been split between registers and
2025   // stack, do not perform tail call, since part of the argument is in caller's
2026   // local frame.
2027   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2028                                       getInfo<ARMFunctionInfo>();
2029   if (AFI_Caller->getArgRegsSaveSize())
2030     return false;
2031
2032   // If the callee takes no arguments then go on to check the results of the
2033   // call.
2034   if (!Outs.empty()) {
2035     // Check if stack adjustment is needed. For now, do not do this if any
2036     // argument is passed on the stack.
2037     SmallVector<CCValAssign, 16> ArgLocs;
2038     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2039                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2040     CCInfo.AnalyzeCallOperands(Outs,
2041                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2042     if (CCInfo.getNextStackOffset()) {
2043       MachineFunction &MF = DAG.getMachineFunction();
2044
2045       // Check if the arguments are already laid out in the right way as
2046       // the caller's fixed stack objects.
2047       MachineFrameInfo *MFI = MF.getFrameInfo();
2048       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2049       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2050       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2051            i != e;
2052            ++i, ++realArgIdx) {
2053         CCValAssign &VA = ArgLocs[i];
2054         EVT RegVT = VA.getLocVT();
2055         SDValue Arg = OutVals[realArgIdx];
2056         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2057         if (VA.getLocInfo() == CCValAssign::Indirect)
2058           return false;
2059         if (VA.needsCustom()) {
2060           // f64 and vector types are split into multiple registers or
2061           // register/stack-slot combinations.  The types will not match
2062           // the registers; give up on memory f64 refs until we figure
2063           // out what to do about this.
2064           if (!VA.isRegLoc())
2065             return false;
2066           if (!ArgLocs[++i].isRegLoc())
2067             return false;
2068           if (RegVT == MVT::v2f64) {
2069             if (!ArgLocs[++i].isRegLoc())
2070               return false;
2071             if (!ArgLocs[++i].isRegLoc())
2072               return false;
2073           }
2074         } else if (!VA.isRegLoc()) {
2075           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2076                                    MFI, MRI, TII))
2077             return false;
2078         }
2079       }
2080     }
2081   }
2082
2083   return true;
2084 }
2085
2086 bool
2087 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2088                                   MachineFunction &MF, bool isVarArg,
2089                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2090                                   LLVMContext &Context) const {
2091   SmallVector<CCValAssign, 16> RVLocs;
2092   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2093   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2094                                                     isVarArg));
2095 }
2096
2097 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2098                                     SDLoc DL, SelectionDAG &DAG) {
2099   const MachineFunction &MF = DAG.getMachineFunction();
2100   const Function *F = MF.getFunction();
2101
2102   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2103
2104   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2105   // version of the "preferred return address". These offsets affect the return
2106   // instruction if this is a return from PL1 without hypervisor extensions.
2107   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2108   //    SWI:     0      "subs pc, lr, #0"
2109   //    ABORT:   +4     "subs pc, lr, #4"
2110   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2111   // UNDEF varies depending on where the exception came from ARM or Thumb
2112   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2113
2114   int64_t LROffset;
2115   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2116       IntKind == "ABORT")
2117     LROffset = 4;
2118   else if (IntKind == "SWI" || IntKind == "UNDEF")
2119     LROffset = 0;
2120   else
2121     report_fatal_error("Unsupported interrupt attribute. If present, value "
2122                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2123
2124   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2125
2126   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2127                      RetOps.data(), RetOps.size());
2128 }
2129
2130 SDValue
2131 ARMTargetLowering::LowerReturn(SDValue Chain,
2132                                CallingConv::ID CallConv, bool isVarArg,
2133                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2134                                const SmallVectorImpl<SDValue> &OutVals,
2135                                SDLoc dl, SelectionDAG &DAG) const {
2136
2137   // CCValAssign - represent the assignment of the return value to a location.
2138   SmallVector<CCValAssign, 16> RVLocs;
2139
2140   // CCState - Info about the registers and stack slots.
2141   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2142                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2143
2144   // Analyze outgoing return values.
2145   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2146                                                isVarArg));
2147
2148   SDValue Flag;
2149   SmallVector<SDValue, 4> RetOps;
2150   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2151
2152   // Copy the result values into the output registers.
2153   for (unsigned i = 0, realRVLocIdx = 0;
2154        i != RVLocs.size();
2155        ++i, ++realRVLocIdx) {
2156     CCValAssign &VA = RVLocs[i];
2157     assert(VA.isRegLoc() && "Can only return in registers!");
2158
2159     SDValue Arg = OutVals[realRVLocIdx];
2160
2161     switch (VA.getLocInfo()) {
2162     default: llvm_unreachable("Unknown loc info!");
2163     case CCValAssign::Full: break;
2164     case CCValAssign::BCvt:
2165       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2166       break;
2167     }
2168
2169     if (VA.needsCustom()) {
2170       if (VA.getLocVT() == MVT::v2f64) {
2171         // Extract the first half and return it in two registers.
2172         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2173                                    DAG.getConstant(0, MVT::i32));
2174         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2175                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2176
2177         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2178         Flag = Chain.getValue(1);
2179         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2180         VA = RVLocs[++i]; // skip ahead to next loc
2181         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2182                                  HalfGPRs.getValue(1), Flag);
2183         Flag = Chain.getValue(1);
2184         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2185         VA = RVLocs[++i]; // skip ahead to next loc
2186
2187         // Extract the 2nd half and fall through to handle it as an f64 value.
2188         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2189                           DAG.getConstant(1, MVT::i32));
2190       }
2191       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2192       // available.
2193       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2194                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2195       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2196       Flag = Chain.getValue(1);
2197       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2198       VA = RVLocs[++i]; // skip ahead to next loc
2199       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2200                                Flag);
2201     } else
2202       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2203
2204     // Guarantee that all emitted copies are
2205     // stuck together, avoiding something bad.
2206     Flag = Chain.getValue(1);
2207     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2208   }
2209
2210   // Update chain and glue.
2211   RetOps[0] = Chain;
2212   if (Flag.getNode())
2213     RetOps.push_back(Flag);
2214
2215   // CPUs which aren't M-class use a special sequence to return from
2216   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2217   // though we use "subs pc, lr, #N").
2218   //
2219   // M-class CPUs actually use a normal return sequence with a special
2220   // (hardware-provided) value in LR, so the normal code path works.
2221   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2222       !Subtarget->isMClass()) {
2223     if (Subtarget->isThumb1Only())
2224       report_fatal_error("interrupt attribute is not supported in Thumb1");
2225     return LowerInterruptReturn(RetOps, dl, DAG);
2226   }
2227
2228   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2229                      RetOps.data(), RetOps.size());
2230 }
2231
2232 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2233   if (N->getNumValues() != 1)
2234     return false;
2235   if (!N->hasNUsesOfValue(1, 0))
2236     return false;
2237
2238   SDValue TCChain = Chain;
2239   SDNode *Copy = *N->use_begin();
2240   if (Copy->getOpcode() == ISD::CopyToReg) {
2241     // If the copy has a glue operand, we conservatively assume it isn't safe to
2242     // perform a tail call.
2243     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2244       return false;
2245     TCChain = Copy->getOperand(0);
2246   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2247     SDNode *VMov = Copy;
2248     // f64 returned in a pair of GPRs.
2249     SmallPtrSet<SDNode*, 2> Copies;
2250     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2251          UI != UE; ++UI) {
2252       if (UI->getOpcode() != ISD::CopyToReg)
2253         return false;
2254       Copies.insert(*UI);
2255     }
2256     if (Copies.size() > 2)
2257       return false;
2258
2259     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2260          UI != UE; ++UI) {
2261       SDValue UseChain = UI->getOperand(0);
2262       if (Copies.count(UseChain.getNode()))
2263         // Second CopyToReg
2264         Copy = *UI;
2265       else
2266         // First CopyToReg
2267         TCChain = UseChain;
2268     }
2269   } else if (Copy->getOpcode() == ISD::BITCAST) {
2270     // f32 returned in a single GPR.
2271     if (!Copy->hasOneUse())
2272       return false;
2273     Copy = *Copy->use_begin();
2274     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2275       return false;
2276     TCChain = Copy->getOperand(0);
2277   } else {
2278     return false;
2279   }
2280
2281   bool HasRet = false;
2282   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2283        UI != UE; ++UI) {
2284     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2285         UI->getOpcode() != ARMISD::INTRET_FLAG)
2286       return false;
2287     HasRet = true;
2288   }
2289
2290   if (!HasRet)
2291     return false;
2292
2293   Chain = TCChain;
2294   return true;
2295 }
2296
2297 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2298   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2299     return false;
2300
2301   if (!CI->isTailCall())
2302     return false;
2303
2304   return !Subtarget->isThumb1Only();
2305 }
2306
2307 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2308 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2309 // one of the above mentioned nodes. It has to be wrapped because otherwise
2310 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2311 // be used to form addressing mode. These wrapped nodes will be selected
2312 // into MOVi.
2313 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2314   EVT PtrVT = Op.getValueType();
2315   // FIXME there is no actual debug info here
2316   SDLoc dl(Op);
2317   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2318   SDValue Res;
2319   if (CP->isMachineConstantPoolEntry())
2320     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2321                                     CP->getAlignment());
2322   else
2323     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2324                                     CP->getAlignment());
2325   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2326 }
2327
2328 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2329   return MachineJumpTableInfo::EK_Inline;
2330 }
2331
2332 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2333                                              SelectionDAG &DAG) const {
2334   MachineFunction &MF = DAG.getMachineFunction();
2335   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2336   unsigned ARMPCLabelIndex = 0;
2337   SDLoc DL(Op);
2338   EVT PtrVT = getPointerTy();
2339   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2340   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2341   SDValue CPAddr;
2342   if (RelocM == Reloc::Static) {
2343     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2344   } else {
2345     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2346     ARMPCLabelIndex = AFI->createPICLabelUId();
2347     ARMConstantPoolValue *CPV =
2348       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2349                                       ARMCP::CPBlockAddress, PCAdj);
2350     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2351   }
2352   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2353   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2354                                MachinePointerInfo::getConstantPool(),
2355                                false, false, false, 0);
2356   if (RelocM == Reloc::Static)
2357     return Result;
2358   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2359   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2360 }
2361
2362 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2363 SDValue
2364 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2365                                                  SelectionDAG &DAG) const {
2366   SDLoc dl(GA);
2367   EVT PtrVT = getPointerTy();
2368   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2369   MachineFunction &MF = DAG.getMachineFunction();
2370   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2371   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2372   ARMConstantPoolValue *CPV =
2373     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2374                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2375   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2376   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2377   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2378                          MachinePointerInfo::getConstantPool(),
2379                          false, false, false, 0);
2380   SDValue Chain = Argument.getValue(1);
2381
2382   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2383   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2384
2385   // call __tls_get_addr.
2386   ArgListTy Args;
2387   ArgListEntry Entry;
2388   Entry.Node = Argument;
2389   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2390   Args.push_back(Entry);
2391   // FIXME: is there useful debug info available here?
2392   TargetLowering::CallLoweringInfo CLI(Chain,
2393                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2394                 false, false, false, false,
2395                 0, CallingConv::C, /*isTailCall=*/false,
2396                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2397                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2398   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2399   return CallResult.first;
2400 }
2401
2402 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2403 // "local exec" model.
2404 SDValue
2405 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2406                                         SelectionDAG &DAG,
2407                                         TLSModel::Model model) const {
2408   const GlobalValue *GV = GA->getGlobal();
2409   SDLoc dl(GA);
2410   SDValue Offset;
2411   SDValue Chain = DAG.getEntryNode();
2412   EVT PtrVT = getPointerTy();
2413   // Get the Thread Pointer
2414   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2415
2416   if (model == TLSModel::InitialExec) {
2417     MachineFunction &MF = DAG.getMachineFunction();
2418     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2419     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2420     // Initial exec model.
2421     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2422     ARMConstantPoolValue *CPV =
2423       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2424                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2425                                       true);
2426     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2427     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2428     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2429                          MachinePointerInfo::getConstantPool(),
2430                          false, false, false, 0);
2431     Chain = Offset.getValue(1);
2432
2433     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2434     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2435
2436     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2437                          MachinePointerInfo::getConstantPool(),
2438                          false, false, false, 0);
2439   } else {
2440     // local exec model
2441     assert(model == TLSModel::LocalExec);
2442     ARMConstantPoolValue *CPV =
2443       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2444     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2445     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2446     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2447                          MachinePointerInfo::getConstantPool(),
2448                          false, false, false, 0);
2449   }
2450
2451   // The address of the thread local variable is the add of the thread
2452   // pointer with the offset of the variable.
2453   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2454 }
2455
2456 SDValue
2457 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2458   // TODO: implement the "local dynamic" model
2459   assert(Subtarget->isTargetELF() &&
2460          "TLS not implemented for non-ELF targets");
2461   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2462
2463   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2464
2465   switch (model) {
2466     case TLSModel::GeneralDynamic:
2467     case TLSModel::LocalDynamic:
2468       return LowerToTLSGeneralDynamicModel(GA, DAG);
2469     case TLSModel::InitialExec:
2470     case TLSModel::LocalExec:
2471       return LowerToTLSExecModels(GA, DAG, model);
2472   }
2473   llvm_unreachable("bogus TLS model");
2474 }
2475
2476 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2477                                                  SelectionDAG &DAG) const {
2478   EVT PtrVT = getPointerTy();
2479   SDLoc dl(Op);
2480   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2481   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2482     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2483     ARMConstantPoolValue *CPV =
2484       ARMConstantPoolConstant::Create(GV,
2485                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2486     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2487     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2488     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2489                                  CPAddr,
2490                                  MachinePointerInfo::getConstantPool(),
2491                                  false, false, false, 0);
2492     SDValue Chain = Result.getValue(1);
2493     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2494     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2495     if (!UseGOTOFF)
2496       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2497                            MachinePointerInfo::getGOT(),
2498                            false, false, false, 0);
2499     return Result;
2500   }
2501
2502   // If we have T2 ops, we can materialize the address directly via movt/movw
2503   // pair. This is always cheaper.
2504   if (Subtarget->useMovt()) {
2505     ++NumMovwMovt;
2506     // FIXME: Once remat is capable of dealing with instructions with register
2507     // operands, expand this into two nodes.
2508     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2509                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2510   } else {
2511     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2512     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2513     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2514                        MachinePointerInfo::getConstantPool(),
2515                        false, false, false, 0);
2516   }
2517 }
2518
2519 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2520                                                     SelectionDAG &DAG) const {
2521   EVT PtrVT = getPointerTy();
2522   SDLoc dl(Op);
2523   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2524   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2525
2526   if (Subtarget->useMovt())
2527     ++NumMovwMovt;
2528
2529   // FIXME: Once remat is capable of dealing with instructions with register
2530   // operands, expand this into multiple nodes
2531   unsigned Wrapper =
2532       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2533
2534   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2535   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2536
2537   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2538     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2539                          MachinePointerInfo::getGOT(), false, false, false, 0);
2540   return Result;
2541 }
2542
2543 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2544                                                     SelectionDAG &DAG) const {
2545   assert(Subtarget->isTargetELF() &&
2546          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2547   MachineFunction &MF = DAG.getMachineFunction();
2548   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2549   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2550   EVT PtrVT = getPointerTy();
2551   SDLoc dl(Op);
2552   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2553   ARMConstantPoolValue *CPV =
2554     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2555                                   ARMPCLabelIndex, PCAdj);
2556   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2557   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2558   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2559                                MachinePointerInfo::getConstantPool(),
2560                                false, false, false, 0);
2561   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2562   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2563 }
2564
2565 SDValue
2566 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2567   SDLoc dl(Op);
2568   SDValue Val = DAG.getConstant(0, MVT::i32);
2569   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2570                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2571                      Op.getOperand(1), Val);
2572 }
2573
2574 SDValue
2575 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2576   SDLoc dl(Op);
2577   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2578                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2579 }
2580
2581 SDValue
2582 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2583                                           const ARMSubtarget *Subtarget) const {
2584   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2585   SDLoc dl(Op);
2586   switch (IntNo) {
2587   default: return SDValue();    // Don't custom lower most intrinsics.
2588   case Intrinsic::arm_thread_pointer: {
2589     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2590     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2591   }
2592   case Intrinsic::eh_sjlj_lsda: {
2593     MachineFunction &MF = DAG.getMachineFunction();
2594     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2595     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2596     EVT PtrVT = getPointerTy();
2597     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2598     SDValue CPAddr;
2599     unsigned PCAdj = (RelocM != Reloc::PIC_)
2600       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2601     ARMConstantPoolValue *CPV =
2602       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2603                                       ARMCP::CPLSDA, PCAdj);
2604     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2605     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2606     SDValue Result =
2607       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2608                   MachinePointerInfo::getConstantPool(),
2609                   false, false, false, 0);
2610
2611     if (RelocM == Reloc::PIC_) {
2612       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2613       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2614     }
2615     return Result;
2616   }
2617   case Intrinsic::arm_neon_vmulls:
2618   case Intrinsic::arm_neon_vmullu: {
2619     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2620       ? ARMISD::VMULLs : ARMISD::VMULLu;
2621     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2622                        Op.getOperand(1), Op.getOperand(2));
2623   }
2624   }
2625 }
2626
2627 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2628                                  const ARMSubtarget *Subtarget) {
2629   // FIXME: handle "fence singlethread" more efficiently.
2630   SDLoc dl(Op);
2631   if (!Subtarget->hasDataBarrier()) {
2632     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2633     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2634     // here.
2635     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2636            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2637     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2638                        DAG.getConstant(0, MVT::i32));
2639   }
2640
2641   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2642   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2643   unsigned Domain = ARM_MB::ISH;
2644   if (Subtarget->isMClass()) {
2645     // Only a full system barrier exists in the M-class architectures.
2646     Domain = ARM_MB::SY;
2647   } else if (Subtarget->isSwift() && Ord == Release) {
2648     // Swift happens to implement ISHST barriers in a way that's compatible with
2649     // Release semantics but weaker than ISH so we'd be fools not to use
2650     // it. Beware: other processors probably don't!
2651     Domain = ARM_MB::ISHST;
2652   }
2653
2654   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2655                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2656                      DAG.getConstant(Domain, MVT::i32));
2657 }
2658
2659 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2660                              const ARMSubtarget *Subtarget) {
2661   // ARM pre v5TE and Thumb1 does not have preload instructions.
2662   if (!(Subtarget->isThumb2() ||
2663         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2664     // Just preserve the chain.
2665     return Op.getOperand(0);
2666
2667   SDLoc dl(Op);
2668   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2669   if (!isRead &&
2670       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2671     // ARMv7 with MP extension has PLDW.
2672     return Op.getOperand(0);
2673
2674   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2675   if (Subtarget->isThumb()) {
2676     // Invert the bits.
2677     isRead = ~isRead & 1;
2678     isData = ~isData & 1;
2679   }
2680
2681   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2682                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2683                      DAG.getConstant(isData, MVT::i32));
2684 }
2685
2686 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2687   MachineFunction &MF = DAG.getMachineFunction();
2688   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2689
2690   // vastart just stores the address of the VarArgsFrameIndex slot into the
2691   // memory location argument.
2692   SDLoc dl(Op);
2693   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2694   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2695   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2696   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2697                       MachinePointerInfo(SV), false, false, 0);
2698 }
2699
2700 SDValue
2701 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2702                                         SDValue &Root, SelectionDAG &DAG,
2703                                         SDLoc dl) const {
2704   MachineFunction &MF = DAG.getMachineFunction();
2705   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2706
2707   const TargetRegisterClass *RC;
2708   if (AFI->isThumb1OnlyFunction())
2709     RC = &ARM::tGPRRegClass;
2710   else
2711     RC = &ARM::GPRRegClass;
2712
2713   // Transform the arguments stored in physical registers into virtual ones.
2714   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2715   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2716
2717   SDValue ArgValue2;
2718   if (NextVA.isMemLoc()) {
2719     MachineFrameInfo *MFI = MF.getFrameInfo();
2720     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2721
2722     // Create load node to retrieve arguments from the stack.
2723     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2724     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2725                             MachinePointerInfo::getFixedStack(FI),
2726                             false, false, false, 0);
2727   } else {
2728     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2729     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2730   }
2731
2732   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2733 }
2734
2735 void
2736 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2737                                   unsigned InRegsParamRecordIdx,
2738                                   unsigned ArgSize,
2739                                   unsigned &ArgRegsSize,
2740                                   unsigned &ArgRegsSaveSize)
2741   const {
2742   unsigned NumGPRs;
2743   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2744     unsigned RBegin, REnd;
2745     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2746     NumGPRs = REnd - RBegin;
2747   } else {
2748     unsigned int firstUnalloced;
2749     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2750                                                 sizeof(GPRArgRegs) /
2751                                                 sizeof(GPRArgRegs[0]));
2752     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2753   }
2754
2755   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2756   ArgRegsSize = NumGPRs * 4;
2757
2758   // If parameter is split between stack and GPRs...
2759   if (NumGPRs && Align > 4 &&
2760       (ArgRegsSize < ArgSize ||
2761         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2762     // Add padding for part of param recovered from GPRs.  For example,
2763     // if Align == 8, its last byte must be at address K*8 - 1.
2764     // We need to do it, since remained (stack) part of parameter has
2765     // stack alignment, and we need to "attach" "GPRs head" without gaps
2766     // to it:
2767     // Stack:
2768     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2769     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2770     //
2771     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2772     unsigned Padding =
2773         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2774     ArgRegsSaveSize = ArgRegsSize + Padding;
2775   } else
2776     // We don't need to extend regs save size for byval parameters if they
2777     // are passed via GPRs only.
2778     ArgRegsSaveSize = ArgRegsSize;
2779 }
2780
2781 // The remaining GPRs hold either the beginning of variable-argument
2782 // data, or the beginning of an aggregate passed by value (usually
2783 // byval).  Either way, we allocate stack slots adjacent to the data
2784 // provided by our caller, and store the unallocated registers there.
2785 // If this is a variadic function, the va_list pointer will begin with
2786 // these values; otherwise, this reassembles a (byval) structure that
2787 // was split between registers and memory.
2788 // Return: The frame index registers were stored into.
2789 int
2790 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2791                                   SDLoc dl, SDValue &Chain,
2792                                   const Value *OrigArg,
2793                                   unsigned InRegsParamRecordIdx,
2794                                   unsigned OffsetFromOrigArg,
2795                                   unsigned ArgOffset,
2796                                   unsigned ArgSize,
2797                                   bool ForceMutable) const {
2798
2799   // Currently, two use-cases possible:
2800   // Case #1. Non-var-args function, and we meet first byval parameter.
2801   //          Setup first unallocated register as first byval register;
2802   //          eat all remained registers
2803   //          (these two actions are performed by HandleByVal method).
2804   //          Then, here, we initialize stack frame with
2805   //          "store-reg" instructions.
2806   // Case #2. Var-args function, that doesn't contain byval parameters.
2807   //          The same: eat all remained unallocated registers,
2808   //          initialize stack frame.
2809
2810   MachineFunction &MF = DAG.getMachineFunction();
2811   MachineFrameInfo *MFI = MF.getFrameInfo();
2812   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2813   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2814   unsigned RBegin, REnd;
2815   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2816     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2817     firstRegToSaveIndex = RBegin - ARM::R0;
2818     lastRegToSaveIndex = REnd - ARM::R0;
2819   } else {
2820     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2821       (GPRArgRegs, array_lengthof(GPRArgRegs));
2822     lastRegToSaveIndex = 4;
2823   }
2824
2825   unsigned ArgRegsSize, ArgRegsSaveSize;
2826   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2827                  ArgRegsSize, ArgRegsSaveSize);
2828
2829   // Store any by-val regs to their spots on the stack so that they may be
2830   // loaded by deferencing the result of formal parameter pointer or va_next.
2831   // Note: once stack area for byval/varargs registers
2832   // was initialized, it can't be initialized again.
2833   if (ArgRegsSaveSize) {
2834
2835     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2836
2837     if (Padding) {
2838       assert(AFI->getStoredByValParamsPadding() == 0 &&
2839              "The only parameter may be padded.");
2840       AFI->setStoredByValParamsPadding(Padding);
2841     }
2842
2843     int FrameIndex = MFI->CreateFixedObject(
2844                       ArgRegsSaveSize,
2845                       Padding + ArgOffset,
2846                       false);
2847     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2848
2849     SmallVector<SDValue, 4> MemOps;
2850     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2851          ++firstRegToSaveIndex, ++i) {
2852       const TargetRegisterClass *RC;
2853       if (AFI->isThumb1OnlyFunction())
2854         RC = &ARM::tGPRRegClass;
2855       else
2856         RC = &ARM::GPRRegClass;
2857
2858       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2859       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2860       SDValue Store =
2861         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2862                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2863                      false, false, 0);
2864       MemOps.push_back(Store);
2865       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2866                         DAG.getConstant(4, getPointerTy()));
2867     }
2868
2869     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2870
2871     if (!MemOps.empty())
2872       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2873                           &MemOps[0], MemOps.size());
2874     return FrameIndex;
2875   } else
2876     // This will point to the next argument passed via stack.
2877     return MFI->CreateFixedObject(
2878         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2879 }
2880
2881 // Setup stack frame, the va_list pointer will start from.
2882 void
2883 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2884                                         SDLoc dl, SDValue &Chain,
2885                                         unsigned ArgOffset,
2886                                         bool ForceMutable) const {
2887   MachineFunction &MF = DAG.getMachineFunction();
2888   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2889
2890   // Try to store any remaining integer argument regs
2891   // to their spots on the stack so that they may be loaded by deferencing
2892   // the result of va_next.
2893   // If there is no regs to be stored, just point address after last
2894   // argument passed via stack.
2895   int FrameIndex =
2896     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2897                    0, ArgOffset, 0, ForceMutable);
2898
2899   AFI->setVarArgsFrameIndex(FrameIndex);
2900 }
2901
2902 SDValue
2903 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2904                                         CallingConv::ID CallConv, bool isVarArg,
2905                                         const SmallVectorImpl<ISD::InputArg>
2906                                           &Ins,
2907                                         SDLoc dl, SelectionDAG &DAG,
2908                                         SmallVectorImpl<SDValue> &InVals)
2909                                           const {
2910   MachineFunction &MF = DAG.getMachineFunction();
2911   MachineFrameInfo *MFI = MF.getFrameInfo();
2912
2913   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2914
2915   // Assign locations to all of the incoming arguments.
2916   SmallVector<CCValAssign, 16> ArgLocs;
2917   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2918                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2919   CCInfo.AnalyzeFormalArguments(Ins,
2920                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2921                                                   isVarArg));
2922
2923   SmallVector<SDValue, 16> ArgValues;
2924   int lastInsIndex = -1;
2925   SDValue ArgValue;
2926   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2927   unsigned CurArgIdx = 0;
2928
2929   // Initially ArgRegsSaveSize is zero.
2930   // Then we increase this value each time we meet byval parameter.
2931   // We also increase this value in case of varargs function.
2932   AFI->setArgRegsSaveSize(0);
2933
2934   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2935     CCValAssign &VA = ArgLocs[i];
2936     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2937     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2938     // Arguments stored in registers.
2939     if (VA.isRegLoc()) {
2940       EVT RegVT = VA.getLocVT();
2941
2942       if (VA.needsCustom()) {
2943         // f64 and vector types are split up into multiple registers or
2944         // combinations of registers and stack slots.
2945         if (VA.getLocVT() == MVT::v2f64) {
2946           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2947                                                    Chain, DAG, dl);
2948           VA = ArgLocs[++i]; // skip ahead to next loc
2949           SDValue ArgValue2;
2950           if (VA.isMemLoc()) {
2951             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2952             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2953             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2954                                     MachinePointerInfo::getFixedStack(FI),
2955                                     false, false, false, 0);
2956           } else {
2957             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2958                                              Chain, DAG, dl);
2959           }
2960           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2961           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2962                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2963           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2964                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2965         } else
2966           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2967
2968       } else {
2969         const TargetRegisterClass *RC;
2970
2971         if (RegVT == MVT::f32)
2972           RC = &ARM::SPRRegClass;
2973         else if (RegVT == MVT::f64)
2974           RC = &ARM::DPRRegClass;
2975         else if (RegVT == MVT::v2f64)
2976           RC = &ARM::QPRRegClass;
2977         else if (RegVT == MVT::i32)
2978           RC = AFI->isThumb1OnlyFunction() ?
2979             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2980             (const TargetRegisterClass*)&ARM::GPRRegClass;
2981         else
2982           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2983
2984         // Transform the arguments in physical registers into virtual ones.
2985         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2986         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2987       }
2988
2989       // If this is an 8 or 16-bit value, it is really passed promoted
2990       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2991       // truncate to the right size.
2992       switch (VA.getLocInfo()) {
2993       default: llvm_unreachable("Unknown loc info!");
2994       case CCValAssign::Full: break;
2995       case CCValAssign::BCvt:
2996         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2997         break;
2998       case CCValAssign::SExt:
2999         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3000                                DAG.getValueType(VA.getValVT()));
3001         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3002         break;
3003       case CCValAssign::ZExt:
3004         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3005                                DAG.getValueType(VA.getValVT()));
3006         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3007         break;
3008       }
3009
3010       InVals.push_back(ArgValue);
3011
3012     } else { // VA.isRegLoc()
3013
3014       // sanity check
3015       assert(VA.isMemLoc());
3016       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3017
3018       int index = ArgLocs[i].getValNo();
3019
3020       // Some Ins[] entries become multiple ArgLoc[] entries.
3021       // Process them only once.
3022       if (index != lastInsIndex)
3023         {
3024           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3025           // FIXME: For now, all byval parameter objects are marked mutable.
3026           // This can be changed with more analysis.
3027           // In case of tail call optimization mark all arguments mutable.
3028           // Since they could be overwritten by lowering of arguments in case of
3029           // a tail call.
3030           if (Flags.isByVal()) {
3031             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3032             int FrameIndex = StoreByValRegs(
3033                 CCInfo, DAG, dl, Chain, CurOrigArg,
3034                 CurByValIndex,
3035                 Ins[VA.getValNo()].PartOffset,
3036                 VA.getLocMemOffset(),
3037                 Flags.getByValSize(),
3038                 true /*force mutable frames*/);
3039             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3040             CCInfo.nextInRegsParam();
3041           } else {
3042             unsigned FIOffset = VA.getLocMemOffset() +
3043                                 AFI->getStoredByValParamsPadding();
3044             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3045                                             FIOffset, true);
3046
3047             // Create load nodes to retrieve arguments from the stack.
3048             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3049             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3050                                          MachinePointerInfo::getFixedStack(FI),
3051                                          false, false, false, 0));
3052           }
3053           lastInsIndex = index;
3054         }
3055     }
3056   }
3057
3058   // varargs
3059   if (isVarArg)
3060     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3061                          CCInfo.getNextStackOffset());
3062
3063   return Chain;
3064 }
3065
3066 /// isFloatingPointZero - Return true if this is +0.0.
3067 static bool isFloatingPointZero(SDValue Op) {
3068   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3069     return CFP->getValueAPF().isPosZero();
3070   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3071     // Maybe this has already been legalized into the constant pool?
3072     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3073       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3074       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3075         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3076           return CFP->getValueAPF().isPosZero();
3077     }
3078   }
3079   return false;
3080 }
3081
3082 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3083 /// the given operands.
3084 SDValue
3085 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3086                              SDValue &ARMcc, SelectionDAG &DAG,
3087                              SDLoc dl) const {
3088   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3089     unsigned C = RHSC->getZExtValue();
3090     if (!isLegalICmpImmediate(C)) {
3091       // Constant does not fit, try adjusting it by one?
3092       switch (CC) {
3093       default: break;
3094       case ISD::SETLT:
3095       case ISD::SETGE:
3096         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3097           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3098           RHS = DAG.getConstant(C-1, MVT::i32);
3099         }
3100         break;
3101       case ISD::SETULT:
3102       case ISD::SETUGE:
3103         if (C != 0 && isLegalICmpImmediate(C-1)) {
3104           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3105           RHS = DAG.getConstant(C-1, MVT::i32);
3106         }
3107         break;
3108       case ISD::SETLE:
3109       case ISD::SETGT:
3110         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3111           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3112           RHS = DAG.getConstant(C+1, MVT::i32);
3113         }
3114         break;
3115       case ISD::SETULE:
3116       case ISD::SETUGT:
3117         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3118           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3119           RHS = DAG.getConstant(C+1, MVT::i32);
3120         }
3121         break;
3122       }
3123     }
3124   }
3125
3126   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3127   ARMISD::NodeType CompareType;
3128   switch (CondCode) {
3129   default:
3130     CompareType = ARMISD::CMP;
3131     break;
3132   case ARMCC::EQ:
3133   case ARMCC::NE:
3134     // Uses only Z Flag
3135     CompareType = ARMISD::CMPZ;
3136     break;
3137   }
3138   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3139   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3140 }
3141
3142 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3143 SDValue
3144 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3145                              SDLoc dl) const {
3146   SDValue Cmp;
3147   if (!isFloatingPointZero(RHS))
3148     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3149   else
3150     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3151   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3152 }
3153
3154 /// duplicateCmp - Glue values can have only one use, so this function
3155 /// duplicates a comparison node.
3156 SDValue
3157 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3158   unsigned Opc = Cmp.getOpcode();
3159   SDLoc DL(Cmp);
3160   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3161     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3162
3163   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3164   Cmp = Cmp.getOperand(0);
3165   Opc = Cmp.getOpcode();
3166   if (Opc == ARMISD::CMPFP)
3167     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3168   else {
3169     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3170     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3171   }
3172   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3173 }
3174
3175 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3176   SDValue Cond = Op.getOperand(0);
3177   SDValue SelectTrue = Op.getOperand(1);
3178   SDValue SelectFalse = Op.getOperand(2);
3179   SDLoc dl(Op);
3180
3181   // Convert:
3182   //
3183   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3184   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3185   //
3186   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3187     const ConstantSDNode *CMOVTrue =
3188       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3189     const ConstantSDNode *CMOVFalse =
3190       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3191
3192     if (CMOVTrue && CMOVFalse) {
3193       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3194       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3195
3196       SDValue True;
3197       SDValue False;
3198       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3199         True = SelectTrue;
3200         False = SelectFalse;
3201       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3202         True = SelectFalse;
3203         False = SelectTrue;
3204       }
3205
3206       if (True.getNode() && False.getNode()) {
3207         EVT VT = Op.getValueType();
3208         SDValue ARMcc = Cond.getOperand(2);
3209         SDValue CCR = Cond.getOperand(3);
3210         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3211         assert(True.getValueType() == VT);
3212         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3213       }
3214     }
3215   }
3216
3217   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3218   // undefined bits before doing a full-word comparison with zero.
3219   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3220                      DAG.getConstant(1, Cond.getValueType()));
3221
3222   return DAG.getSelectCC(dl, Cond,
3223                          DAG.getConstant(0, Cond.getValueType()),
3224                          SelectTrue, SelectFalse, ISD::SETNE);
3225 }
3226
3227 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3228   if (CC == ISD::SETNE)
3229     return ISD::SETEQ;
3230   return ISD::getSetCCInverse(CC, true);
3231 }
3232
3233 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3234                                  bool &swpCmpOps, bool &swpVselOps) {
3235   // Start by selecting the GE condition code for opcodes that return true for
3236   // 'equality'
3237   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3238       CC == ISD::SETULE)
3239     CondCode = ARMCC::GE;
3240
3241   // and GT for opcodes that return false for 'equality'.
3242   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3243            CC == ISD::SETULT)
3244     CondCode = ARMCC::GT;
3245
3246   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3247   // to swap the compare operands.
3248   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3249       CC == ISD::SETULT)
3250     swpCmpOps = true;
3251
3252   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3253   // If we have an unordered opcode, we need to swap the operands to the VSEL
3254   // instruction (effectively negating the condition).
3255   //
3256   // This also has the effect of swapping which one of 'less' or 'greater'
3257   // returns true, so we also swap the compare operands. It also switches
3258   // whether we return true for 'equality', so we compensate by picking the
3259   // opposite condition code to our original choice.
3260   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3261       CC == ISD::SETUGT) {
3262     swpCmpOps = !swpCmpOps;
3263     swpVselOps = !swpVselOps;
3264     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3265   }
3266
3267   // 'ordered' is 'anything but unordered', so use the VS condition code and
3268   // swap the VSEL operands.
3269   if (CC == ISD::SETO) {
3270     CondCode = ARMCC::VS;
3271     swpVselOps = true;
3272   }
3273
3274   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3275   // code and swap the VSEL operands.
3276   if (CC == ISD::SETUNE) {
3277     CondCode = ARMCC::EQ;
3278     swpVselOps = true;
3279   }
3280 }
3281
3282 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3283   EVT VT = Op.getValueType();
3284   SDValue LHS = Op.getOperand(0);
3285   SDValue RHS = Op.getOperand(1);
3286   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3287   SDValue TrueVal = Op.getOperand(2);
3288   SDValue FalseVal = Op.getOperand(3);
3289   SDLoc dl(Op);
3290
3291   if (LHS.getValueType() == MVT::i32) {
3292     // Try to generate VSEL on ARMv8.
3293     // The VSEL instruction can't use all the usual ARM condition
3294     // codes: it only has two bits to select the condition code, so it's
3295     // constrained to use only GE, GT, VS and EQ.
3296     //
3297     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3298     // swap the operands of the previous compare instruction (effectively
3299     // inverting the compare condition, swapping 'less' and 'greater') and
3300     // sometimes need to swap the operands to the VSEL (which inverts the
3301     // condition in the sense of firing whenever the previous condition didn't)
3302     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3303                                       TrueVal.getValueType() == MVT::f64)) {
3304       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3305       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3306           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3307         CC = getInverseCCForVSEL(CC);
3308         std::swap(TrueVal, FalseVal);
3309       }
3310     }
3311
3312     SDValue ARMcc;
3313     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3314     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3315     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3316                        Cmp);
3317   }
3318
3319   ARMCC::CondCodes CondCode, CondCode2;
3320   FPCCToARMCC(CC, CondCode, CondCode2);
3321
3322   // Try to generate VSEL on ARMv8.
3323   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3324                                     TrueVal.getValueType() == MVT::f64)) {
3325     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3326     // same operands, as follows:
3327     //   c = fcmp [ogt, olt, ugt, ult] a, b
3328     //   select c, a, b
3329     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3330     // handled differently than the original code sequence.
3331     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3332         RHS == FalseVal) {
3333       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3334         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3335       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3336         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3337     }
3338
3339     bool swpCmpOps = false;
3340     bool swpVselOps = false;
3341     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3342
3343     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3344         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3345       if (swpCmpOps)
3346         std::swap(LHS, RHS);
3347       if (swpVselOps)
3348         std::swap(TrueVal, FalseVal);
3349     }
3350   }
3351
3352   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3353   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3354   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3355   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3356                                ARMcc, CCR, Cmp);
3357   if (CondCode2 != ARMCC::AL) {
3358     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3359     // FIXME: Needs another CMP because flag can have but one use.
3360     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3361     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3362                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3363   }
3364   return Result;
3365 }
3366
3367 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3368 /// to morph to an integer compare sequence.
3369 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3370                            const ARMSubtarget *Subtarget) {
3371   SDNode *N = Op.getNode();
3372   if (!N->hasOneUse())
3373     // Otherwise it requires moving the value from fp to integer registers.
3374     return false;
3375   if (!N->getNumValues())
3376     return false;
3377   EVT VT = Op.getValueType();
3378   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3379     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3380     // vmrs are very slow, e.g. cortex-a8.
3381     return false;
3382
3383   if (isFloatingPointZero(Op)) {
3384     SeenZero = true;
3385     return true;
3386   }
3387   return ISD::isNormalLoad(N);
3388 }
3389
3390 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3391   if (isFloatingPointZero(Op))
3392     return DAG.getConstant(0, MVT::i32);
3393
3394   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3395     return DAG.getLoad(MVT::i32, SDLoc(Op),
3396                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3397                        Ld->isVolatile(), Ld->isNonTemporal(),
3398                        Ld->isInvariant(), Ld->getAlignment());
3399
3400   llvm_unreachable("Unknown VFP cmp argument!");
3401 }
3402
3403 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3404                            SDValue &RetVal1, SDValue &RetVal2) {
3405   if (isFloatingPointZero(Op)) {
3406     RetVal1 = DAG.getConstant(0, MVT::i32);
3407     RetVal2 = DAG.getConstant(0, MVT::i32);
3408     return;
3409   }
3410
3411   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3412     SDValue Ptr = Ld->getBasePtr();
3413     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3414                           Ld->getChain(), Ptr,
3415                           Ld->getPointerInfo(),
3416                           Ld->isVolatile(), Ld->isNonTemporal(),
3417                           Ld->isInvariant(), Ld->getAlignment());
3418
3419     EVT PtrType = Ptr.getValueType();
3420     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3421     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3422                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3423     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3424                           Ld->getChain(), NewPtr,
3425                           Ld->getPointerInfo().getWithOffset(4),
3426                           Ld->isVolatile(), Ld->isNonTemporal(),
3427                           Ld->isInvariant(), NewAlign);
3428     return;
3429   }
3430
3431   llvm_unreachable("Unknown VFP cmp argument!");
3432 }
3433
3434 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3435 /// f32 and even f64 comparisons to integer ones.
3436 SDValue
3437 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3438   SDValue Chain = Op.getOperand(0);
3439   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3440   SDValue LHS = Op.getOperand(2);
3441   SDValue RHS = Op.getOperand(3);
3442   SDValue Dest = Op.getOperand(4);
3443   SDLoc dl(Op);
3444
3445   bool LHSSeenZero = false;
3446   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3447   bool RHSSeenZero = false;
3448   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3449   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3450     // If unsafe fp math optimization is enabled and there are no other uses of
3451     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3452     // to an integer comparison.
3453     if (CC == ISD::SETOEQ)
3454       CC = ISD::SETEQ;
3455     else if (CC == ISD::SETUNE)
3456       CC = ISD::SETNE;
3457
3458     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3459     SDValue ARMcc;
3460     if (LHS.getValueType() == MVT::f32) {
3461       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3462                         bitcastf32Toi32(LHS, DAG), Mask);
3463       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3464                         bitcastf32Toi32(RHS, DAG), Mask);
3465       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3466       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3467       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3468                          Chain, Dest, ARMcc, CCR, Cmp);
3469     }
3470
3471     SDValue LHS1, LHS2;
3472     SDValue RHS1, RHS2;
3473     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3474     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3475     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3476     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3477     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3478     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3479     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3480     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3481     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3482   }
3483
3484   return SDValue();
3485 }
3486
3487 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3488   SDValue Chain = Op.getOperand(0);
3489   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3490   SDValue LHS = Op.getOperand(2);
3491   SDValue RHS = Op.getOperand(3);
3492   SDValue Dest = Op.getOperand(4);
3493   SDLoc dl(Op);
3494
3495   if (LHS.getValueType() == MVT::i32) {
3496     SDValue ARMcc;
3497     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3498     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3499     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3500                        Chain, Dest, ARMcc, CCR, Cmp);
3501   }
3502
3503   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3504
3505   if (getTargetMachine().Options.UnsafeFPMath &&
3506       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3507        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3508     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3509     if (Result.getNode())
3510       return Result;
3511   }
3512
3513   ARMCC::CondCodes CondCode, CondCode2;
3514   FPCCToARMCC(CC, CondCode, CondCode2);
3515
3516   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3517   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3518   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3519   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3520   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3521   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3522   if (CondCode2 != ARMCC::AL) {
3523     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3524     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3525     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3526   }
3527   return Res;
3528 }
3529
3530 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3531   SDValue Chain = Op.getOperand(0);
3532   SDValue Table = Op.getOperand(1);
3533   SDValue Index = Op.getOperand(2);
3534   SDLoc dl(Op);
3535
3536   EVT PTy = getPointerTy();
3537   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3538   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3539   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3540   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3541   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3542   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3543   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3544   if (Subtarget->isThumb2()) {
3545     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3546     // which does another jump to the destination. This also makes it easier
3547     // to translate it to TBB / TBH later.
3548     // FIXME: This might not work if the function is extremely large.
3549     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3550                        Addr, Op.getOperand(2), JTI, UId);
3551   }
3552   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3553     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3554                        MachinePointerInfo::getJumpTable(),
3555                        false, false, false, 0);
3556     Chain = Addr.getValue(1);
3557     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3558     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3559   } else {
3560     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3561                        MachinePointerInfo::getJumpTable(),
3562                        false, false, false, 0);
3563     Chain = Addr.getValue(1);
3564     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3565   }
3566 }
3567
3568 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3569   EVT VT = Op.getValueType();
3570   SDLoc dl(Op);
3571
3572   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3573     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3574       return Op;
3575     return DAG.UnrollVectorOp(Op.getNode());
3576   }
3577
3578   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3579          "Invalid type for custom lowering!");
3580   if (VT != MVT::v4i16)
3581     return DAG.UnrollVectorOp(Op.getNode());
3582
3583   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3584   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3585 }
3586
3587 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3588   EVT VT = Op.getValueType();
3589   if (VT.isVector())
3590     return LowerVectorFP_TO_INT(Op, DAG);
3591
3592   SDLoc dl(Op);
3593   unsigned Opc;
3594
3595   switch (Op.getOpcode()) {
3596   default: llvm_unreachable("Invalid opcode!");
3597   case ISD::FP_TO_SINT:
3598     Opc = ARMISD::FTOSI;
3599     break;
3600   case ISD::FP_TO_UINT:
3601     Opc = ARMISD::FTOUI;
3602     break;
3603   }
3604   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3605   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3606 }
3607
3608 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3609   EVT VT = Op.getValueType();
3610   SDLoc dl(Op);
3611
3612   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3613     if (VT.getVectorElementType() == MVT::f32)
3614       return Op;
3615     return DAG.UnrollVectorOp(Op.getNode());
3616   }
3617
3618   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3619          "Invalid type for custom lowering!");
3620   if (VT != MVT::v4f32)
3621     return DAG.UnrollVectorOp(Op.getNode());
3622
3623   unsigned CastOpc;
3624   unsigned Opc;
3625   switch (Op.getOpcode()) {
3626   default: llvm_unreachable("Invalid opcode!");
3627   case ISD::SINT_TO_FP:
3628     CastOpc = ISD::SIGN_EXTEND;
3629     Opc = ISD::SINT_TO_FP;
3630     break;
3631   case ISD::UINT_TO_FP:
3632     CastOpc = ISD::ZERO_EXTEND;
3633     Opc = ISD::UINT_TO_FP;
3634     break;
3635   }
3636
3637   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3638   return DAG.getNode(Opc, dl, VT, Op);
3639 }
3640
3641 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3642   EVT VT = Op.getValueType();
3643   if (VT.isVector())
3644     return LowerVectorINT_TO_FP(Op, DAG);
3645
3646   SDLoc dl(Op);
3647   unsigned Opc;
3648
3649   switch (Op.getOpcode()) {
3650   default: llvm_unreachable("Invalid opcode!");
3651   case ISD::SINT_TO_FP:
3652     Opc = ARMISD::SITOF;
3653     break;
3654   case ISD::UINT_TO_FP:
3655     Opc = ARMISD::UITOF;
3656     break;
3657   }
3658
3659   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3660   return DAG.getNode(Opc, dl, VT, Op);
3661 }
3662
3663 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3664   // Implement fcopysign with a fabs and a conditional fneg.
3665   SDValue Tmp0 = Op.getOperand(0);
3666   SDValue Tmp1 = Op.getOperand(1);
3667   SDLoc dl(Op);
3668   EVT VT = Op.getValueType();
3669   EVT SrcVT = Tmp1.getValueType();
3670   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3671     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3672   bool UseNEON = !InGPR && Subtarget->hasNEON();
3673
3674   if (UseNEON) {
3675     // Use VBSL to copy the sign bit.
3676     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3677     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3678                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3679     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3680     if (VT == MVT::f64)
3681       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3682                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3683                          DAG.getConstant(32, MVT::i32));
3684     else /*if (VT == MVT::f32)*/
3685       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3686     if (SrcVT == MVT::f32) {
3687       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3688       if (VT == MVT::f64)
3689         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3690                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3691                            DAG.getConstant(32, MVT::i32));
3692     } else if (VT == MVT::f32)
3693       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3694                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3695                          DAG.getConstant(32, MVT::i32));
3696     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3697     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3698
3699     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3700                                             MVT::i32);
3701     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3702     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3703                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3704
3705     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3706                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3707                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3708     if (VT == MVT::f32) {
3709       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3710       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3711                         DAG.getConstant(0, MVT::i32));
3712     } else {
3713       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3714     }
3715
3716     return Res;
3717   }
3718
3719   // Bitcast operand 1 to i32.
3720   if (SrcVT == MVT::f64)
3721     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3722                        &Tmp1, 1).getValue(1);
3723   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3724
3725   // Or in the signbit with integer operations.
3726   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3727   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3728   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3729   if (VT == MVT::f32) {
3730     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3731                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3732     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3733                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3734   }
3735
3736   // f64: Or the high part with signbit and then combine two parts.
3737   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3738                      &Tmp0, 1);
3739   SDValue Lo = Tmp0.getValue(0);
3740   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3741   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3742   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3743 }
3744
3745 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3746   MachineFunction &MF = DAG.getMachineFunction();
3747   MachineFrameInfo *MFI = MF.getFrameInfo();
3748   MFI->setReturnAddressIsTaken(true);
3749
3750   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3751     return SDValue();
3752
3753   EVT VT = Op.getValueType();
3754   SDLoc dl(Op);
3755   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3756   if (Depth) {
3757     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3758     SDValue Offset = DAG.getConstant(4, MVT::i32);
3759     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3760                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3761                        MachinePointerInfo(), false, false, false, 0);
3762   }
3763
3764   // Return LR, which contains the return address. Mark it an implicit live-in.
3765   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3766   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3767 }
3768
3769 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3770   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3771   MFI->setFrameAddressIsTaken(true);
3772
3773   EVT VT = Op.getValueType();
3774   SDLoc dl(Op);  // FIXME probably not meaningful
3775   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3776   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3777     ? ARM::R7 : ARM::R11;
3778   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3779   while (Depth--)
3780     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3781                             MachinePointerInfo(),
3782                             false, false, false, 0);
3783   return FrameAddr;
3784 }
3785
3786 /// ExpandBITCAST - If the target supports VFP, this function is called to
3787 /// expand a bit convert where either the source or destination type is i64 to
3788 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3789 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3790 /// vectors), since the legalizer won't know what to do with that.
3791 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3793   SDLoc dl(N);
3794   SDValue Op = N->getOperand(0);
3795
3796   // This function is only supposed to be called for i64 types, either as the
3797   // source or destination of the bit convert.
3798   EVT SrcVT = Op.getValueType();
3799   EVT DstVT = N->getValueType(0);
3800   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3801          "ExpandBITCAST called for non-i64 type");
3802
3803   // Turn i64->f64 into VMOVDRR.
3804   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3805     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3806                              DAG.getConstant(0, MVT::i32));
3807     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3808                              DAG.getConstant(1, MVT::i32));
3809     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3810                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3811   }
3812
3813   // Turn f64->i64 into VMOVRRD.
3814   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3815     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3816                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3817     // Merge the pieces into a single i64 value.
3818     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3819   }
3820
3821   return SDValue();
3822 }
3823
3824 /// getZeroVector - Returns a vector of specified type with all zero elements.
3825 /// Zero vectors are used to represent vector negation and in those cases
3826 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3827 /// not support i64 elements, so sometimes the zero vectors will need to be
3828 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3829 /// zero vector.
3830 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3831   assert(VT.isVector() && "Expected a vector type");
3832   // The canonical modified immediate encoding of a zero vector is....0!
3833   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3834   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3835   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3836   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3837 }
3838
3839 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3840 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3841 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3842                                                 SelectionDAG &DAG) const {
3843   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3844   EVT VT = Op.getValueType();
3845   unsigned VTBits = VT.getSizeInBits();
3846   SDLoc dl(Op);
3847   SDValue ShOpLo = Op.getOperand(0);
3848   SDValue ShOpHi = Op.getOperand(1);
3849   SDValue ShAmt  = Op.getOperand(2);
3850   SDValue ARMcc;
3851   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3852
3853   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3854
3855   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3856                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3857   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3858   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3859                                    DAG.getConstant(VTBits, MVT::i32));
3860   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3861   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3862   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3863
3864   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3865   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3866                           ARMcc, DAG, dl);
3867   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3868   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3869                            CCR, Cmp);
3870
3871   SDValue Ops[2] = { Lo, Hi };
3872   return DAG.getMergeValues(Ops, 2, dl);
3873 }
3874
3875 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3876 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3877 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3878                                                SelectionDAG &DAG) const {
3879   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3880   EVT VT = Op.getValueType();
3881   unsigned VTBits = VT.getSizeInBits();
3882   SDLoc dl(Op);
3883   SDValue ShOpLo = Op.getOperand(0);
3884   SDValue ShOpHi = Op.getOperand(1);
3885   SDValue ShAmt  = Op.getOperand(2);
3886   SDValue ARMcc;
3887
3888   assert(Op.getOpcode() == ISD::SHL_PARTS);
3889   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3890                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3891   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3892   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3893                                    DAG.getConstant(VTBits, MVT::i32));
3894   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3895   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3896
3897   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3898   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3899   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3900                           ARMcc, DAG, dl);
3901   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3902   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3903                            CCR, Cmp);
3904
3905   SDValue Ops[2] = { Lo, Hi };
3906   return DAG.getMergeValues(Ops, 2, dl);
3907 }
3908
3909 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3910                                             SelectionDAG &DAG) const {
3911   // The rounding mode is in bits 23:22 of the FPSCR.
3912   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3913   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3914   // so that the shift + and get folded into a bitfield extract.
3915   SDLoc dl(Op);
3916   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3917                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3918                                               MVT::i32));
3919   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3920                                   DAG.getConstant(1U << 22, MVT::i32));
3921   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3922                               DAG.getConstant(22, MVT::i32));
3923   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3924                      DAG.getConstant(3, MVT::i32));
3925 }
3926
3927 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3928                          const ARMSubtarget *ST) {
3929   EVT VT = N->getValueType(0);
3930   SDLoc dl(N);
3931
3932   if (!ST->hasV6T2Ops())
3933     return SDValue();
3934
3935   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3936   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3937 }
3938
3939 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3940 /// for each 16-bit element from operand, repeated.  The basic idea is to
3941 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3942 ///
3943 /// Trace for v4i16:
3944 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3945 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3946 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3947 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3948 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3949 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3950 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3951 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3952 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3953   EVT VT = N->getValueType(0);
3954   SDLoc DL(N);
3955
3956   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3957   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3958   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3959   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3960   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3961   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3962 }
3963
3964 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3965 /// bit-count for each 16-bit element from the operand.  We need slightly
3966 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3967 /// 64/128-bit registers.
3968 ///
3969 /// Trace for v4i16:
3970 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3971 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3972 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3973 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3974 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3975   EVT VT = N->getValueType(0);
3976   SDLoc DL(N);
3977
3978   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3979   if (VT.is64BitVector()) {
3980     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3981     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3982                        DAG.getIntPtrConstant(0));
3983   } else {
3984     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3985                                     BitCounts, DAG.getIntPtrConstant(0));
3986     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3987   }
3988 }
3989
3990 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3991 /// bit-count for each 32-bit element from the operand.  The idea here is
3992 /// to split the vector into 16-bit elements, leverage the 16-bit count
3993 /// routine, and then combine the results.
3994 ///
3995 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3996 /// input    = [v0    v1    ] (vi: 32-bit elements)
3997 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3998 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3999 /// vrev: N0 = [k1 k0 k3 k2 ]
4000 ///            [k0 k1 k2 k3 ]
4001 ///       N1 =+[k1 k0 k3 k2 ]
4002 ///            [k0 k2 k1 k3 ]
4003 ///       N2 =+[k1 k3 k0 k2 ]
4004 ///            [k0    k2    k1    k3    ]
4005 /// Extended =+[k1    k3    k0    k2    ]
4006 ///            [k0    k2    ]
4007 /// Extracted=+[k1    k3    ]
4008 ///
4009 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4010   EVT VT = N->getValueType(0);
4011   SDLoc DL(N);
4012
4013   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4014
4015   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4016   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4017   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4018   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4019   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4020
4021   if (VT.is64BitVector()) {
4022     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4023     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4024                        DAG.getIntPtrConstant(0));
4025   } else {
4026     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4027                                     DAG.getIntPtrConstant(0));
4028     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4029   }
4030 }
4031
4032 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4033                           const ARMSubtarget *ST) {
4034   EVT VT = N->getValueType(0);
4035
4036   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4037   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4038           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4039          "Unexpected type for custom ctpop lowering");
4040
4041   if (VT.getVectorElementType() == MVT::i32)
4042     return lowerCTPOP32BitElements(N, DAG);
4043   else
4044     return lowerCTPOP16BitElements(N, DAG);
4045 }
4046
4047 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4048                           const ARMSubtarget *ST) {
4049   EVT VT = N->getValueType(0);
4050   SDLoc dl(N);
4051
4052   if (!VT.isVector())
4053     return SDValue();
4054
4055   // Lower vector shifts on NEON to use VSHL.
4056   assert(ST->hasNEON() && "unexpected vector shift");
4057
4058   // Left shifts translate directly to the vshiftu intrinsic.
4059   if (N->getOpcode() == ISD::SHL)
4060     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4061                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4062                        N->getOperand(0), N->getOperand(1));
4063
4064   assert((N->getOpcode() == ISD::SRA ||
4065           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4066
4067   // NEON uses the same intrinsics for both left and right shifts.  For
4068   // right shifts, the shift amounts are negative, so negate the vector of
4069   // shift amounts.
4070   EVT ShiftVT = N->getOperand(1).getValueType();
4071   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4072                                      getZeroVector(ShiftVT, DAG, dl),
4073                                      N->getOperand(1));
4074   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4075                              Intrinsic::arm_neon_vshifts :
4076                              Intrinsic::arm_neon_vshiftu);
4077   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4078                      DAG.getConstant(vshiftInt, MVT::i32),
4079                      N->getOperand(0), NegatedCount);
4080 }
4081
4082 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4083                                 const ARMSubtarget *ST) {
4084   EVT VT = N->getValueType(0);
4085   SDLoc dl(N);
4086
4087   // We can get here for a node like i32 = ISD::SHL i32, i64
4088   if (VT != MVT::i64)
4089     return SDValue();
4090
4091   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4092          "Unknown shift to lower!");
4093
4094   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4095   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4096       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4097     return SDValue();
4098
4099   // If we are in thumb mode, we don't have RRX.
4100   if (ST->isThumb1Only()) return SDValue();
4101
4102   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4103   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4104                            DAG.getConstant(0, MVT::i32));
4105   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4106                            DAG.getConstant(1, MVT::i32));
4107
4108   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4109   // captures the result into a carry flag.
4110   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4111   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4112
4113   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4114   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4115
4116   // Merge the pieces into a single i64 value.
4117  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4118 }
4119
4120 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4121   SDValue TmpOp0, TmpOp1;
4122   bool Invert = false;
4123   bool Swap = false;
4124   unsigned Opc = 0;
4125
4126   SDValue Op0 = Op.getOperand(0);
4127   SDValue Op1 = Op.getOperand(1);
4128   SDValue CC = Op.getOperand(2);
4129   EVT VT = Op.getValueType();
4130   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4131   SDLoc dl(Op);
4132
4133   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4134     switch (SetCCOpcode) {
4135     default: llvm_unreachable("Illegal FP comparison");
4136     case ISD::SETUNE:
4137     case ISD::SETNE:  Invert = true; // Fallthrough
4138     case ISD::SETOEQ:
4139     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4140     case ISD::SETOLT:
4141     case ISD::SETLT: Swap = true; // Fallthrough
4142     case ISD::SETOGT:
4143     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4144     case ISD::SETOLE:
4145     case ISD::SETLE:  Swap = true; // Fallthrough
4146     case ISD::SETOGE:
4147     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4148     case ISD::SETUGE: Swap = true; // Fallthrough
4149     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4150     case ISD::SETUGT: Swap = true; // Fallthrough
4151     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4152     case ISD::SETUEQ: Invert = true; // Fallthrough
4153     case ISD::SETONE:
4154       // Expand this to (OLT | OGT).
4155       TmpOp0 = Op0;
4156       TmpOp1 = Op1;
4157       Opc = ISD::OR;
4158       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4159       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4160       break;
4161     case ISD::SETUO: Invert = true; // Fallthrough
4162     case ISD::SETO:
4163       // Expand this to (OLT | OGE).
4164       TmpOp0 = Op0;
4165       TmpOp1 = Op1;
4166       Opc = ISD::OR;
4167       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4168       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4169       break;
4170     }
4171   } else {
4172     // Integer comparisons.
4173     switch (SetCCOpcode) {
4174     default: llvm_unreachable("Illegal integer comparison");
4175     case ISD::SETNE:  Invert = true;
4176     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4177     case ISD::SETLT:  Swap = true;
4178     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4179     case ISD::SETLE:  Swap = true;
4180     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4181     case ISD::SETULT: Swap = true;
4182     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4183     case ISD::SETULE: Swap = true;
4184     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4185     }
4186
4187     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4188     if (Opc == ARMISD::VCEQ) {
4189
4190       SDValue AndOp;
4191       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4192         AndOp = Op0;
4193       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4194         AndOp = Op1;
4195
4196       // Ignore bitconvert.
4197       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4198         AndOp = AndOp.getOperand(0);
4199
4200       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4201         Opc = ARMISD::VTST;
4202         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4203         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4204         Invert = !Invert;
4205       }
4206     }
4207   }
4208
4209   if (Swap)
4210     std::swap(Op0, Op1);
4211
4212   // If one of the operands is a constant vector zero, attempt to fold the
4213   // comparison to a specialized compare-against-zero form.
4214   SDValue SingleOp;
4215   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4216     SingleOp = Op0;
4217   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4218     if (Opc == ARMISD::VCGE)
4219       Opc = ARMISD::VCLEZ;
4220     else if (Opc == ARMISD::VCGT)
4221       Opc = ARMISD::VCLTZ;
4222     SingleOp = Op1;
4223   }
4224
4225   SDValue Result;
4226   if (SingleOp.getNode()) {
4227     switch (Opc) {
4228     case ARMISD::VCEQ:
4229       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4230     case ARMISD::VCGE:
4231       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4232     case ARMISD::VCLEZ:
4233       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4234     case ARMISD::VCGT:
4235       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4236     case ARMISD::VCLTZ:
4237       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4238     default:
4239       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4240     }
4241   } else {
4242      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4243   }
4244
4245   if (Invert)
4246     Result = DAG.getNOT(dl, Result, VT);
4247
4248   return Result;
4249 }
4250
4251 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4252 /// valid vector constant for a NEON instruction with a "modified immediate"
4253 /// operand (e.g., VMOV).  If so, return the encoded value.
4254 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4255                                  unsigned SplatBitSize, SelectionDAG &DAG,
4256                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4257   unsigned OpCmode, Imm;
4258
4259   // SplatBitSize is set to the smallest size that splats the vector, so a
4260   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4261   // immediate instructions others than VMOV do not support the 8-bit encoding
4262   // of a zero vector, and the default encoding of zero is supposed to be the
4263   // 32-bit version.
4264   if (SplatBits == 0)
4265     SplatBitSize = 32;
4266
4267   switch (SplatBitSize) {
4268   case 8:
4269     if (type != VMOVModImm)
4270       return SDValue();
4271     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4272     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4273     OpCmode = 0xe;
4274     Imm = SplatBits;
4275     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4276     break;
4277
4278   case 16:
4279     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4280     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4281     if ((SplatBits & ~0xff) == 0) {
4282       // Value = 0x00nn: Op=x, Cmode=100x.
4283       OpCmode = 0x8;
4284       Imm = SplatBits;
4285       break;
4286     }
4287     if ((SplatBits & ~0xff00) == 0) {
4288       // Value = 0xnn00: Op=x, Cmode=101x.
4289       OpCmode = 0xa;
4290       Imm = SplatBits >> 8;
4291       break;
4292     }
4293     return SDValue();
4294
4295   case 32:
4296     // NEON's 32-bit VMOV supports splat values where:
4297     // * only one byte is nonzero, or
4298     // * the least significant byte is 0xff and the second byte is nonzero, or
4299     // * the least significant 2 bytes are 0xff and the third is nonzero.
4300     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4301     if ((SplatBits & ~0xff) == 0) {
4302       // Value = 0x000000nn: Op=x, Cmode=000x.
4303       OpCmode = 0;
4304       Imm = SplatBits;
4305       break;
4306     }
4307     if ((SplatBits & ~0xff00) == 0) {
4308       // Value = 0x0000nn00: Op=x, Cmode=001x.
4309       OpCmode = 0x2;
4310       Imm = SplatBits >> 8;
4311       break;
4312     }
4313     if ((SplatBits & ~0xff0000) == 0) {
4314       // Value = 0x00nn0000: Op=x, Cmode=010x.
4315       OpCmode = 0x4;
4316       Imm = SplatBits >> 16;
4317       break;
4318     }
4319     if ((SplatBits & ~0xff000000) == 0) {
4320       // Value = 0xnn000000: Op=x, Cmode=011x.
4321       OpCmode = 0x6;
4322       Imm = SplatBits >> 24;
4323       break;
4324     }
4325
4326     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4327     if (type == OtherModImm) return SDValue();
4328
4329     if ((SplatBits & ~0xffff) == 0 &&
4330         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4331       // Value = 0x0000nnff: Op=x, Cmode=1100.
4332       OpCmode = 0xc;
4333       Imm = SplatBits >> 8;
4334       SplatBits |= 0xff;
4335       break;
4336     }
4337
4338     if ((SplatBits & ~0xffffff) == 0 &&
4339         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4340       // Value = 0x00nnffff: Op=x, Cmode=1101.
4341       OpCmode = 0xd;
4342       Imm = SplatBits >> 16;
4343       SplatBits |= 0xffff;
4344       break;
4345     }
4346
4347     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4348     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4349     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4350     // and fall through here to test for a valid 64-bit splat.  But, then the
4351     // caller would also need to check and handle the change in size.
4352     return SDValue();
4353
4354   case 64: {
4355     if (type != VMOVModImm)
4356       return SDValue();
4357     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4358     uint64_t BitMask = 0xff;
4359     uint64_t Val = 0;
4360     unsigned ImmMask = 1;
4361     Imm = 0;
4362     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4363       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4364         Val |= BitMask;
4365         Imm |= ImmMask;
4366       } else if ((SplatBits & BitMask) != 0) {
4367         return SDValue();
4368       }
4369       BitMask <<= 8;
4370       ImmMask <<= 1;
4371     }
4372     // Op=1, Cmode=1110.
4373     OpCmode = 0x1e;
4374     SplatBits = Val;
4375     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4376     break;
4377   }
4378
4379   default:
4380     llvm_unreachable("unexpected size for isNEONModifiedImm");
4381   }
4382
4383   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4384   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4385 }
4386
4387 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4388                                            const ARMSubtarget *ST) const {
4389   if (!ST->hasVFP3())
4390     return SDValue();
4391
4392   bool IsDouble = Op.getValueType() == MVT::f64;
4393   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4394
4395   // Try splatting with a VMOV.f32...
4396   APFloat FPVal = CFP->getValueAPF();
4397   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4398
4399   if (ImmVal != -1) {
4400     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4401       // We have code in place to select a valid ConstantFP already, no need to
4402       // do any mangling.
4403       return Op;
4404     }
4405
4406     // It's a float and we are trying to use NEON operations where
4407     // possible. Lower it to a splat followed by an extract.
4408     SDLoc DL(Op);
4409     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4410     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4411                                       NewVal);
4412     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4413                        DAG.getConstant(0, MVT::i32));
4414   }
4415
4416   // The rest of our options are NEON only, make sure that's allowed before
4417   // proceeding..
4418   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4419     return SDValue();
4420
4421   EVT VMovVT;
4422   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4423
4424   // It wouldn't really be worth bothering for doubles except for one very
4425   // important value, which does happen to match: 0.0. So make sure we don't do
4426   // anything stupid.
4427   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4428     return SDValue();
4429
4430   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4431   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4432                                      false, VMOVModImm);
4433   if (NewVal != SDValue()) {
4434     SDLoc DL(Op);
4435     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4436                                       NewVal);
4437     if (IsDouble)
4438       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4439
4440     // It's a float: cast and extract a vector element.
4441     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4442                                        VecConstant);
4443     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4444                        DAG.getConstant(0, MVT::i32));
4445   }
4446
4447   // Finally, try a VMVN.i32
4448   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4449                              false, VMVNModImm);
4450   if (NewVal != SDValue()) {
4451     SDLoc DL(Op);
4452     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4453
4454     if (IsDouble)
4455       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4456
4457     // It's a float: cast and extract a vector element.
4458     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4459                                        VecConstant);
4460     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4461                        DAG.getConstant(0, MVT::i32));
4462   }
4463
4464   return SDValue();
4465 }
4466
4467 // check if an VEXT instruction can handle the shuffle mask when the
4468 // vector sources of the shuffle are the same.
4469 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4470   unsigned NumElts = VT.getVectorNumElements();
4471
4472   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4473   if (M[0] < 0)
4474     return false;
4475
4476   Imm = M[0];
4477
4478   // If this is a VEXT shuffle, the immediate value is the index of the first
4479   // element.  The other shuffle indices must be the successive elements after
4480   // the first one.
4481   unsigned ExpectedElt = Imm;
4482   for (unsigned i = 1; i < NumElts; ++i) {
4483     // Increment the expected index.  If it wraps around, just follow it
4484     // back to index zero and keep going.
4485     ++ExpectedElt;
4486     if (ExpectedElt == NumElts)
4487       ExpectedElt = 0;
4488
4489     if (M[i] < 0) continue; // ignore UNDEF indices
4490     if (ExpectedElt != static_cast<unsigned>(M[i]))
4491       return false;
4492   }
4493
4494   return true;
4495 }
4496
4497
4498 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4499                        bool &ReverseVEXT, unsigned &Imm) {
4500   unsigned NumElts = VT.getVectorNumElements();
4501   ReverseVEXT = false;
4502
4503   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4504   if (M[0] < 0)
4505     return false;
4506
4507   Imm = M[0];
4508
4509   // If this is a VEXT shuffle, the immediate value is the index of the first
4510   // element.  The other shuffle indices must be the successive elements after
4511   // the first one.
4512   unsigned ExpectedElt = Imm;
4513   for (unsigned i = 1; i < NumElts; ++i) {
4514     // Increment the expected index.  If it wraps around, it may still be
4515     // a VEXT but the source vectors must be swapped.
4516     ExpectedElt += 1;
4517     if (ExpectedElt == NumElts * 2) {
4518       ExpectedElt = 0;
4519       ReverseVEXT = true;
4520     }
4521
4522     if (M[i] < 0) continue; // ignore UNDEF indices
4523     if (ExpectedElt != static_cast<unsigned>(M[i]))
4524       return false;
4525   }
4526
4527   // Adjust the index value if the source operands will be swapped.
4528   if (ReverseVEXT)
4529     Imm -= NumElts;
4530
4531   return true;
4532 }
4533
4534 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4535 /// instruction with the specified blocksize.  (The order of the elements
4536 /// within each block of the vector is reversed.)
4537 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4538   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4539          "Only possible block sizes for VREV are: 16, 32, 64");
4540
4541   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4542   if (EltSz == 64)
4543     return false;
4544
4545   unsigned NumElts = VT.getVectorNumElements();
4546   unsigned BlockElts = M[0] + 1;
4547   // If the first shuffle index is UNDEF, be optimistic.
4548   if (M[0] < 0)
4549     BlockElts = BlockSize / EltSz;
4550
4551   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4552     return false;
4553
4554   for (unsigned i = 0; i < NumElts; ++i) {
4555     if (M[i] < 0) continue; // ignore UNDEF indices
4556     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4557       return false;
4558   }
4559
4560   return true;
4561 }
4562
4563 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4564   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4565   // range, then 0 is placed into the resulting vector. So pretty much any mask
4566   // of 8 elements can work here.
4567   return VT == MVT::v8i8 && M.size() == 8;
4568 }
4569
4570 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4571   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4572   if (EltSz == 64)
4573     return false;
4574
4575   unsigned NumElts = VT.getVectorNumElements();
4576   WhichResult = (M[0] == 0 ? 0 : 1);
4577   for (unsigned i = 0; i < NumElts; i += 2) {
4578     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4579         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4580       return false;
4581   }
4582   return true;
4583 }
4584
4585 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4586 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4587 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4588 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4589   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4590   if (EltSz == 64)
4591     return false;
4592
4593   unsigned NumElts = VT.getVectorNumElements();
4594   WhichResult = (M[0] == 0 ? 0 : 1);
4595   for (unsigned i = 0; i < NumElts; i += 2) {
4596     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4597         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4598       return false;
4599   }
4600   return true;
4601 }
4602
4603 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4604   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4605   if (EltSz == 64)
4606     return false;
4607
4608   unsigned NumElts = VT.getVectorNumElements();
4609   WhichResult = (M[0] == 0 ? 0 : 1);
4610   for (unsigned i = 0; i != NumElts; ++i) {
4611     if (M[i] < 0) continue; // ignore UNDEF indices
4612     if ((unsigned) M[i] != 2 * i + WhichResult)
4613       return false;
4614   }
4615
4616   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4617   if (VT.is64BitVector() && EltSz == 32)
4618     return false;
4619
4620   return true;
4621 }
4622
4623 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4624 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4625 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4626 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4627   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4628   if (EltSz == 64)
4629     return false;
4630
4631   unsigned Half = VT.getVectorNumElements() / 2;
4632   WhichResult = (M[0] == 0 ? 0 : 1);
4633   for (unsigned j = 0; j != 2; ++j) {
4634     unsigned Idx = WhichResult;
4635     for (unsigned i = 0; i != Half; ++i) {
4636       int MIdx = M[i + j * Half];
4637       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4638         return false;
4639       Idx += 2;
4640     }
4641   }
4642
4643   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4644   if (VT.is64BitVector() && EltSz == 32)
4645     return false;
4646
4647   return true;
4648 }
4649
4650 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4651   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4652   if (EltSz == 64)
4653     return false;
4654
4655   unsigned NumElts = VT.getVectorNumElements();
4656   WhichResult = (M[0] == 0 ? 0 : 1);
4657   unsigned Idx = WhichResult * NumElts / 2;
4658   for (unsigned i = 0; i != NumElts; i += 2) {
4659     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4660         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4661       return false;
4662     Idx += 1;
4663   }
4664
4665   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4666   if (VT.is64BitVector() && EltSz == 32)
4667     return false;
4668
4669   return true;
4670 }
4671
4672 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4673 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4674 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4675 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4676   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4677   if (EltSz == 64)
4678     return false;
4679
4680   unsigned NumElts = VT.getVectorNumElements();
4681   WhichResult = (M[0] == 0 ? 0 : 1);
4682   unsigned Idx = WhichResult * NumElts / 2;
4683   for (unsigned i = 0; i != NumElts; i += 2) {
4684     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4685         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4686       return false;
4687     Idx += 1;
4688   }
4689
4690   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4691   if (VT.is64BitVector() && EltSz == 32)
4692     return false;
4693
4694   return true;
4695 }
4696
4697 /// \return true if this is a reverse operation on an vector.
4698 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4699   unsigned NumElts = VT.getVectorNumElements();
4700   // Make sure the mask has the right size.
4701   if (NumElts != M.size())
4702       return false;
4703
4704   // Look for <15, ..., 3, -1, 1, 0>.
4705   for (unsigned i = 0; i != NumElts; ++i)
4706     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4707       return false;
4708
4709   return true;
4710 }
4711
4712 // If N is an integer constant that can be moved into a register in one
4713 // instruction, return an SDValue of such a constant (will become a MOV
4714 // instruction).  Otherwise return null.
4715 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4716                                      const ARMSubtarget *ST, SDLoc dl) {
4717   uint64_t Val;
4718   if (!isa<ConstantSDNode>(N))
4719     return SDValue();
4720   Val = cast<ConstantSDNode>(N)->getZExtValue();
4721
4722   if (ST->isThumb1Only()) {
4723     if (Val <= 255 || ~Val <= 255)
4724       return DAG.getConstant(Val, MVT::i32);
4725   } else {
4726     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4727       return DAG.getConstant(Val, MVT::i32);
4728   }
4729   return SDValue();
4730 }
4731
4732 // If this is a case we can't handle, return null and let the default
4733 // expansion code take care of it.
4734 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4735                                              const ARMSubtarget *ST) const {
4736   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4737   SDLoc dl(Op);
4738   EVT VT = Op.getValueType();
4739
4740   APInt SplatBits, SplatUndef;
4741   unsigned SplatBitSize;
4742   bool HasAnyUndefs;
4743   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4744     if (SplatBitSize <= 64) {
4745       // Check if an immediate VMOV works.
4746       EVT VmovVT;
4747       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4748                                       SplatUndef.getZExtValue(), SplatBitSize,
4749                                       DAG, VmovVT, VT.is128BitVector(),
4750                                       VMOVModImm);
4751       if (Val.getNode()) {
4752         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4753         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4754       }
4755
4756       // Try an immediate VMVN.
4757       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4758       Val = isNEONModifiedImm(NegatedImm,
4759                                       SplatUndef.getZExtValue(), SplatBitSize,
4760                                       DAG, VmovVT, VT.is128BitVector(),
4761                                       VMVNModImm);
4762       if (Val.getNode()) {
4763         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4764         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4765       }
4766
4767       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4768       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4769         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4770         if (ImmVal != -1) {
4771           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4772           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4773         }
4774       }
4775     }
4776   }
4777
4778   // Scan through the operands to see if only one value is used.
4779   //
4780   // As an optimisation, even if more than one value is used it may be more
4781   // profitable to splat with one value then change some lanes.
4782   //
4783   // Heuristically we decide to do this if the vector has a "dominant" value,
4784   // defined as splatted to more than half of the lanes.
4785   unsigned NumElts = VT.getVectorNumElements();
4786   bool isOnlyLowElement = true;
4787   bool usesOnlyOneValue = true;
4788   bool hasDominantValue = false;
4789   bool isConstant = true;
4790
4791   // Map of the number of times a particular SDValue appears in the
4792   // element list.
4793   DenseMap<SDValue, unsigned> ValueCounts;
4794   SDValue Value;
4795   for (unsigned i = 0; i < NumElts; ++i) {
4796     SDValue V = Op.getOperand(i);
4797     if (V.getOpcode() == ISD::UNDEF)
4798       continue;
4799     if (i > 0)
4800       isOnlyLowElement = false;
4801     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4802       isConstant = false;
4803
4804     ValueCounts.insert(std::make_pair(V, 0));
4805     unsigned &Count = ValueCounts[V];
4806
4807     // Is this value dominant? (takes up more than half of the lanes)
4808     if (++Count > (NumElts / 2)) {
4809       hasDominantValue = true;
4810       Value = V;
4811     }
4812   }
4813   if (ValueCounts.size() != 1)
4814     usesOnlyOneValue = false;
4815   if (!Value.getNode() && ValueCounts.size() > 0)
4816     Value = ValueCounts.begin()->first;
4817
4818   if (ValueCounts.size() == 0)
4819     return DAG.getUNDEF(VT);
4820
4821   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4822   // Keep going if we are hitting this case.
4823   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4824     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4825
4826   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4827
4828   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4829   // i32 and try again.
4830   if (hasDominantValue && EltSize <= 32) {
4831     if (!isConstant) {
4832       SDValue N;
4833
4834       // If we are VDUPing a value that comes directly from a vector, that will
4835       // cause an unnecessary move to and from a GPR, where instead we could
4836       // just use VDUPLANE. We can only do this if the lane being extracted
4837       // is at a constant index, as the VDUP from lane instructions only have
4838       // constant-index forms.
4839       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4840           isa<ConstantSDNode>(Value->getOperand(1))) {
4841         // We need to create a new undef vector to use for the VDUPLANE if the
4842         // size of the vector from which we get the value is different than the
4843         // size of the vector that we need to create. We will insert the element
4844         // such that the register coalescer will remove unnecessary copies.
4845         if (VT != Value->getOperand(0).getValueType()) {
4846           ConstantSDNode *constIndex;
4847           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4848           assert(constIndex && "The index is not a constant!");
4849           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4850                              VT.getVectorNumElements();
4851           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4852                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4853                         Value, DAG.getConstant(index, MVT::i32)),
4854                            DAG.getConstant(index, MVT::i32));
4855         } else
4856           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4857                         Value->getOperand(0), Value->getOperand(1));
4858       } else
4859         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4860
4861       if (!usesOnlyOneValue) {
4862         // The dominant value was splatted as 'N', but we now have to insert
4863         // all differing elements.
4864         for (unsigned I = 0; I < NumElts; ++I) {
4865           if (Op.getOperand(I) == Value)
4866             continue;
4867           SmallVector<SDValue, 3> Ops;
4868           Ops.push_back(N);
4869           Ops.push_back(Op.getOperand(I));
4870           Ops.push_back(DAG.getConstant(I, MVT::i32));
4871           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4872         }
4873       }
4874       return N;
4875     }
4876     if (VT.getVectorElementType().isFloatingPoint()) {
4877       SmallVector<SDValue, 8> Ops;
4878       for (unsigned i = 0; i < NumElts; ++i)
4879         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4880                                   Op.getOperand(i)));
4881       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4882       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4883       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4884       if (Val.getNode())
4885         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4886     }
4887     if (usesOnlyOneValue) {
4888       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4889       if (isConstant && Val.getNode())
4890         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4891     }
4892   }
4893
4894   // If all elements are constants and the case above didn't get hit, fall back
4895   // to the default expansion, which will generate a load from the constant
4896   // pool.
4897   if (isConstant)
4898     return SDValue();
4899
4900   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4901   if (NumElts >= 4) {
4902     SDValue shuffle = ReconstructShuffle(Op, DAG);
4903     if (shuffle != SDValue())
4904       return shuffle;
4905   }
4906
4907   // Vectors with 32- or 64-bit elements can be built by directly assigning
4908   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4909   // will be legalized.
4910   if (EltSize >= 32) {
4911     // Do the expansion with floating-point types, since that is what the VFP
4912     // registers are defined to use, and since i64 is not legal.
4913     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4914     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4915     SmallVector<SDValue, 8> Ops;
4916     for (unsigned i = 0; i < NumElts; ++i)
4917       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4918     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4919     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4920   }
4921
4922   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4923   // know the default expansion would otherwise fall back on something even
4924   // worse. For a vector with one or two non-undef values, that's
4925   // scalar_to_vector for the elements followed by a shuffle (provided the
4926   // shuffle is valid for the target) and materialization element by element
4927   // on the stack followed by a load for everything else.
4928   if (!isConstant && !usesOnlyOneValue) {
4929     SDValue Vec = DAG.getUNDEF(VT);
4930     for (unsigned i = 0 ; i < NumElts; ++i) {
4931       SDValue V = Op.getOperand(i);
4932       if (V.getOpcode() == ISD::UNDEF)
4933         continue;
4934       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4935       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4936     }
4937     return Vec;
4938   }
4939
4940   return SDValue();
4941 }
4942
4943 // Gather data to see if the operation can be modelled as a
4944 // shuffle in combination with VEXTs.
4945 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4946                                               SelectionDAG &DAG) const {
4947   SDLoc dl(Op);
4948   EVT VT = Op.getValueType();
4949   unsigned NumElts = VT.getVectorNumElements();
4950
4951   SmallVector<SDValue, 2> SourceVecs;
4952   SmallVector<unsigned, 2> MinElts;
4953   SmallVector<unsigned, 2> MaxElts;
4954
4955   for (unsigned i = 0; i < NumElts; ++i) {
4956     SDValue V = Op.getOperand(i);
4957     if (V.getOpcode() == ISD::UNDEF)
4958       continue;
4959     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4960       // A shuffle can only come from building a vector from various
4961       // elements of other vectors.
4962       return SDValue();
4963     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4964                VT.getVectorElementType()) {
4965       // This code doesn't know how to handle shuffles where the vector
4966       // element types do not match (this happens because type legalization
4967       // promotes the return type of EXTRACT_VECTOR_ELT).
4968       // FIXME: It might be appropriate to extend this code to handle
4969       // mismatched types.
4970       return SDValue();
4971     }
4972
4973     // Record this extraction against the appropriate vector if possible...
4974     SDValue SourceVec = V.getOperand(0);
4975     // If the element number isn't a constant, we can't effectively
4976     // analyze what's going on.
4977     if (!isa<ConstantSDNode>(V.getOperand(1)))
4978       return SDValue();
4979     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4980     bool FoundSource = false;
4981     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4982       if (SourceVecs[j] == SourceVec) {
4983         if (MinElts[j] > EltNo)
4984           MinElts[j] = EltNo;
4985         if (MaxElts[j] < EltNo)
4986           MaxElts[j] = EltNo;
4987         FoundSource = true;
4988         break;
4989       }
4990     }
4991
4992     // Or record a new source if not...
4993     if (!FoundSource) {
4994       SourceVecs.push_back(SourceVec);
4995       MinElts.push_back(EltNo);
4996       MaxElts.push_back(EltNo);
4997     }
4998   }
4999
5000   // Currently only do something sane when at most two source vectors
5001   // involved.
5002   if (SourceVecs.size() > 2)
5003     return SDValue();
5004
5005   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5006   int VEXTOffsets[2] = {0, 0};
5007
5008   // This loop extracts the usage patterns of the source vectors
5009   // and prepares appropriate SDValues for a shuffle if possible.
5010   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5011     if (SourceVecs[i].getValueType() == VT) {
5012       // No VEXT necessary
5013       ShuffleSrcs[i] = SourceVecs[i];
5014       VEXTOffsets[i] = 0;
5015       continue;
5016     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5017       // It probably isn't worth padding out a smaller vector just to
5018       // break it down again in a shuffle.
5019       return SDValue();
5020     }
5021
5022     // Since only 64-bit and 128-bit vectors are legal on ARM and
5023     // we've eliminated the other cases...
5024     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5025            "unexpected vector sizes in ReconstructShuffle");
5026
5027     if (MaxElts[i] - MinElts[i] >= NumElts) {
5028       // Span too large for a VEXT to cope
5029       return SDValue();
5030     }
5031
5032     if (MinElts[i] >= NumElts) {
5033       // The extraction can just take the second half
5034       VEXTOffsets[i] = NumElts;
5035       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5036                                    SourceVecs[i],
5037                                    DAG.getIntPtrConstant(NumElts));
5038     } else if (MaxElts[i] < NumElts) {
5039       // The extraction can just take the first half
5040       VEXTOffsets[i] = 0;
5041       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5042                                    SourceVecs[i],
5043                                    DAG.getIntPtrConstant(0));
5044     } else {
5045       // An actual VEXT is needed
5046       VEXTOffsets[i] = MinElts[i];
5047       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5048                                      SourceVecs[i],
5049                                      DAG.getIntPtrConstant(0));
5050       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5051                                      SourceVecs[i],
5052                                      DAG.getIntPtrConstant(NumElts));
5053       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5054                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5055     }
5056   }
5057
5058   SmallVector<int, 8> Mask;
5059
5060   for (unsigned i = 0; i < NumElts; ++i) {
5061     SDValue Entry = Op.getOperand(i);
5062     if (Entry.getOpcode() == ISD::UNDEF) {
5063       Mask.push_back(-1);
5064       continue;
5065     }
5066
5067     SDValue ExtractVec = Entry.getOperand(0);
5068     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5069                                           .getOperand(1))->getSExtValue();
5070     if (ExtractVec == SourceVecs[0]) {
5071       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5072     } else {
5073       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5074     }
5075   }
5076
5077   // Final check before we try to produce nonsense...
5078   if (isShuffleMaskLegal(Mask, VT))
5079     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5080                                 &Mask[0]);
5081
5082   return SDValue();
5083 }
5084
5085 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5086 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5087 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5088 /// are assumed to be legal.
5089 bool
5090 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5091                                       EVT VT) const {
5092   if (VT.getVectorNumElements() == 4 &&
5093       (VT.is128BitVector() || VT.is64BitVector())) {
5094     unsigned PFIndexes[4];
5095     for (unsigned i = 0; i != 4; ++i) {
5096       if (M[i] < 0)
5097         PFIndexes[i] = 8;
5098       else
5099         PFIndexes[i] = M[i];
5100     }
5101
5102     // Compute the index in the perfect shuffle table.
5103     unsigned PFTableIndex =
5104       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5105     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5106     unsigned Cost = (PFEntry >> 30);
5107
5108     if (Cost <= 4)
5109       return true;
5110   }
5111
5112   bool ReverseVEXT;
5113   unsigned Imm, WhichResult;
5114
5115   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5116   return (EltSize >= 32 ||
5117           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5118           isVREVMask(M, VT, 64) ||
5119           isVREVMask(M, VT, 32) ||
5120           isVREVMask(M, VT, 16) ||
5121           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5122           isVTBLMask(M, VT) ||
5123           isVTRNMask(M, VT, WhichResult) ||
5124           isVUZPMask(M, VT, WhichResult) ||
5125           isVZIPMask(M, VT, WhichResult) ||
5126           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5127           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5128           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5129           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5130 }
5131
5132 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5133 /// the specified operations to build the shuffle.
5134 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5135                                       SDValue RHS, SelectionDAG &DAG,
5136                                       SDLoc dl) {
5137   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5138   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5139   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5140
5141   enum {
5142     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5143     OP_VREV,
5144     OP_VDUP0,
5145     OP_VDUP1,
5146     OP_VDUP2,
5147     OP_VDUP3,
5148     OP_VEXT1,
5149     OP_VEXT2,
5150     OP_VEXT3,
5151     OP_VUZPL, // VUZP, left result
5152     OP_VUZPR, // VUZP, right result
5153     OP_VZIPL, // VZIP, left result
5154     OP_VZIPR, // VZIP, right result
5155     OP_VTRNL, // VTRN, left result
5156     OP_VTRNR  // VTRN, right result
5157   };
5158
5159   if (OpNum == OP_COPY) {
5160     if (LHSID == (1*9+2)*9+3) return LHS;
5161     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5162     return RHS;
5163   }
5164
5165   SDValue OpLHS, OpRHS;
5166   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5167   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5168   EVT VT = OpLHS.getValueType();
5169
5170   switch (OpNum) {
5171   default: llvm_unreachable("Unknown shuffle opcode!");
5172   case OP_VREV:
5173     // VREV divides the vector in half and swaps within the half.
5174     if (VT.getVectorElementType() == MVT::i32 ||
5175         VT.getVectorElementType() == MVT::f32)
5176       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5177     // vrev <4 x i16> -> VREV32
5178     if (VT.getVectorElementType() == MVT::i16)
5179       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5180     // vrev <4 x i8> -> VREV16
5181     assert(VT.getVectorElementType() == MVT::i8);
5182     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5183   case OP_VDUP0:
5184   case OP_VDUP1:
5185   case OP_VDUP2:
5186   case OP_VDUP3:
5187     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5188                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5189   case OP_VEXT1:
5190   case OP_VEXT2:
5191   case OP_VEXT3:
5192     return DAG.getNode(ARMISD::VEXT, dl, VT,
5193                        OpLHS, OpRHS,
5194                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5195   case OP_VUZPL:
5196   case OP_VUZPR:
5197     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5198                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5199   case OP_VZIPL:
5200   case OP_VZIPR:
5201     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5202                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5203   case OP_VTRNL:
5204   case OP_VTRNR:
5205     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5206                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5207   }
5208 }
5209
5210 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5211                                        ArrayRef<int> ShuffleMask,
5212                                        SelectionDAG &DAG) {
5213   // Check to see if we can use the VTBL instruction.
5214   SDValue V1 = Op.getOperand(0);
5215   SDValue V2 = Op.getOperand(1);
5216   SDLoc DL(Op);
5217
5218   SmallVector<SDValue, 8> VTBLMask;
5219   for (ArrayRef<int>::iterator
5220          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5221     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5222
5223   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5224     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5225                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5226                                    &VTBLMask[0], 8));
5227
5228   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5229                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5230                                  &VTBLMask[0], 8));
5231 }
5232
5233 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5234                                                       SelectionDAG &DAG) {
5235   SDLoc DL(Op);
5236   SDValue OpLHS = Op.getOperand(0);
5237   EVT VT = OpLHS.getValueType();
5238
5239   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5240          "Expect an v8i16/v16i8 type");
5241   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5242   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5243   // extract the first 8 bytes into the top double word and the last 8 bytes
5244   // into the bottom double word. The v8i16 case is similar.
5245   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5246   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5247                      DAG.getConstant(ExtractNum, MVT::i32));
5248 }
5249
5250 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5251   SDValue V1 = Op.getOperand(0);
5252   SDValue V2 = Op.getOperand(1);
5253   SDLoc dl(Op);
5254   EVT VT = Op.getValueType();
5255   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5256
5257   // Convert shuffles that are directly supported on NEON to target-specific
5258   // DAG nodes, instead of keeping them as shuffles and matching them again
5259   // during code selection.  This is more efficient and avoids the possibility
5260   // of inconsistencies between legalization and selection.
5261   // FIXME: floating-point vectors should be canonicalized to integer vectors
5262   // of the same time so that they get CSEd properly.
5263   ArrayRef<int> ShuffleMask = SVN->getMask();
5264
5265   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5266   if (EltSize <= 32) {
5267     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5268       int Lane = SVN->getSplatIndex();
5269       // If this is undef splat, generate it via "just" vdup, if possible.
5270       if (Lane == -1) Lane = 0;
5271
5272       // Test if V1 is a SCALAR_TO_VECTOR.
5273       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5274         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5275       }
5276       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5277       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5278       // reaches it).
5279       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5280           !isa<ConstantSDNode>(V1.getOperand(0))) {
5281         bool IsScalarToVector = true;
5282         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5283           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5284             IsScalarToVector = false;
5285             break;
5286           }
5287         if (IsScalarToVector)
5288           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5289       }
5290       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5291                          DAG.getConstant(Lane, MVT::i32));
5292     }
5293
5294     bool ReverseVEXT;
5295     unsigned Imm;
5296     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5297       if (ReverseVEXT)
5298         std::swap(V1, V2);
5299       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5300                          DAG.getConstant(Imm, MVT::i32));
5301     }
5302
5303     if (isVREVMask(ShuffleMask, VT, 64))
5304       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5305     if (isVREVMask(ShuffleMask, VT, 32))
5306       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5307     if (isVREVMask(ShuffleMask, VT, 16))
5308       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5309
5310     if (V2->getOpcode() == ISD::UNDEF &&
5311         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5312       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5313                          DAG.getConstant(Imm, MVT::i32));
5314     }
5315
5316     // Check for Neon shuffles that modify both input vectors in place.
5317     // If both results are used, i.e., if there are two shuffles with the same
5318     // source operands and with masks corresponding to both results of one of
5319     // these operations, DAG memoization will ensure that a single node is
5320     // used for both shuffles.
5321     unsigned WhichResult;
5322     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5323       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5324                          V1, V2).getValue(WhichResult);
5325     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5326       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5327                          V1, V2).getValue(WhichResult);
5328     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5329       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5330                          V1, V2).getValue(WhichResult);
5331
5332     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5333       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5334                          V1, V1).getValue(WhichResult);
5335     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5336       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5337                          V1, V1).getValue(WhichResult);
5338     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5339       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5340                          V1, V1).getValue(WhichResult);
5341   }
5342
5343   // If the shuffle is not directly supported and it has 4 elements, use
5344   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5345   unsigned NumElts = VT.getVectorNumElements();
5346   if (NumElts == 4) {
5347     unsigned PFIndexes[4];
5348     for (unsigned i = 0; i != 4; ++i) {
5349       if (ShuffleMask[i] < 0)
5350         PFIndexes[i] = 8;
5351       else
5352         PFIndexes[i] = ShuffleMask[i];
5353     }
5354
5355     // Compute the index in the perfect shuffle table.
5356     unsigned PFTableIndex =
5357       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5358     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5359     unsigned Cost = (PFEntry >> 30);
5360
5361     if (Cost <= 4)
5362       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5363   }
5364
5365   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5366   if (EltSize >= 32) {
5367     // Do the expansion with floating-point types, since that is what the VFP
5368     // registers are defined to use, and since i64 is not legal.
5369     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5370     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5371     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5372     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5373     SmallVector<SDValue, 8> Ops;
5374     for (unsigned i = 0; i < NumElts; ++i) {
5375       if (ShuffleMask[i] < 0)
5376         Ops.push_back(DAG.getUNDEF(EltVT));
5377       else
5378         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5379                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5380                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5381                                                   MVT::i32)));
5382     }
5383     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5384     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5385   }
5386
5387   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5388     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5389
5390   if (VT == MVT::v8i8) {
5391     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5392     if (NewOp.getNode())
5393       return NewOp;
5394   }
5395
5396   return SDValue();
5397 }
5398
5399 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5400   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5401   SDValue Lane = Op.getOperand(2);
5402   if (!isa<ConstantSDNode>(Lane))
5403     return SDValue();
5404
5405   return Op;
5406 }
5407
5408 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5409   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5410   SDValue Lane = Op.getOperand(1);
5411   if (!isa<ConstantSDNode>(Lane))
5412     return SDValue();
5413
5414   SDValue Vec = Op.getOperand(0);
5415   if (Op.getValueType() == MVT::i32 &&
5416       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5417     SDLoc dl(Op);
5418     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5419   }
5420
5421   return Op;
5422 }
5423
5424 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5425   // The only time a CONCAT_VECTORS operation can have legal types is when
5426   // two 64-bit vectors are concatenated to a 128-bit vector.
5427   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5428          "unexpected CONCAT_VECTORS");
5429   SDLoc dl(Op);
5430   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5431   SDValue Op0 = Op.getOperand(0);
5432   SDValue Op1 = Op.getOperand(1);
5433   if (Op0.getOpcode() != ISD::UNDEF)
5434     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5435                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5436                       DAG.getIntPtrConstant(0));
5437   if (Op1.getOpcode() != ISD::UNDEF)
5438     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5439                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5440                       DAG.getIntPtrConstant(1));
5441   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5442 }
5443
5444 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5445 /// element has been zero/sign-extended, depending on the isSigned parameter,
5446 /// from an integer type half its size.
5447 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5448                                    bool isSigned) {
5449   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5450   EVT VT = N->getValueType(0);
5451   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5452     SDNode *BVN = N->getOperand(0).getNode();
5453     if (BVN->getValueType(0) != MVT::v4i32 ||
5454         BVN->getOpcode() != ISD::BUILD_VECTOR)
5455       return false;
5456     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5457     unsigned HiElt = 1 - LoElt;
5458     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5459     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5460     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5461     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5462     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5463       return false;
5464     if (isSigned) {
5465       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5466           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5467         return true;
5468     } else {
5469       if (Hi0->isNullValue() && Hi1->isNullValue())
5470         return true;
5471     }
5472     return false;
5473   }
5474
5475   if (N->getOpcode() != ISD::BUILD_VECTOR)
5476     return false;
5477
5478   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5479     SDNode *Elt = N->getOperand(i).getNode();
5480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5481       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5482       unsigned HalfSize = EltSize / 2;
5483       if (isSigned) {
5484         if (!isIntN(HalfSize, C->getSExtValue()))
5485           return false;
5486       } else {
5487         if (!isUIntN(HalfSize, C->getZExtValue()))
5488           return false;
5489       }
5490       continue;
5491     }
5492     return false;
5493   }
5494
5495   return true;
5496 }
5497
5498 /// isSignExtended - Check if a node is a vector value that is sign-extended
5499 /// or a constant BUILD_VECTOR with sign-extended elements.
5500 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5501   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5502     return true;
5503   if (isExtendedBUILD_VECTOR(N, DAG, true))
5504     return true;
5505   return false;
5506 }
5507
5508 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5509 /// or a constant BUILD_VECTOR with zero-extended elements.
5510 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5511   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5512     return true;
5513   if (isExtendedBUILD_VECTOR(N, DAG, false))
5514     return true;
5515   return false;
5516 }
5517
5518 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5519   if (OrigVT.getSizeInBits() >= 64)
5520     return OrigVT;
5521
5522   assert(OrigVT.isSimple() && "Expecting a simple value type");
5523
5524   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5525   switch (OrigSimpleTy) {
5526   default: llvm_unreachable("Unexpected Vector Type");
5527   case MVT::v2i8:
5528   case MVT::v2i16:
5529      return MVT::v2i32;
5530   case MVT::v4i8:
5531     return  MVT::v4i16;
5532   }
5533 }
5534
5535 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5536 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5537 /// We insert the required extension here to get the vector to fill a D register.
5538 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5539                                             const EVT &OrigTy,
5540                                             const EVT &ExtTy,
5541                                             unsigned ExtOpcode) {
5542   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5543   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5544   // 64-bits we need to insert a new extension so that it will be 64-bits.
5545   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5546   if (OrigTy.getSizeInBits() >= 64)
5547     return N;
5548
5549   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5550   EVT NewVT = getExtensionTo64Bits(OrigTy);
5551
5552   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5553 }
5554
5555 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5556 /// does not do any sign/zero extension. If the original vector is less
5557 /// than 64 bits, an appropriate extension will be added after the load to
5558 /// reach a total size of 64 bits. We have to add the extension separately
5559 /// because ARM does not have a sign/zero extending load for vectors.
5560 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5561   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5562
5563   // The load already has the right type.
5564   if (ExtendedTy == LD->getMemoryVT())
5565     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5566                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5567                 LD->isNonTemporal(), LD->isInvariant(),
5568                 LD->getAlignment());
5569
5570   // We need to create a zextload/sextload. We cannot just create a load
5571   // followed by a zext/zext node because LowerMUL is also run during normal
5572   // operation legalization where we can't create illegal types.
5573   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5574                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5575                         LD->getMemoryVT(), LD->isVolatile(),
5576                         LD->isNonTemporal(), LD->getAlignment());
5577 }
5578
5579 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5580 /// extending load, or BUILD_VECTOR with extended elements, return the
5581 /// unextended value. The unextended vector should be 64 bits so that it can
5582 /// be used as an operand to a VMULL instruction. If the original vector size
5583 /// before extension is less than 64 bits we add a an extension to resize
5584 /// the vector to 64 bits.
5585 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5586   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5587     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5588                                         N->getOperand(0)->getValueType(0),
5589                                         N->getValueType(0),
5590                                         N->getOpcode());
5591
5592   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5593     return SkipLoadExtensionForVMULL(LD, DAG);
5594
5595   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5596   // have been legalized as a BITCAST from v4i32.
5597   if (N->getOpcode() == ISD::BITCAST) {
5598     SDNode *BVN = N->getOperand(0).getNode();
5599     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5600            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5601     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5602     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5603                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5604   }
5605   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5606   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5607   EVT VT = N->getValueType(0);
5608   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5609   unsigned NumElts = VT.getVectorNumElements();
5610   MVT TruncVT = MVT::getIntegerVT(EltSize);
5611   SmallVector<SDValue, 8> Ops;
5612   for (unsigned i = 0; i != NumElts; ++i) {
5613     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5614     const APInt &CInt = C->getAPIntValue();
5615     // Element types smaller than 32 bits are not legal, so use i32 elements.
5616     // The values are implicitly truncated so sext vs. zext doesn't matter.
5617     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5618   }
5619   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5620                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5621 }
5622
5623 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5624   unsigned Opcode = N->getOpcode();
5625   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5626     SDNode *N0 = N->getOperand(0).getNode();
5627     SDNode *N1 = N->getOperand(1).getNode();
5628     return N0->hasOneUse() && N1->hasOneUse() &&
5629       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5630   }
5631   return false;
5632 }
5633
5634 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5635   unsigned Opcode = N->getOpcode();
5636   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5637     SDNode *N0 = N->getOperand(0).getNode();
5638     SDNode *N1 = N->getOperand(1).getNode();
5639     return N0->hasOneUse() && N1->hasOneUse() &&
5640       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5641   }
5642   return false;
5643 }
5644
5645 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5646   // Multiplications are only custom-lowered for 128-bit vectors so that
5647   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5648   EVT VT = Op.getValueType();
5649   assert(VT.is128BitVector() && VT.isInteger() &&
5650          "unexpected type for custom-lowering ISD::MUL");
5651   SDNode *N0 = Op.getOperand(0).getNode();
5652   SDNode *N1 = Op.getOperand(1).getNode();
5653   unsigned NewOpc = 0;
5654   bool isMLA = false;
5655   bool isN0SExt = isSignExtended(N0, DAG);
5656   bool isN1SExt = isSignExtended(N1, DAG);
5657   if (isN0SExt && isN1SExt)
5658     NewOpc = ARMISD::VMULLs;
5659   else {
5660     bool isN0ZExt = isZeroExtended(N0, DAG);
5661     bool isN1ZExt = isZeroExtended(N1, DAG);
5662     if (isN0ZExt && isN1ZExt)
5663       NewOpc = ARMISD::VMULLu;
5664     else if (isN1SExt || isN1ZExt) {
5665       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5666       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5667       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5668         NewOpc = ARMISD::VMULLs;
5669         isMLA = true;
5670       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5671         NewOpc = ARMISD::VMULLu;
5672         isMLA = true;
5673       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5674         std::swap(N0, N1);
5675         NewOpc = ARMISD::VMULLu;
5676         isMLA = true;
5677       }
5678     }
5679
5680     if (!NewOpc) {
5681       if (VT == MVT::v2i64)
5682         // Fall through to expand this.  It is not legal.
5683         return SDValue();
5684       else
5685         // Other vector multiplications are legal.
5686         return Op;
5687     }
5688   }
5689
5690   // Legalize to a VMULL instruction.
5691   SDLoc DL(Op);
5692   SDValue Op0;
5693   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5694   if (!isMLA) {
5695     Op0 = SkipExtensionForVMULL(N0, DAG);
5696     assert(Op0.getValueType().is64BitVector() &&
5697            Op1.getValueType().is64BitVector() &&
5698            "unexpected types for extended operands to VMULL");
5699     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5700   }
5701
5702   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5703   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5704   //   vmull q0, d4, d6
5705   //   vmlal q0, d5, d6
5706   // is faster than
5707   //   vaddl q0, d4, d5
5708   //   vmovl q1, d6
5709   //   vmul  q0, q0, q1
5710   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5711   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5712   EVT Op1VT = Op1.getValueType();
5713   return DAG.getNode(N0->getOpcode(), DL, VT,
5714                      DAG.getNode(NewOpc, DL, VT,
5715                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5716                      DAG.getNode(NewOpc, DL, VT,
5717                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5718 }
5719
5720 static SDValue
5721 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5722   // Convert to float
5723   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5724   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5725   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5726   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5727   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5728   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5729   // Get reciprocal estimate.
5730   // float4 recip = vrecpeq_f32(yf);
5731   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5732                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5733   // Because char has a smaller range than uchar, we can actually get away
5734   // without any newton steps.  This requires that we use a weird bias
5735   // of 0xb000, however (again, this has been exhaustively tested).
5736   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5737   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5738   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5739   Y = DAG.getConstant(0xb000, MVT::i32);
5740   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5741   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5742   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5743   // Convert back to short.
5744   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5745   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5746   return X;
5747 }
5748
5749 static SDValue
5750 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5751   SDValue N2;
5752   // Convert to float.
5753   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5754   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5755   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5756   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5757   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5758   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5759
5760   // Use reciprocal estimate and one refinement step.
5761   // float4 recip = vrecpeq_f32(yf);
5762   // recip *= vrecpsq_f32(yf, recip);
5763   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5764                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5765   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5766                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5767                    N1, N2);
5768   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5769   // Because short has a smaller range than ushort, we can actually get away
5770   // with only a single newton step.  This requires that we use a weird bias
5771   // of 89, however (again, this has been exhaustively tested).
5772   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5773   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5774   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5775   N1 = DAG.getConstant(0x89, MVT::i32);
5776   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5777   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5778   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5779   // Convert back to integer and return.
5780   // return vmovn_s32(vcvt_s32_f32(result));
5781   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5782   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5783   return N0;
5784 }
5785
5786 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5787   EVT VT = Op.getValueType();
5788   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5789          "unexpected type for custom-lowering ISD::SDIV");
5790
5791   SDLoc dl(Op);
5792   SDValue N0 = Op.getOperand(0);
5793   SDValue N1 = Op.getOperand(1);
5794   SDValue N2, N3;
5795
5796   if (VT == MVT::v8i8) {
5797     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5798     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5799
5800     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5801                      DAG.getIntPtrConstant(4));
5802     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5803                      DAG.getIntPtrConstant(4));
5804     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5805                      DAG.getIntPtrConstant(0));
5806     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5807                      DAG.getIntPtrConstant(0));
5808
5809     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5810     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5811
5812     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5813     N0 = LowerCONCAT_VECTORS(N0, DAG);
5814
5815     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5816     return N0;
5817   }
5818   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5819 }
5820
5821 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5822   EVT VT = Op.getValueType();
5823   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5824          "unexpected type for custom-lowering ISD::UDIV");
5825
5826   SDLoc dl(Op);
5827   SDValue N0 = Op.getOperand(0);
5828   SDValue N1 = Op.getOperand(1);
5829   SDValue N2, N3;
5830
5831   if (VT == MVT::v8i8) {
5832     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5833     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5834
5835     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5836                      DAG.getIntPtrConstant(4));
5837     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5838                      DAG.getIntPtrConstant(4));
5839     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5840                      DAG.getIntPtrConstant(0));
5841     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5842                      DAG.getIntPtrConstant(0));
5843
5844     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5845     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5846
5847     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5848     N0 = LowerCONCAT_VECTORS(N0, DAG);
5849
5850     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5851                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5852                      N0);
5853     return N0;
5854   }
5855
5856   // v4i16 sdiv ... Convert to float.
5857   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5858   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5859   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5860   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5861   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5862   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5863
5864   // Use reciprocal estimate and two refinement steps.
5865   // float4 recip = vrecpeq_f32(yf);
5866   // recip *= vrecpsq_f32(yf, recip);
5867   // recip *= vrecpsq_f32(yf, recip);
5868   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5869                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5870   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5871                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5872                    BN1, N2);
5873   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5874   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5875                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5876                    BN1, N2);
5877   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5878   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5879   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5880   // and that it will never cause us to return an answer too large).
5881   // float4 result = as_float4(as_int4(xf*recip) + 2);
5882   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5883   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5884   N1 = DAG.getConstant(2, MVT::i32);
5885   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5886   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5887   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5888   // Convert back to integer and return.
5889   // return vmovn_u32(vcvt_s32_f32(result));
5890   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5891   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5892   return N0;
5893 }
5894
5895 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5896   EVT VT = Op.getNode()->getValueType(0);
5897   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5898
5899   unsigned Opc;
5900   bool ExtraOp = false;
5901   switch (Op.getOpcode()) {
5902   default: llvm_unreachable("Invalid code");
5903   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5904   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5905   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5906   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5907   }
5908
5909   if (!ExtraOp)
5910     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5911                        Op.getOperand(1));
5912   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5913                      Op.getOperand(1), Op.getOperand(2));
5914 }
5915
5916 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5917   assert(Subtarget->isTargetDarwin());
5918
5919   // For iOS, we want to call an alternative entry point: __sincos_stret,
5920   // return values are passed via sret.
5921   SDLoc dl(Op);
5922   SDValue Arg = Op.getOperand(0);
5923   EVT ArgVT = Arg.getValueType();
5924   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5925
5926   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5928
5929   // Pair of floats / doubles used to pass the result.
5930   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5931
5932   // Create stack object for sret.
5933   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5934   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5935   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5936   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5937
5938   ArgListTy Args;
5939   ArgListEntry Entry;
5940
5941   Entry.Node = SRet;
5942   Entry.Ty = RetTy->getPointerTo();
5943   Entry.isSExt = false;
5944   Entry.isZExt = false;
5945   Entry.isSRet = true;
5946   Args.push_back(Entry);
5947
5948   Entry.Node = Arg;
5949   Entry.Ty = ArgTy;
5950   Entry.isSExt = false;
5951   Entry.isZExt = false;
5952   Args.push_back(Entry);
5953
5954   const char *LibcallName  = (ArgVT == MVT::f64)
5955   ? "__sincos_stret" : "__sincosf_stret";
5956   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5957
5958   TargetLowering::
5959   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5960                        false, false, false, false, 0,
5961                        CallingConv::C, /*isTaillCall=*/false,
5962                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5963                        Callee, Args, DAG, dl);
5964   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5965
5966   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5967                                 MachinePointerInfo(), false, false, false, 0);
5968
5969   // Address of cos field.
5970   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5971                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5972   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5973                                 MachinePointerInfo(), false, false, false, 0);
5974
5975   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5976   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5977                      LoadSin.getValue(0), LoadCos.getValue(0));
5978 }
5979
5980 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5981   // Monotonic load/store is legal for all targets
5982   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5983     return Op;
5984
5985   // Acquire/Release load/store is not legal for targets without a
5986   // dmb or equivalent available.
5987   return SDValue();
5988 }
5989
5990 static void
5991 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5992                     SelectionDAG &DAG) {
5993   SDLoc dl(Node);
5994   assert (Node->getValueType(0) == MVT::i64 &&
5995           "Only know how to expand i64 atomics");
5996   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
5997
5998   SmallVector<SDValue, 6> Ops;
5999   Ops.push_back(Node->getOperand(0)); // Chain
6000   Ops.push_back(Node->getOperand(1)); // Ptr
6001   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6002     // Low part
6003     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6004                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6005     // High part
6006     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6007                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6008   }
6009   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6010   SDValue Result =
6011     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6012                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6013                   AN->getSynchScope());
6014   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6015   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6016   Results.push_back(Result.getValue(2));
6017 }
6018
6019 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6020                                     SmallVectorImpl<SDValue> &Results,
6021                                     SelectionDAG &DAG,
6022                                     const ARMSubtarget *Subtarget) {
6023   SDLoc DL(N);
6024   SDValue Cycles32, OutChain;
6025
6026   if (Subtarget->hasPerfMon()) {
6027     // Under Power Management extensions, the cycle-count is:
6028     //    mrc p15, #0, <Rt>, c9, c13, #0
6029     SDValue Ops[] = { N->getOperand(0), // Chain
6030                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6031                       DAG.getConstant(15, MVT::i32),
6032                       DAG.getConstant(0, MVT::i32),
6033                       DAG.getConstant(9, MVT::i32),
6034                       DAG.getConstant(13, MVT::i32),
6035                       DAG.getConstant(0, MVT::i32)
6036     };
6037
6038     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6039                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6040                            array_lengthof(Ops));
6041     OutChain = Cycles32.getValue(1);
6042   } else {
6043     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6044     // there are older ARM CPUs that have implementation-specific ways of
6045     // obtaining this information (FIXME!).
6046     Cycles32 = DAG.getConstant(0, MVT::i32);
6047     OutChain = DAG.getEntryNode();
6048   }
6049
6050
6051   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6052                                  Cycles32, DAG.getConstant(0, MVT::i32));
6053   Results.push_back(Cycles64);
6054   Results.push_back(OutChain);
6055 }
6056
6057 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6058   switch (Op.getOpcode()) {
6059   default: llvm_unreachable("Don't know how to custom lower this!");
6060   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6061   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6062   case ISD::GlobalAddress:
6063     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6064       LowerGlobalAddressELF(Op, DAG);
6065   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6066   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6067   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6068   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6069   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6070   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6071   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6072   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6073   case ISD::SINT_TO_FP:
6074   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6075   case ISD::FP_TO_SINT:
6076   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6077   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6078   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6079   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6080   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6081   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6082   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6083   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6084                                                                Subtarget);
6085   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6086   case ISD::SHL:
6087   case ISD::SRL:
6088   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6089   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6090   case ISD::SRL_PARTS:
6091   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6092   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6093   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6094   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6095   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6096   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6097   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6098   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6099   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6100   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6101   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6102   case ISD::MUL:           return LowerMUL(Op, DAG);
6103   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6104   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6105   case ISD::ADDC:
6106   case ISD::ADDE:
6107   case ISD::SUBC:
6108   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6109   case ISD::ATOMIC_LOAD:
6110   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6111   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6112   case ISD::SDIVREM:
6113   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6114   }
6115 }
6116
6117 /// ReplaceNodeResults - Replace the results of node with an illegal result
6118 /// type with new values built out of custom code.
6119 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6120                                            SmallVectorImpl<SDValue>&Results,
6121                                            SelectionDAG &DAG) const {
6122   SDValue Res;
6123   switch (N->getOpcode()) {
6124   default:
6125     llvm_unreachable("Don't know how to custom expand this!");
6126   case ISD::BITCAST:
6127     Res = ExpandBITCAST(N, DAG);
6128     break;
6129   case ISD::SRL:
6130   case ISD::SRA:
6131     Res = Expand64BitShift(N, DAG, Subtarget);
6132     break;
6133   case ISD::READCYCLECOUNTER:
6134     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6135     return;
6136   case ISD::ATOMIC_STORE:
6137   case ISD::ATOMIC_LOAD:
6138   case ISD::ATOMIC_LOAD_ADD:
6139   case ISD::ATOMIC_LOAD_AND:
6140   case ISD::ATOMIC_LOAD_NAND:
6141   case ISD::ATOMIC_LOAD_OR:
6142   case ISD::ATOMIC_LOAD_SUB:
6143   case ISD::ATOMIC_LOAD_XOR:
6144   case ISD::ATOMIC_SWAP:
6145   case ISD::ATOMIC_CMP_SWAP:
6146   case ISD::ATOMIC_LOAD_MIN:
6147   case ISD::ATOMIC_LOAD_UMIN:
6148   case ISD::ATOMIC_LOAD_MAX:
6149   case ISD::ATOMIC_LOAD_UMAX:
6150     ReplaceATOMIC_OP_64(N, Results, DAG);
6151     return;
6152   }
6153   if (Res.getNode())
6154     Results.push_back(Res);
6155 }
6156
6157 //===----------------------------------------------------------------------===//
6158 //                           ARM Scheduler Hooks
6159 //===----------------------------------------------------------------------===//
6160
6161 MachineBasicBlock *
6162 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6163                                      MachineBasicBlock *BB,
6164                                      unsigned Size) const {
6165   unsigned dest    = MI->getOperand(0).getReg();
6166   unsigned ptr     = MI->getOperand(1).getReg();
6167   unsigned oldval  = MI->getOperand(2).getReg();
6168   unsigned newval  = MI->getOperand(3).getReg();
6169   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6170   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6171   DebugLoc dl = MI->getDebugLoc();
6172   bool isThumb2 = Subtarget->isThumb2();
6173
6174   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6175   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6176     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6177     (const TargetRegisterClass*)&ARM::GPRRegClass);
6178
6179   if (isThumb2) {
6180     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6181     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6182     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6183   }
6184
6185   unsigned ldrOpc, strOpc;
6186   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6187
6188   MachineFunction *MF = BB->getParent();
6189   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6190   MachineFunction::iterator It = BB;
6191   ++It; // insert the new blocks after the current block
6192
6193   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6194   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6195   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6196   MF->insert(It, loop1MBB);
6197   MF->insert(It, loop2MBB);
6198   MF->insert(It, exitMBB);
6199
6200   // Transfer the remainder of BB and its successor edges to exitMBB.
6201   exitMBB->splice(exitMBB->begin(), BB,
6202                   llvm::next(MachineBasicBlock::iterator(MI)),
6203                   BB->end());
6204   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6205
6206   //  thisMBB:
6207   //   ...
6208   //   fallthrough --> loop1MBB
6209   BB->addSuccessor(loop1MBB);
6210
6211   // loop1MBB:
6212   //   ldrex dest, [ptr]
6213   //   cmp dest, oldval
6214   //   bne exitMBB
6215   BB = loop1MBB;
6216   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6217   if (ldrOpc == ARM::t2LDREX)
6218     MIB.addImm(0);
6219   AddDefaultPred(MIB);
6220   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6221                  .addReg(dest).addReg(oldval));
6222   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6223     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6224   BB->addSuccessor(loop2MBB);
6225   BB->addSuccessor(exitMBB);
6226
6227   // loop2MBB:
6228   //   strex scratch, newval, [ptr]
6229   //   cmp scratch, #0
6230   //   bne loop1MBB
6231   BB = loop2MBB;
6232   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6233   if (strOpc == ARM::t2STREX)
6234     MIB.addImm(0);
6235   AddDefaultPred(MIB);
6236   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6237                  .addReg(scratch).addImm(0));
6238   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6239     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6240   BB->addSuccessor(loop1MBB);
6241   BB->addSuccessor(exitMBB);
6242
6243   //  exitMBB:
6244   //   ...
6245   BB = exitMBB;
6246
6247   MI->eraseFromParent();   // The instruction is gone now.
6248
6249   return BB;
6250 }
6251
6252 MachineBasicBlock *
6253 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6254                                     unsigned Size, unsigned BinOpcode) const {
6255   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6256   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6257
6258   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6259   MachineFunction *MF = BB->getParent();
6260   MachineFunction::iterator It = BB;
6261   ++It;
6262
6263   unsigned dest = MI->getOperand(0).getReg();
6264   unsigned ptr = MI->getOperand(1).getReg();
6265   unsigned incr = MI->getOperand(2).getReg();
6266   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6267   DebugLoc dl = MI->getDebugLoc();
6268   bool isThumb2 = Subtarget->isThumb2();
6269
6270   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6271   if (isThumb2) {
6272     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6273     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6274     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6275   }
6276
6277   unsigned ldrOpc, strOpc;
6278   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6279
6280   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6281   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6282   MF->insert(It, loopMBB);
6283   MF->insert(It, exitMBB);
6284
6285   // Transfer the remainder of BB and its successor edges to exitMBB.
6286   exitMBB->splice(exitMBB->begin(), BB,
6287                   llvm::next(MachineBasicBlock::iterator(MI)),
6288                   BB->end());
6289   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6290
6291   const TargetRegisterClass *TRC = isThumb2 ?
6292     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6293     (const TargetRegisterClass*)&ARM::GPRRegClass;
6294   unsigned scratch = MRI.createVirtualRegister(TRC);
6295   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6296
6297   //  thisMBB:
6298   //   ...
6299   //   fallthrough --> loopMBB
6300   BB->addSuccessor(loopMBB);
6301
6302   //  loopMBB:
6303   //   ldrex dest, ptr
6304   //   <binop> scratch2, dest, incr
6305   //   strex scratch, scratch2, ptr
6306   //   cmp scratch, #0
6307   //   bne- loopMBB
6308   //   fallthrough --> exitMBB
6309   BB = loopMBB;
6310   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6311   if (ldrOpc == ARM::t2LDREX)
6312     MIB.addImm(0);
6313   AddDefaultPred(MIB);
6314   if (BinOpcode) {
6315     // operand order needs to go the other way for NAND
6316     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6317       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6318                      addReg(incr).addReg(dest)).addReg(0);
6319     else
6320       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6321                      addReg(dest).addReg(incr)).addReg(0);
6322   }
6323
6324   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6325   if (strOpc == ARM::t2STREX)
6326     MIB.addImm(0);
6327   AddDefaultPred(MIB);
6328   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6329                  .addReg(scratch).addImm(0));
6330   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6331     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6332
6333   BB->addSuccessor(loopMBB);
6334   BB->addSuccessor(exitMBB);
6335
6336   //  exitMBB:
6337   //   ...
6338   BB = exitMBB;
6339
6340   MI->eraseFromParent();   // The instruction is gone now.
6341
6342   return BB;
6343 }
6344
6345 MachineBasicBlock *
6346 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6347                                           MachineBasicBlock *BB,
6348                                           unsigned Size,
6349                                           bool signExtend,
6350                                           ARMCC::CondCodes Cond) const {
6351   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6352
6353   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6354   MachineFunction *MF = BB->getParent();
6355   MachineFunction::iterator It = BB;
6356   ++It;
6357
6358   unsigned dest = MI->getOperand(0).getReg();
6359   unsigned ptr = MI->getOperand(1).getReg();
6360   unsigned incr = MI->getOperand(2).getReg();
6361   unsigned oldval = dest;
6362   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6363   DebugLoc dl = MI->getDebugLoc();
6364   bool isThumb2 = Subtarget->isThumb2();
6365
6366   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6367   if (isThumb2) {
6368     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6369     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6370     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6371   }
6372
6373   unsigned ldrOpc, strOpc, extendOpc;
6374   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6375   switch (Size) {
6376   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6377   case 1:
6378     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6379     break;
6380   case 2:
6381     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6382     break;
6383   case 4:
6384     extendOpc = 0;
6385     break;
6386   }
6387
6388   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6389   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6390   MF->insert(It, loopMBB);
6391   MF->insert(It, exitMBB);
6392
6393   // Transfer the remainder of BB and its successor edges to exitMBB.
6394   exitMBB->splice(exitMBB->begin(), BB,
6395                   llvm::next(MachineBasicBlock::iterator(MI)),
6396                   BB->end());
6397   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6398
6399   const TargetRegisterClass *TRC = isThumb2 ?
6400     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6401     (const TargetRegisterClass*)&ARM::GPRRegClass;
6402   unsigned scratch = MRI.createVirtualRegister(TRC);
6403   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6404
6405   //  thisMBB:
6406   //   ...
6407   //   fallthrough --> loopMBB
6408   BB->addSuccessor(loopMBB);
6409
6410   //  loopMBB:
6411   //   ldrex dest, ptr
6412   //   (sign extend dest, if required)
6413   //   cmp dest, incr
6414   //   cmov.cond scratch2, incr, dest
6415   //   strex scratch, scratch2, ptr
6416   //   cmp scratch, #0
6417   //   bne- loopMBB
6418   //   fallthrough --> exitMBB
6419   BB = loopMBB;
6420   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6421   if (ldrOpc == ARM::t2LDREX)
6422     MIB.addImm(0);
6423   AddDefaultPred(MIB);
6424
6425   // Sign extend the value, if necessary.
6426   if (signExtend && extendOpc) {
6427     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6428                                                 : &ARM::GPRnopcRegClass);
6429     if (!isThumb2)
6430       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6431     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6432                      .addReg(dest)
6433                      .addImm(0));
6434   }
6435
6436   // Build compare and cmov instructions.
6437   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6438                  .addReg(oldval).addReg(incr));
6439   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6440          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6441
6442   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6443   if (strOpc == ARM::t2STREX)
6444     MIB.addImm(0);
6445   AddDefaultPred(MIB);
6446   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6447                  .addReg(scratch).addImm(0));
6448   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6449     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6450
6451   BB->addSuccessor(loopMBB);
6452   BB->addSuccessor(exitMBB);
6453
6454   //  exitMBB:
6455   //   ...
6456   BB = exitMBB;
6457
6458   MI->eraseFromParent();   // The instruction is gone now.
6459
6460   return BB;
6461 }
6462
6463 MachineBasicBlock *
6464 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6465                                       unsigned Op1, unsigned Op2,
6466                                       bool NeedsCarry, bool IsCmpxchg,
6467                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6468   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6469   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6470
6471   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6472   MachineFunction *MF = BB->getParent();
6473   MachineFunction::iterator It = BB;
6474   ++It;
6475
6476   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6477   unsigned offset = (isStore ? -2 : 0);
6478   unsigned destlo = MI->getOperand(0).getReg();
6479   unsigned desthi = MI->getOperand(1).getReg();
6480   unsigned ptr = MI->getOperand(offset+2).getReg();
6481   unsigned vallo = MI->getOperand(offset+3).getReg();
6482   unsigned valhi = MI->getOperand(offset+4).getReg();
6483   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6484   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6485   DebugLoc dl = MI->getDebugLoc();
6486   bool isThumb2 = Subtarget->isThumb2();
6487
6488   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6489   if (isThumb2) {
6490     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6491     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6492     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6493     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6494     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6495   }
6496
6497   unsigned ldrOpc, strOpc;
6498   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6499
6500   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6501   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6502   if (IsCmpxchg || IsMinMax)
6503     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6504   if (IsCmpxchg)
6505     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6506   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6507
6508   MF->insert(It, loopMBB);
6509   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6510   if (IsCmpxchg) MF->insert(It, cont2BB);
6511   MF->insert(It, exitMBB);
6512
6513   // Transfer the remainder of BB and its successor edges to exitMBB.
6514   exitMBB->splice(exitMBB->begin(), BB,
6515                   llvm::next(MachineBasicBlock::iterator(MI)),
6516                   BB->end());
6517   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6518
6519   const TargetRegisterClass *TRC = isThumb2 ?
6520     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6521     (const TargetRegisterClass*)&ARM::GPRRegClass;
6522   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6523
6524   //  thisMBB:
6525   //   ...
6526   //   fallthrough --> loopMBB
6527   BB->addSuccessor(loopMBB);
6528
6529   //  loopMBB:
6530   //   ldrexd r2, r3, ptr
6531   //   <binopa> r0, r2, incr
6532   //   <binopb> r1, r3, incr
6533   //   strexd storesuccess, r0, r1, ptr
6534   //   cmp storesuccess, #0
6535   //   bne- loopMBB
6536   //   fallthrough --> exitMBB
6537   BB = loopMBB;
6538
6539   if (!isStore) {
6540     // Load
6541     if (isThumb2) {
6542       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6543                      .addReg(destlo, RegState::Define)
6544                      .addReg(desthi, RegState::Define)
6545                      .addReg(ptr));
6546     } else {
6547       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6548       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6549                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6550       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6551       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6552         .addReg(GPRPair0, 0, ARM::gsub_0);
6553       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6554         .addReg(GPRPair0, 0, ARM::gsub_1);
6555     }
6556   }
6557
6558   unsigned StoreLo, StoreHi;
6559   if (IsCmpxchg) {
6560     // Add early exit
6561     for (unsigned i = 0; i < 2; i++) {
6562       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6563                                                          ARM::CMPrr))
6564                      .addReg(i == 0 ? destlo : desthi)
6565                      .addReg(i == 0 ? vallo : valhi));
6566       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6567         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6568       BB->addSuccessor(exitMBB);
6569       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6570       BB = (i == 0 ? contBB : cont2BB);
6571     }
6572
6573     // Copy to physregs for strexd
6574     StoreLo = MI->getOperand(5).getReg();
6575     StoreHi = MI->getOperand(6).getReg();
6576   } else if (Op1) {
6577     // Perform binary operation
6578     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6579     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6580                    .addReg(destlo).addReg(vallo))
6581         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6582     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6583     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6584                    .addReg(desthi).addReg(valhi))
6585         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6586
6587     StoreLo = tmpRegLo;
6588     StoreHi = tmpRegHi;
6589   } else {
6590     // Copy to physregs for strexd
6591     StoreLo = vallo;
6592     StoreHi = valhi;
6593   }
6594   if (IsMinMax) {
6595     // Compare and branch to exit block.
6596     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6597       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6598     BB->addSuccessor(exitMBB);
6599     BB->addSuccessor(contBB);
6600     BB = contBB;
6601     StoreLo = vallo;
6602     StoreHi = valhi;
6603   }
6604
6605   // Store
6606   if (isThumb2) {
6607     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6608     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6609     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6610                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6611   } else {
6612     // Marshal a pair...
6613     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6614     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6615     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6616     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6617     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6618       .addReg(UndefPair)
6619       .addReg(StoreLo)
6620       .addImm(ARM::gsub_0);
6621     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6622       .addReg(r1)
6623       .addReg(StoreHi)
6624       .addImm(ARM::gsub_1);
6625
6626     // ...and store it
6627     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6628                    .addReg(StorePair).addReg(ptr));
6629   }
6630   // Cmp+jump
6631   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6632                  .addReg(storesuccess).addImm(0));
6633   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6634     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6635
6636   BB->addSuccessor(loopMBB);
6637   BB->addSuccessor(exitMBB);
6638
6639   //  exitMBB:
6640   //   ...
6641   BB = exitMBB;
6642
6643   MI->eraseFromParent();   // The instruction is gone now.
6644
6645   return BB;
6646 }
6647
6648 MachineBasicBlock *
6649 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6650
6651   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6652
6653   unsigned destlo = MI->getOperand(0).getReg();
6654   unsigned desthi = MI->getOperand(1).getReg();
6655   unsigned ptr = MI->getOperand(2).getReg();
6656   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6657   DebugLoc dl = MI->getDebugLoc();
6658   bool isThumb2 = Subtarget->isThumb2();
6659
6660   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6661   if (isThumb2) {
6662     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6663     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6664     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6665   }
6666   unsigned ldrOpc, strOpc;
6667   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6668
6669   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6670
6671   if (isThumb2) {
6672     MIB.addReg(destlo, RegState::Define)
6673        .addReg(desthi, RegState::Define)
6674        .addReg(ptr);
6675
6676   } else {
6677     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6678     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6679
6680     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6681     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6682       .addReg(GPRPair0, 0, ARM::gsub_0);
6683     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6684       .addReg(GPRPair0, 0, ARM::gsub_1);
6685   }
6686   AddDefaultPred(MIB);
6687
6688   MI->eraseFromParent();   // The instruction is gone now.
6689
6690   return BB;
6691 }
6692
6693 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6694 /// registers the function context.
6695 void ARMTargetLowering::
6696 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6697                        MachineBasicBlock *DispatchBB, int FI) const {
6698   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6699   DebugLoc dl = MI->getDebugLoc();
6700   MachineFunction *MF = MBB->getParent();
6701   MachineRegisterInfo *MRI = &MF->getRegInfo();
6702   MachineConstantPool *MCP = MF->getConstantPool();
6703   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6704   const Function *F = MF->getFunction();
6705
6706   bool isThumb = Subtarget->isThumb();
6707   bool isThumb2 = Subtarget->isThumb2();
6708
6709   unsigned PCLabelId = AFI->createPICLabelUId();
6710   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6711   ARMConstantPoolValue *CPV =
6712     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6713   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6714
6715   const TargetRegisterClass *TRC = isThumb ?
6716     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6717     (const TargetRegisterClass*)&ARM::GPRRegClass;
6718
6719   // Grab constant pool and fixed stack memory operands.
6720   MachineMemOperand *CPMMO =
6721     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6722                              MachineMemOperand::MOLoad, 4, 4);
6723
6724   MachineMemOperand *FIMMOSt =
6725     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6726                              MachineMemOperand::MOStore, 4, 4);
6727
6728   // Load the address of the dispatch MBB into the jump buffer.
6729   if (isThumb2) {
6730     // Incoming value: jbuf
6731     //   ldr.n  r5, LCPI1_1
6732     //   orr    r5, r5, #1
6733     //   add    r5, pc
6734     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6735     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6736     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6737                    .addConstantPoolIndex(CPI)
6738                    .addMemOperand(CPMMO));
6739     // Set the low bit because of thumb mode.
6740     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6741     AddDefaultCC(
6742       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6743                      .addReg(NewVReg1, RegState::Kill)
6744                      .addImm(0x01)));
6745     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6746     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6747       .addReg(NewVReg2, RegState::Kill)
6748       .addImm(PCLabelId);
6749     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6750                    .addReg(NewVReg3, RegState::Kill)
6751                    .addFrameIndex(FI)
6752                    .addImm(36)  // &jbuf[1] :: pc
6753                    .addMemOperand(FIMMOSt));
6754   } else if (isThumb) {
6755     // Incoming value: jbuf
6756     //   ldr.n  r1, LCPI1_4
6757     //   add    r1, pc
6758     //   mov    r2, #1
6759     //   orrs   r1, r2
6760     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6761     //   str    r1, [r2]
6762     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6763     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6764                    .addConstantPoolIndex(CPI)
6765                    .addMemOperand(CPMMO));
6766     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6767     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6768       .addReg(NewVReg1, RegState::Kill)
6769       .addImm(PCLabelId);
6770     // Set the low bit because of thumb mode.
6771     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6772     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6773                    .addReg(ARM::CPSR, RegState::Define)
6774                    .addImm(1));
6775     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6776     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6777                    .addReg(ARM::CPSR, RegState::Define)
6778                    .addReg(NewVReg2, RegState::Kill)
6779                    .addReg(NewVReg3, RegState::Kill));
6780     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6781     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6782                    .addFrameIndex(FI)
6783                    .addImm(36)); // &jbuf[1] :: pc
6784     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6785                    .addReg(NewVReg4, RegState::Kill)
6786                    .addReg(NewVReg5, RegState::Kill)
6787                    .addImm(0)
6788                    .addMemOperand(FIMMOSt));
6789   } else {
6790     // Incoming value: jbuf
6791     //   ldr  r1, LCPI1_1
6792     //   add  r1, pc, r1
6793     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6794     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6795     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6796                    .addConstantPoolIndex(CPI)
6797                    .addImm(0)
6798                    .addMemOperand(CPMMO));
6799     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6800     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6801                    .addReg(NewVReg1, RegState::Kill)
6802                    .addImm(PCLabelId));
6803     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6804                    .addReg(NewVReg2, RegState::Kill)
6805                    .addFrameIndex(FI)
6806                    .addImm(36)  // &jbuf[1] :: pc
6807                    .addMemOperand(FIMMOSt));
6808   }
6809 }
6810
6811 MachineBasicBlock *ARMTargetLowering::
6812 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6813   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6814   DebugLoc dl = MI->getDebugLoc();
6815   MachineFunction *MF = MBB->getParent();
6816   MachineRegisterInfo *MRI = &MF->getRegInfo();
6817   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6818   MachineFrameInfo *MFI = MF->getFrameInfo();
6819   int FI = MFI->getFunctionContextIndex();
6820
6821   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6822     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6823     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6824
6825   // Get a mapping of the call site numbers to all of the landing pads they're
6826   // associated with.
6827   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6828   unsigned MaxCSNum = 0;
6829   MachineModuleInfo &MMI = MF->getMMI();
6830   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6831        ++BB) {
6832     if (!BB->isLandingPad()) continue;
6833
6834     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6835     // pad.
6836     for (MachineBasicBlock::iterator
6837            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6838       if (!II->isEHLabel()) continue;
6839
6840       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6841       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6842
6843       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6844       for (SmallVectorImpl<unsigned>::iterator
6845              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6846            CSI != CSE; ++CSI) {
6847         CallSiteNumToLPad[*CSI].push_back(BB);
6848         MaxCSNum = std::max(MaxCSNum, *CSI);
6849       }
6850       break;
6851     }
6852   }
6853
6854   // Get an ordered list of the machine basic blocks for the jump table.
6855   std::vector<MachineBasicBlock*> LPadList;
6856   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6857   LPadList.reserve(CallSiteNumToLPad.size());
6858   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6859     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6860     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6861            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6862       LPadList.push_back(*II);
6863       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6864     }
6865   }
6866
6867   assert(!LPadList.empty() &&
6868          "No landing pad destinations for the dispatch jump table!");
6869
6870   // Create the jump table and associated information.
6871   MachineJumpTableInfo *JTI =
6872     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6873   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6874   unsigned UId = AFI->createJumpTableUId();
6875   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6876
6877   // Create the MBBs for the dispatch code.
6878
6879   // Shove the dispatch's address into the return slot in the function context.
6880   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6881   DispatchBB->setIsLandingPad();
6882
6883   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6884   unsigned trap_opcode;
6885   if (Subtarget->isThumb())
6886     trap_opcode = ARM::tTRAP;
6887   else
6888     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6889
6890   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6891   DispatchBB->addSuccessor(TrapBB);
6892
6893   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6894   DispatchBB->addSuccessor(DispContBB);
6895
6896   // Insert and MBBs.
6897   MF->insert(MF->end(), DispatchBB);
6898   MF->insert(MF->end(), DispContBB);
6899   MF->insert(MF->end(), TrapBB);
6900
6901   // Insert code into the entry block that creates and registers the function
6902   // context.
6903   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6904
6905   MachineMemOperand *FIMMOLd =
6906     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6907                              MachineMemOperand::MOLoad |
6908                              MachineMemOperand::MOVolatile, 4, 4);
6909
6910   MachineInstrBuilder MIB;
6911   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6912
6913   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6914   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6915
6916   // Add a register mask with no preserved registers.  This results in all
6917   // registers being marked as clobbered.
6918   MIB.addRegMask(RI.getNoPreservedMask());
6919
6920   unsigned NumLPads = LPadList.size();
6921   if (Subtarget->isThumb2()) {
6922     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6923     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6924                    .addFrameIndex(FI)
6925                    .addImm(4)
6926                    .addMemOperand(FIMMOLd));
6927
6928     if (NumLPads < 256) {
6929       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6930                      .addReg(NewVReg1)
6931                      .addImm(LPadList.size()));
6932     } else {
6933       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6934       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6935                      .addImm(NumLPads & 0xFFFF));
6936
6937       unsigned VReg2 = VReg1;
6938       if ((NumLPads & 0xFFFF0000) != 0) {
6939         VReg2 = MRI->createVirtualRegister(TRC);
6940         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6941                        .addReg(VReg1)
6942                        .addImm(NumLPads >> 16));
6943       }
6944
6945       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6946                      .addReg(NewVReg1)
6947                      .addReg(VReg2));
6948     }
6949
6950     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6951       .addMBB(TrapBB)
6952       .addImm(ARMCC::HI)
6953       .addReg(ARM::CPSR);
6954
6955     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6956     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6957                    .addJumpTableIndex(MJTI)
6958                    .addImm(UId));
6959
6960     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6961     AddDefaultCC(
6962       AddDefaultPred(
6963         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6964         .addReg(NewVReg3, RegState::Kill)
6965         .addReg(NewVReg1)
6966         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6967
6968     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6969       .addReg(NewVReg4, RegState::Kill)
6970       .addReg(NewVReg1)
6971       .addJumpTableIndex(MJTI)
6972       .addImm(UId);
6973   } else if (Subtarget->isThumb()) {
6974     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6975     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6976                    .addFrameIndex(FI)
6977                    .addImm(1)
6978                    .addMemOperand(FIMMOLd));
6979
6980     if (NumLPads < 256) {
6981       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6982                      .addReg(NewVReg1)
6983                      .addImm(NumLPads));
6984     } else {
6985       MachineConstantPool *ConstantPool = MF->getConstantPool();
6986       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6987       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6988
6989       // MachineConstantPool wants an explicit alignment.
6990       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6991       if (Align == 0)
6992         Align = getDataLayout()->getTypeAllocSize(C->getType());
6993       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6994
6995       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6996       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6997                      .addReg(VReg1, RegState::Define)
6998                      .addConstantPoolIndex(Idx));
6999       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7000                      .addReg(NewVReg1)
7001                      .addReg(VReg1));
7002     }
7003
7004     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7005       .addMBB(TrapBB)
7006       .addImm(ARMCC::HI)
7007       .addReg(ARM::CPSR);
7008
7009     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7010     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7011                    .addReg(ARM::CPSR, RegState::Define)
7012                    .addReg(NewVReg1)
7013                    .addImm(2));
7014
7015     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7016     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7017                    .addJumpTableIndex(MJTI)
7018                    .addImm(UId));
7019
7020     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7021     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7022                    .addReg(ARM::CPSR, RegState::Define)
7023                    .addReg(NewVReg2, RegState::Kill)
7024                    .addReg(NewVReg3));
7025
7026     MachineMemOperand *JTMMOLd =
7027       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7028                                MachineMemOperand::MOLoad, 4, 4);
7029
7030     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7031     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7032                    .addReg(NewVReg4, RegState::Kill)
7033                    .addImm(0)
7034                    .addMemOperand(JTMMOLd));
7035
7036     unsigned NewVReg6 = NewVReg5;
7037     if (RelocM == Reloc::PIC_) {
7038       NewVReg6 = MRI->createVirtualRegister(TRC);
7039       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7040                      .addReg(ARM::CPSR, RegState::Define)
7041                      .addReg(NewVReg5, RegState::Kill)
7042                      .addReg(NewVReg3));
7043     }
7044
7045     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7046       .addReg(NewVReg6, RegState::Kill)
7047       .addJumpTableIndex(MJTI)
7048       .addImm(UId);
7049   } else {
7050     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7051     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7052                    .addFrameIndex(FI)
7053                    .addImm(4)
7054                    .addMemOperand(FIMMOLd));
7055
7056     if (NumLPads < 256) {
7057       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7058                      .addReg(NewVReg1)
7059                      .addImm(NumLPads));
7060     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7061       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7062       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7063                      .addImm(NumLPads & 0xFFFF));
7064
7065       unsigned VReg2 = VReg1;
7066       if ((NumLPads & 0xFFFF0000) != 0) {
7067         VReg2 = MRI->createVirtualRegister(TRC);
7068         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7069                        .addReg(VReg1)
7070                        .addImm(NumLPads >> 16));
7071       }
7072
7073       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7074                      .addReg(NewVReg1)
7075                      .addReg(VReg2));
7076     } else {
7077       MachineConstantPool *ConstantPool = MF->getConstantPool();
7078       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7079       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7080
7081       // MachineConstantPool wants an explicit alignment.
7082       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7083       if (Align == 0)
7084         Align = getDataLayout()->getTypeAllocSize(C->getType());
7085       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7086
7087       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7088       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7089                      .addReg(VReg1, RegState::Define)
7090                      .addConstantPoolIndex(Idx)
7091                      .addImm(0));
7092       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7093                      .addReg(NewVReg1)
7094                      .addReg(VReg1, RegState::Kill));
7095     }
7096
7097     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7098       .addMBB(TrapBB)
7099       .addImm(ARMCC::HI)
7100       .addReg(ARM::CPSR);
7101
7102     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7103     AddDefaultCC(
7104       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7105                      .addReg(NewVReg1)
7106                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7107     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7108     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7109                    .addJumpTableIndex(MJTI)
7110                    .addImm(UId));
7111
7112     MachineMemOperand *JTMMOLd =
7113       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7114                                MachineMemOperand::MOLoad, 4, 4);
7115     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7116     AddDefaultPred(
7117       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7118       .addReg(NewVReg3, RegState::Kill)
7119       .addReg(NewVReg4)
7120       .addImm(0)
7121       .addMemOperand(JTMMOLd));
7122
7123     if (RelocM == Reloc::PIC_) {
7124       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7125         .addReg(NewVReg5, RegState::Kill)
7126         .addReg(NewVReg4)
7127         .addJumpTableIndex(MJTI)
7128         .addImm(UId);
7129     } else {
7130       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7131         .addReg(NewVReg5, RegState::Kill)
7132         .addJumpTableIndex(MJTI)
7133         .addImm(UId);
7134     }
7135   }
7136
7137   // Add the jump table entries as successors to the MBB.
7138   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7139   for (std::vector<MachineBasicBlock*>::iterator
7140          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7141     MachineBasicBlock *CurMBB = *I;
7142     if (SeenMBBs.insert(CurMBB))
7143       DispContBB->addSuccessor(CurMBB);
7144   }
7145
7146   // N.B. the order the invoke BBs are processed in doesn't matter here.
7147   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7148   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7149   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7150          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7151     MachineBasicBlock *BB = *I;
7152
7153     // Remove the landing pad successor from the invoke block and replace it
7154     // with the new dispatch block.
7155     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7156                                                   BB->succ_end());
7157     while (!Successors.empty()) {
7158       MachineBasicBlock *SMBB = Successors.pop_back_val();
7159       if (SMBB->isLandingPad()) {
7160         BB->removeSuccessor(SMBB);
7161         MBBLPads.push_back(SMBB);
7162       }
7163     }
7164
7165     BB->addSuccessor(DispatchBB);
7166
7167     // Find the invoke call and mark all of the callee-saved registers as
7168     // 'implicit defined' so that they're spilled. This prevents code from
7169     // moving instructions to before the EH block, where they will never be
7170     // executed.
7171     for (MachineBasicBlock::reverse_iterator
7172            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7173       if (!II->isCall()) continue;
7174
7175       DenseMap<unsigned, bool> DefRegs;
7176       for (MachineInstr::mop_iterator
7177              OI = II->operands_begin(), OE = II->operands_end();
7178            OI != OE; ++OI) {
7179         if (!OI->isReg()) continue;
7180         DefRegs[OI->getReg()] = true;
7181       }
7182
7183       MachineInstrBuilder MIB(*MF, &*II);
7184
7185       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7186         unsigned Reg = SavedRegs[i];
7187         if (Subtarget->isThumb2() &&
7188             !ARM::tGPRRegClass.contains(Reg) &&
7189             !ARM::hGPRRegClass.contains(Reg))
7190           continue;
7191         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7192           continue;
7193         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7194           continue;
7195         if (!DefRegs[Reg])
7196           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7197       }
7198
7199       break;
7200     }
7201   }
7202
7203   // Mark all former landing pads as non-landing pads. The dispatch is the only
7204   // landing pad now.
7205   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7206          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7207     (*I)->setIsLandingPad(false);
7208
7209   // The instruction is gone now.
7210   MI->eraseFromParent();
7211
7212   return MBB;
7213 }
7214
7215 static
7216 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7217   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7218        E = MBB->succ_end(); I != E; ++I)
7219     if (*I != Succ)
7220       return *I;
7221   llvm_unreachable("Expecting a BB with two successors!");
7222 }
7223
7224 /// Return the load opcode for a given load size. If load size >= 8,
7225 /// neon opcode will be returned.
7226 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7227   if (LdSize >= 8)
7228     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7229                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7230   if (IsThumb1)
7231     return LdSize == 4 ? ARM::tLDRi
7232                        : LdSize == 2 ? ARM::tLDRHi
7233                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7234   if (IsThumb2)
7235     return LdSize == 4 ? ARM::t2LDR_POST
7236                        : LdSize == 2 ? ARM::t2LDRH_POST
7237                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7238   return LdSize == 4 ? ARM::LDR_POST_IMM
7239                      : LdSize == 2 ? ARM::LDRH_POST
7240                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7241 }
7242
7243 /// Return the store opcode for a given store size. If store size >= 8,
7244 /// neon opcode will be returned.
7245 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7246   if (StSize >= 8)
7247     return StSize == 16 ? ARM::VST1q32wb_fixed
7248                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7249   if (IsThumb1)
7250     return StSize == 4 ? ARM::tSTRi
7251                        : StSize == 2 ? ARM::tSTRHi
7252                                      : StSize == 1 ? ARM::tSTRBi : 0;
7253   if (IsThumb2)
7254     return StSize == 4 ? ARM::t2STR_POST
7255                        : StSize == 2 ? ARM::t2STRH_POST
7256                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7257   return StSize == 4 ? ARM::STR_POST_IMM
7258                      : StSize == 2 ? ARM::STRH_POST
7259                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7260 }
7261
7262 /// Emit a post-increment load operation with given size. The instructions
7263 /// will be added to BB at Pos.
7264 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7265                        const TargetInstrInfo *TII, DebugLoc dl,
7266                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7267                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7268   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7269   assert(LdOpc != 0 && "Should have a load opcode");
7270   if (LdSize >= 8) {
7271     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7272                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7273                        .addImm(0));
7274   } else if (IsThumb1) {
7275     // load + update AddrIn
7276     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7277                        .addReg(AddrIn).addImm(0));
7278     MachineInstrBuilder MIB =
7279         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7280     MIB = AddDefaultT1CC(MIB);
7281     MIB.addReg(AddrIn).addImm(LdSize);
7282     AddDefaultPred(MIB);
7283   } else if (IsThumb2) {
7284     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7285                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7286                        .addImm(LdSize));
7287   } else { // arm
7288     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7289                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7290                        .addReg(0).addImm(LdSize));
7291   }
7292 }
7293
7294 /// Emit a post-increment store operation with given size. The instructions
7295 /// will be added to BB at Pos.
7296 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7297                        const TargetInstrInfo *TII, DebugLoc dl,
7298                        unsigned StSize, unsigned Data, unsigned AddrIn,
7299                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7300   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7301   assert(StOpc != 0 && "Should have a store opcode");
7302   if (StSize >= 8) {
7303     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7304                        .addReg(AddrIn).addImm(0).addReg(Data));
7305   } else if (IsThumb1) {
7306     // store + update AddrIn
7307     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7308                        .addReg(AddrIn).addImm(0));
7309     MachineInstrBuilder MIB =
7310         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7311     MIB = AddDefaultT1CC(MIB);
7312     MIB.addReg(AddrIn).addImm(StSize);
7313     AddDefaultPred(MIB);
7314   } else if (IsThumb2) {
7315     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7316                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7317   } else { // arm
7318     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7319                        .addReg(Data).addReg(AddrIn).addReg(0)
7320                        .addImm(StSize));
7321   }
7322 }
7323
7324 MachineBasicBlock *
7325 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7326                                    MachineBasicBlock *BB) const {
7327   // This pseudo instruction has 3 operands: dst, src, size
7328   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7329   // Otherwise, we will generate unrolled scalar copies.
7330   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7331   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7332   MachineFunction::iterator It = BB;
7333   ++It;
7334
7335   unsigned dest = MI->getOperand(0).getReg();
7336   unsigned src = MI->getOperand(1).getReg();
7337   unsigned SizeVal = MI->getOperand(2).getImm();
7338   unsigned Align = MI->getOperand(3).getImm();
7339   DebugLoc dl = MI->getDebugLoc();
7340
7341   MachineFunction *MF = BB->getParent();
7342   MachineRegisterInfo &MRI = MF->getRegInfo();
7343   unsigned UnitSize = 0;
7344   const TargetRegisterClass *TRC = 0;
7345   const TargetRegisterClass *VecTRC = 0;
7346
7347   bool IsThumb1 = Subtarget->isThumb1Only();
7348   bool IsThumb2 = Subtarget->isThumb2();
7349
7350   if (Align & 1) {
7351     UnitSize = 1;
7352   } else if (Align & 2) {
7353     UnitSize = 2;
7354   } else {
7355     // Check whether we can use NEON instructions.
7356     if (!MF->getFunction()->getAttributes().
7357           hasAttribute(AttributeSet::FunctionIndex,
7358                        Attribute::NoImplicitFloat) &&
7359         Subtarget->hasNEON()) {
7360       if ((Align % 16 == 0) && SizeVal >= 16)
7361         UnitSize = 16;
7362       else if ((Align % 8 == 0) && SizeVal >= 8)
7363         UnitSize = 8;
7364     }
7365     // Can't use NEON instructions.
7366     if (UnitSize == 0)
7367       UnitSize = 4;
7368   }
7369
7370   // Select the correct opcode and register class for unit size load/store
7371   bool IsNeon = UnitSize >= 8;
7372   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7373                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7374   if (IsNeon)
7375     VecTRC = UnitSize == 16
7376                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7377                  : UnitSize == 8
7378                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7379                        : 0;
7380
7381   unsigned BytesLeft = SizeVal % UnitSize;
7382   unsigned LoopSize = SizeVal - BytesLeft;
7383
7384   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7385     // Use LDR and STR to copy.
7386     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7387     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7388     unsigned srcIn = src;
7389     unsigned destIn = dest;
7390     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7391       unsigned srcOut = MRI.createVirtualRegister(TRC);
7392       unsigned destOut = MRI.createVirtualRegister(TRC);
7393       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7394       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7395                  IsThumb1, IsThumb2);
7396       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7397                  IsThumb1, IsThumb2);
7398       srcIn = srcOut;
7399       destIn = destOut;
7400     }
7401
7402     // Handle the leftover bytes with LDRB and STRB.
7403     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7404     // [destOut] = STRB_POST(scratch, destIn, 1)
7405     for (unsigned i = 0; i < BytesLeft; i++) {
7406       unsigned srcOut = MRI.createVirtualRegister(TRC);
7407       unsigned destOut = MRI.createVirtualRegister(TRC);
7408       unsigned scratch = MRI.createVirtualRegister(TRC);
7409       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7410                  IsThumb1, IsThumb2);
7411       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7412                  IsThumb1, IsThumb2);
7413       srcIn = srcOut;
7414       destIn = destOut;
7415     }
7416     MI->eraseFromParent();   // The instruction is gone now.
7417     return BB;
7418   }
7419
7420   // Expand the pseudo op to a loop.
7421   // thisMBB:
7422   //   ...
7423   //   movw varEnd, # --> with thumb2
7424   //   movt varEnd, #
7425   //   ldrcp varEnd, idx --> without thumb2
7426   //   fallthrough --> loopMBB
7427   // loopMBB:
7428   //   PHI varPhi, varEnd, varLoop
7429   //   PHI srcPhi, src, srcLoop
7430   //   PHI destPhi, dst, destLoop
7431   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7432   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7433   //   subs varLoop, varPhi, #UnitSize
7434   //   bne loopMBB
7435   //   fallthrough --> exitMBB
7436   // exitMBB:
7437   //   epilogue to handle left-over bytes
7438   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7439   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7440   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7441   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7442   MF->insert(It, loopMBB);
7443   MF->insert(It, exitMBB);
7444
7445   // Transfer the remainder of BB and its successor edges to exitMBB.
7446   exitMBB->splice(exitMBB->begin(), BB,
7447                   llvm::next(MachineBasicBlock::iterator(MI)),
7448                   BB->end());
7449   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7450
7451   // Load an immediate to varEnd.
7452   unsigned varEnd = MRI.createVirtualRegister(TRC);
7453   if (IsThumb2) {
7454     unsigned Vtmp = varEnd;
7455     if ((LoopSize & 0xFFFF0000) != 0)
7456       Vtmp = MRI.createVirtualRegister(TRC);
7457     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7458                        .addImm(LoopSize & 0xFFFF));
7459
7460     if ((LoopSize & 0xFFFF0000) != 0)
7461       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7462                          .addReg(Vtmp).addImm(LoopSize >> 16));
7463   } else {
7464     MachineConstantPool *ConstantPool = MF->getConstantPool();
7465     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7466     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7467
7468     // MachineConstantPool wants an explicit alignment.
7469     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7470     if (Align == 0)
7471       Align = getDataLayout()->getTypeAllocSize(C->getType());
7472     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7473
7474     if (IsThumb1)
7475       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7476           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7477     else
7478       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7479           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7480   }
7481   BB->addSuccessor(loopMBB);
7482
7483   // Generate the loop body:
7484   //   varPhi = PHI(varLoop, varEnd)
7485   //   srcPhi = PHI(srcLoop, src)
7486   //   destPhi = PHI(destLoop, dst)
7487   MachineBasicBlock *entryBB = BB;
7488   BB = loopMBB;
7489   unsigned varLoop = MRI.createVirtualRegister(TRC);
7490   unsigned varPhi = MRI.createVirtualRegister(TRC);
7491   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7492   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7493   unsigned destLoop = MRI.createVirtualRegister(TRC);
7494   unsigned destPhi = MRI.createVirtualRegister(TRC);
7495
7496   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7497     .addReg(varLoop).addMBB(loopMBB)
7498     .addReg(varEnd).addMBB(entryBB);
7499   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7500     .addReg(srcLoop).addMBB(loopMBB)
7501     .addReg(src).addMBB(entryBB);
7502   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7503     .addReg(destLoop).addMBB(loopMBB)
7504     .addReg(dest).addMBB(entryBB);
7505
7506   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7507   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7508   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7509   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7510              IsThumb1, IsThumb2);
7511   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7512              IsThumb1, IsThumb2);
7513
7514   // Decrement loop variable by UnitSize.
7515   if (IsThumb1) {
7516     MachineInstrBuilder MIB =
7517         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7518     MIB = AddDefaultT1CC(MIB);
7519     MIB.addReg(varPhi).addImm(UnitSize);
7520     AddDefaultPred(MIB);
7521   } else {
7522     MachineInstrBuilder MIB =
7523         BuildMI(*BB, BB->end(), dl,
7524                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7525     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7526     MIB->getOperand(5).setReg(ARM::CPSR);
7527     MIB->getOperand(5).setIsDef(true);
7528   }
7529   BuildMI(*BB, BB->end(), dl,
7530           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7531       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7532
7533   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7534   BB->addSuccessor(loopMBB);
7535   BB->addSuccessor(exitMBB);
7536
7537   // Add epilogue to handle BytesLeft.
7538   BB = exitMBB;
7539   MachineInstr *StartOfExit = exitMBB->begin();
7540
7541   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7542   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7543   unsigned srcIn = srcLoop;
7544   unsigned destIn = destLoop;
7545   for (unsigned i = 0; i < BytesLeft; i++) {
7546     unsigned srcOut = MRI.createVirtualRegister(TRC);
7547     unsigned destOut = MRI.createVirtualRegister(TRC);
7548     unsigned scratch = MRI.createVirtualRegister(TRC);
7549     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7550                IsThumb1, IsThumb2);
7551     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7552                IsThumb1, IsThumb2);
7553     srcIn = srcOut;
7554     destIn = destOut;
7555   }
7556
7557   MI->eraseFromParent();   // The instruction is gone now.
7558   return BB;
7559 }
7560
7561 MachineBasicBlock *
7562 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7563                                                MachineBasicBlock *BB) const {
7564   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7565   DebugLoc dl = MI->getDebugLoc();
7566   bool isThumb2 = Subtarget->isThumb2();
7567   switch (MI->getOpcode()) {
7568   default: {
7569     MI->dump();
7570     llvm_unreachable("Unexpected instr type to insert");
7571   }
7572   // The Thumb2 pre-indexed stores have the same MI operands, they just
7573   // define them differently in the .td files from the isel patterns, so
7574   // they need pseudos.
7575   case ARM::t2STR_preidx:
7576     MI->setDesc(TII->get(ARM::t2STR_PRE));
7577     return BB;
7578   case ARM::t2STRB_preidx:
7579     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7580     return BB;
7581   case ARM::t2STRH_preidx:
7582     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7583     return BB;
7584
7585   case ARM::STRi_preidx:
7586   case ARM::STRBi_preidx: {
7587     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7588       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7589     // Decode the offset.
7590     unsigned Offset = MI->getOperand(4).getImm();
7591     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7592     Offset = ARM_AM::getAM2Offset(Offset);
7593     if (isSub)
7594       Offset = -Offset;
7595
7596     MachineMemOperand *MMO = *MI->memoperands_begin();
7597     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7598       .addOperand(MI->getOperand(0))  // Rn_wb
7599       .addOperand(MI->getOperand(1))  // Rt
7600       .addOperand(MI->getOperand(2))  // Rn
7601       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7602       .addOperand(MI->getOperand(5))  // pred
7603       .addOperand(MI->getOperand(6))
7604       .addMemOperand(MMO);
7605     MI->eraseFromParent();
7606     return BB;
7607   }
7608   case ARM::STRr_preidx:
7609   case ARM::STRBr_preidx:
7610   case ARM::STRH_preidx: {
7611     unsigned NewOpc;
7612     switch (MI->getOpcode()) {
7613     default: llvm_unreachable("unexpected opcode!");
7614     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7615     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7616     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7617     }
7618     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7619     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7620       MIB.addOperand(MI->getOperand(i));
7621     MI->eraseFromParent();
7622     return BB;
7623   }
7624   case ARM::ATOMIC_LOAD_ADD_I8:
7625      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7626   case ARM::ATOMIC_LOAD_ADD_I16:
7627      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7628   case ARM::ATOMIC_LOAD_ADD_I32:
7629      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7630
7631   case ARM::ATOMIC_LOAD_AND_I8:
7632      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7633   case ARM::ATOMIC_LOAD_AND_I16:
7634      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7635   case ARM::ATOMIC_LOAD_AND_I32:
7636      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7637
7638   case ARM::ATOMIC_LOAD_OR_I8:
7639      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7640   case ARM::ATOMIC_LOAD_OR_I16:
7641      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7642   case ARM::ATOMIC_LOAD_OR_I32:
7643      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7644
7645   case ARM::ATOMIC_LOAD_XOR_I8:
7646      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7647   case ARM::ATOMIC_LOAD_XOR_I16:
7648      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7649   case ARM::ATOMIC_LOAD_XOR_I32:
7650      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7651
7652   case ARM::ATOMIC_LOAD_NAND_I8:
7653      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7654   case ARM::ATOMIC_LOAD_NAND_I16:
7655      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7656   case ARM::ATOMIC_LOAD_NAND_I32:
7657      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7658
7659   case ARM::ATOMIC_LOAD_SUB_I8:
7660      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7661   case ARM::ATOMIC_LOAD_SUB_I16:
7662      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7663   case ARM::ATOMIC_LOAD_SUB_I32:
7664      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7665
7666   case ARM::ATOMIC_LOAD_MIN_I8:
7667      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7668   case ARM::ATOMIC_LOAD_MIN_I16:
7669      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7670   case ARM::ATOMIC_LOAD_MIN_I32:
7671      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7672
7673   case ARM::ATOMIC_LOAD_MAX_I8:
7674      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7675   case ARM::ATOMIC_LOAD_MAX_I16:
7676      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7677   case ARM::ATOMIC_LOAD_MAX_I32:
7678      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7679
7680   case ARM::ATOMIC_LOAD_UMIN_I8:
7681      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7682   case ARM::ATOMIC_LOAD_UMIN_I16:
7683      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7684   case ARM::ATOMIC_LOAD_UMIN_I32:
7685      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7686
7687   case ARM::ATOMIC_LOAD_UMAX_I8:
7688      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7689   case ARM::ATOMIC_LOAD_UMAX_I16:
7690      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7691   case ARM::ATOMIC_LOAD_UMAX_I32:
7692      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7693
7694   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7695   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7696   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7697
7698   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7699   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7700   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7701
7702   case ARM::ATOMIC_LOAD_I64:
7703     return EmitAtomicLoad64(MI, BB);
7704
7705   case ARM::ATOMIC_LOAD_ADD_I64:
7706     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7707                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7708                               /*NeedsCarry*/ true);
7709   case ARM::ATOMIC_LOAD_SUB_I64:
7710     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7711                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7712                               /*NeedsCarry*/ true);
7713   case ARM::ATOMIC_LOAD_OR_I64:
7714     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7715                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7716   case ARM::ATOMIC_LOAD_XOR_I64:
7717     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7718                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7719   case ARM::ATOMIC_LOAD_AND_I64:
7720     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7721                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7722   case ARM::ATOMIC_STORE_I64:
7723   case ARM::ATOMIC_SWAP_I64:
7724     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7725   case ARM::ATOMIC_CMP_SWAP_I64:
7726     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7727                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7728                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7729   case ARM::ATOMIC_LOAD_MIN_I64:
7730     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7731                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7732                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7733                               /*IsMinMax*/ true, ARMCC::LT);
7734   case ARM::ATOMIC_LOAD_MAX_I64:
7735     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7736                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7737                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7738                               /*IsMinMax*/ true, ARMCC::GE);
7739   case ARM::ATOMIC_LOAD_UMIN_I64:
7740     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7741                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7742                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7743                               /*IsMinMax*/ true, ARMCC::LO);
7744   case ARM::ATOMIC_LOAD_UMAX_I64:
7745     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7746                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7747                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7748                               /*IsMinMax*/ true, ARMCC::HS);
7749
7750   case ARM::tMOVCCr_pseudo: {
7751     // To "insert" a SELECT_CC instruction, we actually have to insert the
7752     // diamond control-flow pattern.  The incoming instruction knows the
7753     // destination vreg to set, the condition code register to branch on, the
7754     // true/false values to select between, and a branch opcode to use.
7755     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7756     MachineFunction::iterator It = BB;
7757     ++It;
7758
7759     //  thisMBB:
7760     //  ...
7761     //   TrueVal = ...
7762     //   cmpTY ccX, r1, r2
7763     //   bCC copy1MBB
7764     //   fallthrough --> copy0MBB
7765     MachineBasicBlock *thisMBB  = BB;
7766     MachineFunction *F = BB->getParent();
7767     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7768     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7769     F->insert(It, copy0MBB);
7770     F->insert(It, sinkMBB);
7771
7772     // Transfer the remainder of BB and its successor edges to sinkMBB.
7773     sinkMBB->splice(sinkMBB->begin(), BB,
7774                     llvm::next(MachineBasicBlock::iterator(MI)),
7775                     BB->end());
7776     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7777
7778     BB->addSuccessor(copy0MBB);
7779     BB->addSuccessor(sinkMBB);
7780
7781     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7782       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7783
7784     //  copy0MBB:
7785     //   %FalseValue = ...
7786     //   # fallthrough to sinkMBB
7787     BB = copy0MBB;
7788
7789     // Update machine-CFG edges
7790     BB->addSuccessor(sinkMBB);
7791
7792     //  sinkMBB:
7793     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7794     //  ...
7795     BB = sinkMBB;
7796     BuildMI(*BB, BB->begin(), dl,
7797             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7798       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7799       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7800
7801     MI->eraseFromParent();   // The pseudo instruction is gone now.
7802     return BB;
7803   }
7804
7805   case ARM::BCCi64:
7806   case ARM::BCCZi64: {
7807     // If there is an unconditional branch to the other successor, remove it.
7808     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7809
7810     // Compare both parts that make up the double comparison separately for
7811     // equality.
7812     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7813
7814     unsigned LHS1 = MI->getOperand(1).getReg();
7815     unsigned LHS2 = MI->getOperand(2).getReg();
7816     if (RHSisZero) {
7817       AddDefaultPred(BuildMI(BB, dl,
7818                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7819                      .addReg(LHS1).addImm(0));
7820       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7821         .addReg(LHS2).addImm(0)
7822         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7823     } else {
7824       unsigned RHS1 = MI->getOperand(3).getReg();
7825       unsigned RHS2 = MI->getOperand(4).getReg();
7826       AddDefaultPred(BuildMI(BB, dl,
7827                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7828                      .addReg(LHS1).addReg(RHS1));
7829       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7830         .addReg(LHS2).addReg(RHS2)
7831         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7832     }
7833
7834     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7835     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7836     if (MI->getOperand(0).getImm() == ARMCC::NE)
7837       std::swap(destMBB, exitMBB);
7838
7839     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7840       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7841     if (isThumb2)
7842       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7843     else
7844       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7845
7846     MI->eraseFromParent();   // The pseudo instruction is gone now.
7847     return BB;
7848   }
7849
7850   case ARM::Int_eh_sjlj_setjmp:
7851   case ARM::Int_eh_sjlj_setjmp_nofp:
7852   case ARM::tInt_eh_sjlj_setjmp:
7853   case ARM::t2Int_eh_sjlj_setjmp:
7854   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7855     EmitSjLjDispatchBlock(MI, BB);
7856     return BB;
7857
7858   case ARM::ABS:
7859   case ARM::t2ABS: {
7860     // To insert an ABS instruction, we have to insert the
7861     // diamond control-flow pattern.  The incoming instruction knows the
7862     // source vreg to test against 0, the destination vreg to set,
7863     // the condition code register to branch on, the
7864     // true/false values to select between, and a branch opcode to use.
7865     // It transforms
7866     //     V1 = ABS V0
7867     // into
7868     //     V2 = MOVS V0
7869     //     BCC                      (branch to SinkBB if V0 >= 0)
7870     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7871     //     SinkBB: V1 = PHI(V2, V3)
7872     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7873     MachineFunction::iterator BBI = BB;
7874     ++BBI;
7875     MachineFunction *Fn = BB->getParent();
7876     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7877     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7878     Fn->insert(BBI, RSBBB);
7879     Fn->insert(BBI, SinkBB);
7880
7881     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7882     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7883     bool isThumb2 = Subtarget->isThumb2();
7884     MachineRegisterInfo &MRI = Fn->getRegInfo();
7885     // In Thumb mode S must not be specified if source register is the SP or
7886     // PC and if destination register is the SP, so restrict register class
7887     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7888       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7889       (const TargetRegisterClass*)&ARM::GPRRegClass);
7890
7891     // Transfer the remainder of BB and its successor edges to sinkMBB.
7892     SinkBB->splice(SinkBB->begin(), BB,
7893       llvm::next(MachineBasicBlock::iterator(MI)),
7894       BB->end());
7895     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7896
7897     BB->addSuccessor(RSBBB);
7898     BB->addSuccessor(SinkBB);
7899
7900     // fall through to SinkMBB
7901     RSBBB->addSuccessor(SinkBB);
7902
7903     // insert a cmp at the end of BB
7904     AddDefaultPred(BuildMI(BB, dl,
7905                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7906                    .addReg(ABSSrcReg).addImm(0));
7907
7908     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7909     BuildMI(BB, dl,
7910       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7911       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7912
7913     // insert rsbri in RSBBB
7914     // Note: BCC and rsbri will be converted into predicated rsbmi
7915     // by if-conversion pass
7916     BuildMI(*RSBBB, RSBBB->begin(), dl,
7917       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7918       .addReg(ABSSrcReg, RegState::Kill)
7919       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7920
7921     // insert PHI in SinkBB,
7922     // reuse ABSDstReg to not change uses of ABS instruction
7923     BuildMI(*SinkBB, SinkBB->begin(), dl,
7924       TII->get(ARM::PHI), ABSDstReg)
7925       .addReg(NewRsbDstReg).addMBB(RSBBB)
7926       .addReg(ABSSrcReg).addMBB(BB);
7927
7928     // remove ABS instruction
7929     MI->eraseFromParent();
7930
7931     // return last added BB
7932     return SinkBB;
7933   }
7934   case ARM::COPY_STRUCT_BYVAL_I32:
7935     ++NumLoopByVals;
7936     return EmitStructByval(MI, BB);
7937   }
7938 }
7939
7940 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7941                                                       SDNode *Node) const {
7942   if (!MI->hasPostISelHook()) {
7943     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7944            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7945     return;
7946   }
7947
7948   const MCInstrDesc *MCID = &MI->getDesc();
7949   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7950   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7951   // operand is still set to noreg. If needed, set the optional operand's
7952   // register to CPSR, and remove the redundant implicit def.
7953   //
7954   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7955
7956   // Rename pseudo opcodes.
7957   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7958   if (NewOpc) {
7959     const ARMBaseInstrInfo *TII =
7960       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7961     MCID = &TII->get(NewOpc);
7962
7963     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7964            "converted opcode should be the same except for cc_out");
7965
7966     MI->setDesc(*MCID);
7967
7968     // Add the optional cc_out operand
7969     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7970   }
7971   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7972
7973   // Any ARM instruction that sets the 's' bit should specify an optional
7974   // "cc_out" operand in the last operand position.
7975   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7976     assert(!NewOpc && "Optional cc_out operand required");
7977     return;
7978   }
7979   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7980   // since we already have an optional CPSR def.
7981   bool definesCPSR = false;
7982   bool deadCPSR = false;
7983   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7984        i != e; ++i) {
7985     const MachineOperand &MO = MI->getOperand(i);
7986     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7987       definesCPSR = true;
7988       if (MO.isDead())
7989         deadCPSR = true;
7990       MI->RemoveOperand(i);
7991       break;
7992     }
7993   }
7994   if (!definesCPSR) {
7995     assert(!NewOpc && "Optional cc_out operand required");
7996     return;
7997   }
7998   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7999   if (deadCPSR) {
8000     assert(!MI->getOperand(ccOutIdx).getReg() &&
8001            "expect uninitialized optional cc_out operand");
8002     return;
8003   }
8004
8005   // If this instruction was defined with an optional CPSR def and its dag node
8006   // had a live implicit CPSR def, then activate the optional CPSR def.
8007   MachineOperand &MO = MI->getOperand(ccOutIdx);
8008   MO.setReg(ARM::CPSR);
8009   MO.setIsDef(true);
8010 }
8011
8012 //===----------------------------------------------------------------------===//
8013 //                           ARM Optimization Hooks
8014 //===----------------------------------------------------------------------===//
8015
8016 // Helper function that checks if N is a null or all ones constant.
8017 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8018   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8019   if (!C)
8020     return false;
8021   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8022 }
8023
8024 // Return true if N is conditionally 0 or all ones.
8025 // Detects these expressions where cc is an i1 value:
8026 //
8027 //   (select cc 0, y)   [AllOnes=0]
8028 //   (select cc y, 0)   [AllOnes=0]
8029 //   (zext cc)          [AllOnes=0]
8030 //   (sext cc)          [AllOnes=0/1]
8031 //   (select cc -1, y)  [AllOnes=1]
8032 //   (select cc y, -1)  [AllOnes=1]
8033 //
8034 // Invert is set when N is the null/all ones constant when CC is false.
8035 // OtherOp is set to the alternative value of N.
8036 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8037                                        SDValue &CC, bool &Invert,
8038                                        SDValue &OtherOp,
8039                                        SelectionDAG &DAG) {
8040   switch (N->getOpcode()) {
8041   default: return false;
8042   case ISD::SELECT: {
8043     CC = N->getOperand(0);
8044     SDValue N1 = N->getOperand(1);
8045     SDValue N2 = N->getOperand(2);
8046     if (isZeroOrAllOnes(N1, AllOnes)) {
8047       Invert = false;
8048       OtherOp = N2;
8049       return true;
8050     }
8051     if (isZeroOrAllOnes(N2, AllOnes)) {
8052       Invert = true;
8053       OtherOp = N1;
8054       return true;
8055     }
8056     return false;
8057   }
8058   case ISD::ZERO_EXTEND:
8059     // (zext cc) can never be the all ones value.
8060     if (AllOnes)
8061       return false;
8062     // Fall through.
8063   case ISD::SIGN_EXTEND: {
8064     EVT VT = N->getValueType(0);
8065     CC = N->getOperand(0);
8066     if (CC.getValueType() != MVT::i1)
8067       return false;
8068     Invert = !AllOnes;
8069     if (AllOnes)
8070       // When looking for an AllOnes constant, N is an sext, and the 'other'
8071       // value is 0.
8072       OtherOp = DAG.getConstant(0, VT);
8073     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8074       // When looking for a 0 constant, N can be zext or sext.
8075       OtherOp = DAG.getConstant(1, VT);
8076     else
8077       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8078     return true;
8079   }
8080   }
8081 }
8082
8083 // Combine a constant select operand into its use:
8084 //
8085 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8086 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8087 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8088 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8089 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8090 //
8091 // The transform is rejected if the select doesn't have a constant operand that
8092 // is null, or all ones when AllOnes is set.
8093 //
8094 // Also recognize sext/zext from i1:
8095 //
8096 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8097 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8098 //
8099 // These transformations eventually create predicated instructions.
8100 //
8101 // @param N       The node to transform.
8102 // @param Slct    The N operand that is a select.
8103 // @param OtherOp The other N operand (x above).
8104 // @param DCI     Context.
8105 // @param AllOnes Require the select constant to be all ones instead of null.
8106 // @returns The new node, or SDValue() on failure.
8107 static
8108 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8109                             TargetLowering::DAGCombinerInfo &DCI,
8110                             bool AllOnes = false) {
8111   SelectionDAG &DAG = DCI.DAG;
8112   EVT VT = N->getValueType(0);
8113   SDValue NonConstantVal;
8114   SDValue CCOp;
8115   bool SwapSelectOps;
8116   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8117                                   NonConstantVal, DAG))
8118     return SDValue();
8119
8120   // Slct is now know to be the desired identity constant when CC is true.
8121   SDValue TrueVal = OtherOp;
8122   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8123                                  OtherOp, NonConstantVal);
8124   // Unless SwapSelectOps says CC should be false.
8125   if (SwapSelectOps)
8126     std::swap(TrueVal, FalseVal);
8127
8128   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8129                      CCOp, TrueVal, FalseVal);
8130 }
8131
8132 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8133 static
8134 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8135                                        TargetLowering::DAGCombinerInfo &DCI) {
8136   SDValue N0 = N->getOperand(0);
8137   SDValue N1 = N->getOperand(1);
8138   if (N0.getNode()->hasOneUse()) {
8139     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8140     if (Result.getNode())
8141       return Result;
8142   }
8143   if (N1.getNode()->hasOneUse()) {
8144     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8145     if (Result.getNode())
8146       return Result;
8147   }
8148   return SDValue();
8149 }
8150
8151 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8152 // (only after legalization).
8153 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8154                                  TargetLowering::DAGCombinerInfo &DCI,
8155                                  const ARMSubtarget *Subtarget) {
8156
8157   // Only perform optimization if after legalize, and if NEON is available. We
8158   // also expected both operands to be BUILD_VECTORs.
8159   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8160       || N0.getOpcode() != ISD::BUILD_VECTOR
8161       || N1.getOpcode() != ISD::BUILD_VECTOR)
8162     return SDValue();
8163
8164   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8165   EVT VT = N->getValueType(0);
8166   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8167     return SDValue();
8168
8169   // Check that the vector operands are of the right form.
8170   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8171   // operands, where N is the size of the formed vector.
8172   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8173   // index such that we have a pair wise add pattern.
8174
8175   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8176   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8177     return SDValue();
8178   SDValue Vec = N0->getOperand(0)->getOperand(0);
8179   SDNode *V = Vec.getNode();
8180   unsigned nextIndex = 0;
8181
8182   // For each operands to the ADD which are BUILD_VECTORs,
8183   // check to see if each of their operands are an EXTRACT_VECTOR with
8184   // the same vector and appropriate index.
8185   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8186     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8187         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8188
8189       SDValue ExtVec0 = N0->getOperand(i);
8190       SDValue ExtVec1 = N1->getOperand(i);
8191
8192       // First operand is the vector, verify its the same.
8193       if (V != ExtVec0->getOperand(0).getNode() ||
8194           V != ExtVec1->getOperand(0).getNode())
8195         return SDValue();
8196
8197       // Second is the constant, verify its correct.
8198       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8199       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8200
8201       // For the constant, we want to see all the even or all the odd.
8202       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8203           || C1->getZExtValue() != nextIndex+1)
8204         return SDValue();
8205
8206       // Increment index.
8207       nextIndex+=2;
8208     } else
8209       return SDValue();
8210   }
8211
8212   // Create VPADDL node.
8213   SelectionDAG &DAG = DCI.DAG;
8214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8215
8216   // Build operand list.
8217   SmallVector<SDValue, 8> Ops;
8218   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8219                                 TLI.getPointerTy()));
8220
8221   // Input is the vector.
8222   Ops.push_back(Vec);
8223
8224   // Get widened type and narrowed type.
8225   MVT widenType;
8226   unsigned numElem = VT.getVectorNumElements();
8227   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8228     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8229     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8230     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8231     default:
8232       llvm_unreachable("Invalid vector element type for padd optimization.");
8233   }
8234
8235   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8236                             widenType, &Ops[0], Ops.size());
8237   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8238 }
8239
8240 static SDValue findMUL_LOHI(SDValue V) {
8241   if (V->getOpcode() == ISD::UMUL_LOHI ||
8242       V->getOpcode() == ISD::SMUL_LOHI)
8243     return V;
8244   return SDValue();
8245 }
8246
8247 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8248                                      TargetLowering::DAGCombinerInfo &DCI,
8249                                      const ARMSubtarget *Subtarget) {
8250
8251   if (Subtarget->isThumb1Only()) return SDValue();
8252
8253   // Only perform the checks after legalize when the pattern is available.
8254   if (DCI.isBeforeLegalize()) return SDValue();
8255
8256   // Look for multiply add opportunities.
8257   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8258   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8259   // a glue link from the first add to the second add.
8260   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8261   // a S/UMLAL instruction.
8262   //          loAdd   UMUL_LOHI
8263   //            \    / :lo    \ :hi
8264   //             \  /          \          [no multiline comment]
8265   //              ADDC         |  hiAdd
8266   //                 \ :glue  /  /
8267   //                  \      /  /
8268   //                    ADDE
8269   //
8270   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8271   SDValue AddcOp0 = AddcNode->getOperand(0);
8272   SDValue AddcOp1 = AddcNode->getOperand(1);
8273
8274   // Check if the two operands are from the same mul_lohi node.
8275   if (AddcOp0.getNode() == AddcOp1.getNode())
8276     return SDValue();
8277
8278   assert(AddcNode->getNumValues() == 2 &&
8279          AddcNode->getValueType(0) == MVT::i32 &&
8280          "Expect ADDC with two result values. First: i32");
8281
8282   // Check that we have a glued ADDC node.
8283   if (AddcNode->getValueType(1) != MVT::Glue)
8284     return SDValue();
8285
8286   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8287   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8288       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8289       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8290       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8291     return SDValue();
8292
8293   // Look for the glued ADDE.
8294   SDNode* AddeNode = AddcNode->getGluedUser();
8295   if (AddeNode == NULL)
8296     return SDValue();
8297
8298   // Make sure it is really an ADDE.
8299   if (AddeNode->getOpcode() != ISD::ADDE)
8300     return SDValue();
8301
8302   assert(AddeNode->getNumOperands() == 3 &&
8303          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8304          "ADDE node has the wrong inputs");
8305
8306   // Check for the triangle shape.
8307   SDValue AddeOp0 = AddeNode->getOperand(0);
8308   SDValue AddeOp1 = AddeNode->getOperand(1);
8309
8310   // Make sure that the ADDE operands are not coming from the same node.
8311   if (AddeOp0.getNode() == AddeOp1.getNode())
8312     return SDValue();
8313
8314   // Find the MUL_LOHI node walking up ADDE's operands.
8315   bool IsLeftOperandMUL = false;
8316   SDValue MULOp = findMUL_LOHI(AddeOp0);
8317   if (MULOp == SDValue())
8318    MULOp = findMUL_LOHI(AddeOp1);
8319   else
8320     IsLeftOperandMUL = true;
8321   if (MULOp == SDValue())
8322      return SDValue();
8323
8324   // Figure out the right opcode.
8325   unsigned Opc = MULOp->getOpcode();
8326   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8327
8328   // Figure out the high and low input values to the MLAL node.
8329   SDValue* HiMul = &MULOp;
8330   SDValue* HiAdd = NULL;
8331   SDValue* LoMul = NULL;
8332   SDValue* LowAdd = NULL;
8333
8334   if (IsLeftOperandMUL)
8335     HiAdd = &AddeOp1;
8336   else
8337     HiAdd = &AddeOp0;
8338
8339
8340   if (AddcOp0->getOpcode() == Opc) {
8341     LoMul = &AddcOp0;
8342     LowAdd = &AddcOp1;
8343   }
8344   if (AddcOp1->getOpcode() == Opc) {
8345     LoMul = &AddcOp1;
8346     LowAdd = &AddcOp0;
8347   }
8348
8349   if (LoMul == NULL)
8350     return SDValue();
8351
8352   if (LoMul->getNode() != HiMul->getNode())
8353     return SDValue();
8354
8355   // Create the merged node.
8356   SelectionDAG &DAG = DCI.DAG;
8357
8358   // Build operand list.
8359   SmallVector<SDValue, 8> Ops;
8360   Ops.push_back(LoMul->getOperand(0));
8361   Ops.push_back(LoMul->getOperand(1));
8362   Ops.push_back(*LowAdd);
8363   Ops.push_back(*HiAdd);
8364
8365   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8366                                  DAG.getVTList(MVT::i32, MVT::i32),
8367                                  &Ops[0], Ops.size());
8368
8369   // Replace the ADDs' nodes uses by the MLA node's values.
8370   SDValue HiMLALResult(MLALNode.getNode(), 1);
8371   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8372
8373   SDValue LoMLALResult(MLALNode.getNode(), 0);
8374   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8375
8376   // Return original node to notify the driver to stop replacing.
8377   SDValue resNode(AddcNode, 0);
8378   return resNode;
8379 }
8380
8381 /// PerformADDCCombine - Target-specific dag combine transform from
8382 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8383 static SDValue PerformADDCCombine(SDNode *N,
8384                                  TargetLowering::DAGCombinerInfo &DCI,
8385                                  const ARMSubtarget *Subtarget) {
8386
8387   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8388
8389 }
8390
8391 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8392 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8393 /// called with the default operands, and if that fails, with commuted
8394 /// operands.
8395 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8396                                           TargetLowering::DAGCombinerInfo &DCI,
8397                                           const ARMSubtarget *Subtarget){
8398
8399   // Attempt to create vpaddl for this add.
8400   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8401   if (Result.getNode())
8402     return Result;
8403
8404   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8405   if (N0.getNode()->hasOneUse()) {
8406     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8407     if (Result.getNode()) return Result;
8408   }
8409   return SDValue();
8410 }
8411
8412 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8413 ///
8414 static SDValue PerformADDCombine(SDNode *N,
8415                                  TargetLowering::DAGCombinerInfo &DCI,
8416                                  const ARMSubtarget *Subtarget) {
8417   SDValue N0 = N->getOperand(0);
8418   SDValue N1 = N->getOperand(1);
8419
8420   // First try with the default operand order.
8421   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8422   if (Result.getNode())
8423     return Result;
8424
8425   // If that didn't work, try again with the operands commuted.
8426   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8427 }
8428
8429 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8430 ///
8431 static SDValue PerformSUBCombine(SDNode *N,
8432                                  TargetLowering::DAGCombinerInfo &DCI) {
8433   SDValue N0 = N->getOperand(0);
8434   SDValue N1 = N->getOperand(1);
8435
8436   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8437   if (N1.getNode()->hasOneUse()) {
8438     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8439     if (Result.getNode()) return Result;
8440   }
8441
8442   return SDValue();
8443 }
8444
8445 /// PerformVMULCombine
8446 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8447 /// special multiplier accumulator forwarding.
8448 ///   vmul d3, d0, d2
8449 ///   vmla d3, d1, d2
8450 /// is faster than
8451 ///   vadd d3, d0, d1
8452 ///   vmul d3, d3, d2
8453 //  However, for (A + B) * (A + B),
8454 //    vadd d2, d0, d1
8455 //    vmul d3, d0, d2
8456 //    vmla d3, d1, d2
8457 //  is slower than
8458 //    vadd d2, d0, d1
8459 //    vmul d3, d2, d2
8460 static SDValue PerformVMULCombine(SDNode *N,
8461                                   TargetLowering::DAGCombinerInfo &DCI,
8462                                   const ARMSubtarget *Subtarget) {
8463   if (!Subtarget->hasVMLxForwarding())
8464     return SDValue();
8465
8466   SelectionDAG &DAG = DCI.DAG;
8467   SDValue N0 = N->getOperand(0);
8468   SDValue N1 = N->getOperand(1);
8469   unsigned Opcode = N0.getOpcode();
8470   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8471       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8472     Opcode = N1.getOpcode();
8473     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8474         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8475       return SDValue();
8476     std::swap(N0, N1);
8477   }
8478
8479   if (N0 == N1)
8480     return SDValue();
8481
8482   EVT VT = N->getValueType(0);
8483   SDLoc DL(N);
8484   SDValue N00 = N0->getOperand(0);
8485   SDValue N01 = N0->getOperand(1);
8486   return DAG.getNode(Opcode, DL, VT,
8487                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8488                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8489 }
8490
8491 static SDValue PerformMULCombine(SDNode *N,
8492                                  TargetLowering::DAGCombinerInfo &DCI,
8493                                  const ARMSubtarget *Subtarget) {
8494   SelectionDAG &DAG = DCI.DAG;
8495
8496   if (Subtarget->isThumb1Only())
8497     return SDValue();
8498
8499   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8500     return SDValue();
8501
8502   EVT VT = N->getValueType(0);
8503   if (VT.is64BitVector() || VT.is128BitVector())
8504     return PerformVMULCombine(N, DCI, Subtarget);
8505   if (VT != MVT::i32)
8506     return SDValue();
8507
8508   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8509   if (!C)
8510     return SDValue();
8511
8512   int64_t MulAmt = C->getSExtValue();
8513   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8514
8515   ShiftAmt = ShiftAmt & (32 - 1);
8516   SDValue V = N->getOperand(0);
8517   SDLoc DL(N);
8518
8519   SDValue Res;
8520   MulAmt >>= ShiftAmt;
8521
8522   if (MulAmt >= 0) {
8523     if (isPowerOf2_32(MulAmt - 1)) {
8524       // (mul x, 2^N + 1) => (add (shl x, N), x)
8525       Res = DAG.getNode(ISD::ADD, DL, VT,
8526                         V,
8527                         DAG.getNode(ISD::SHL, DL, VT,
8528                                     V,
8529                                     DAG.getConstant(Log2_32(MulAmt - 1),
8530                                                     MVT::i32)));
8531     } else if (isPowerOf2_32(MulAmt + 1)) {
8532       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8533       Res = DAG.getNode(ISD::SUB, DL, VT,
8534                         DAG.getNode(ISD::SHL, DL, VT,
8535                                     V,
8536                                     DAG.getConstant(Log2_32(MulAmt + 1),
8537                                                     MVT::i32)),
8538                         V);
8539     } else
8540       return SDValue();
8541   } else {
8542     uint64_t MulAmtAbs = -MulAmt;
8543     if (isPowerOf2_32(MulAmtAbs + 1)) {
8544       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8545       Res = DAG.getNode(ISD::SUB, DL, VT,
8546                         V,
8547                         DAG.getNode(ISD::SHL, DL, VT,
8548                                     V,
8549                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8550                                                     MVT::i32)));
8551     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8552       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8553       Res = DAG.getNode(ISD::ADD, DL, VT,
8554                         V,
8555                         DAG.getNode(ISD::SHL, DL, VT,
8556                                     V,
8557                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8558                                                     MVT::i32)));
8559       Res = DAG.getNode(ISD::SUB, DL, VT,
8560                         DAG.getConstant(0, MVT::i32),Res);
8561
8562     } else
8563       return SDValue();
8564   }
8565
8566   if (ShiftAmt != 0)
8567     Res = DAG.getNode(ISD::SHL, DL, VT,
8568                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8569
8570   // Do not add new nodes to DAG combiner worklist.
8571   DCI.CombineTo(N, Res, false);
8572   return SDValue();
8573 }
8574
8575 static SDValue PerformANDCombine(SDNode *N,
8576                                  TargetLowering::DAGCombinerInfo &DCI,
8577                                  const ARMSubtarget *Subtarget) {
8578
8579   // Attempt to use immediate-form VBIC
8580   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8581   SDLoc dl(N);
8582   EVT VT = N->getValueType(0);
8583   SelectionDAG &DAG = DCI.DAG;
8584
8585   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8586     return SDValue();
8587
8588   APInt SplatBits, SplatUndef;
8589   unsigned SplatBitSize;
8590   bool HasAnyUndefs;
8591   if (BVN &&
8592       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8593     if (SplatBitSize <= 64) {
8594       EVT VbicVT;
8595       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8596                                       SplatUndef.getZExtValue(), SplatBitSize,
8597                                       DAG, VbicVT, VT.is128BitVector(),
8598                                       OtherModImm);
8599       if (Val.getNode()) {
8600         SDValue Input =
8601           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8602         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8603         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8604       }
8605     }
8606   }
8607
8608   if (!Subtarget->isThumb1Only()) {
8609     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8610     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8611     if (Result.getNode())
8612       return Result;
8613   }
8614
8615   return SDValue();
8616 }
8617
8618 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8619 static SDValue PerformORCombine(SDNode *N,
8620                                 TargetLowering::DAGCombinerInfo &DCI,
8621                                 const ARMSubtarget *Subtarget) {
8622   // Attempt to use immediate-form VORR
8623   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8624   SDLoc dl(N);
8625   EVT VT = N->getValueType(0);
8626   SelectionDAG &DAG = DCI.DAG;
8627
8628   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8629     return SDValue();
8630
8631   APInt SplatBits, SplatUndef;
8632   unsigned SplatBitSize;
8633   bool HasAnyUndefs;
8634   if (BVN && Subtarget->hasNEON() &&
8635       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8636     if (SplatBitSize <= 64) {
8637       EVT VorrVT;
8638       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8639                                       SplatUndef.getZExtValue(), SplatBitSize,
8640                                       DAG, VorrVT, VT.is128BitVector(),
8641                                       OtherModImm);
8642       if (Val.getNode()) {
8643         SDValue Input =
8644           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8645         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8646         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8647       }
8648     }
8649   }
8650
8651   if (!Subtarget->isThumb1Only()) {
8652     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8653     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8654     if (Result.getNode())
8655       return Result;
8656   }
8657
8658   // The code below optimizes (or (and X, Y), Z).
8659   // The AND operand needs to have a single user to make these optimizations
8660   // profitable.
8661   SDValue N0 = N->getOperand(0);
8662   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8663     return SDValue();
8664   SDValue N1 = N->getOperand(1);
8665
8666   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8667   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8668       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8669     APInt SplatUndef;
8670     unsigned SplatBitSize;
8671     bool HasAnyUndefs;
8672
8673     APInt SplatBits0, SplatBits1;
8674     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8675     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8676     // Ensure that the second operand of both ands are constants
8677     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8678                                       HasAnyUndefs) && !HasAnyUndefs) {
8679         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8680                                           HasAnyUndefs) && !HasAnyUndefs) {
8681             // Ensure that the bit width of the constants are the same and that
8682             // the splat arguments are logical inverses as per the pattern we
8683             // are trying to simplify.
8684             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8685                 SplatBits0 == ~SplatBits1) {
8686                 // Canonicalize the vector type to make instruction selection
8687                 // simpler.
8688                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8689                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8690                                              N0->getOperand(1),
8691                                              N0->getOperand(0),
8692                                              N1->getOperand(0));
8693                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8694             }
8695         }
8696     }
8697   }
8698
8699   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8700   // reasonable.
8701
8702   // BFI is only available on V6T2+
8703   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8704     return SDValue();
8705
8706   SDLoc DL(N);
8707   // 1) or (and A, mask), val => ARMbfi A, val, mask
8708   //      iff (val & mask) == val
8709   //
8710   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8711   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8712   //          && mask == ~mask2
8713   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8714   //          && ~mask == mask2
8715   //  (i.e., copy a bitfield value into another bitfield of the same width)
8716
8717   if (VT != MVT::i32)
8718     return SDValue();
8719
8720   SDValue N00 = N0.getOperand(0);
8721
8722   // The value and the mask need to be constants so we can verify this is
8723   // actually a bitfield set. If the mask is 0xffff, we can do better
8724   // via a movt instruction, so don't use BFI in that case.
8725   SDValue MaskOp = N0.getOperand(1);
8726   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8727   if (!MaskC)
8728     return SDValue();
8729   unsigned Mask = MaskC->getZExtValue();
8730   if (Mask == 0xffff)
8731     return SDValue();
8732   SDValue Res;
8733   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8735   if (N1C) {
8736     unsigned Val = N1C->getZExtValue();
8737     if ((Val & ~Mask) != Val)
8738       return SDValue();
8739
8740     if (ARM::isBitFieldInvertedMask(Mask)) {
8741       Val >>= countTrailingZeros(~Mask);
8742
8743       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8744                         DAG.getConstant(Val, MVT::i32),
8745                         DAG.getConstant(Mask, MVT::i32));
8746
8747       // Do not add new nodes to DAG combiner worklist.
8748       DCI.CombineTo(N, Res, false);
8749       return SDValue();
8750     }
8751   } else if (N1.getOpcode() == ISD::AND) {
8752     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8753     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8754     if (!N11C)
8755       return SDValue();
8756     unsigned Mask2 = N11C->getZExtValue();
8757
8758     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8759     // as is to match.
8760     if (ARM::isBitFieldInvertedMask(Mask) &&
8761         (Mask == ~Mask2)) {
8762       // The pack halfword instruction works better for masks that fit it,
8763       // so use that when it's available.
8764       if (Subtarget->hasT2ExtractPack() &&
8765           (Mask == 0xffff || Mask == 0xffff0000))
8766         return SDValue();
8767       // 2a
8768       unsigned amt = countTrailingZeros(Mask2);
8769       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8770                         DAG.getConstant(amt, MVT::i32));
8771       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8772                         DAG.getConstant(Mask, MVT::i32));
8773       // Do not add new nodes to DAG combiner worklist.
8774       DCI.CombineTo(N, Res, false);
8775       return SDValue();
8776     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8777                (~Mask == Mask2)) {
8778       // The pack halfword instruction works better for masks that fit it,
8779       // so use that when it's available.
8780       if (Subtarget->hasT2ExtractPack() &&
8781           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8782         return SDValue();
8783       // 2b
8784       unsigned lsb = countTrailingZeros(Mask);
8785       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8786                         DAG.getConstant(lsb, MVT::i32));
8787       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8788                         DAG.getConstant(Mask2, MVT::i32));
8789       // Do not add new nodes to DAG combiner worklist.
8790       DCI.CombineTo(N, Res, false);
8791       return SDValue();
8792     }
8793   }
8794
8795   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8796       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8797       ARM::isBitFieldInvertedMask(~Mask)) {
8798     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8799     // where lsb(mask) == #shamt and masked bits of B are known zero.
8800     SDValue ShAmt = N00.getOperand(1);
8801     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8802     unsigned LSB = countTrailingZeros(Mask);
8803     if (ShAmtC != LSB)
8804       return SDValue();
8805
8806     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8807                       DAG.getConstant(~Mask, MVT::i32));
8808
8809     // Do not add new nodes to DAG combiner worklist.
8810     DCI.CombineTo(N, Res, false);
8811   }
8812
8813   return SDValue();
8814 }
8815
8816 static SDValue PerformXORCombine(SDNode *N,
8817                                  TargetLowering::DAGCombinerInfo &DCI,
8818                                  const ARMSubtarget *Subtarget) {
8819   EVT VT = N->getValueType(0);
8820   SelectionDAG &DAG = DCI.DAG;
8821
8822   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8823     return SDValue();
8824
8825   if (!Subtarget->isThumb1Only()) {
8826     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8827     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8828     if (Result.getNode())
8829       return Result;
8830   }
8831
8832   return SDValue();
8833 }
8834
8835 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8836 /// the bits being cleared by the AND are not demanded by the BFI.
8837 static SDValue PerformBFICombine(SDNode *N,
8838                                  TargetLowering::DAGCombinerInfo &DCI) {
8839   SDValue N1 = N->getOperand(1);
8840   if (N1.getOpcode() == ISD::AND) {
8841     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8842     if (!N11C)
8843       return SDValue();
8844     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8845     unsigned LSB = countTrailingZeros(~InvMask);
8846     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8847     unsigned Mask = (1 << Width)-1;
8848     unsigned Mask2 = N11C->getZExtValue();
8849     if ((Mask & (~Mask2)) == 0)
8850       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8851                              N->getOperand(0), N1.getOperand(0),
8852                              N->getOperand(2));
8853   }
8854   return SDValue();
8855 }
8856
8857 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8858 /// ARMISD::VMOVRRD.
8859 static SDValue PerformVMOVRRDCombine(SDNode *N,
8860                                      TargetLowering::DAGCombinerInfo &DCI) {
8861   // vmovrrd(vmovdrr x, y) -> x,y
8862   SDValue InDouble = N->getOperand(0);
8863   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8864     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8865
8866   // vmovrrd(load f64) -> (load i32), (load i32)
8867   SDNode *InNode = InDouble.getNode();
8868   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8869       InNode->getValueType(0) == MVT::f64 &&
8870       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8871       !cast<LoadSDNode>(InNode)->isVolatile()) {
8872     // TODO: Should this be done for non-FrameIndex operands?
8873     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8874
8875     SelectionDAG &DAG = DCI.DAG;
8876     SDLoc DL(LD);
8877     SDValue BasePtr = LD->getBasePtr();
8878     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8879                                  LD->getPointerInfo(), LD->isVolatile(),
8880                                  LD->isNonTemporal(), LD->isInvariant(),
8881                                  LD->getAlignment());
8882
8883     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8884                                     DAG.getConstant(4, MVT::i32));
8885     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8886                                  LD->getPointerInfo(), LD->isVolatile(),
8887                                  LD->isNonTemporal(), LD->isInvariant(),
8888                                  std::min(4U, LD->getAlignment() / 2));
8889
8890     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8891     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8892     DCI.RemoveFromWorklist(LD);
8893     DAG.DeleteNode(LD);
8894     return Result;
8895   }
8896
8897   return SDValue();
8898 }
8899
8900 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8901 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8902 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8903   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8904   SDValue Op0 = N->getOperand(0);
8905   SDValue Op1 = N->getOperand(1);
8906   if (Op0.getOpcode() == ISD::BITCAST)
8907     Op0 = Op0.getOperand(0);
8908   if (Op1.getOpcode() == ISD::BITCAST)
8909     Op1 = Op1.getOperand(0);
8910   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8911       Op0.getNode() == Op1.getNode() &&
8912       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8913     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8914                        N->getValueType(0), Op0.getOperand(0));
8915   return SDValue();
8916 }
8917
8918 /// PerformSTORECombine - Target-specific dag combine xforms for
8919 /// ISD::STORE.
8920 static SDValue PerformSTORECombine(SDNode *N,
8921                                    TargetLowering::DAGCombinerInfo &DCI) {
8922   StoreSDNode *St = cast<StoreSDNode>(N);
8923   if (St->isVolatile())
8924     return SDValue();
8925
8926   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8927   // pack all of the elements in one place.  Next, store to memory in fewer
8928   // chunks.
8929   SDValue StVal = St->getValue();
8930   EVT VT = StVal.getValueType();
8931   if (St->isTruncatingStore() && VT.isVector()) {
8932     SelectionDAG &DAG = DCI.DAG;
8933     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8934     EVT StVT = St->getMemoryVT();
8935     unsigned NumElems = VT.getVectorNumElements();
8936     assert(StVT != VT && "Cannot truncate to the same type");
8937     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8938     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8939
8940     // From, To sizes and ElemCount must be pow of two
8941     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8942
8943     // We are going to use the original vector elt for storing.
8944     // Accumulated smaller vector elements must be a multiple of the store size.
8945     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8946
8947     unsigned SizeRatio  = FromEltSz / ToEltSz;
8948     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8949
8950     // Create a type on which we perform the shuffle.
8951     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8952                                      NumElems*SizeRatio);
8953     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8954
8955     SDLoc DL(St);
8956     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8957     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8958     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8959
8960     // Can't shuffle using an illegal type.
8961     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8962
8963     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8964                                 DAG.getUNDEF(WideVec.getValueType()),
8965                                 ShuffleVec.data());
8966     // At this point all of the data is stored at the bottom of the
8967     // register. We now need to save it to mem.
8968
8969     // Find the largest store unit
8970     MVT StoreType = MVT::i8;
8971     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8972          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8973       MVT Tp = (MVT::SimpleValueType)tp;
8974       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8975         StoreType = Tp;
8976     }
8977     // Didn't find a legal store type.
8978     if (!TLI.isTypeLegal(StoreType))
8979       return SDValue();
8980
8981     // Bitcast the original vector into a vector of store-size units
8982     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8983             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8984     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8985     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8986     SmallVector<SDValue, 8> Chains;
8987     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8988                                         TLI.getPointerTy());
8989     SDValue BasePtr = St->getBasePtr();
8990
8991     // Perform one or more big stores into memory.
8992     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8993     for (unsigned I = 0; I < E; I++) {
8994       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8995                                    StoreType, ShuffWide,
8996                                    DAG.getIntPtrConstant(I));
8997       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8998                                 St->getPointerInfo(), St->isVolatile(),
8999                                 St->isNonTemporal(), St->getAlignment());
9000       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9001                             Increment);
9002       Chains.push_back(Ch);
9003     }
9004     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9005                        Chains.size());
9006   }
9007
9008   if (!ISD::isNormalStore(St))
9009     return SDValue();
9010
9011   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9012   // ARM stores of arguments in the same cache line.
9013   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9014       StVal.getNode()->hasOneUse()) {
9015     SelectionDAG  &DAG = DCI.DAG;
9016     SDLoc DL(St);
9017     SDValue BasePtr = St->getBasePtr();
9018     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9019                                   StVal.getNode()->getOperand(0), BasePtr,
9020                                   St->getPointerInfo(), St->isVolatile(),
9021                                   St->isNonTemporal(), St->getAlignment());
9022
9023     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9024                                     DAG.getConstant(4, MVT::i32));
9025     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9026                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9027                         St->isNonTemporal(),
9028                         std::min(4U, St->getAlignment() / 2));
9029   }
9030
9031   if (StVal.getValueType() != MVT::i64 ||
9032       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9033     return SDValue();
9034
9035   // Bitcast an i64 store extracted from a vector to f64.
9036   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9037   SelectionDAG &DAG = DCI.DAG;
9038   SDLoc dl(StVal);
9039   SDValue IntVec = StVal.getOperand(0);
9040   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9041                                  IntVec.getValueType().getVectorNumElements());
9042   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9043   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9044                                Vec, StVal.getOperand(1));
9045   dl = SDLoc(N);
9046   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9047   // Make the DAGCombiner fold the bitcasts.
9048   DCI.AddToWorklist(Vec.getNode());
9049   DCI.AddToWorklist(ExtElt.getNode());
9050   DCI.AddToWorklist(V.getNode());
9051   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9052                       St->getPointerInfo(), St->isVolatile(),
9053                       St->isNonTemporal(), St->getAlignment(),
9054                       St->getTBAAInfo());
9055 }
9056
9057 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9058 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9059 /// i64 vector to have f64 elements, since the value can then be loaded
9060 /// directly into a VFP register.
9061 static bool hasNormalLoadOperand(SDNode *N) {
9062   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9063   for (unsigned i = 0; i < NumElts; ++i) {
9064     SDNode *Elt = N->getOperand(i).getNode();
9065     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9066       return true;
9067   }
9068   return false;
9069 }
9070
9071 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9072 /// ISD::BUILD_VECTOR.
9073 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9074                                           TargetLowering::DAGCombinerInfo &DCI){
9075   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9076   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9077   // into a pair of GPRs, which is fine when the value is used as a scalar,
9078   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9079   SelectionDAG &DAG = DCI.DAG;
9080   if (N->getNumOperands() == 2) {
9081     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9082     if (RV.getNode())
9083       return RV;
9084   }
9085
9086   // Load i64 elements as f64 values so that type legalization does not split
9087   // them up into i32 values.
9088   EVT VT = N->getValueType(0);
9089   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9090     return SDValue();
9091   SDLoc dl(N);
9092   SmallVector<SDValue, 8> Ops;
9093   unsigned NumElts = VT.getVectorNumElements();
9094   for (unsigned i = 0; i < NumElts; ++i) {
9095     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9096     Ops.push_back(V);
9097     // Make the DAGCombiner fold the bitcast.
9098     DCI.AddToWorklist(V.getNode());
9099   }
9100   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9101   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9102   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9103 }
9104
9105 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9106 static SDValue
9107 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9108   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9109   // At that time, we may have inserted bitcasts from integer to float.
9110   // If these bitcasts have survived DAGCombine, change the lowering of this
9111   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9112   // force to use floating point types.
9113
9114   // Make sure we can change the type of the vector.
9115   // This is possible iff:
9116   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9117   //    1.1. Vector is used only once.
9118   //    1.2. Use is a bit convert to an integer type.
9119   // 2. The size of its operands are 32-bits (64-bits are not legal).
9120   EVT VT = N->getValueType(0);
9121   EVT EltVT = VT.getVectorElementType();
9122
9123   // Check 1.1. and 2.
9124   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9125     return SDValue();
9126
9127   // By construction, the input type must be float.
9128   assert(EltVT == MVT::f32 && "Unexpected type!");
9129
9130   // Check 1.2.
9131   SDNode *Use = *N->use_begin();
9132   if (Use->getOpcode() != ISD::BITCAST ||
9133       Use->getValueType(0).isFloatingPoint())
9134     return SDValue();
9135
9136   // Check profitability.
9137   // Model is, if more than half of the relevant operands are bitcast from
9138   // i32, turn the build_vector into a sequence of insert_vector_elt.
9139   // Relevant operands are everything that is not statically
9140   // (i.e., at compile time) bitcasted.
9141   unsigned NumOfBitCastedElts = 0;
9142   unsigned NumElts = VT.getVectorNumElements();
9143   unsigned NumOfRelevantElts = NumElts;
9144   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9145     SDValue Elt = N->getOperand(Idx);
9146     if (Elt->getOpcode() == ISD::BITCAST) {
9147       // Assume only bit cast to i32 will go away.
9148       if (Elt->getOperand(0).getValueType() == MVT::i32)
9149         ++NumOfBitCastedElts;
9150     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9151       // Constants are statically casted, thus do not count them as
9152       // relevant operands.
9153       --NumOfRelevantElts;
9154   }
9155
9156   // Check if more than half of the elements require a non-free bitcast.
9157   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9158     return SDValue();
9159
9160   SelectionDAG &DAG = DCI.DAG;
9161   // Create the new vector type.
9162   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9163   // Check if the type is legal.
9164   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9165   if (!TLI.isTypeLegal(VecVT))
9166     return SDValue();
9167
9168   // Combine:
9169   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9170   // => BITCAST INSERT_VECTOR_ELT
9171   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9172   //                      (BITCAST EN), N.
9173   SDValue Vec = DAG.getUNDEF(VecVT);
9174   SDLoc dl(N);
9175   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9176     SDValue V = N->getOperand(Idx);
9177     if (V.getOpcode() == ISD::UNDEF)
9178       continue;
9179     if (V.getOpcode() == ISD::BITCAST &&
9180         V->getOperand(0).getValueType() == MVT::i32)
9181       // Fold obvious case.
9182       V = V.getOperand(0);
9183     else {
9184       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9185       // Make the DAGCombiner fold the bitcasts.
9186       DCI.AddToWorklist(V.getNode());
9187     }
9188     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9189     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9190   }
9191   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9192   // Make the DAGCombiner fold the bitcasts.
9193   DCI.AddToWorklist(Vec.getNode());
9194   return Vec;
9195 }
9196
9197 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9198 /// ISD::INSERT_VECTOR_ELT.
9199 static SDValue PerformInsertEltCombine(SDNode *N,
9200                                        TargetLowering::DAGCombinerInfo &DCI) {
9201   // Bitcast an i64 load inserted into a vector to f64.
9202   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9203   EVT VT = N->getValueType(0);
9204   SDNode *Elt = N->getOperand(1).getNode();
9205   if (VT.getVectorElementType() != MVT::i64 ||
9206       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9207     return SDValue();
9208
9209   SelectionDAG &DAG = DCI.DAG;
9210   SDLoc dl(N);
9211   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9212                                  VT.getVectorNumElements());
9213   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9214   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9215   // Make the DAGCombiner fold the bitcasts.
9216   DCI.AddToWorklist(Vec.getNode());
9217   DCI.AddToWorklist(V.getNode());
9218   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9219                                Vec, V, N->getOperand(2));
9220   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9221 }
9222
9223 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9224 /// ISD::VECTOR_SHUFFLE.
9225 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9226   // The LLVM shufflevector instruction does not require the shuffle mask
9227   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9228   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9229   // operands do not match the mask length, they are extended by concatenating
9230   // them with undef vectors.  That is probably the right thing for other
9231   // targets, but for NEON it is better to concatenate two double-register
9232   // size vector operands into a single quad-register size vector.  Do that
9233   // transformation here:
9234   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9235   //   shuffle(concat(v1, v2), undef)
9236   SDValue Op0 = N->getOperand(0);
9237   SDValue Op1 = N->getOperand(1);
9238   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9239       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9240       Op0.getNumOperands() != 2 ||
9241       Op1.getNumOperands() != 2)
9242     return SDValue();
9243   SDValue Concat0Op1 = Op0.getOperand(1);
9244   SDValue Concat1Op1 = Op1.getOperand(1);
9245   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9246       Concat1Op1.getOpcode() != ISD::UNDEF)
9247     return SDValue();
9248   // Skip the transformation if any of the types are illegal.
9249   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9250   EVT VT = N->getValueType(0);
9251   if (!TLI.isTypeLegal(VT) ||
9252       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9253       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9254     return SDValue();
9255
9256   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9257                                   Op0.getOperand(0), Op1.getOperand(0));
9258   // Translate the shuffle mask.
9259   SmallVector<int, 16> NewMask;
9260   unsigned NumElts = VT.getVectorNumElements();
9261   unsigned HalfElts = NumElts/2;
9262   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9263   for (unsigned n = 0; n < NumElts; ++n) {
9264     int MaskElt = SVN->getMaskElt(n);
9265     int NewElt = -1;
9266     if (MaskElt < (int)HalfElts)
9267       NewElt = MaskElt;
9268     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9269       NewElt = HalfElts + MaskElt - NumElts;
9270     NewMask.push_back(NewElt);
9271   }
9272   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9273                               DAG.getUNDEF(VT), NewMask.data());
9274 }
9275
9276 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9277 /// NEON load/store intrinsics to merge base address updates.
9278 static SDValue CombineBaseUpdate(SDNode *N,
9279                                  TargetLowering::DAGCombinerInfo &DCI) {
9280   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9281     return SDValue();
9282
9283   SelectionDAG &DAG = DCI.DAG;
9284   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9285                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9286   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9287   SDValue Addr = N->getOperand(AddrOpIdx);
9288
9289   // Search for a use of the address operand that is an increment.
9290   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9291          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9292     SDNode *User = *UI;
9293     if (User->getOpcode() != ISD::ADD ||
9294         UI.getUse().getResNo() != Addr.getResNo())
9295       continue;
9296
9297     // Check that the add is independent of the load/store.  Otherwise, folding
9298     // it would create a cycle.
9299     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9300       continue;
9301
9302     // Find the new opcode for the updating load/store.
9303     bool isLoad = true;
9304     bool isLaneOp = false;
9305     unsigned NewOpc = 0;
9306     unsigned NumVecs = 0;
9307     if (isIntrinsic) {
9308       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9309       switch (IntNo) {
9310       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9311       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9312         NumVecs = 1; break;
9313       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9314         NumVecs = 2; break;
9315       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9316         NumVecs = 3; break;
9317       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9318         NumVecs = 4; break;
9319       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9320         NumVecs = 2; isLaneOp = true; break;
9321       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9322         NumVecs = 3; isLaneOp = true; break;
9323       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9324         NumVecs = 4; isLaneOp = true; break;
9325       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9326         NumVecs = 1; isLoad = false; break;
9327       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9328         NumVecs = 2; isLoad = false; break;
9329       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9330         NumVecs = 3; isLoad = false; break;
9331       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9332         NumVecs = 4; isLoad = false; break;
9333       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9334         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9335       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9336         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9337       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9338         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9339       }
9340     } else {
9341       isLaneOp = true;
9342       switch (N->getOpcode()) {
9343       default: llvm_unreachable("unexpected opcode for Neon base update");
9344       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9345       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9346       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9347       }
9348     }
9349
9350     // Find the size of memory referenced by the load/store.
9351     EVT VecTy;
9352     if (isLoad)
9353       VecTy = N->getValueType(0);
9354     else
9355       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9356     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9357     if (isLaneOp)
9358       NumBytes /= VecTy.getVectorNumElements();
9359
9360     // If the increment is a constant, it must match the memory ref size.
9361     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9362     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9363       uint64_t IncVal = CInc->getZExtValue();
9364       if (IncVal != NumBytes)
9365         continue;
9366     } else if (NumBytes >= 3 * 16) {
9367       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9368       // separate instructions that make it harder to use a non-constant update.
9369       continue;
9370     }
9371
9372     // Create the new updating load/store node.
9373     EVT Tys[6];
9374     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9375     unsigned n;
9376     for (n = 0; n < NumResultVecs; ++n)
9377       Tys[n] = VecTy;
9378     Tys[n++] = MVT::i32;
9379     Tys[n] = MVT::Other;
9380     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9381     SmallVector<SDValue, 8> Ops;
9382     Ops.push_back(N->getOperand(0)); // incoming chain
9383     Ops.push_back(N->getOperand(AddrOpIdx));
9384     Ops.push_back(Inc);
9385     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9386       Ops.push_back(N->getOperand(i));
9387     }
9388     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9389     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9390                                            Ops.data(), Ops.size(),
9391                                            MemInt->getMemoryVT(),
9392                                            MemInt->getMemOperand());
9393
9394     // Update the uses.
9395     std::vector<SDValue> NewResults;
9396     for (unsigned i = 0; i < NumResultVecs; ++i) {
9397       NewResults.push_back(SDValue(UpdN.getNode(), i));
9398     }
9399     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9400     DCI.CombineTo(N, NewResults);
9401     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9402
9403     break;
9404   }
9405   return SDValue();
9406 }
9407
9408 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9409 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9410 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9411 /// return true.
9412 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9413   SelectionDAG &DAG = DCI.DAG;
9414   EVT VT = N->getValueType(0);
9415   // vldN-dup instructions only support 64-bit vectors for N > 1.
9416   if (!VT.is64BitVector())
9417     return false;
9418
9419   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9420   SDNode *VLD = N->getOperand(0).getNode();
9421   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9422     return false;
9423   unsigned NumVecs = 0;
9424   unsigned NewOpc = 0;
9425   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9426   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9427     NumVecs = 2;
9428     NewOpc = ARMISD::VLD2DUP;
9429   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9430     NumVecs = 3;
9431     NewOpc = ARMISD::VLD3DUP;
9432   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9433     NumVecs = 4;
9434     NewOpc = ARMISD::VLD4DUP;
9435   } else {
9436     return false;
9437   }
9438
9439   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9440   // numbers match the load.
9441   unsigned VLDLaneNo =
9442     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9443   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9444        UI != UE; ++UI) {
9445     // Ignore uses of the chain result.
9446     if (UI.getUse().getResNo() == NumVecs)
9447       continue;
9448     SDNode *User = *UI;
9449     if (User->getOpcode() != ARMISD::VDUPLANE ||
9450         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9451       return false;
9452   }
9453
9454   // Create the vldN-dup node.
9455   EVT Tys[5];
9456   unsigned n;
9457   for (n = 0; n < NumVecs; ++n)
9458     Tys[n] = VT;
9459   Tys[n] = MVT::Other;
9460   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9461   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9462   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9463   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9464                                            Ops, 2, VLDMemInt->getMemoryVT(),
9465                                            VLDMemInt->getMemOperand());
9466
9467   // Update the uses.
9468   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9469        UI != UE; ++UI) {
9470     unsigned ResNo = UI.getUse().getResNo();
9471     // Ignore uses of the chain result.
9472     if (ResNo == NumVecs)
9473       continue;
9474     SDNode *User = *UI;
9475     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9476   }
9477
9478   // Now the vldN-lane intrinsic is dead except for its chain result.
9479   // Update uses of the chain.
9480   std::vector<SDValue> VLDDupResults;
9481   for (unsigned n = 0; n < NumVecs; ++n)
9482     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9483   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9484   DCI.CombineTo(VLD, VLDDupResults);
9485
9486   return true;
9487 }
9488
9489 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9490 /// ARMISD::VDUPLANE.
9491 static SDValue PerformVDUPLANECombine(SDNode *N,
9492                                       TargetLowering::DAGCombinerInfo &DCI) {
9493   SDValue Op = N->getOperand(0);
9494
9495   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9496   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9497   if (CombineVLDDUP(N, DCI))
9498     return SDValue(N, 0);
9499
9500   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9501   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9502   while (Op.getOpcode() == ISD::BITCAST)
9503     Op = Op.getOperand(0);
9504   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9505     return SDValue();
9506
9507   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9508   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9509   // The canonical VMOV for a zero vector uses a 32-bit element size.
9510   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9511   unsigned EltBits;
9512   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9513     EltSize = 8;
9514   EVT VT = N->getValueType(0);
9515   if (EltSize > VT.getVectorElementType().getSizeInBits())
9516     return SDValue();
9517
9518   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9519 }
9520
9521 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9522 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9523 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9524 {
9525   integerPart cN;
9526   integerPart c0 = 0;
9527   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9528        I != E; I++) {
9529     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9530     if (!C)
9531       return false;
9532
9533     bool isExact;
9534     APFloat APF = C->getValueAPF();
9535     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9536         != APFloat::opOK || !isExact)
9537       return false;
9538
9539     c0 = (I == 0) ? cN : c0;
9540     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9541       return false;
9542   }
9543   C = c0;
9544   return true;
9545 }
9546
9547 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9548 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9549 /// when the VMUL has a constant operand that is a power of 2.
9550 ///
9551 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9552 ///  vmul.f32        d16, d17, d16
9553 ///  vcvt.s32.f32    d16, d16
9554 /// becomes:
9555 ///  vcvt.s32.f32    d16, d16, #3
9556 static SDValue PerformVCVTCombine(SDNode *N,
9557                                   TargetLowering::DAGCombinerInfo &DCI,
9558                                   const ARMSubtarget *Subtarget) {
9559   SelectionDAG &DAG = DCI.DAG;
9560   SDValue Op = N->getOperand(0);
9561
9562   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9563       Op.getOpcode() != ISD::FMUL)
9564     return SDValue();
9565
9566   uint64_t C;
9567   SDValue N0 = Op->getOperand(0);
9568   SDValue ConstVec = Op->getOperand(1);
9569   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9570
9571   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9572       !isConstVecPow2(ConstVec, isSigned, C))
9573     return SDValue();
9574
9575   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9576   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9577   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9578     // These instructions only exist converting from f32 to i32. We can handle
9579     // smaller integers by generating an extra truncate, but larger ones would
9580     // be lossy.
9581     return SDValue();
9582   }
9583
9584   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9585     Intrinsic::arm_neon_vcvtfp2fxu;
9586   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9587   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9588                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9589                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9590                                  DAG.getConstant(Log2_64(C), MVT::i32));
9591
9592   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9593     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9594
9595   return FixConv;
9596 }
9597
9598 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9599 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9600 /// when the VDIV has a constant operand that is a power of 2.
9601 ///
9602 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9603 ///  vcvt.f32.s32    d16, d16
9604 ///  vdiv.f32        d16, d17, d16
9605 /// becomes:
9606 ///  vcvt.f32.s32    d16, d16, #3
9607 static SDValue PerformVDIVCombine(SDNode *N,
9608                                   TargetLowering::DAGCombinerInfo &DCI,
9609                                   const ARMSubtarget *Subtarget) {
9610   SelectionDAG &DAG = DCI.DAG;
9611   SDValue Op = N->getOperand(0);
9612   unsigned OpOpcode = Op.getNode()->getOpcode();
9613
9614   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9615       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9616     return SDValue();
9617
9618   uint64_t C;
9619   SDValue ConstVec = N->getOperand(1);
9620   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9621
9622   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9623       !isConstVecPow2(ConstVec, isSigned, C))
9624     return SDValue();
9625
9626   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9627   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9628   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9629     // These instructions only exist converting from i32 to f32. We can handle
9630     // smaller integers by generating an extra extend, but larger ones would
9631     // be lossy.
9632     return SDValue();
9633   }
9634
9635   SDValue ConvInput = Op.getOperand(0);
9636   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9637   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9638     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9639                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9640                             ConvInput);
9641
9642   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9643     Intrinsic::arm_neon_vcvtfxu2fp;
9644   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9645                      Op.getValueType(),
9646                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9647                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9648 }
9649
9650 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9651 /// operand of a vector shift operation, where all the elements of the
9652 /// build_vector must have the same constant integer value.
9653 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9654   // Ignore bit_converts.
9655   while (Op.getOpcode() == ISD::BITCAST)
9656     Op = Op.getOperand(0);
9657   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9658   APInt SplatBits, SplatUndef;
9659   unsigned SplatBitSize;
9660   bool HasAnyUndefs;
9661   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9662                                       HasAnyUndefs, ElementBits) ||
9663       SplatBitSize > ElementBits)
9664     return false;
9665   Cnt = SplatBits.getSExtValue();
9666   return true;
9667 }
9668
9669 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9670 /// operand of a vector shift left operation.  That value must be in the range:
9671 ///   0 <= Value < ElementBits for a left shift; or
9672 ///   0 <= Value <= ElementBits for a long left shift.
9673 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9674   assert(VT.isVector() && "vector shift count is not a vector type");
9675   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9676   if (! getVShiftImm(Op, ElementBits, Cnt))
9677     return false;
9678   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9679 }
9680
9681 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9682 /// operand of a vector shift right operation.  For a shift opcode, the value
9683 /// is positive, but for an intrinsic the value count must be negative. The
9684 /// absolute value must be in the range:
9685 ///   1 <= |Value| <= ElementBits for a right shift; or
9686 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9687 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9688                          int64_t &Cnt) {
9689   assert(VT.isVector() && "vector shift count is not a vector type");
9690   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9691   if (! getVShiftImm(Op, ElementBits, Cnt))
9692     return false;
9693   if (isIntrinsic)
9694     Cnt = -Cnt;
9695   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9696 }
9697
9698 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9699 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9700   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9701   switch (IntNo) {
9702   default:
9703     // Don't do anything for most intrinsics.
9704     break;
9705
9706   // Vector shifts: check for immediate versions and lower them.
9707   // Note: This is done during DAG combining instead of DAG legalizing because
9708   // the build_vectors for 64-bit vector element shift counts are generally
9709   // not legal, and it is hard to see their values after they get legalized to
9710   // loads from a constant pool.
9711   case Intrinsic::arm_neon_vshifts:
9712   case Intrinsic::arm_neon_vshiftu:
9713   case Intrinsic::arm_neon_vrshifts:
9714   case Intrinsic::arm_neon_vrshiftu:
9715   case Intrinsic::arm_neon_vrshiftn:
9716   case Intrinsic::arm_neon_vqshifts:
9717   case Intrinsic::arm_neon_vqshiftu:
9718   case Intrinsic::arm_neon_vqshiftsu:
9719   case Intrinsic::arm_neon_vqshiftns:
9720   case Intrinsic::arm_neon_vqshiftnu:
9721   case Intrinsic::arm_neon_vqshiftnsu:
9722   case Intrinsic::arm_neon_vqrshiftns:
9723   case Intrinsic::arm_neon_vqrshiftnu:
9724   case Intrinsic::arm_neon_vqrshiftnsu: {
9725     EVT VT = N->getOperand(1).getValueType();
9726     int64_t Cnt;
9727     unsigned VShiftOpc = 0;
9728
9729     switch (IntNo) {
9730     case Intrinsic::arm_neon_vshifts:
9731     case Intrinsic::arm_neon_vshiftu:
9732       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9733         VShiftOpc = ARMISD::VSHL;
9734         break;
9735       }
9736       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9737         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9738                      ARMISD::VSHRs : ARMISD::VSHRu);
9739         break;
9740       }
9741       return SDValue();
9742
9743     case Intrinsic::arm_neon_vrshifts:
9744     case Intrinsic::arm_neon_vrshiftu:
9745       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9746         break;
9747       return SDValue();
9748
9749     case Intrinsic::arm_neon_vqshifts:
9750     case Intrinsic::arm_neon_vqshiftu:
9751       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9752         break;
9753       return SDValue();
9754
9755     case Intrinsic::arm_neon_vqshiftsu:
9756       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9757         break;
9758       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9759
9760     case Intrinsic::arm_neon_vrshiftn:
9761     case Intrinsic::arm_neon_vqshiftns:
9762     case Intrinsic::arm_neon_vqshiftnu:
9763     case Intrinsic::arm_neon_vqshiftnsu:
9764     case Intrinsic::arm_neon_vqrshiftns:
9765     case Intrinsic::arm_neon_vqrshiftnu:
9766     case Intrinsic::arm_neon_vqrshiftnsu:
9767       // Narrowing shifts require an immediate right shift.
9768       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9769         break;
9770       llvm_unreachable("invalid shift count for narrowing vector shift "
9771                        "intrinsic");
9772
9773     default:
9774       llvm_unreachable("unhandled vector shift");
9775     }
9776
9777     switch (IntNo) {
9778     case Intrinsic::arm_neon_vshifts:
9779     case Intrinsic::arm_neon_vshiftu:
9780       // Opcode already set above.
9781       break;
9782     case Intrinsic::arm_neon_vrshifts:
9783       VShiftOpc = ARMISD::VRSHRs; break;
9784     case Intrinsic::arm_neon_vrshiftu:
9785       VShiftOpc = ARMISD::VRSHRu; break;
9786     case Intrinsic::arm_neon_vrshiftn:
9787       VShiftOpc = ARMISD::VRSHRN; break;
9788     case Intrinsic::arm_neon_vqshifts:
9789       VShiftOpc = ARMISD::VQSHLs; break;
9790     case Intrinsic::arm_neon_vqshiftu:
9791       VShiftOpc = ARMISD::VQSHLu; break;
9792     case Intrinsic::arm_neon_vqshiftsu:
9793       VShiftOpc = ARMISD::VQSHLsu; break;
9794     case Intrinsic::arm_neon_vqshiftns:
9795       VShiftOpc = ARMISD::VQSHRNs; break;
9796     case Intrinsic::arm_neon_vqshiftnu:
9797       VShiftOpc = ARMISD::VQSHRNu; break;
9798     case Intrinsic::arm_neon_vqshiftnsu:
9799       VShiftOpc = ARMISD::VQSHRNsu; break;
9800     case Intrinsic::arm_neon_vqrshiftns:
9801       VShiftOpc = ARMISD::VQRSHRNs; break;
9802     case Intrinsic::arm_neon_vqrshiftnu:
9803       VShiftOpc = ARMISD::VQRSHRNu; break;
9804     case Intrinsic::arm_neon_vqrshiftnsu:
9805       VShiftOpc = ARMISD::VQRSHRNsu; break;
9806     }
9807
9808     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9809                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9810   }
9811
9812   case Intrinsic::arm_neon_vshiftins: {
9813     EVT VT = N->getOperand(1).getValueType();
9814     int64_t Cnt;
9815     unsigned VShiftOpc = 0;
9816
9817     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9818       VShiftOpc = ARMISD::VSLI;
9819     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9820       VShiftOpc = ARMISD::VSRI;
9821     else {
9822       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9823     }
9824
9825     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9826                        N->getOperand(1), N->getOperand(2),
9827                        DAG.getConstant(Cnt, MVT::i32));
9828   }
9829
9830   case Intrinsic::arm_neon_vqrshifts:
9831   case Intrinsic::arm_neon_vqrshiftu:
9832     // No immediate versions of these to check for.
9833     break;
9834   }
9835
9836   return SDValue();
9837 }
9838
9839 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9840 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9841 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9842 /// vector element shift counts are generally not legal, and it is hard to see
9843 /// their values after they get legalized to loads from a constant pool.
9844 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9845                                    const ARMSubtarget *ST) {
9846   EVT VT = N->getValueType(0);
9847   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9848     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9849     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9850     SDValue N1 = N->getOperand(1);
9851     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9852       SDValue N0 = N->getOperand(0);
9853       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9854           DAG.MaskedValueIsZero(N0.getOperand(0),
9855                                 APInt::getHighBitsSet(32, 16)))
9856         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9857     }
9858   }
9859
9860   // Nothing to be done for scalar shifts.
9861   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9862   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9863     return SDValue();
9864
9865   assert(ST->hasNEON() && "unexpected vector shift");
9866   int64_t Cnt;
9867
9868   switch (N->getOpcode()) {
9869   default: llvm_unreachable("unexpected shift opcode");
9870
9871   case ISD::SHL:
9872     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9873       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9874                          DAG.getConstant(Cnt, MVT::i32));
9875     break;
9876
9877   case ISD::SRA:
9878   case ISD::SRL:
9879     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9880       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9881                             ARMISD::VSHRs : ARMISD::VSHRu);
9882       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9883                          DAG.getConstant(Cnt, MVT::i32));
9884     }
9885   }
9886   return SDValue();
9887 }
9888
9889 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9890 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9891 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9892                                     const ARMSubtarget *ST) {
9893   SDValue N0 = N->getOperand(0);
9894
9895   // Check for sign- and zero-extensions of vector extract operations of 8-
9896   // and 16-bit vector elements.  NEON supports these directly.  They are
9897   // handled during DAG combining because type legalization will promote them
9898   // to 32-bit types and it is messy to recognize the operations after that.
9899   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9900     SDValue Vec = N0.getOperand(0);
9901     SDValue Lane = N0.getOperand(1);
9902     EVT VT = N->getValueType(0);
9903     EVT EltVT = N0.getValueType();
9904     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9905
9906     if (VT == MVT::i32 &&
9907         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9908         TLI.isTypeLegal(Vec.getValueType()) &&
9909         isa<ConstantSDNode>(Lane)) {
9910
9911       unsigned Opc = 0;
9912       switch (N->getOpcode()) {
9913       default: llvm_unreachable("unexpected opcode");
9914       case ISD::SIGN_EXTEND:
9915         Opc = ARMISD::VGETLANEs;
9916         break;
9917       case ISD::ZERO_EXTEND:
9918       case ISD::ANY_EXTEND:
9919         Opc = ARMISD::VGETLANEu;
9920         break;
9921       }
9922       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9923     }
9924   }
9925
9926   return SDValue();
9927 }
9928
9929 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9930 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9931 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9932                                        const ARMSubtarget *ST) {
9933   // If the target supports NEON, try to use vmax/vmin instructions for f32
9934   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9935   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9936   // a NaN; only do the transformation when it matches that behavior.
9937
9938   // For now only do this when using NEON for FP operations; if using VFP, it
9939   // is not obvious that the benefit outweighs the cost of switching to the
9940   // NEON pipeline.
9941   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9942       N->getValueType(0) != MVT::f32)
9943     return SDValue();
9944
9945   SDValue CondLHS = N->getOperand(0);
9946   SDValue CondRHS = N->getOperand(1);
9947   SDValue LHS = N->getOperand(2);
9948   SDValue RHS = N->getOperand(3);
9949   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9950
9951   unsigned Opcode = 0;
9952   bool IsReversed;
9953   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9954     IsReversed = false; // x CC y ? x : y
9955   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9956     IsReversed = true ; // x CC y ? y : x
9957   } else {
9958     return SDValue();
9959   }
9960
9961   bool IsUnordered;
9962   switch (CC) {
9963   default: break;
9964   case ISD::SETOLT:
9965   case ISD::SETOLE:
9966   case ISD::SETLT:
9967   case ISD::SETLE:
9968   case ISD::SETULT:
9969   case ISD::SETULE:
9970     // If LHS is NaN, an ordered comparison will be false and the result will
9971     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9972     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9973     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9974     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9975       break;
9976     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9977     // will return -0, so vmin can only be used for unsafe math or if one of
9978     // the operands is known to be nonzero.
9979     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9980         !DAG.getTarget().Options.UnsafeFPMath &&
9981         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9982       break;
9983     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9984     break;
9985
9986   case ISD::SETOGT:
9987   case ISD::SETOGE:
9988   case ISD::SETGT:
9989   case ISD::SETGE:
9990   case ISD::SETUGT:
9991   case ISD::SETUGE:
9992     // If LHS is NaN, an ordered comparison will be false and the result will
9993     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9994     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9995     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9996     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9997       break;
9998     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9999     // will return +0, so vmax can only be used for unsafe math or if one of
10000     // the operands is known to be nonzero.
10001     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10002         !DAG.getTarget().Options.UnsafeFPMath &&
10003         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10004       break;
10005     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10006     break;
10007   }
10008
10009   if (!Opcode)
10010     return SDValue();
10011   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10012 }
10013
10014 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10015 SDValue
10016 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10017   SDValue Cmp = N->getOperand(4);
10018   if (Cmp.getOpcode() != ARMISD::CMPZ)
10019     // Only looking at EQ and NE cases.
10020     return SDValue();
10021
10022   EVT VT = N->getValueType(0);
10023   SDLoc dl(N);
10024   SDValue LHS = Cmp.getOperand(0);
10025   SDValue RHS = Cmp.getOperand(1);
10026   SDValue FalseVal = N->getOperand(0);
10027   SDValue TrueVal = N->getOperand(1);
10028   SDValue ARMcc = N->getOperand(2);
10029   ARMCC::CondCodes CC =
10030     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10031
10032   // Simplify
10033   //   mov     r1, r0
10034   //   cmp     r1, x
10035   //   mov     r0, y
10036   //   moveq   r0, x
10037   // to
10038   //   cmp     r0, x
10039   //   movne   r0, y
10040   //
10041   //   mov     r1, r0
10042   //   cmp     r1, x
10043   //   mov     r0, x
10044   //   movne   r0, y
10045   // to
10046   //   cmp     r0, x
10047   //   movne   r0, y
10048   /// FIXME: Turn this into a target neutral optimization?
10049   SDValue Res;
10050   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10051     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10052                       N->getOperand(3), Cmp);
10053   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10054     SDValue ARMcc;
10055     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10056     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10057                       N->getOperand(3), NewCmp);
10058   }
10059
10060   if (Res.getNode()) {
10061     APInt KnownZero, KnownOne;
10062     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10063     // Capture demanded bits information that would be otherwise lost.
10064     if (KnownZero == 0xfffffffe)
10065       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10066                         DAG.getValueType(MVT::i1));
10067     else if (KnownZero == 0xffffff00)
10068       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10069                         DAG.getValueType(MVT::i8));
10070     else if (KnownZero == 0xffff0000)
10071       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10072                         DAG.getValueType(MVT::i16));
10073   }
10074
10075   return Res;
10076 }
10077
10078 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10079                                              DAGCombinerInfo &DCI) const {
10080   switch (N->getOpcode()) {
10081   default: break;
10082   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10083   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10084   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10085   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10086   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10087   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10088   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10089   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10090   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10091   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10092   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10093   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10094   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10095   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10096   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10097   case ISD::FP_TO_SINT:
10098   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10099   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10100   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10101   case ISD::SHL:
10102   case ISD::SRA:
10103   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10104   case ISD::SIGN_EXTEND:
10105   case ISD::ZERO_EXTEND:
10106   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10107   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10108   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10109   case ARMISD::VLD2DUP:
10110   case ARMISD::VLD3DUP:
10111   case ARMISD::VLD4DUP:
10112     return CombineBaseUpdate(N, DCI);
10113   case ARMISD::BUILD_VECTOR:
10114     return PerformARMBUILD_VECTORCombine(N, DCI);
10115   case ISD::INTRINSIC_VOID:
10116   case ISD::INTRINSIC_W_CHAIN:
10117     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10118     case Intrinsic::arm_neon_vld1:
10119     case Intrinsic::arm_neon_vld2:
10120     case Intrinsic::arm_neon_vld3:
10121     case Intrinsic::arm_neon_vld4:
10122     case Intrinsic::arm_neon_vld2lane:
10123     case Intrinsic::arm_neon_vld3lane:
10124     case Intrinsic::arm_neon_vld4lane:
10125     case Intrinsic::arm_neon_vst1:
10126     case Intrinsic::arm_neon_vst2:
10127     case Intrinsic::arm_neon_vst3:
10128     case Intrinsic::arm_neon_vst4:
10129     case Intrinsic::arm_neon_vst2lane:
10130     case Intrinsic::arm_neon_vst3lane:
10131     case Intrinsic::arm_neon_vst4lane:
10132       return CombineBaseUpdate(N, DCI);
10133     default: break;
10134     }
10135     break;
10136   }
10137   return SDValue();
10138 }
10139
10140 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10141                                                           EVT VT) const {
10142   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10143 }
10144
10145 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10146                                                       bool *Fast) const {
10147   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10148   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10149
10150   switch (VT.getSimpleVT().SimpleTy) {
10151   default:
10152     return false;
10153   case MVT::i8:
10154   case MVT::i16:
10155   case MVT::i32: {
10156     // Unaligned access can use (for example) LRDB, LRDH, LDR
10157     if (AllowsUnaligned) {
10158       if (Fast)
10159         *Fast = Subtarget->hasV7Ops();
10160       return true;
10161     }
10162     return false;
10163   }
10164   case MVT::f64:
10165   case MVT::v2f64: {
10166     // For any little-endian targets with neon, we can support unaligned ld/st
10167     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10168     // A big-endian target may also explicitly support unaligned accesses
10169     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10170       if (Fast)
10171         *Fast = true;
10172       return true;
10173     }
10174     return false;
10175   }
10176   }
10177 }
10178
10179 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10180                        unsigned AlignCheck) {
10181   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10182           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10183 }
10184
10185 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10186                                            unsigned DstAlign, unsigned SrcAlign,
10187                                            bool IsMemset, bool ZeroMemset,
10188                                            bool MemcpyStrSrc,
10189                                            MachineFunction &MF) const {
10190   const Function *F = MF.getFunction();
10191
10192   // See if we can use NEON instructions for this...
10193   if ((!IsMemset || ZeroMemset) &&
10194       Subtarget->hasNEON() &&
10195       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10196                                        Attribute::NoImplicitFloat)) {
10197     bool Fast;
10198     if (Size >= 16 &&
10199         (memOpAlign(SrcAlign, DstAlign, 16) ||
10200          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10201       return MVT::v2f64;
10202     } else if (Size >= 8 &&
10203                (memOpAlign(SrcAlign, DstAlign, 8) ||
10204                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10205       return MVT::f64;
10206     }
10207   }
10208
10209   // Lowering to i32/i16 if the size permits.
10210   if (Size >= 4)
10211     return MVT::i32;
10212   else if (Size >= 2)
10213     return MVT::i16;
10214
10215   // Let the target-independent logic figure it out.
10216   return MVT::Other;
10217 }
10218
10219 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10220   if (Val.getOpcode() != ISD::LOAD)
10221     return false;
10222
10223   EVT VT1 = Val.getValueType();
10224   if (!VT1.isSimple() || !VT1.isInteger() ||
10225       !VT2.isSimple() || !VT2.isInteger())
10226     return false;
10227
10228   switch (VT1.getSimpleVT().SimpleTy) {
10229   default: break;
10230   case MVT::i1:
10231   case MVT::i8:
10232   case MVT::i16:
10233     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10234     return true;
10235   }
10236
10237   return false;
10238 }
10239
10240 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10241   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10242     return false;
10243
10244   if (!isTypeLegal(EVT::getEVT(Ty1)))
10245     return false;
10246
10247   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10248
10249   // Assuming the caller doesn't have a zeroext or signext return parameter,
10250   // truncation all the way down to i1 is valid.
10251   return true;
10252 }
10253
10254
10255 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10256   if (V < 0)
10257     return false;
10258
10259   unsigned Scale = 1;
10260   switch (VT.getSimpleVT().SimpleTy) {
10261   default: return false;
10262   case MVT::i1:
10263   case MVT::i8:
10264     // Scale == 1;
10265     break;
10266   case MVT::i16:
10267     // Scale == 2;
10268     Scale = 2;
10269     break;
10270   case MVT::i32:
10271     // Scale == 4;
10272     Scale = 4;
10273     break;
10274   }
10275
10276   if ((V & (Scale - 1)) != 0)
10277     return false;
10278   V /= Scale;
10279   return V == (V & ((1LL << 5) - 1));
10280 }
10281
10282 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10283                                       const ARMSubtarget *Subtarget) {
10284   bool isNeg = false;
10285   if (V < 0) {
10286     isNeg = true;
10287     V = - V;
10288   }
10289
10290   switch (VT.getSimpleVT().SimpleTy) {
10291   default: return false;
10292   case MVT::i1:
10293   case MVT::i8:
10294   case MVT::i16:
10295   case MVT::i32:
10296     // + imm12 or - imm8
10297     if (isNeg)
10298       return V == (V & ((1LL << 8) - 1));
10299     return V == (V & ((1LL << 12) - 1));
10300   case MVT::f32:
10301   case MVT::f64:
10302     // Same as ARM mode. FIXME: NEON?
10303     if (!Subtarget->hasVFP2())
10304       return false;
10305     if ((V & 3) != 0)
10306       return false;
10307     V >>= 2;
10308     return V == (V & ((1LL << 8) - 1));
10309   }
10310 }
10311
10312 /// isLegalAddressImmediate - Return true if the integer value can be used
10313 /// as the offset of the target addressing mode for load / store of the
10314 /// given type.
10315 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10316                                     const ARMSubtarget *Subtarget) {
10317   if (V == 0)
10318     return true;
10319
10320   if (!VT.isSimple())
10321     return false;
10322
10323   if (Subtarget->isThumb1Only())
10324     return isLegalT1AddressImmediate(V, VT);
10325   else if (Subtarget->isThumb2())
10326     return isLegalT2AddressImmediate(V, VT, Subtarget);
10327
10328   // ARM mode.
10329   if (V < 0)
10330     V = - V;
10331   switch (VT.getSimpleVT().SimpleTy) {
10332   default: return false;
10333   case MVT::i1:
10334   case MVT::i8:
10335   case MVT::i32:
10336     // +- imm12
10337     return V == (V & ((1LL << 12) - 1));
10338   case MVT::i16:
10339     // +- imm8
10340     return V == (V & ((1LL << 8) - 1));
10341   case MVT::f32:
10342   case MVT::f64:
10343     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10344       return false;
10345     if ((V & 3) != 0)
10346       return false;
10347     V >>= 2;
10348     return V == (V & ((1LL << 8) - 1));
10349   }
10350 }
10351
10352 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10353                                                       EVT VT) const {
10354   int Scale = AM.Scale;
10355   if (Scale < 0)
10356     return false;
10357
10358   switch (VT.getSimpleVT().SimpleTy) {
10359   default: return false;
10360   case MVT::i1:
10361   case MVT::i8:
10362   case MVT::i16:
10363   case MVT::i32:
10364     if (Scale == 1)
10365       return true;
10366     // r + r << imm
10367     Scale = Scale & ~1;
10368     return Scale == 2 || Scale == 4 || Scale == 8;
10369   case MVT::i64:
10370     // r + r
10371     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10372       return true;
10373     return false;
10374   case MVT::isVoid:
10375     // Note, we allow "void" uses (basically, uses that aren't loads or
10376     // stores), because arm allows folding a scale into many arithmetic
10377     // operations.  This should be made more precise and revisited later.
10378
10379     // Allow r << imm, but the imm has to be a multiple of two.
10380     if (Scale & 1) return false;
10381     return isPowerOf2_32(Scale);
10382   }
10383 }
10384
10385 /// isLegalAddressingMode - Return true if the addressing mode represented
10386 /// by AM is legal for this target, for a load/store of the specified type.
10387 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10388                                               Type *Ty) const {
10389   EVT VT = getValueType(Ty, true);
10390   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10391     return false;
10392
10393   // Can never fold addr of global into load/store.
10394   if (AM.BaseGV)
10395     return false;
10396
10397   switch (AM.Scale) {
10398   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10399     break;
10400   case 1:
10401     if (Subtarget->isThumb1Only())
10402       return false;
10403     // FALL THROUGH.
10404   default:
10405     // ARM doesn't support any R+R*scale+imm addr modes.
10406     if (AM.BaseOffs)
10407       return false;
10408
10409     if (!VT.isSimple())
10410       return false;
10411
10412     if (Subtarget->isThumb2())
10413       return isLegalT2ScaledAddressingMode(AM, VT);
10414
10415     int Scale = AM.Scale;
10416     switch (VT.getSimpleVT().SimpleTy) {
10417     default: return false;
10418     case MVT::i1:
10419     case MVT::i8:
10420     case MVT::i32:
10421       if (Scale < 0) Scale = -Scale;
10422       if (Scale == 1)
10423         return true;
10424       // r + r << imm
10425       return isPowerOf2_32(Scale & ~1);
10426     case MVT::i16:
10427     case MVT::i64:
10428       // r + r
10429       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10430         return true;
10431       return false;
10432
10433     case MVT::isVoid:
10434       // Note, we allow "void" uses (basically, uses that aren't loads or
10435       // stores), because arm allows folding a scale into many arithmetic
10436       // operations.  This should be made more precise and revisited later.
10437
10438       // Allow r << imm, but the imm has to be a multiple of two.
10439       if (Scale & 1) return false;
10440       return isPowerOf2_32(Scale);
10441     }
10442   }
10443   return true;
10444 }
10445
10446 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10447 /// icmp immediate, that is the target has icmp instructions which can compare
10448 /// a register against the immediate without having to materialize the
10449 /// immediate into a register.
10450 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10451   // Thumb2 and ARM modes can use cmn for negative immediates.
10452   if (!Subtarget->isThumb())
10453     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10454   if (Subtarget->isThumb2())
10455     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10456   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10457   return Imm >= 0 && Imm <= 255;
10458 }
10459
10460 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10461 /// *or sub* immediate, that is the target has add or sub instructions which can
10462 /// add a register with the immediate without having to materialize the
10463 /// immediate into a register.
10464 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10465   // Same encoding for add/sub, just flip the sign.
10466   int64_t AbsImm = llvm::abs64(Imm);
10467   if (!Subtarget->isThumb())
10468     return ARM_AM::getSOImmVal(AbsImm) != -1;
10469   if (Subtarget->isThumb2())
10470     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10471   // Thumb1 only has 8-bit unsigned immediate.
10472   return AbsImm >= 0 && AbsImm <= 255;
10473 }
10474
10475 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10476                                       bool isSEXTLoad, SDValue &Base,
10477                                       SDValue &Offset, bool &isInc,
10478                                       SelectionDAG &DAG) {
10479   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10480     return false;
10481
10482   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10483     // AddressingMode 3
10484     Base = Ptr->getOperand(0);
10485     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10486       int RHSC = (int)RHS->getZExtValue();
10487       if (RHSC < 0 && RHSC > -256) {
10488         assert(Ptr->getOpcode() == ISD::ADD);
10489         isInc = false;
10490         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10491         return true;
10492       }
10493     }
10494     isInc = (Ptr->getOpcode() == ISD::ADD);
10495     Offset = Ptr->getOperand(1);
10496     return true;
10497   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10498     // AddressingMode 2
10499     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10500       int RHSC = (int)RHS->getZExtValue();
10501       if (RHSC < 0 && RHSC > -0x1000) {
10502         assert(Ptr->getOpcode() == ISD::ADD);
10503         isInc = false;
10504         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10505         Base = Ptr->getOperand(0);
10506         return true;
10507       }
10508     }
10509
10510     if (Ptr->getOpcode() == ISD::ADD) {
10511       isInc = true;
10512       ARM_AM::ShiftOpc ShOpcVal=
10513         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10514       if (ShOpcVal != ARM_AM::no_shift) {
10515         Base = Ptr->getOperand(1);
10516         Offset = Ptr->getOperand(0);
10517       } else {
10518         Base = Ptr->getOperand(0);
10519         Offset = Ptr->getOperand(1);
10520       }
10521       return true;
10522     }
10523
10524     isInc = (Ptr->getOpcode() == ISD::ADD);
10525     Base = Ptr->getOperand(0);
10526     Offset = Ptr->getOperand(1);
10527     return true;
10528   }
10529
10530   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10531   return false;
10532 }
10533
10534 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10535                                      bool isSEXTLoad, SDValue &Base,
10536                                      SDValue &Offset, bool &isInc,
10537                                      SelectionDAG &DAG) {
10538   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10539     return false;
10540
10541   Base = Ptr->getOperand(0);
10542   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10543     int RHSC = (int)RHS->getZExtValue();
10544     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10545       assert(Ptr->getOpcode() == ISD::ADD);
10546       isInc = false;
10547       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10548       return true;
10549     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10550       isInc = Ptr->getOpcode() == ISD::ADD;
10551       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10552       return true;
10553     }
10554   }
10555
10556   return false;
10557 }
10558
10559 /// getPreIndexedAddressParts - returns true by value, base pointer and
10560 /// offset pointer and addressing mode by reference if the node's address
10561 /// can be legally represented as pre-indexed load / store address.
10562 bool
10563 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10564                                              SDValue &Offset,
10565                                              ISD::MemIndexedMode &AM,
10566                                              SelectionDAG &DAG) const {
10567   if (Subtarget->isThumb1Only())
10568     return false;
10569
10570   EVT VT;
10571   SDValue Ptr;
10572   bool isSEXTLoad = false;
10573   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10574     Ptr = LD->getBasePtr();
10575     VT  = LD->getMemoryVT();
10576     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10577   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10578     Ptr = ST->getBasePtr();
10579     VT  = ST->getMemoryVT();
10580   } else
10581     return false;
10582
10583   bool isInc;
10584   bool isLegal = false;
10585   if (Subtarget->isThumb2())
10586     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10587                                        Offset, isInc, DAG);
10588   else
10589     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10590                                         Offset, isInc, DAG);
10591   if (!isLegal)
10592     return false;
10593
10594   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10595   return true;
10596 }
10597
10598 /// getPostIndexedAddressParts - returns true by value, base pointer and
10599 /// offset pointer and addressing mode by reference if this node can be
10600 /// combined with a load / store to form a post-indexed load / store.
10601 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10602                                                    SDValue &Base,
10603                                                    SDValue &Offset,
10604                                                    ISD::MemIndexedMode &AM,
10605                                                    SelectionDAG &DAG) const {
10606   if (Subtarget->isThumb1Only())
10607     return false;
10608
10609   EVT VT;
10610   SDValue Ptr;
10611   bool isSEXTLoad = false;
10612   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10613     VT  = LD->getMemoryVT();
10614     Ptr = LD->getBasePtr();
10615     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10616   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10617     VT  = ST->getMemoryVT();
10618     Ptr = ST->getBasePtr();
10619   } else
10620     return false;
10621
10622   bool isInc;
10623   bool isLegal = false;
10624   if (Subtarget->isThumb2())
10625     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10626                                        isInc, DAG);
10627   else
10628     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10629                                         isInc, DAG);
10630   if (!isLegal)
10631     return false;
10632
10633   if (Ptr != Base) {
10634     // Swap base ptr and offset to catch more post-index load / store when
10635     // it's legal. In Thumb2 mode, offset must be an immediate.
10636     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10637         !Subtarget->isThumb2())
10638       std::swap(Base, Offset);
10639
10640     // Post-indexed load / store update the base pointer.
10641     if (Ptr != Base)
10642       return false;
10643   }
10644
10645   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10646   return true;
10647 }
10648
10649 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10650                                                        APInt &KnownZero,
10651                                                        APInt &KnownOne,
10652                                                        const SelectionDAG &DAG,
10653                                                        unsigned Depth) const {
10654   unsigned BitWidth = KnownOne.getBitWidth();
10655   KnownZero = KnownOne = APInt(BitWidth, 0);
10656   switch (Op.getOpcode()) {
10657   default: break;
10658   case ARMISD::ADDC:
10659   case ARMISD::ADDE:
10660   case ARMISD::SUBC:
10661   case ARMISD::SUBE:
10662     // These nodes' second result is a boolean
10663     if (Op.getResNo() == 0)
10664       break;
10665     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10666     break;
10667   case ARMISD::CMOV: {
10668     // Bits are known zero/one if known on the LHS and RHS.
10669     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10670     if (KnownZero == 0 && KnownOne == 0) return;
10671
10672     APInt KnownZeroRHS, KnownOneRHS;
10673     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10674     KnownZero &= KnownZeroRHS;
10675     KnownOne  &= KnownOneRHS;
10676     return;
10677   }
10678   }
10679 }
10680
10681 //===----------------------------------------------------------------------===//
10682 //                           ARM Inline Assembly Support
10683 //===----------------------------------------------------------------------===//
10684
10685 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10686   // Looking for "rev" which is V6+.
10687   if (!Subtarget->hasV6Ops())
10688     return false;
10689
10690   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10691   std::string AsmStr = IA->getAsmString();
10692   SmallVector<StringRef, 4> AsmPieces;
10693   SplitString(AsmStr, AsmPieces, ";\n");
10694
10695   switch (AsmPieces.size()) {
10696   default: return false;
10697   case 1:
10698     AsmStr = AsmPieces[0];
10699     AsmPieces.clear();
10700     SplitString(AsmStr, AsmPieces, " \t,");
10701
10702     // rev $0, $1
10703     if (AsmPieces.size() == 3 &&
10704         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10705         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10706       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10707       if (Ty && Ty->getBitWidth() == 32)
10708         return IntrinsicLowering::LowerToByteSwap(CI);
10709     }
10710     break;
10711   }
10712
10713   return false;
10714 }
10715
10716 /// getConstraintType - Given a constraint letter, return the type of
10717 /// constraint it is for this target.
10718 ARMTargetLowering::ConstraintType
10719 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10720   if (Constraint.size() == 1) {
10721     switch (Constraint[0]) {
10722     default:  break;
10723     case 'l': return C_RegisterClass;
10724     case 'w': return C_RegisterClass;
10725     case 'h': return C_RegisterClass;
10726     case 'x': return C_RegisterClass;
10727     case 't': return C_RegisterClass;
10728     case 'j': return C_Other; // Constant for movw.
10729       // An address with a single base register. Due to the way we
10730       // currently handle addresses it is the same as an 'r' memory constraint.
10731     case 'Q': return C_Memory;
10732     }
10733   } else if (Constraint.size() == 2) {
10734     switch (Constraint[0]) {
10735     default: break;
10736     // All 'U+' constraints are addresses.
10737     case 'U': return C_Memory;
10738     }
10739   }
10740   return TargetLowering::getConstraintType(Constraint);
10741 }
10742
10743 /// Examine constraint type and operand type and determine a weight value.
10744 /// This object must already have been set up with the operand type
10745 /// and the current alternative constraint selected.
10746 TargetLowering::ConstraintWeight
10747 ARMTargetLowering::getSingleConstraintMatchWeight(
10748     AsmOperandInfo &info, const char *constraint) const {
10749   ConstraintWeight weight = CW_Invalid;
10750   Value *CallOperandVal = info.CallOperandVal;
10751     // If we don't have a value, we can't do a match,
10752     // but allow it at the lowest weight.
10753   if (CallOperandVal == NULL)
10754     return CW_Default;
10755   Type *type = CallOperandVal->getType();
10756   // Look at the constraint type.
10757   switch (*constraint) {
10758   default:
10759     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10760     break;
10761   case 'l':
10762     if (type->isIntegerTy()) {
10763       if (Subtarget->isThumb())
10764         weight = CW_SpecificReg;
10765       else
10766         weight = CW_Register;
10767     }
10768     break;
10769   case 'w':
10770     if (type->isFloatingPointTy())
10771       weight = CW_Register;
10772     break;
10773   }
10774   return weight;
10775 }
10776
10777 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10778 RCPair
10779 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10780                                                 MVT VT) const {
10781   if (Constraint.size() == 1) {
10782     // GCC ARM Constraint Letters
10783     switch (Constraint[0]) {
10784     case 'l': // Low regs or general regs.
10785       if (Subtarget->isThumb())
10786         return RCPair(0U, &ARM::tGPRRegClass);
10787       return RCPair(0U, &ARM::GPRRegClass);
10788     case 'h': // High regs or no regs.
10789       if (Subtarget->isThumb())
10790         return RCPair(0U, &ARM::hGPRRegClass);
10791       break;
10792     case 'r':
10793       return RCPair(0U, &ARM::GPRRegClass);
10794     case 'w':
10795       if (VT == MVT::Other)
10796         break;
10797       if (VT == MVT::f32)
10798         return RCPair(0U, &ARM::SPRRegClass);
10799       if (VT.getSizeInBits() == 64)
10800         return RCPair(0U, &ARM::DPRRegClass);
10801       if (VT.getSizeInBits() == 128)
10802         return RCPair(0U, &ARM::QPRRegClass);
10803       break;
10804     case 'x':
10805       if (VT == MVT::Other)
10806         break;
10807       if (VT == MVT::f32)
10808         return RCPair(0U, &ARM::SPR_8RegClass);
10809       if (VT.getSizeInBits() == 64)
10810         return RCPair(0U, &ARM::DPR_8RegClass);
10811       if (VT.getSizeInBits() == 128)
10812         return RCPair(0U, &ARM::QPR_8RegClass);
10813       break;
10814     case 't':
10815       if (VT == MVT::f32)
10816         return RCPair(0U, &ARM::SPRRegClass);
10817       break;
10818     }
10819   }
10820   if (StringRef("{cc}").equals_lower(Constraint))
10821     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10822
10823   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10824 }
10825
10826 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10827 /// vector.  If it is invalid, don't add anything to Ops.
10828 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10829                                                      std::string &Constraint,
10830                                                      std::vector<SDValue>&Ops,
10831                                                      SelectionDAG &DAG) const {
10832   SDValue Result(0, 0);
10833
10834   // Currently only support length 1 constraints.
10835   if (Constraint.length() != 1) return;
10836
10837   char ConstraintLetter = Constraint[0];
10838   switch (ConstraintLetter) {
10839   default: break;
10840   case 'j':
10841   case 'I': case 'J': case 'K': case 'L':
10842   case 'M': case 'N': case 'O':
10843     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10844     if (!C)
10845       return;
10846
10847     int64_t CVal64 = C->getSExtValue();
10848     int CVal = (int) CVal64;
10849     // None of these constraints allow values larger than 32 bits.  Check
10850     // that the value fits in an int.
10851     if (CVal != CVal64)
10852       return;
10853
10854     switch (ConstraintLetter) {
10855       case 'j':
10856         // Constant suitable for movw, must be between 0 and
10857         // 65535.
10858         if (Subtarget->hasV6T2Ops())
10859           if (CVal >= 0 && CVal <= 65535)
10860             break;
10861         return;
10862       case 'I':
10863         if (Subtarget->isThumb1Only()) {
10864           // This must be a constant between 0 and 255, for ADD
10865           // immediates.
10866           if (CVal >= 0 && CVal <= 255)
10867             break;
10868         } else if (Subtarget->isThumb2()) {
10869           // A constant that can be used as an immediate value in a
10870           // data-processing instruction.
10871           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10872             break;
10873         } else {
10874           // A constant that can be used as an immediate value in a
10875           // data-processing instruction.
10876           if (ARM_AM::getSOImmVal(CVal) != -1)
10877             break;
10878         }
10879         return;
10880
10881       case 'J':
10882         if (Subtarget->isThumb()) {  // FIXME thumb2
10883           // This must be a constant between -255 and -1, for negated ADD
10884           // immediates. This can be used in GCC with an "n" modifier that
10885           // prints the negated value, for use with SUB instructions. It is
10886           // not useful otherwise but is implemented for compatibility.
10887           if (CVal >= -255 && CVal <= -1)
10888             break;
10889         } else {
10890           // This must be a constant between -4095 and 4095. It is not clear
10891           // what this constraint is intended for. Implemented for
10892           // compatibility with GCC.
10893           if (CVal >= -4095 && CVal <= 4095)
10894             break;
10895         }
10896         return;
10897
10898       case 'K':
10899         if (Subtarget->isThumb1Only()) {
10900           // A 32-bit value where only one byte has a nonzero value. Exclude
10901           // zero to match GCC. This constraint is used by GCC internally for
10902           // constants that can be loaded with a move/shift combination.
10903           // It is not useful otherwise but is implemented for compatibility.
10904           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10905             break;
10906         } else if (Subtarget->isThumb2()) {
10907           // A constant whose bitwise inverse can be used as an immediate
10908           // value in a data-processing instruction. This can be used in GCC
10909           // with a "B" modifier that prints the inverted value, for use with
10910           // BIC and MVN instructions. It is not useful otherwise but is
10911           // implemented for compatibility.
10912           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10913             break;
10914         } else {
10915           // A constant whose bitwise inverse can be used as an immediate
10916           // value in a data-processing instruction. This can be used in GCC
10917           // with a "B" modifier that prints the inverted value, for use with
10918           // BIC and MVN instructions. It is not useful otherwise but is
10919           // implemented for compatibility.
10920           if (ARM_AM::getSOImmVal(~CVal) != -1)
10921             break;
10922         }
10923         return;
10924
10925       case 'L':
10926         if (Subtarget->isThumb1Only()) {
10927           // This must be a constant between -7 and 7,
10928           // for 3-operand ADD/SUB immediate instructions.
10929           if (CVal >= -7 && CVal < 7)
10930             break;
10931         } else if (Subtarget->isThumb2()) {
10932           // A constant whose negation can be used as an immediate value in a
10933           // data-processing instruction. This can be used in GCC with an "n"
10934           // modifier that prints the negated value, for use with SUB
10935           // instructions. It is not useful otherwise but is implemented for
10936           // compatibility.
10937           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10938             break;
10939         } else {
10940           // A constant whose negation can be used as an immediate value in a
10941           // data-processing instruction. This can be used in GCC with an "n"
10942           // modifier that prints the negated value, for use with SUB
10943           // instructions. It is not useful otherwise but is implemented for
10944           // compatibility.
10945           if (ARM_AM::getSOImmVal(-CVal) != -1)
10946             break;
10947         }
10948         return;
10949
10950       case 'M':
10951         if (Subtarget->isThumb()) { // FIXME thumb2
10952           // This must be a multiple of 4 between 0 and 1020, for
10953           // ADD sp + immediate.
10954           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10955             break;
10956         } else {
10957           // A power of two or a constant between 0 and 32.  This is used in
10958           // GCC for the shift amount on shifted register operands, but it is
10959           // useful in general for any shift amounts.
10960           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10961             break;
10962         }
10963         return;
10964
10965       case 'N':
10966         if (Subtarget->isThumb()) {  // FIXME thumb2
10967           // This must be a constant between 0 and 31, for shift amounts.
10968           if (CVal >= 0 && CVal <= 31)
10969             break;
10970         }
10971         return;
10972
10973       case 'O':
10974         if (Subtarget->isThumb()) {  // FIXME thumb2
10975           // This must be a multiple of 4 between -508 and 508, for
10976           // ADD/SUB sp = sp + immediate.
10977           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10978             break;
10979         }
10980         return;
10981     }
10982     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10983     break;
10984   }
10985
10986   if (Result.getNode()) {
10987     Ops.push_back(Result);
10988     return;
10989   }
10990   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10991 }
10992
10993 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10994   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10995   unsigned Opcode = Op->getOpcode();
10996   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10997       "Invalid opcode for Div/Rem lowering");
10998   bool isSigned = (Opcode == ISD::SDIVREM);
10999   EVT VT = Op->getValueType(0);
11000   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11001
11002   RTLIB::Libcall LC;
11003   switch (VT.getSimpleVT().SimpleTy) {
11004   default: llvm_unreachable("Unexpected request for libcall!");
11005   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11006   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11007   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11008   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11009   }
11010
11011   SDValue InChain = DAG.getEntryNode();
11012
11013   TargetLowering::ArgListTy Args;
11014   TargetLowering::ArgListEntry Entry;
11015   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11016     EVT ArgVT = Op->getOperand(i).getValueType();
11017     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11018     Entry.Node = Op->getOperand(i);
11019     Entry.Ty = ArgTy;
11020     Entry.isSExt = isSigned;
11021     Entry.isZExt = !isSigned;
11022     Args.push_back(Entry);
11023   }
11024
11025   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11026                                          getPointerTy());
11027
11028   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11029
11030   SDLoc dl(Op);
11031   TargetLowering::
11032   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11033                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11034                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11035                     Callee, Args, DAG, dl);
11036   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11037
11038   return CallInfo.first;
11039 }
11040
11041 bool
11042 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11043   // The ARM target isn't yet aware of offsets.
11044   return false;
11045 }
11046
11047 bool ARM::isBitFieldInvertedMask(unsigned v) {
11048   if (v == 0xffffffff)
11049     return false;
11050
11051   // there can be 1's on either or both "outsides", all the "inside"
11052   // bits must be 0's
11053   unsigned TO = CountTrailingOnes_32(v);
11054   unsigned LO = CountLeadingOnes_32(v);
11055   v = (v >> TO) << TO;
11056   v = (v << LO) >> LO;
11057   return v == 0;
11058 }
11059
11060 /// isFPImmLegal - Returns true if the target can instruction select the
11061 /// specified FP immediate natively. If false, the legalizer will
11062 /// materialize the FP immediate as a load from a constant pool.
11063 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11064   if (!Subtarget->hasVFP3())
11065     return false;
11066   if (VT == MVT::f32)
11067     return ARM_AM::getFP32Imm(Imm) != -1;
11068   if (VT == MVT::f64)
11069     return ARM_AM::getFP64Imm(Imm) != -1;
11070   return false;
11071 }
11072
11073 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11074 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11075 /// specified in the intrinsic calls.
11076 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11077                                            const CallInst &I,
11078                                            unsigned Intrinsic) const {
11079   switch (Intrinsic) {
11080   case Intrinsic::arm_neon_vld1:
11081   case Intrinsic::arm_neon_vld2:
11082   case Intrinsic::arm_neon_vld3:
11083   case Intrinsic::arm_neon_vld4:
11084   case Intrinsic::arm_neon_vld2lane:
11085   case Intrinsic::arm_neon_vld3lane:
11086   case Intrinsic::arm_neon_vld4lane: {
11087     Info.opc = ISD::INTRINSIC_W_CHAIN;
11088     // Conservatively set memVT to the entire set of vectors loaded.
11089     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11090     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11091     Info.ptrVal = I.getArgOperand(0);
11092     Info.offset = 0;
11093     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11094     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11095     Info.vol = false; // volatile loads with NEON intrinsics not supported
11096     Info.readMem = true;
11097     Info.writeMem = false;
11098     return true;
11099   }
11100   case Intrinsic::arm_neon_vst1:
11101   case Intrinsic::arm_neon_vst2:
11102   case Intrinsic::arm_neon_vst3:
11103   case Intrinsic::arm_neon_vst4:
11104   case Intrinsic::arm_neon_vst2lane:
11105   case Intrinsic::arm_neon_vst3lane:
11106   case Intrinsic::arm_neon_vst4lane: {
11107     Info.opc = ISD::INTRINSIC_VOID;
11108     // Conservatively set memVT to the entire set of vectors stored.
11109     unsigned NumElts = 0;
11110     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11111       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11112       if (!ArgTy->isVectorTy())
11113         break;
11114       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11115     }
11116     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11117     Info.ptrVal = I.getArgOperand(0);
11118     Info.offset = 0;
11119     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11120     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11121     Info.vol = false; // volatile stores with NEON intrinsics not supported
11122     Info.readMem = false;
11123     Info.writeMem = true;
11124     return true;
11125   }
11126   case Intrinsic::arm_ldrex: {
11127     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11128     Info.opc = ISD::INTRINSIC_W_CHAIN;
11129     Info.memVT = MVT::getVT(PtrTy->getElementType());
11130     Info.ptrVal = I.getArgOperand(0);
11131     Info.offset = 0;
11132     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11133     Info.vol = true;
11134     Info.readMem = true;
11135     Info.writeMem = false;
11136     return true;
11137   }
11138   case Intrinsic::arm_strex: {
11139     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11140     Info.opc = ISD::INTRINSIC_W_CHAIN;
11141     Info.memVT = MVT::getVT(PtrTy->getElementType());
11142     Info.ptrVal = I.getArgOperand(1);
11143     Info.offset = 0;
11144     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11145     Info.vol = true;
11146     Info.readMem = false;
11147     Info.writeMem = true;
11148     return true;
11149   }
11150   case Intrinsic::arm_strexd: {
11151     Info.opc = ISD::INTRINSIC_W_CHAIN;
11152     Info.memVT = MVT::i64;
11153     Info.ptrVal = I.getArgOperand(2);
11154     Info.offset = 0;
11155     Info.align = 8;
11156     Info.vol = true;
11157     Info.readMem = false;
11158     Info.writeMem = true;
11159     return true;
11160   }
11161   case Intrinsic::arm_ldrexd: {
11162     Info.opc = ISD::INTRINSIC_W_CHAIN;
11163     Info.memVT = MVT::i64;
11164     Info.ptrVal = I.getArgOperand(0);
11165     Info.offset = 0;
11166     Info.align = 8;
11167     Info.vol = true;
11168     Info.readMem = true;
11169     Info.writeMem = false;
11170     return true;
11171   }
11172   default:
11173     break;
11174   }
11175
11176   return false;
11177 }
11178
11179 /// \brief Returns true if it is beneficial to convert a load of a constant
11180 /// to just the constant itself.
11181 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11182                                                           Type *Ty) const {
11183   assert(Ty->isIntegerTy());
11184
11185   unsigned Bits = Ty->getPrimitiveSizeInBits();
11186   if (Bits == 0 || Bits > 32)
11187     return false;
11188   return true;
11189 }