[C++11] Replace llvm::next and llvm::prior with std::next and std::prev.
[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                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6203   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6204
6205   //  thisMBB:
6206   //   ...
6207   //   fallthrough --> loop1MBB
6208   BB->addSuccessor(loop1MBB);
6209
6210   // loop1MBB:
6211   //   ldrex dest, [ptr]
6212   //   cmp dest, oldval
6213   //   bne exitMBB
6214   BB = loop1MBB;
6215   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6216   if (ldrOpc == ARM::t2LDREX)
6217     MIB.addImm(0);
6218   AddDefaultPred(MIB);
6219   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6220                  .addReg(dest).addReg(oldval));
6221   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6222     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6223   BB->addSuccessor(loop2MBB);
6224   BB->addSuccessor(exitMBB);
6225
6226   // loop2MBB:
6227   //   strex scratch, newval, [ptr]
6228   //   cmp scratch, #0
6229   //   bne loop1MBB
6230   BB = loop2MBB;
6231   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6232   if (strOpc == ARM::t2STREX)
6233     MIB.addImm(0);
6234   AddDefaultPred(MIB);
6235   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6236                  .addReg(scratch).addImm(0));
6237   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6238     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6239   BB->addSuccessor(loop1MBB);
6240   BB->addSuccessor(exitMBB);
6241
6242   //  exitMBB:
6243   //   ...
6244   BB = exitMBB;
6245
6246   MI->eraseFromParent();   // The instruction is gone now.
6247
6248   return BB;
6249 }
6250
6251 MachineBasicBlock *
6252 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6253                                     unsigned Size, unsigned BinOpcode) const {
6254   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6255   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6256
6257   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6258   MachineFunction *MF = BB->getParent();
6259   MachineFunction::iterator It = BB;
6260   ++It;
6261
6262   unsigned dest = MI->getOperand(0).getReg();
6263   unsigned ptr = MI->getOperand(1).getReg();
6264   unsigned incr = MI->getOperand(2).getReg();
6265   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6266   DebugLoc dl = MI->getDebugLoc();
6267   bool isThumb2 = Subtarget->isThumb2();
6268
6269   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6270   if (isThumb2) {
6271     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6272     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6273     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6274   }
6275
6276   unsigned ldrOpc, strOpc;
6277   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6278
6279   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6280   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6281   MF->insert(It, loopMBB);
6282   MF->insert(It, exitMBB);
6283
6284   // Transfer the remainder of BB and its successor edges to exitMBB.
6285   exitMBB->splice(exitMBB->begin(), BB,
6286                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6287   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6288
6289   const TargetRegisterClass *TRC = isThumb2 ?
6290     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6291     (const TargetRegisterClass*)&ARM::GPRRegClass;
6292   unsigned scratch = MRI.createVirtualRegister(TRC);
6293   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6294
6295   //  thisMBB:
6296   //   ...
6297   //   fallthrough --> loopMBB
6298   BB->addSuccessor(loopMBB);
6299
6300   //  loopMBB:
6301   //   ldrex dest, ptr
6302   //   <binop> scratch2, dest, incr
6303   //   strex scratch, scratch2, ptr
6304   //   cmp scratch, #0
6305   //   bne- loopMBB
6306   //   fallthrough --> exitMBB
6307   BB = loopMBB;
6308   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6309   if (ldrOpc == ARM::t2LDREX)
6310     MIB.addImm(0);
6311   AddDefaultPred(MIB);
6312   if (BinOpcode) {
6313     // operand order needs to go the other way for NAND
6314     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6315       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6316                      addReg(incr).addReg(dest)).addReg(0);
6317     else
6318       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6319                      addReg(dest).addReg(incr)).addReg(0);
6320   }
6321
6322   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6323   if (strOpc == ARM::t2STREX)
6324     MIB.addImm(0);
6325   AddDefaultPred(MIB);
6326   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6327                  .addReg(scratch).addImm(0));
6328   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6329     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6330
6331   BB->addSuccessor(loopMBB);
6332   BB->addSuccessor(exitMBB);
6333
6334   //  exitMBB:
6335   //   ...
6336   BB = exitMBB;
6337
6338   MI->eraseFromParent();   // The instruction is gone now.
6339
6340   return BB;
6341 }
6342
6343 MachineBasicBlock *
6344 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6345                                           MachineBasicBlock *BB,
6346                                           unsigned Size,
6347                                           bool signExtend,
6348                                           ARMCC::CondCodes Cond) const {
6349   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6350
6351   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6352   MachineFunction *MF = BB->getParent();
6353   MachineFunction::iterator It = BB;
6354   ++It;
6355
6356   unsigned dest = MI->getOperand(0).getReg();
6357   unsigned ptr = MI->getOperand(1).getReg();
6358   unsigned incr = MI->getOperand(2).getReg();
6359   unsigned oldval = dest;
6360   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6361   DebugLoc dl = MI->getDebugLoc();
6362   bool isThumb2 = Subtarget->isThumb2();
6363
6364   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6365   if (isThumb2) {
6366     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6367     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6368     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6369   }
6370
6371   unsigned ldrOpc, strOpc, extendOpc;
6372   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6373   switch (Size) {
6374   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6375   case 1:
6376     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6377     break;
6378   case 2:
6379     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6380     break;
6381   case 4:
6382     extendOpc = 0;
6383     break;
6384   }
6385
6386   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6387   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6388   MF->insert(It, loopMBB);
6389   MF->insert(It, exitMBB);
6390
6391   // Transfer the remainder of BB and its successor edges to exitMBB.
6392   exitMBB->splice(exitMBB->begin(), BB,
6393                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6394   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6395
6396   const TargetRegisterClass *TRC = isThumb2 ?
6397     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6398     (const TargetRegisterClass*)&ARM::GPRRegClass;
6399   unsigned scratch = MRI.createVirtualRegister(TRC);
6400   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6401
6402   //  thisMBB:
6403   //   ...
6404   //   fallthrough --> loopMBB
6405   BB->addSuccessor(loopMBB);
6406
6407   //  loopMBB:
6408   //   ldrex dest, ptr
6409   //   (sign extend dest, if required)
6410   //   cmp dest, incr
6411   //   cmov.cond scratch2, incr, dest
6412   //   strex scratch, scratch2, ptr
6413   //   cmp scratch, #0
6414   //   bne- loopMBB
6415   //   fallthrough --> exitMBB
6416   BB = loopMBB;
6417   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6418   if (ldrOpc == ARM::t2LDREX)
6419     MIB.addImm(0);
6420   AddDefaultPred(MIB);
6421
6422   // Sign extend the value, if necessary.
6423   if (signExtend && extendOpc) {
6424     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6425                                                 : &ARM::GPRnopcRegClass);
6426     if (!isThumb2)
6427       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6428     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6429                      .addReg(dest)
6430                      .addImm(0));
6431   }
6432
6433   // Build compare and cmov instructions.
6434   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6435                  .addReg(oldval).addReg(incr));
6436   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6437          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6438
6439   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6440   if (strOpc == ARM::t2STREX)
6441     MIB.addImm(0);
6442   AddDefaultPred(MIB);
6443   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6444                  .addReg(scratch).addImm(0));
6445   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6446     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6447
6448   BB->addSuccessor(loopMBB);
6449   BB->addSuccessor(exitMBB);
6450
6451   //  exitMBB:
6452   //   ...
6453   BB = exitMBB;
6454
6455   MI->eraseFromParent();   // The instruction is gone now.
6456
6457   return BB;
6458 }
6459
6460 MachineBasicBlock *
6461 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6462                                       unsigned Op1, unsigned Op2,
6463                                       bool NeedsCarry, bool IsCmpxchg,
6464                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6465   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6466   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6467
6468   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6469   MachineFunction *MF = BB->getParent();
6470   MachineFunction::iterator It = BB;
6471   ++It;
6472
6473   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6474   unsigned offset = (isStore ? -2 : 0);
6475   unsigned destlo = MI->getOperand(0).getReg();
6476   unsigned desthi = MI->getOperand(1).getReg();
6477   unsigned ptr = MI->getOperand(offset+2).getReg();
6478   unsigned vallo = MI->getOperand(offset+3).getReg();
6479   unsigned valhi = MI->getOperand(offset+4).getReg();
6480   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6481   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6482   DebugLoc dl = MI->getDebugLoc();
6483   bool isThumb2 = Subtarget->isThumb2();
6484
6485   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6486   if (isThumb2) {
6487     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6488     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6489     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6490     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6491     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6492   }
6493
6494   unsigned ldrOpc, strOpc;
6495   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6496
6497   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6498   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6499   if (IsCmpxchg || IsMinMax)
6500     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6501   if (IsCmpxchg)
6502     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6503   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6504
6505   MF->insert(It, loopMBB);
6506   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6507   if (IsCmpxchg) MF->insert(It, cont2BB);
6508   MF->insert(It, exitMBB);
6509
6510   // Transfer the remainder of BB and its successor edges to exitMBB.
6511   exitMBB->splice(exitMBB->begin(), BB,
6512                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6513   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6514
6515   const TargetRegisterClass *TRC = isThumb2 ?
6516     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6517     (const TargetRegisterClass*)&ARM::GPRRegClass;
6518   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6519
6520   //  thisMBB:
6521   //   ...
6522   //   fallthrough --> loopMBB
6523   BB->addSuccessor(loopMBB);
6524
6525   //  loopMBB:
6526   //   ldrexd r2, r3, ptr
6527   //   <binopa> r0, r2, incr
6528   //   <binopb> r1, r3, incr
6529   //   strexd storesuccess, r0, r1, ptr
6530   //   cmp storesuccess, #0
6531   //   bne- loopMBB
6532   //   fallthrough --> exitMBB
6533   BB = loopMBB;
6534
6535   if (!isStore) {
6536     // Load
6537     if (isThumb2) {
6538       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6539                      .addReg(destlo, RegState::Define)
6540                      .addReg(desthi, RegState::Define)
6541                      .addReg(ptr));
6542     } else {
6543       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6544       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6545                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6546       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6547       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6548         .addReg(GPRPair0, 0, ARM::gsub_0);
6549       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6550         .addReg(GPRPair0, 0, ARM::gsub_1);
6551     }
6552   }
6553
6554   unsigned StoreLo, StoreHi;
6555   if (IsCmpxchg) {
6556     // Add early exit
6557     for (unsigned i = 0; i < 2; i++) {
6558       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6559                                                          ARM::CMPrr))
6560                      .addReg(i == 0 ? destlo : desthi)
6561                      .addReg(i == 0 ? vallo : valhi));
6562       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6563         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6564       BB->addSuccessor(exitMBB);
6565       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6566       BB = (i == 0 ? contBB : cont2BB);
6567     }
6568
6569     // Copy to physregs for strexd
6570     StoreLo = MI->getOperand(5).getReg();
6571     StoreHi = MI->getOperand(6).getReg();
6572   } else if (Op1) {
6573     // Perform binary operation
6574     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6575     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6576                    .addReg(destlo).addReg(vallo))
6577         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6578     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6579     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6580                    .addReg(desthi).addReg(valhi))
6581         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6582
6583     StoreLo = tmpRegLo;
6584     StoreHi = tmpRegHi;
6585   } else {
6586     // Copy to physregs for strexd
6587     StoreLo = vallo;
6588     StoreHi = valhi;
6589   }
6590   if (IsMinMax) {
6591     // Compare and branch to exit block.
6592     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6593       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6594     BB->addSuccessor(exitMBB);
6595     BB->addSuccessor(contBB);
6596     BB = contBB;
6597     StoreLo = vallo;
6598     StoreHi = valhi;
6599   }
6600
6601   // Store
6602   if (isThumb2) {
6603     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6604     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6605     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6606                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6607   } else {
6608     // Marshal a pair...
6609     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6610     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6611     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6612     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6613     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6614       .addReg(UndefPair)
6615       .addReg(StoreLo)
6616       .addImm(ARM::gsub_0);
6617     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6618       .addReg(r1)
6619       .addReg(StoreHi)
6620       .addImm(ARM::gsub_1);
6621
6622     // ...and store it
6623     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6624                    .addReg(StorePair).addReg(ptr));
6625   }
6626   // Cmp+jump
6627   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6628                  .addReg(storesuccess).addImm(0));
6629   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6630     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6631
6632   BB->addSuccessor(loopMBB);
6633   BB->addSuccessor(exitMBB);
6634
6635   //  exitMBB:
6636   //   ...
6637   BB = exitMBB;
6638
6639   MI->eraseFromParent();   // The instruction is gone now.
6640
6641   return BB;
6642 }
6643
6644 MachineBasicBlock *
6645 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6646
6647   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6648
6649   unsigned destlo = MI->getOperand(0).getReg();
6650   unsigned desthi = MI->getOperand(1).getReg();
6651   unsigned ptr = MI->getOperand(2).getReg();
6652   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6653   DebugLoc dl = MI->getDebugLoc();
6654   bool isThumb2 = Subtarget->isThumb2();
6655
6656   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6657   if (isThumb2) {
6658     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6659     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6660     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6661   }
6662   unsigned ldrOpc, strOpc;
6663   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6664
6665   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6666
6667   if (isThumb2) {
6668     MIB.addReg(destlo, RegState::Define)
6669        .addReg(desthi, RegState::Define)
6670        .addReg(ptr);
6671
6672   } else {
6673     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6674     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6675
6676     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6677     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6678       .addReg(GPRPair0, 0, ARM::gsub_0);
6679     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6680       .addReg(GPRPair0, 0, ARM::gsub_1);
6681   }
6682   AddDefaultPred(MIB);
6683
6684   MI->eraseFromParent();   // The instruction is gone now.
6685
6686   return BB;
6687 }
6688
6689 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6690 /// registers the function context.
6691 void ARMTargetLowering::
6692 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6693                        MachineBasicBlock *DispatchBB, int FI) const {
6694   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6695   DebugLoc dl = MI->getDebugLoc();
6696   MachineFunction *MF = MBB->getParent();
6697   MachineRegisterInfo *MRI = &MF->getRegInfo();
6698   MachineConstantPool *MCP = MF->getConstantPool();
6699   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6700   const Function *F = MF->getFunction();
6701
6702   bool isThumb = Subtarget->isThumb();
6703   bool isThumb2 = Subtarget->isThumb2();
6704
6705   unsigned PCLabelId = AFI->createPICLabelUId();
6706   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6707   ARMConstantPoolValue *CPV =
6708     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6709   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6710
6711   const TargetRegisterClass *TRC = isThumb ?
6712     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6713     (const TargetRegisterClass*)&ARM::GPRRegClass;
6714
6715   // Grab constant pool and fixed stack memory operands.
6716   MachineMemOperand *CPMMO =
6717     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6718                              MachineMemOperand::MOLoad, 4, 4);
6719
6720   MachineMemOperand *FIMMOSt =
6721     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6722                              MachineMemOperand::MOStore, 4, 4);
6723
6724   // Load the address of the dispatch MBB into the jump buffer.
6725   if (isThumb2) {
6726     // Incoming value: jbuf
6727     //   ldr.n  r5, LCPI1_1
6728     //   orr    r5, r5, #1
6729     //   add    r5, pc
6730     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6731     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6732     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6733                    .addConstantPoolIndex(CPI)
6734                    .addMemOperand(CPMMO));
6735     // Set the low bit because of thumb mode.
6736     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6737     AddDefaultCC(
6738       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6739                      .addReg(NewVReg1, RegState::Kill)
6740                      .addImm(0x01)));
6741     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6742     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6743       .addReg(NewVReg2, RegState::Kill)
6744       .addImm(PCLabelId);
6745     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6746                    .addReg(NewVReg3, RegState::Kill)
6747                    .addFrameIndex(FI)
6748                    .addImm(36)  // &jbuf[1] :: pc
6749                    .addMemOperand(FIMMOSt));
6750   } else if (isThumb) {
6751     // Incoming value: jbuf
6752     //   ldr.n  r1, LCPI1_4
6753     //   add    r1, pc
6754     //   mov    r2, #1
6755     //   orrs   r1, r2
6756     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6757     //   str    r1, [r2]
6758     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6759     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6760                    .addConstantPoolIndex(CPI)
6761                    .addMemOperand(CPMMO));
6762     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6763     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6764       .addReg(NewVReg1, RegState::Kill)
6765       .addImm(PCLabelId);
6766     // Set the low bit because of thumb mode.
6767     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6768     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6769                    .addReg(ARM::CPSR, RegState::Define)
6770                    .addImm(1));
6771     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6772     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6773                    .addReg(ARM::CPSR, RegState::Define)
6774                    .addReg(NewVReg2, RegState::Kill)
6775                    .addReg(NewVReg3, RegState::Kill));
6776     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6777     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6778                    .addFrameIndex(FI)
6779                    .addImm(36)); // &jbuf[1] :: pc
6780     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6781                    .addReg(NewVReg4, RegState::Kill)
6782                    .addReg(NewVReg5, RegState::Kill)
6783                    .addImm(0)
6784                    .addMemOperand(FIMMOSt));
6785   } else {
6786     // Incoming value: jbuf
6787     //   ldr  r1, LCPI1_1
6788     //   add  r1, pc, r1
6789     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6790     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6791     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6792                    .addConstantPoolIndex(CPI)
6793                    .addImm(0)
6794                    .addMemOperand(CPMMO));
6795     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6796     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6797                    .addReg(NewVReg1, RegState::Kill)
6798                    .addImm(PCLabelId));
6799     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6800                    .addReg(NewVReg2, RegState::Kill)
6801                    .addFrameIndex(FI)
6802                    .addImm(36)  // &jbuf[1] :: pc
6803                    .addMemOperand(FIMMOSt));
6804   }
6805 }
6806
6807 MachineBasicBlock *ARMTargetLowering::
6808 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6809   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6810   DebugLoc dl = MI->getDebugLoc();
6811   MachineFunction *MF = MBB->getParent();
6812   MachineRegisterInfo *MRI = &MF->getRegInfo();
6813   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6814   MachineFrameInfo *MFI = MF->getFrameInfo();
6815   int FI = MFI->getFunctionContextIndex();
6816
6817   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6818     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6819     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6820
6821   // Get a mapping of the call site numbers to all of the landing pads they're
6822   // associated with.
6823   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6824   unsigned MaxCSNum = 0;
6825   MachineModuleInfo &MMI = MF->getMMI();
6826   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6827        ++BB) {
6828     if (!BB->isLandingPad()) continue;
6829
6830     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6831     // pad.
6832     for (MachineBasicBlock::iterator
6833            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6834       if (!II->isEHLabel()) continue;
6835
6836       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6837       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6838
6839       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6840       for (SmallVectorImpl<unsigned>::iterator
6841              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6842            CSI != CSE; ++CSI) {
6843         CallSiteNumToLPad[*CSI].push_back(BB);
6844         MaxCSNum = std::max(MaxCSNum, *CSI);
6845       }
6846       break;
6847     }
6848   }
6849
6850   // Get an ordered list of the machine basic blocks for the jump table.
6851   std::vector<MachineBasicBlock*> LPadList;
6852   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6853   LPadList.reserve(CallSiteNumToLPad.size());
6854   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6855     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6856     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6857            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6858       LPadList.push_back(*II);
6859       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6860     }
6861   }
6862
6863   assert(!LPadList.empty() &&
6864          "No landing pad destinations for the dispatch jump table!");
6865
6866   // Create the jump table and associated information.
6867   MachineJumpTableInfo *JTI =
6868     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6869   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6870   unsigned UId = AFI->createJumpTableUId();
6871   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6872
6873   // Create the MBBs for the dispatch code.
6874
6875   // Shove the dispatch's address into the return slot in the function context.
6876   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6877   DispatchBB->setIsLandingPad();
6878
6879   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6880   unsigned trap_opcode;
6881   if (Subtarget->isThumb())
6882     trap_opcode = ARM::tTRAP;
6883   else
6884     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6885
6886   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6887   DispatchBB->addSuccessor(TrapBB);
6888
6889   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6890   DispatchBB->addSuccessor(DispContBB);
6891
6892   // Insert and MBBs.
6893   MF->insert(MF->end(), DispatchBB);
6894   MF->insert(MF->end(), DispContBB);
6895   MF->insert(MF->end(), TrapBB);
6896
6897   // Insert code into the entry block that creates and registers the function
6898   // context.
6899   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6900
6901   MachineMemOperand *FIMMOLd =
6902     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6903                              MachineMemOperand::MOLoad |
6904                              MachineMemOperand::MOVolatile, 4, 4);
6905
6906   MachineInstrBuilder MIB;
6907   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6908
6909   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6910   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6911
6912   // Add a register mask with no preserved registers.  This results in all
6913   // registers being marked as clobbered.
6914   MIB.addRegMask(RI.getNoPreservedMask());
6915
6916   unsigned NumLPads = LPadList.size();
6917   if (Subtarget->isThumb2()) {
6918     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6919     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6920                    .addFrameIndex(FI)
6921                    .addImm(4)
6922                    .addMemOperand(FIMMOLd));
6923
6924     if (NumLPads < 256) {
6925       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6926                      .addReg(NewVReg1)
6927                      .addImm(LPadList.size()));
6928     } else {
6929       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6930       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6931                      .addImm(NumLPads & 0xFFFF));
6932
6933       unsigned VReg2 = VReg1;
6934       if ((NumLPads & 0xFFFF0000) != 0) {
6935         VReg2 = MRI->createVirtualRegister(TRC);
6936         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6937                        .addReg(VReg1)
6938                        .addImm(NumLPads >> 16));
6939       }
6940
6941       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6942                      .addReg(NewVReg1)
6943                      .addReg(VReg2));
6944     }
6945
6946     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6947       .addMBB(TrapBB)
6948       .addImm(ARMCC::HI)
6949       .addReg(ARM::CPSR);
6950
6951     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6952     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6953                    .addJumpTableIndex(MJTI)
6954                    .addImm(UId));
6955
6956     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6957     AddDefaultCC(
6958       AddDefaultPred(
6959         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6960         .addReg(NewVReg3, RegState::Kill)
6961         .addReg(NewVReg1)
6962         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6963
6964     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6965       .addReg(NewVReg4, RegState::Kill)
6966       .addReg(NewVReg1)
6967       .addJumpTableIndex(MJTI)
6968       .addImm(UId);
6969   } else if (Subtarget->isThumb()) {
6970     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6971     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6972                    .addFrameIndex(FI)
6973                    .addImm(1)
6974                    .addMemOperand(FIMMOLd));
6975
6976     if (NumLPads < 256) {
6977       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6978                      .addReg(NewVReg1)
6979                      .addImm(NumLPads));
6980     } else {
6981       MachineConstantPool *ConstantPool = MF->getConstantPool();
6982       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6983       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6984
6985       // MachineConstantPool wants an explicit alignment.
6986       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6987       if (Align == 0)
6988         Align = getDataLayout()->getTypeAllocSize(C->getType());
6989       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6990
6991       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6992       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6993                      .addReg(VReg1, RegState::Define)
6994                      .addConstantPoolIndex(Idx));
6995       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6996                      .addReg(NewVReg1)
6997                      .addReg(VReg1));
6998     }
6999
7000     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7001       .addMBB(TrapBB)
7002       .addImm(ARMCC::HI)
7003       .addReg(ARM::CPSR);
7004
7005     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7006     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7007                    .addReg(ARM::CPSR, RegState::Define)
7008                    .addReg(NewVReg1)
7009                    .addImm(2));
7010
7011     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7012     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7013                    .addJumpTableIndex(MJTI)
7014                    .addImm(UId));
7015
7016     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7017     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7018                    .addReg(ARM::CPSR, RegState::Define)
7019                    .addReg(NewVReg2, RegState::Kill)
7020                    .addReg(NewVReg3));
7021
7022     MachineMemOperand *JTMMOLd =
7023       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7024                                MachineMemOperand::MOLoad, 4, 4);
7025
7026     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7027     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7028                    .addReg(NewVReg4, RegState::Kill)
7029                    .addImm(0)
7030                    .addMemOperand(JTMMOLd));
7031
7032     unsigned NewVReg6 = NewVReg5;
7033     if (RelocM == Reloc::PIC_) {
7034       NewVReg6 = MRI->createVirtualRegister(TRC);
7035       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7036                      .addReg(ARM::CPSR, RegState::Define)
7037                      .addReg(NewVReg5, RegState::Kill)
7038                      .addReg(NewVReg3));
7039     }
7040
7041     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7042       .addReg(NewVReg6, RegState::Kill)
7043       .addJumpTableIndex(MJTI)
7044       .addImm(UId);
7045   } else {
7046     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7047     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7048                    .addFrameIndex(FI)
7049                    .addImm(4)
7050                    .addMemOperand(FIMMOLd));
7051
7052     if (NumLPads < 256) {
7053       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7054                      .addReg(NewVReg1)
7055                      .addImm(NumLPads));
7056     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7057       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7058       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7059                      .addImm(NumLPads & 0xFFFF));
7060
7061       unsigned VReg2 = VReg1;
7062       if ((NumLPads & 0xFFFF0000) != 0) {
7063         VReg2 = MRI->createVirtualRegister(TRC);
7064         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7065                        .addReg(VReg1)
7066                        .addImm(NumLPads >> 16));
7067       }
7068
7069       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7070                      .addReg(NewVReg1)
7071                      .addReg(VReg2));
7072     } else {
7073       MachineConstantPool *ConstantPool = MF->getConstantPool();
7074       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7075       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7076
7077       // MachineConstantPool wants an explicit alignment.
7078       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7079       if (Align == 0)
7080         Align = getDataLayout()->getTypeAllocSize(C->getType());
7081       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7082
7083       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7084       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7085                      .addReg(VReg1, RegState::Define)
7086                      .addConstantPoolIndex(Idx)
7087                      .addImm(0));
7088       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7089                      .addReg(NewVReg1)
7090                      .addReg(VReg1, RegState::Kill));
7091     }
7092
7093     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7094       .addMBB(TrapBB)
7095       .addImm(ARMCC::HI)
7096       .addReg(ARM::CPSR);
7097
7098     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7099     AddDefaultCC(
7100       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7101                      .addReg(NewVReg1)
7102                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7103     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7104     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7105                    .addJumpTableIndex(MJTI)
7106                    .addImm(UId));
7107
7108     MachineMemOperand *JTMMOLd =
7109       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7110                                MachineMemOperand::MOLoad, 4, 4);
7111     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7112     AddDefaultPred(
7113       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7114       .addReg(NewVReg3, RegState::Kill)
7115       .addReg(NewVReg4)
7116       .addImm(0)
7117       .addMemOperand(JTMMOLd));
7118
7119     if (RelocM == Reloc::PIC_) {
7120       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7121         .addReg(NewVReg5, RegState::Kill)
7122         .addReg(NewVReg4)
7123         .addJumpTableIndex(MJTI)
7124         .addImm(UId);
7125     } else {
7126       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7127         .addReg(NewVReg5, RegState::Kill)
7128         .addJumpTableIndex(MJTI)
7129         .addImm(UId);
7130     }
7131   }
7132
7133   // Add the jump table entries as successors to the MBB.
7134   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7135   for (std::vector<MachineBasicBlock*>::iterator
7136          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7137     MachineBasicBlock *CurMBB = *I;
7138     if (SeenMBBs.insert(CurMBB))
7139       DispContBB->addSuccessor(CurMBB);
7140   }
7141
7142   // N.B. the order the invoke BBs are processed in doesn't matter here.
7143   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7144   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7145   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7146          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7147     MachineBasicBlock *BB = *I;
7148
7149     // Remove the landing pad successor from the invoke block and replace it
7150     // with the new dispatch block.
7151     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7152                                                   BB->succ_end());
7153     while (!Successors.empty()) {
7154       MachineBasicBlock *SMBB = Successors.pop_back_val();
7155       if (SMBB->isLandingPad()) {
7156         BB->removeSuccessor(SMBB);
7157         MBBLPads.push_back(SMBB);
7158       }
7159     }
7160
7161     BB->addSuccessor(DispatchBB);
7162
7163     // Find the invoke call and mark all of the callee-saved registers as
7164     // 'implicit defined' so that they're spilled. This prevents code from
7165     // moving instructions to before the EH block, where they will never be
7166     // executed.
7167     for (MachineBasicBlock::reverse_iterator
7168            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7169       if (!II->isCall()) continue;
7170
7171       DenseMap<unsigned, bool> DefRegs;
7172       for (MachineInstr::mop_iterator
7173              OI = II->operands_begin(), OE = II->operands_end();
7174            OI != OE; ++OI) {
7175         if (!OI->isReg()) continue;
7176         DefRegs[OI->getReg()] = true;
7177       }
7178
7179       MachineInstrBuilder MIB(*MF, &*II);
7180
7181       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7182         unsigned Reg = SavedRegs[i];
7183         if (Subtarget->isThumb2() &&
7184             !ARM::tGPRRegClass.contains(Reg) &&
7185             !ARM::hGPRRegClass.contains(Reg))
7186           continue;
7187         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7188           continue;
7189         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7190           continue;
7191         if (!DefRegs[Reg])
7192           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7193       }
7194
7195       break;
7196     }
7197   }
7198
7199   // Mark all former landing pads as non-landing pads. The dispatch is the only
7200   // landing pad now.
7201   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7202          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7203     (*I)->setIsLandingPad(false);
7204
7205   // The instruction is gone now.
7206   MI->eraseFromParent();
7207
7208   return MBB;
7209 }
7210
7211 static
7212 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7213   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7214        E = MBB->succ_end(); I != E; ++I)
7215     if (*I != Succ)
7216       return *I;
7217   llvm_unreachable("Expecting a BB with two successors!");
7218 }
7219
7220 /// Return the load opcode for a given load size. If load size >= 8,
7221 /// neon opcode will be returned.
7222 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7223   if (LdSize >= 8)
7224     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7225                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7226   if (IsThumb1)
7227     return LdSize == 4 ? ARM::tLDRi
7228                        : LdSize == 2 ? ARM::tLDRHi
7229                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7230   if (IsThumb2)
7231     return LdSize == 4 ? ARM::t2LDR_POST
7232                        : LdSize == 2 ? ARM::t2LDRH_POST
7233                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7234   return LdSize == 4 ? ARM::LDR_POST_IMM
7235                      : LdSize == 2 ? ARM::LDRH_POST
7236                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7237 }
7238
7239 /// Return the store opcode for a given store size. If store size >= 8,
7240 /// neon opcode will be returned.
7241 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7242   if (StSize >= 8)
7243     return StSize == 16 ? ARM::VST1q32wb_fixed
7244                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7245   if (IsThumb1)
7246     return StSize == 4 ? ARM::tSTRi
7247                        : StSize == 2 ? ARM::tSTRHi
7248                                      : StSize == 1 ? ARM::tSTRBi : 0;
7249   if (IsThumb2)
7250     return StSize == 4 ? ARM::t2STR_POST
7251                        : StSize == 2 ? ARM::t2STRH_POST
7252                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7253   return StSize == 4 ? ARM::STR_POST_IMM
7254                      : StSize == 2 ? ARM::STRH_POST
7255                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7256 }
7257
7258 /// Emit a post-increment load operation with given size. The instructions
7259 /// will be added to BB at Pos.
7260 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7261                        const TargetInstrInfo *TII, DebugLoc dl,
7262                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7263                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7264   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7265   assert(LdOpc != 0 && "Should have a load opcode");
7266   if (LdSize >= 8) {
7267     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7268                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7269                        .addImm(0));
7270   } else if (IsThumb1) {
7271     // load + update AddrIn
7272     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7273                        .addReg(AddrIn).addImm(0));
7274     MachineInstrBuilder MIB =
7275         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7276     MIB = AddDefaultT1CC(MIB);
7277     MIB.addReg(AddrIn).addImm(LdSize);
7278     AddDefaultPred(MIB);
7279   } else if (IsThumb2) {
7280     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7281                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7282                        .addImm(LdSize));
7283   } else { // arm
7284     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7285                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7286                        .addReg(0).addImm(LdSize));
7287   }
7288 }
7289
7290 /// Emit a post-increment store operation with given size. The instructions
7291 /// will be added to BB at Pos.
7292 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7293                        const TargetInstrInfo *TII, DebugLoc dl,
7294                        unsigned StSize, unsigned Data, unsigned AddrIn,
7295                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7296   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7297   assert(StOpc != 0 && "Should have a store opcode");
7298   if (StSize >= 8) {
7299     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7300                        .addReg(AddrIn).addImm(0).addReg(Data));
7301   } else if (IsThumb1) {
7302     // store + update AddrIn
7303     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7304                        .addReg(AddrIn).addImm(0));
7305     MachineInstrBuilder MIB =
7306         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7307     MIB = AddDefaultT1CC(MIB);
7308     MIB.addReg(AddrIn).addImm(StSize);
7309     AddDefaultPred(MIB);
7310   } else if (IsThumb2) {
7311     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7312                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7313   } else { // arm
7314     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7315                        .addReg(Data).addReg(AddrIn).addReg(0)
7316                        .addImm(StSize));
7317   }
7318 }
7319
7320 MachineBasicBlock *
7321 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7322                                    MachineBasicBlock *BB) const {
7323   // This pseudo instruction has 3 operands: dst, src, size
7324   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7325   // Otherwise, we will generate unrolled scalar copies.
7326   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7327   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7328   MachineFunction::iterator It = BB;
7329   ++It;
7330
7331   unsigned dest = MI->getOperand(0).getReg();
7332   unsigned src = MI->getOperand(1).getReg();
7333   unsigned SizeVal = MI->getOperand(2).getImm();
7334   unsigned Align = MI->getOperand(3).getImm();
7335   DebugLoc dl = MI->getDebugLoc();
7336
7337   MachineFunction *MF = BB->getParent();
7338   MachineRegisterInfo &MRI = MF->getRegInfo();
7339   unsigned UnitSize = 0;
7340   const TargetRegisterClass *TRC = 0;
7341   const TargetRegisterClass *VecTRC = 0;
7342
7343   bool IsThumb1 = Subtarget->isThumb1Only();
7344   bool IsThumb2 = Subtarget->isThumb2();
7345
7346   if (Align & 1) {
7347     UnitSize = 1;
7348   } else if (Align & 2) {
7349     UnitSize = 2;
7350   } else {
7351     // Check whether we can use NEON instructions.
7352     if (!MF->getFunction()->getAttributes().
7353           hasAttribute(AttributeSet::FunctionIndex,
7354                        Attribute::NoImplicitFloat) &&
7355         Subtarget->hasNEON()) {
7356       if ((Align % 16 == 0) && SizeVal >= 16)
7357         UnitSize = 16;
7358       else if ((Align % 8 == 0) && SizeVal >= 8)
7359         UnitSize = 8;
7360     }
7361     // Can't use NEON instructions.
7362     if (UnitSize == 0)
7363       UnitSize = 4;
7364   }
7365
7366   // Select the correct opcode and register class for unit size load/store
7367   bool IsNeon = UnitSize >= 8;
7368   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7369                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7370   if (IsNeon)
7371     VecTRC = UnitSize == 16
7372                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7373                  : UnitSize == 8
7374                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7375                        : 0;
7376
7377   unsigned BytesLeft = SizeVal % UnitSize;
7378   unsigned LoopSize = SizeVal - BytesLeft;
7379
7380   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7381     // Use LDR and STR to copy.
7382     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7383     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7384     unsigned srcIn = src;
7385     unsigned destIn = dest;
7386     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7387       unsigned srcOut = MRI.createVirtualRegister(TRC);
7388       unsigned destOut = MRI.createVirtualRegister(TRC);
7389       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7390       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7391                  IsThumb1, IsThumb2);
7392       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7393                  IsThumb1, IsThumb2);
7394       srcIn = srcOut;
7395       destIn = destOut;
7396     }
7397
7398     // Handle the leftover bytes with LDRB and STRB.
7399     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7400     // [destOut] = STRB_POST(scratch, destIn, 1)
7401     for (unsigned i = 0; i < BytesLeft; i++) {
7402       unsigned srcOut = MRI.createVirtualRegister(TRC);
7403       unsigned destOut = MRI.createVirtualRegister(TRC);
7404       unsigned scratch = MRI.createVirtualRegister(TRC);
7405       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7406                  IsThumb1, IsThumb2);
7407       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7408                  IsThumb1, IsThumb2);
7409       srcIn = srcOut;
7410       destIn = destOut;
7411     }
7412     MI->eraseFromParent();   // The instruction is gone now.
7413     return BB;
7414   }
7415
7416   // Expand the pseudo op to a loop.
7417   // thisMBB:
7418   //   ...
7419   //   movw varEnd, # --> with thumb2
7420   //   movt varEnd, #
7421   //   ldrcp varEnd, idx --> without thumb2
7422   //   fallthrough --> loopMBB
7423   // loopMBB:
7424   //   PHI varPhi, varEnd, varLoop
7425   //   PHI srcPhi, src, srcLoop
7426   //   PHI destPhi, dst, destLoop
7427   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7428   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7429   //   subs varLoop, varPhi, #UnitSize
7430   //   bne loopMBB
7431   //   fallthrough --> exitMBB
7432   // exitMBB:
7433   //   epilogue to handle left-over bytes
7434   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7435   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7436   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7437   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7438   MF->insert(It, loopMBB);
7439   MF->insert(It, exitMBB);
7440
7441   // Transfer the remainder of BB and its successor edges to exitMBB.
7442   exitMBB->splice(exitMBB->begin(), BB,
7443                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7444   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7445
7446   // Load an immediate to varEnd.
7447   unsigned varEnd = MRI.createVirtualRegister(TRC);
7448   if (IsThumb2) {
7449     unsigned Vtmp = varEnd;
7450     if ((LoopSize & 0xFFFF0000) != 0)
7451       Vtmp = MRI.createVirtualRegister(TRC);
7452     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7453                        .addImm(LoopSize & 0xFFFF));
7454
7455     if ((LoopSize & 0xFFFF0000) != 0)
7456       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7457                          .addReg(Vtmp).addImm(LoopSize >> 16));
7458   } else {
7459     MachineConstantPool *ConstantPool = MF->getConstantPool();
7460     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7461     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7462
7463     // MachineConstantPool wants an explicit alignment.
7464     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7465     if (Align == 0)
7466       Align = getDataLayout()->getTypeAllocSize(C->getType());
7467     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7468
7469     if (IsThumb1)
7470       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7471           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7472     else
7473       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7474           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7475   }
7476   BB->addSuccessor(loopMBB);
7477
7478   // Generate the loop body:
7479   //   varPhi = PHI(varLoop, varEnd)
7480   //   srcPhi = PHI(srcLoop, src)
7481   //   destPhi = PHI(destLoop, dst)
7482   MachineBasicBlock *entryBB = BB;
7483   BB = loopMBB;
7484   unsigned varLoop = MRI.createVirtualRegister(TRC);
7485   unsigned varPhi = MRI.createVirtualRegister(TRC);
7486   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7487   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7488   unsigned destLoop = MRI.createVirtualRegister(TRC);
7489   unsigned destPhi = MRI.createVirtualRegister(TRC);
7490
7491   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7492     .addReg(varLoop).addMBB(loopMBB)
7493     .addReg(varEnd).addMBB(entryBB);
7494   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7495     .addReg(srcLoop).addMBB(loopMBB)
7496     .addReg(src).addMBB(entryBB);
7497   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7498     .addReg(destLoop).addMBB(loopMBB)
7499     .addReg(dest).addMBB(entryBB);
7500
7501   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7502   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7503   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7504   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7505              IsThumb1, IsThumb2);
7506   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7507              IsThumb1, IsThumb2);
7508
7509   // Decrement loop variable by UnitSize.
7510   if (IsThumb1) {
7511     MachineInstrBuilder MIB =
7512         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7513     MIB = AddDefaultT1CC(MIB);
7514     MIB.addReg(varPhi).addImm(UnitSize);
7515     AddDefaultPred(MIB);
7516   } else {
7517     MachineInstrBuilder MIB =
7518         BuildMI(*BB, BB->end(), dl,
7519                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7520     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7521     MIB->getOperand(5).setReg(ARM::CPSR);
7522     MIB->getOperand(5).setIsDef(true);
7523   }
7524   BuildMI(*BB, BB->end(), dl,
7525           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7526       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7527
7528   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7529   BB->addSuccessor(loopMBB);
7530   BB->addSuccessor(exitMBB);
7531
7532   // Add epilogue to handle BytesLeft.
7533   BB = exitMBB;
7534   MachineInstr *StartOfExit = exitMBB->begin();
7535
7536   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7537   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7538   unsigned srcIn = srcLoop;
7539   unsigned destIn = destLoop;
7540   for (unsigned i = 0; i < BytesLeft; i++) {
7541     unsigned srcOut = MRI.createVirtualRegister(TRC);
7542     unsigned destOut = MRI.createVirtualRegister(TRC);
7543     unsigned scratch = MRI.createVirtualRegister(TRC);
7544     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7545                IsThumb1, IsThumb2);
7546     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7547                IsThumb1, IsThumb2);
7548     srcIn = srcOut;
7549     destIn = destOut;
7550   }
7551
7552   MI->eraseFromParent();   // The instruction is gone now.
7553   return BB;
7554 }
7555
7556 MachineBasicBlock *
7557 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7558                                                MachineBasicBlock *BB) const {
7559   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7560   DebugLoc dl = MI->getDebugLoc();
7561   bool isThumb2 = Subtarget->isThumb2();
7562   switch (MI->getOpcode()) {
7563   default: {
7564     MI->dump();
7565     llvm_unreachable("Unexpected instr type to insert");
7566   }
7567   // The Thumb2 pre-indexed stores have the same MI operands, they just
7568   // define them differently in the .td files from the isel patterns, so
7569   // they need pseudos.
7570   case ARM::t2STR_preidx:
7571     MI->setDesc(TII->get(ARM::t2STR_PRE));
7572     return BB;
7573   case ARM::t2STRB_preidx:
7574     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7575     return BB;
7576   case ARM::t2STRH_preidx:
7577     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7578     return BB;
7579
7580   case ARM::STRi_preidx:
7581   case ARM::STRBi_preidx: {
7582     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7583       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7584     // Decode the offset.
7585     unsigned Offset = MI->getOperand(4).getImm();
7586     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7587     Offset = ARM_AM::getAM2Offset(Offset);
7588     if (isSub)
7589       Offset = -Offset;
7590
7591     MachineMemOperand *MMO = *MI->memoperands_begin();
7592     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7593       .addOperand(MI->getOperand(0))  // Rn_wb
7594       .addOperand(MI->getOperand(1))  // Rt
7595       .addOperand(MI->getOperand(2))  // Rn
7596       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7597       .addOperand(MI->getOperand(5))  // pred
7598       .addOperand(MI->getOperand(6))
7599       .addMemOperand(MMO);
7600     MI->eraseFromParent();
7601     return BB;
7602   }
7603   case ARM::STRr_preidx:
7604   case ARM::STRBr_preidx:
7605   case ARM::STRH_preidx: {
7606     unsigned NewOpc;
7607     switch (MI->getOpcode()) {
7608     default: llvm_unreachable("unexpected opcode!");
7609     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7610     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7611     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7612     }
7613     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7614     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7615       MIB.addOperand(MI->getOperand(i));
7616     MI->eraseFromParent();
7617     return BB;
7618   }
7619   case ARM::ATOMIC_LOAD_ADD_I8:
7620      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7621   case ARM::ATOMIC_LOAD_ADD_I16:
7622      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7623   case ARM::ATOMIC_LOAD_ADD_I32:
7624      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7625
7626   case ARM::ATOMIC_LOAD_AND_I8:
7627      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7628   case ARM::ATOMIC_LOAD_AND_I16:
7629      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7630   case ARM::ATOMIC_LOAD_AND_I32:
7631      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7632
7633   case ARM::ATOMIC_LOAD_OR_I8:
7634      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7635   case ARM::ATOMIC_LOAD_OR_I16:
7636      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7637   case ARM::ATOMIC_LOAD_OR_I32:
7638      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7639
7640   case ARM::ATOMIC_LOAD_XOR_I8:
7641      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7642   case ARM::ATOMIC_LOAD_XOR_I16:
7643      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7644   case ARM::ATOMIC_LOAD_XOR_I32:
7645      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7646
7647   case ARM::ATOMIC_LOAD_NAND_I8:
7648      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7649   case ARM::ATOMIC_LOAD_NAND_I16:
7650      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7651   case ARM::ATOMIC_LOAD_NAND_I32:
7652      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7653
7654   case ARM::ATOMIC_LOAD_SUB_I8:
7655      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7656   case ARM::ATOMIC_LOAD_SUB_I16:
7657      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7658   case ARM::ATOMIC_LOAD_SUB_I32:
7659      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7660
7661   case ARM::ATOMIC_LOAD_MIN_I8:
7662      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7663   case ARM::ATOMIC_LOAD_MIN_I16:
7664      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7665   case ARM::ATOMIC_LOAD_MIN_I32:
7666      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7667
7668   case ARM::ATOMIC_LOAD_MAX_I8:
7669      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7670   case ARM::ATOMIC_LOAD_MAX_I16:
7671      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7672   case ARM::ATOMIC_LOAD_MAX_I32:
7673      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7674
7675   case ARM::ATOMIC_LOAD_UMIN_I8:
7676      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7677   case ARM::ATOMIC_LOAD_UMIN_I16:
7678      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7679   case ARM::ATOMIC_LOAD_UMIN_I32:
7680      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7681
7682   case ARM::ATOMIC_LOAD_UMAX_I8:
7683      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7684   case ARM::ATOMIC_LOAD_UMAX_I16:
7685      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7686   case ARM::ATOMIC_LOAD_UMAX_I32:
7687      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7688
7689   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7690   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7691   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7692
7693   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7694   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7695   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7696
7697   case ARM::ATOMIC_LOAD_I64:
7698     return EmitAtomicLoad64(MI, BB);
7699
7700   case ARM::ATOMIC_LOAD_ADD_I64:
7701     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7702                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7703                               /*NeedsCarry*/ true);
7704   case ARM::ATOMIC_LOAD_SUB_I64:
7705     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7706                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7707                               /*NeedsCarry*/ true);
7708   case ARM::ATOMIC_LOAD_OR_I64:
7709     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7710                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7711   case ARM::ATOMIC_LOAD_XOR_I64:
7712     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7713                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7714   case ARM::ATOMIC_LOAD_AND_I64:
7715     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7716                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7717   case ARM::ATOMIC_STORE_I64:
7718   case ARM::ATOMIC_SWAP_I64:
7719     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7720   case ARM::ATOMIC_CMP_SWAP_I64:
7721     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7722                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7723                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7724   case ARM::ATOMIC_LOAD_MIN_I64:
7725     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7726                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7727                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7728                               /*IsMinMax*/ true, ARMCC::LT);
7729   case ARM::ATOMIC_LOAD_MAX_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::GE);
7734   case ARM::ATOMIC_LOAD_UMIN_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::LO);
7739   case ARM::ATOMIC_LOAD_UMAX_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::HS);
7744
7745   case ARM::tMOVCCr_pseudo: {
7746     // To "insert" a SELECT_CC instruction, we actually have to insert the
7747     // diamond control-flow pattern.  The incoming instruction knows the
7748     // destination vreg to set, the condition code register to branch on, the
7749     // true/false values to select between, and a branch opcode to use.
7750     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7751     MachineFunction::iterator It = BB;
7752     ++It;
7753
7754     //  thisMBB:
7755     //  ...
7756     //   TrueVal = ...
7757     //   cmpTY ccX, r1, r2
7758     //   bCC copy1MBB
7759     //   fallthrough --> copy0MBB
7760     MachineBasicBlock *thisMBB  = BB;
7761     MachineFunction *F = BB->getParent();
7762     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7763     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7764     F->insert(It, copy0MBB);
7765     F->insert(It, sinkMBB);
7766
7767     // Transfer the remainder of BB and its successor edges to sinkMBB.
7768     sinkMBB->splice(sinkMBB->begin(), BB,
7769                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7770     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7771
7772     BB->addSuccessor(copy0MBB);
7773     BB->addSuccessor(sinkMBB);
7774
7775     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7776       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7777
7778     //  copy0MBB:
7779     //   %FalseValue = ...
7780     //   # fallthrough to sinkMBB
7781     BB = copy0MBB;
7782
7783     // Update machine-CFG edges
7784     BB->addSuccessor(sinkMBB);
7785
7786     //  sinkMBB:
7787     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7788     //  ...
7789     BB = sinkMBB;
7790     BuildMI(*BB, BB->begin(), dl,
7791             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7792       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7793       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7794
7795     MI->eraseFromParent();   // The pseudo instruction is gone now.
7796     return BB;
7797   }
7798
7799   case ARM::BCCi64:
7800   case ARM::BCCZi64: {
7801     // If there is an unconditional branch to the other successor, remove it.
7802     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7803
7804     // Compare both parts that make up the double comparison separately for
7805     // equality.
7806     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7807
7808     unsigned LHS1 = MI->getOperand(1).getReg();
7809     unsigned LHS2 = MI->getOperand(2).getReg();
7810     if (RHSisZero) {
7811       AddDefaultPred(BuildMI(BB, dl,
7812                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7813                      .addReg(LHS1).addImm(0));
7814       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7815         .addReg(LHS2).addImm(0)
7816         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7817     } else {
7818       unsigned RHS1 = MI->getOperand(3).getReg();
7819       unsigned RHS2 = MI->getOperand(4).getReg();
7820       AddDefaultPred(BuildMI(BB, dl,
7821                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7822                      .addReg(LHS1).addReg(RHS1));
7823       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7824         .addReg(LHS2).addReg(RHS2)
7825         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7826     }
7827
7828     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7829     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7830     if (MI->getOperand(0).getImm() == ARMCC::NE)
7831       std::swap(destMBB, exitMBB);
7832
7833     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7834       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7835     if (isThumb2)
7836       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7837     else
7838       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7839
7840     MI->eraseFromParent();   // The pseudo instruction is gone now.
7841     return BB;
7842   }
7843
7844   case ARM::Int_eh_sjlj_setjmp:
7845   case ARM::Int_eh_sjlj_setjmp_nofp:
7846   case ARM::tInt_eh_sjlj_setjmp:
7847   case ARM::t2Int_eh_sjlj_setjmp:
7848   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7849     EmitSjLjDispatchBlock(MI, BB);
7850     return BB;
7851
7852   case ARM::ABS:
7853   case ARM::t2ABS: {
7854     // To insert an ABS instruction, we have to insert the
7855     // diamond control-flow pattern.  The incoming instruction knows the
7856     // source vreg to test against 0, the destination vreg to set,
7857     // the condition code register to branch on, the
7858     // true/false values to select between, and a branch opcode to use.
7859     // It transforms
7860     //     V1 = ABS V0
7861     // into
7862     //     V2 = MOVS V0
7863     //     BCC                      (branch to SinkBB if V0 >= 0)
7864     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7865     //     SinkBB: V1 = PHI(V2, V3)
7866     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7867     MachineFunction::iterator BBI = BB;
7868     ++BBI;
7869     MachineFunction *Fn = BB->getParent();
7870     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7871     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7872     Fn->insert(BBI, RSBBB);
7873     Fn->insert(BBI, SinkBB);
7874
7875     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7876     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7877     bool isThumb2 = Subtarget->isThumb2();
7878     MachineRegisterInfo &MRI = Fn->getRegInfo();
7879     // In Thumb mode S must not be specified if source register is the SP or
7880     // PC and if destination register is the SP, so restrict register class
7881     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7882       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7883       (const TargetRegisterClass*)&ARM::GPRRegClass);
7884
7885     // Transfer the remainder of BB and its successor edges to sinkMBB.
7886     SinkBB->splice(SinkBB->begin(), BB,
7887                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7888     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7889
7890     BB->addSuccessor(RSBBB);
7891     BB->addSuccessor(SinkBB);
7892
7893     // fall through to SinkMBB
7894     RSBBB->addSuccessor(SinkBB);
7895
7896     // insert a cmp at the end of BB
7897     AddDefaultPred(BuildMI(BB, dl,
7898                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7899                    .addReg(ABSSrcReg).addImm(0));
7900
7901     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7902     BuildMI(BB, dl,
7903       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7904       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7905
7906     // insert rsbri in RSBBB
7907     // Note: BCC and rsbri will be converted into predicated rsbmi
7908     // by if-conversion pass
7909     BuildMI(*RSBBB, RSBBB->begin(), dl,
7910       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7911       .addReg(ABSSrcReg, RegState::Kill)
7912       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7913
7914     // insert PHI in SinkBB,
7915     // reuse ABSDstReg to not change uses of ABS instruction
7916     BuildMI(*SinkBB, SinkBB->begin(), dl,
7917       TII->get(ARM::PHI), ABSDstReg)
7918       .addReg(NewRsbDstReg).addMBB(RSBBB)
7919       .addReg(ABSSrcReg).addMBB(BB);
7920
7921     // remove ABS instruction
7922     MI->eraseFromParent();
7923
7924     // return last added BB
7925     return SinkBB;
7926   }
7927   case ARM::COPY_STRUCT_BYVAL_I32:
7928     ++NumLoopByVals;
7929     return EmitStructByval(MI, BB);
7930   }
7931 }
7932
7933 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7934                                                       SDNode *Node) const {
7935   if (!MI->hasPostISelHook()) {
7936     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7937            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7938     return;
7939   }
7940
7941   const MCInstrDesc *MCID = &MI->getDesc();
7942   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7943   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7944   // operand is still set to noreg. If needed, set the optional operand's
7945   // register to CPSR, and remove the redundant implicit def.
7946   //
7947   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7948
7949   // Rename pseudo opcodes.
7950   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7951   if (NewOpc) {
7952     const ARMBaseInstrInfo *TII =
7953       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7954     MCID = &TII->get(NewOpc);
7955
7956     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7957            "converted opcode should be the same except for cc_out");
7958
7959     MI->setDesc(*MCID);
7960
7961     // Add the optional cc_out operand
7962     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7963   }
7964   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7965
7966   // Any ARM instruction that sets the 's' bit should specify an optional
7967   // "cc_out" operand in the last operand position.
7968   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7969     assert(!NewOpc && "Optional cc_out operand required");
7970     return;
7971   }
7972   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7973   // since we already have an optional CPSR def.
7974   bool definesCPSR = false;
7975   bool deadCPSR = false;
7976   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7977        i != e; ++i) {
7978     const MachineOperand &MO = MI->getOperand(i);
7979     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7980       definesCPSR = true;
7981       if (MO.isDead())
7982         deadCPSR = true;
7983       MI->RemoveOperand(i);
7984       break;
7985     }
7986   }
7987   if (!definesCPSR) {
7988     assert(!NewOpc && "Optional cc_out operand required");
7989     return;
7990   }
7991   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7992   if (deadCPSR) {
7993     assert(!MI->getOperand(ccOutIdx).getReg() &&
7994            "expect uninitialized optional cc_out operand");
7995     return;
7996   }
7997
7998   // If this instruction was defined with an optional CPSR def and its dag node
7999   // had a live implicit CPSR def, then activate the optional CPSR def.
8000   MachineOperand &MO = MI->getOperand(ccOutIdx);
8001   MO.setReg(ARM::CPSR);
8002   MO.setIsDef(true);
8003 }
8004
8005 //===----------------------------------------------------------------------===//
8006 //                           ARM Optimization Hooks
8007 //===----------------------------------------------------------------------===//
8008
8009 // Helper function that checks if N is a null or all ones constant.
8010 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8011   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8012   if (!C)
8013     return false;
8014   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8015 }
8016
8017 // Return true if N is conditionally 0 or all ones.
8018 // Detects these expressions where cc is an i1 value:
8019 //
8020 //   (select cc 0, y)   [AllOnes=0]
8021 //   (select cc y, 0)   [AllOnes=0]
8022 //   (zext cc)          [AllOnes=0]
8023 //   (sext cc)          [AllOnes=0/1]
8024 //   (select cc -1, y)  [AllOnes=1]
8025 //   (select cc y, -1)  [AllOnes=1]
8026 //
8027 // Invert is set when N is the null/all ones constant when CC is false.
8028 // OtherOp is set to the alternative value of N.
8029 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8030                                        SDValue &CC, bool &Invert,
8031                                        SDValue &OtherOp,
8032                                        SelectionDAG &DAG) {
8033   switch (N->getOpcode()) {
8034   default: return false;
8035   case ISD::SELECT: {
8036     CC = N->getOperand(0);
8037     SDValue N1 = N->getOperand(1);
8038     SDValue N2 = N->getOperand(2);
8039     if (isZeroOrAllOnes(N1, AllOnes)) {
8040       Invert = false;
8041       OtherOp = N2;
8042       return true;
8043     }
8044     if (isZeroOrAllOnes(N2, AllOnes)) {
8045       Invert = true;
8046       OtherOp = N1;
8047       return true;
8048     }
8049     return false;
8050   }
8051   case ISD::ZERO_EXTEND:
8052     // (zext cc) can never be the all ones value.
8053     if (AllOnes)
8054       return false;
8055     // Fall through.
8056   case ISD::SIGN_EXTEND: {
8057     EVT VT = N->getValueType(0);
8058     CC = N->getOperand(0);
8059     if (CC.getValueType() != MVT::i1)
8060       return false;
8061     Invert = !AllOnes;
8062     if (AllOnes)
8063       // When looking for an AllOnes constant, N is an sext, and the 'other'
8064       // value is 0.
8065       OtherOp = DAG.getConstant(0, VT);
8066     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8067       // When looking for a 0 constant, N can be zext or sext.
8068       OtherOp = DAG.getConstant(1, VT);
8069     else
8070       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8071     return true;
8072   }
8073   }
8074 }
8075
8076 // Combine a constant select operand into its use:
8077 //
8078 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8079 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8080 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8081 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8082 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8083 //
8084 // The transform is rejected if the select doesn't have a constant operand that
8085 // is null, or all ones when AllOnes is set.
8086 //
8087 // Also recognize sext/zext from i1:
8088 //
8089 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8090 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8091 //
8092 // These transformations eventually create predicated instructions.
8093 //
8094 // @param N       The node to transform.
8095 // @param Slct    The N operand that is a select.
8096 // @param OtherOp The other N operand (x above).
8097 // @param DCI     Context.
8098 // @param AllOnes Require the select constant to be all ones instead of null.
8099 // @returns The new node, or SDValue() on failure.
8100 static
8101 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8102                             TargetLowering::DAGCombinerInfo &DCI,
8103                             bool AllOnes = false) {
8104   SelectionDAG &DAG = DCI.DAG;
8105   EVT VT = N->getValueType(0);
8106   SDValue NonConstantVal;
8107   SDValue CCOp;
8108   bool SwapSelectOps;
8109   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8110                                   NonConstantVal, DAG))
8111     return SDValue();
8112
8113   // Slct is now know to be the desired identity constant when CC is true.
8114   SDValue TrueVal = OtherOp;
8115   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8116                                  OtherOp, NonConstantVal);
8117   // Unless SwapSelectOps says CC should be false.
8118   if (SwapSelectOps)
8119     std::swap(TrueVal, FalseVal);
8120
8121   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8122                      CCOp, TrueVal, FalseVal);
8123 }
8124
8125 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8126 static
8127 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8128                                        TargetLowering::DAGCombinerInfo &DCI) {
8129   SDValue N0 = N->getOperand(0);
8130   SDValue N1 = N->getOperand(1);
8131   if (N0.getNode()->hasOneUse()) {
8132     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8133     if (Result.getNode())
8134       return Result;
8135   }
8136   if (N1.getNode()->hasOneUse()) {
8137     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8138     if (Result.getNode())
8139       return Result;
8140   }
8141   return SDValue();
8142 }
8143
8144 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8145 // (only after legalization).
8146 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8147                                  TargetLowering::DAGCombinerInfo &DCI,
8148                                  const ARMSubtarget *Subtarget) {
8149
8150   // Only perform optimization if after legalize, and if NEON is available. We
8151   // also expected both operands to be BUILD_VECTORs.
8152   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8153       || N0.getOpcode() != ISD::BUILD_VECTOR
8154       || N1.getOpcode() != ISD::BUILD_VECTOR)
8155     return SDValue();
8156
8157   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8158   EVT VT = N->getValueType(0);
8159   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8160     return SDValue();
8161
8162   // Check that the vector operands are of the right form.
8163   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8164   // operands, where N is the size of the formed vector.
8165   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8166   // index such that we have a pair wise add pattern.
8167
8168   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8169   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8170     return SDValue();
8171   SDValue Vec = N0->getOperand(0)->getOperand(0);
8172   SDNode *V = Vec.getNode();
8173   unsigned nextIndex = 0;
8174
8175   // For each operands to the ADD which are BUILD_VECTORs,
8176   // check to see if each of their operands are an EXTRACT_VECTOR with
8177   // the same vector and appropriate index.
8178   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8179     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8180         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8181
8182       SDValue ExtVec0 = N0->getOperand(i);
8183       SDValue ExtVec1 = N1->getOperand(i);
8184
8185       // First operand is the vector, verify its the same.
8186       if (V != ExtVec0->getOperand(0).getNode() ||
8187           V != ExtVec1->getOperand(0).getNode())
8188         return SDValue();
8189
8190       // Second is the constant, verify its correct.
8191       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8192       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8193
8194       // For the constant, we want to see all the even or all the odd.
8195       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8196           || C1->getZExtValue() != nextIndex+1)
8197         return SDValue();
8198
8199       // Increment index.
8200       nextIndex+=2;
8201     } else
8202       return SDValue();
8203   }
8204
8205   // Create VPADDL node.
8206   SelectionDAG &DAG = DCI.DAG;
8207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8208
8209   // Build operand list.
8210   SmallVector<SDValue, 8> Ops;
8211   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8212                                 TLI.getPointerTy()));
8213
8214   // Input is the vector.
8215   Ops.push_back(Vec);
8216
8217   // Get widened type and narrowed type.
8218   MVT widenType;
8219   unsigned numElem = VT.getVectorNumElements();
8220   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8221     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8222     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8223     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8224     default:
8225       llvm_unreachable("Invalid vector element type for padd optimization.");
8226   }
8227
8228   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8229                             widenType, &Ops[0], Ops.size());
8230   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8231 }
8232
8233 static SDValue findMUL_LOHI(SDValue V) {
8234   if (V->getOpcode() == ISD::UMUL_LOHI ||
8235       V->getOpcode() == ISD::SMUL_LOHI)
8236     return V;
8237   return SDValue();
8238 }
8239
8240 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8241                                      TargetLowering::DAGCombinerInfo &DCI,
8242                                      const ARMSubtarget *Subtarget) {
8243
8244   if (Subtarget->isThumb1Only()) return SDValue();
8245
8246   // Only perform the checks after legalize when the pattern is available.
8247   if (DCI.isBeforeLegalize()) return SDValue();
8248
8249   // Look for multiply add opportunities.
8250   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8251   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8252   // a glue link from the first add to the second add.
8253   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8254   // a S/UMLAL instruction.
8255   //          loAdd   UMUL_LOHI
8256   //            \    / :lo    \ :hi
8257   //             \  /          \          [no multiline comment]
8258   //              ADDC         |  hiAdd
8259   //                 \ :glue  /  /
8260   //                  \      /  /
8261   //                    ADDE
8262   //
8263   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8264   SDValue AddcOp0 = AddcNode->getOperand(0);
8265   SDValue AddcOp1 = AddcNode->getOperand(1);
8266
8267   // Check if the two operands are from the same mul_lohi node.
8268   if (AddcOp0.getNode() == AddcOp1.getNode())
8269     return SDValue();
8270
8271   assert(AddcNode->getNumValues() == 2 &&
8272          AddcNode->getValueType(0) == MVT::i32 &&
8273          "Expect ADDC with two result values. First: i32");
8274
8275   // Check that we have a glued ADDC node.
8276   if (AddcNode->getValueType(1) != MVT::Glue)
8277     return SDValue();
8278
8279   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8280   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8281       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8282       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8283       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8284     return SDValue();
8285
8286   // Look for the glued ADDE.
8287   SDNode* AddeNode = AddcNode->getGluedUser();
8288   if (AddeNode == NULL)
8289     return SDValue();
8290
8291   // Make sure it is really an ADDE.
8292   if (AddeNode->getOpcode() != ISD::ADDE)
8293     return SDValue();
8294
8295   assert(AddeNode->getNumOperands() == 3 &&
8296          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8297          "ADDE node has the wrong inputs");
8298
8299   // Check for the triangle shape.
8300   SDValue AddeOp0 = AddeNode->getOperand(0);
8301   SDValue AddeOp1 = AddeNode->getOperand(1);
8302
8303   // Make sure that the ADDE operands are not coming from the same node.
8304   if (AddeOp0.getNode() == AddeOp1.getNode())
8305     return SDValue();
8306
8307   // Find the MUL_LOHI node walking up ADDE's operands.
8308   bool IsLeftOperandMUL = false;
8309   SDValue MULOp = findMUL_LOHI(AddeOp0);
8310   if (MULOp == SDValue())
8311    MULOp = findMUL_LOHI(AddeOp1);
8312   else
8313     IsLeftOperandMUL = true;
8314   if (MULOp == SDValue())
8315      return SDValue();
8316
8317   // Figure out the right opcode.
8318   unsigned Opc = MULOp->getOpcode();
8319   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8320
8321   // Figure out the high and low input values to the MLAL node.
8322   SDValue* HiMul = &MULOp;
8323   SDValue* HiAdd = NULL;
8324   SDValue* LoMul = NULL;
8325   SDValue* LowAdd = NULL;
8326
8327   if (IsLeftOperandMUL)
8328     HiAdd = &AddeOp1;
8329   else
8330     HiAdd = &AddeOp0;
8331
8332
8333   if (AddcOp0->getOpcode() == Opc) {
8334     LoMul = &AddcOp0;
8335     LowAdd = &AddcOp1;
8336   }
8337   if (AddcOp1->getOpcode() == Opc) {
8338     LoMul = &AddcOp1;
8339     LowAdd = &AddcOp0;
8340   }
8341
8342   if (LoMul == NULL)
8343     return SDValue();
8344
8345   if (LoMul->getNode() != HiMul->getNode())
8346     return SDValue();
8347
8348   // Create the merged node.
8349   SelectionDAG &DAG = DCI.DAG;
8350
8351   // Build operand list.
8352   SmallVector<SDValue, 8> Ops;
8353   Ops.push_back(LoMul->getOperand(0));
8354   Ops.push_back(LoMul->getOperand(1));
8355   Ops.push_back(*LowAdd);
8356   Ops.push_back(*HiAdd);
8357
8358   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8359                                  DAG.getVTList(MVT::i32, MVT::i32),
8360                                  &Ops[0], Ops.size());
8361
8362   // Replace the ADDs' nodes uses by the MLA node's values.
8363   SDValue HiMLALResult(MLALNode.getNode(), 1);
8364   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8365
8366   SDValue LoMLALResult(MLALNode.getNode(), 0);
8367   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8368
8369   // Return original node to notify the driver to stop replacing.
8370   SDValue resNode(AddcNode, 0);
8371   return resNode;
8372 }
8373
8374 /// PerformADDCCombine - Target-specific dag combine transform from
8375 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8376 static SDValue PerformADDCCombine(SDNode *N,
8377                                  TargetLowering::DAGCombinerInfo &DCI,
8378                                  const ARMSubtarget *Subtarget) {
8379
8380   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8381
8382 }
8383
8384 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8385 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8386 /// called with the default operands, and if that fails, with commuted
8387 /// operands.
8388 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8389                                           TargetLowering::DAGCombinerInfo &DCI,
8390                                           const ARMSubtarget *Subtarget){
8391
8392   // Attempt to create vpaddl for this add.
8393   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8394   if (Result.getNode())
8395     return Result;
8396
8397   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8398   if (N0.getNode()->hasOneUse()) {
8399     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8400     if (Result.getNode()) return Result;
8401   }
8402   return SDValue();
8403 }
8404
8405 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8406 ///
8407 static SDValue PerformADDCombine(SDNode *N,
8408                                  TargetLowering::DAGCombinerInfo &DCI,
8409                                  const ARMSubtarget *Subtarget) {
8410   SDValue N0 = N->getOperand(0);
8411   SDValue N1 = N->getOperand(1);
8412
8413   // First try with the default operand order.
8414   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8415   if (Result.getNode())
8416     return Result;
8417
8418   // If that didn't work, try again with the operands commuted.
8419   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8420 }
8421
8422 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8423 ///
8424 static SDValue PerformSUBCombine(SDNode *N,
8425                                  TargetLowering::DAGCombinerInfo &DCI) {
8426   SDValue N0 = N->getOperand(0);
8427   SDValue N1 = N->getOperand(1);
8428
8429   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8430   if (N1.getNode()->hasOneUse()) {
8431     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8432     if (Result.getNode()) return Result;
8433   }
8434
8435   return SDValue();
8436 }
8437
8438 /// PerformVMULCombine
8439 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8440 /// special multiplier accumulator forwarding.
8441 ///   vmul d3, d0, d2
8442 ///   vmla d3, d1, d2
8443 /// is faster than
8444 ///   vadd d3, d0, d1
8445 ///   vmul d3, d3, d2
8446 //  However, for (A + B) * (A + B),
8447 //    vadd d2, d0, d1
8448 //    vmul d3, d0, d2
8449 //    vmla d3, d1, d2
8450 //  is slower than
8451 //    vadd d2, d0, d1
8452 //    vmul d3, d2, d2
8453 static SDValue PerformVMULCombine(SDNode *N,
8454                                   TargetLowering::DAGCombinerInfo &DCI,
8455                                   const ARMSubtarget *Subtarget) {
8456   if (!Subtarget->hasVMLxForwarding())
8457     return SDValue();
8458
8459   SelectionDAG &DAG = DCI.DAG;
8460   SDValue N0 = N->getOperand(0);
8461   SDValue N1 = N->getOperand(1);
8462   unsigned Opcode = N0.getOpcode();
8463   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8464       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8465     Opcode = N1.getOpcode();
8466     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8467         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8468       return SDValue();
8469     std::swap(N0, N1);
8470   }
8471
8472   if (N0 == N1)
8473     return SDValue();
8474
8475   EVT VT = N->getValueType(0);
8476   SDLoc DL(N);
8477   SDValue N00 = N0->getOperand(0);
8478   SDValue N01 = N0->getOperand(1);
8479   return DAG.getNode(Opcode, DL, VT,
8480                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8481                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8482 }
8483
8484 static SDValue PerformMULCombine(SDNode *N,
8485                                  TargetLowering::DAGCombinerInfo &DCI,
8486                                  const ARMSubtarget *Subtarget) {
8487   SelectionDAG &DAG = DCI.DAG;
8488
8489   if (Subtarget->isThumb1Only())
8490     return SDValue();
8491
8492   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8493     return SDValue();
8494
8495   EVT VT = N->getValueType(0);
8496   if (VT.is64BitVector() || VT.is128BitVector())
8497     return PerformVMULCombine(N, DCI, Subtarget);
8498   if (VT != MVT::i32)
8499     return SDValue();
8500
8501   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8502   if (!C)
8503     return SDValue();
8504
8505   int64_t MulAmt = C->getSExtValue();
8506   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8507
8508   ShiftAmt = ShiftAmt & (32 - 1);
8509   SDValue V = N->getOperand(0);
8510   SDLoc DL(N);
8511
8512   SDValue Res;
8513   MulAmt >>= ShiftAmt;
8514
8515   if (MulAmt >= 0) {
8516     if (isPowerOf2_32(MulAmt - 1)) {
8517       // (mul x, 2^N + 1) => (add (shl x, N), x)
8518       Res = DAG.getNode(ISD::ADD, DL, VT,
8519                         V,
8520                         DAG.getNode(ISD::SHL, DL, VT,
8521                                     V,
8522                                     DAG.getConstant(Log2_32(MulAmt - 1),
8523                                                     MVT::i32)));
8524     } else if (isPowerOf2_32(MulAmt + 1)) {
8525       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8526       Res = DAG.getNode(ISD::SUB, DL, VT,
8527                         DAG.getNode(ISD::SHL, DL, VT,
8528                                     V,
8529                                     DAG.getConstant(Log2_32(MulAmt + 1),
8530                                                     MVT::i32)),
8531                         V);
8532     } else
8533       return SDValue();
8534   } else {
8535     uint64_t MulAmtAbs = -MulAmt;
8536     if (isPowerOf2_32(MulAmtAbs + 1)) {
8537       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8538       Res = DAG.getNode(ISD::SUB, DL, VT,
8539                         V,
8540                         DAG.getNode(ISD::SHL, DL, VT,
8541                                     V,
8542                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8543                                                     MVT::i32)));
8544     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8545       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8546       Res = DAG.getNode(ISD::ADD, DL, VT,
8547                         V,
8548                         DAG.getNode(ISD::SHL, DL, VT,
8549                                     V,
8550                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8551                                                     MVT::i32)));
8552       Res = DAG.getNode(ISD::SUB, DL, VT,
8553                         DAG.getConstant(0, MVT::i32),Res);
8554
8555     } else
8556       return SDValue();
8557   }
8558
8559   if (ShiftAmt != 0)
8560     Res = DAG.getNode(ISD::SHL, DL, VT,
8561                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8562
8563   // Do not add new nodes to DAG combiner worklist.
8564   DCI.CombineTo(N, Res, false);
8565   return SDValue();
8566 }
8567
8568 static SDValue PerformANDCombine(SDNode *N,
8569                                  TargetLowering::DAGCombinerInfo &DCI,
8570                                  const ARMSubtarget *Subtarget) {
8571
8572   // Attempt to use immediate-form VBIC
8573   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8574   SDLoc dl(N);
8575   EVT VT = N->getValueType(0);
8576   SelectionDAG &DAG = DCI.DAG;
8577
8578   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8579     return SDValue();
8580
8581   APInt SplatBits, SplatUndef;
8582   unsigned SplatBitSize;
8583   bool HasAnyUndefs;
8584   if (BVN &&
8585       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8586     if (SplatBitSize <= 64) {
8587       EVT VbicVT;
8588       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8589                                       SplatUndef.getZExtValue(), SplatBitSize,
8590                                       DAG, VbicVT, VT.is128BitVector(),
8591                                       OtherModImm);
8592       if (Val.getNode()) {
8593         SDValue Input =
8594           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8595         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8596         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8597       }
8598     }
8599   }
8600
8601   if (!Subtarget->isThumb1Only()) {
8602     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8603     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8604     if (Result.getNode())
8605       return Result;
8606   }
8607
8608   return SDValue();
8609 }
8610
8611 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8612 static SDValue PerformORCombine(SDNode *N,
8613                                 TargetLowering::DAGCombinerInfo &DCI,
8614                                 const ARMSubtarget *Subtarget) {
8615   // Attempt to use immediate-form VORR
8616   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8617   SDLoc dl(N);
8618   EVT VT = N->getValueType(0);
8619   SelectionDAG &DAG = DCI.DAG;
8620
8621   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8622     return SDValue();
8623
8624   APInt SplatBits, SplatUndef;
8625   unsigned SplatBitSize;
8626   bool HasAnyUndefs;
8627   if (BVN && Subtarget->hasNEON() &&
8628       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8629     if (SplatBitSize <= 64) {
8630       EVT VorrVT;
8631       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8632                                       SplatUndef.getZExtValue(), SplatBitSize,
8633                                       DAG, VorrVT, VT.is128BitVector(),
8634                                       OtherModImm);
8635       if (Val.getNode()) {
8636         SDValue Input =
8637           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8638         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8639         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8640       }
8641     }
8642   }
8643
8644   if (!Subtarget->isThumb1Only()) {
8645     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8646     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8647     if (Result.getNode())
8648       return Result;
8649   }
8650
8651   // The code below optimizes (or (and X, Y), Z).
8652   // The AND operand needs to have a single user to make these optimizations
8653   // profitable.
8654   SDValue N0 = N->getOperand(0);
8655   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8656     return SDValue();
8657   SDValue N1 = N->getOperand(1);
8658
8659   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8660   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8661       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8662     APInt SplatUndef;
8663     unsigned SplatBitSize;
8664     bool HasAnyUndefs;
8665
8666     APInt SplatBits0, SplatBits1;
8667     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8668     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8669     // Ensure that the second operand of both ands are constants
8670     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8671                                       HasAnyUndefs) && !HasAnyUndefs) {
8672         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8673                                           HasAnyUndefs) && !HasAnyUndefs) {
8674             // Ensure that the bit width of the constants are the same and that
8675             // the splat arguments are logical inverses as per the pattern we
8676             // are trying to simplify.
8677             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8678                 SplatBits0 == ~SplatBits1) {
8679                 // Canonicalize the vector type to make instruction selection
8680                 // simpler.
8681                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8682                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8683                                              N0->getOperand(1),
8684                                              N0->getOperand(0),
8685                                              N1->getOperand(0));
8686                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8687             }
8688         }
8689     }
8690   }
8691
8692   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8693   // reasonable.
8694
8695   // BFI is only available on V6T2+
8696   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8697     return SDValue();
8698
8699   SDLoc DL(N);
8700   // 1) or (and A, mask), val => ARMbfi A, val, mask
8701   //      iff (val & mask) == val
8702   //
8703   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8704   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8705   //          && mask == ~mask2
8706   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8707   //          && ~mask == mask2
8708   //  (i.e., copy a bitfield value into another bitfield of the same width)
8709
8710   if (VT != MVT::i32)
8711     return SDValue();
8712
8713   SDValue N00 = N0.getOperand(0);
8714
8715   // The value and the mask need to be constants so we can verify this is
8716   // actually a bitfield set. If the mask is 0xffff, we can do better
8717   // via a movt instruction, so don't use BFI in that case.
8718   SDValue MaskOp = N0.getOperand(1);
8719   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8720   if (!MaskC)
8721     return SDValue();
8722   unsigned Mask = MaskC->getZExtValue();
8723   if (Mask == 0xffff)
8724     return SDValue();
8725   SDValue Res;
8726   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8727   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8728   if (N1C) {
8729     unsigned Val = N1C->getZExtValue();
8730     if ((Val & ~Mask) != Val)
8731       return SDValue();
8732
8733     if (ARM::isBitFieldInvertedMask(Mask)) {
8734       Val >>= countTrailingZeros(~Mask);
8735
8736       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8737                         DAG.getConstant(Val, MVT::i32),
8738                         DAG.getConstant(Mask, MVT::i32));
8739
8740       // Do not add new nodes to DAG combiner worklist.
8741       DCI.CombineTo(N, Res, false);
8742       return SDValue();
8743     }
8744   } else if (N1.getOpcode() == ISD::AND) {
8745     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8746     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8747     if (!N11C)
8748       return SDValue();
8749     unsigned Mask2 = N11C->getZExtValue();
8750
8751     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8752     // as is to match.
8753     if (ARM::isBitFieldInvertedMask(Mask) &&
8754         (Mask == ~Mask2)) {
8755       // The pack halfword instruction works better for masks that fit it,
8756       // so use that when it's available.
8757       if (Subtarget->hasT2ExtractPack() &&
8758           (Mask == 0xffff || Mask == 0xffff0000))
8759         return SDValue();
8760       // 2a
8761       unsigned amt = countTrailingZeros(Mask2);
8762       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8763                         DAG.getConstant(amt, MVT::i32));
8764       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8765                         DAG.getConstant(Mask, MVT::i32));
8766       // Do not add new nodes to DAG combiner worklist.
8767       DCI.CombineTo(N, Res, false);
8768       return SDValue();
8769     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8770                (~Mask == Mask2)) {
8771       // The pack halfword instruction works better for masks that fit it,
8772       // so use that when it's available.
8773       if (Subtarget->hasT2ExtractPack() &&
8774           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8775         return SDValue();
8776       // 2b
8777       unsigned lsb = countTrailingZeros(Mask);
8778       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8779                         DAG.getConstant(lsb, MVT::i32));
8780       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8781                         DAG.getConstant(Mask2, MVT::i32));
8782       // Do not add new nodes to DAG combiner worklist.
8783       DCI.CombineTo(N, Res, false);
8784       return SDValue();
8785     }
8786   }
8787
8788   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8789       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8790       ARM::isBitFieldInvertedMask(~Mask)) {
8791     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8792     // where lsb(mask) == #shamt and masked bits of B are known zero.
8793     SDValue ShAmt = N00.getOperand(1);
8794     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8795     unsigned LSB = countTrailingZeros(Mask);
8796     if (ShAmtC != LSB)
8797       return SDValue();
8798
8799     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8800                       DAG.getConstant(~Mask, MVT::i32));
8801
8802     // Do not add new nodes to DAG combiner worklist.
8803     DCI.CombineTo(N, Res, false);
8804   }
8805
8806   return SDValue();
8807 }
8808
8809 static SDValue PerformXORCombine(SDNode *N,
8810                                  TargetLowering::DAGCombinerInfo &DCI,
8811                                  const ARMSubtarget *Subtarget) {
8812   EVT VT = N->getValueType(0);
8813   SelectionDAG &DAG = DCI.DAG;
8814
8815   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8816     return SDValue();
8817
8818   if (!Subtarget->isThumb1Only()) {
8819     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8820     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8821     if (Result.getNode())
8822       return Result;
8823   }
8824
8825   return SDValue();
8826 }
8827
8828 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8829 /// the bits being cleared by the AND are not demanded by the BFI.
8830 static SDValue PerformBFICombine(SDNode *N,
8831                                  TargetLowering::DAGCombinerInfo &DCI) {
8832   SDValue N1 = N->getOperand(1);
8833   if (N1.getOpcode() == ISD::AND) {
8834     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8835     if (!N11C)
8836       return SDValue();
8837     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8838     unsigned LSB = countTrailingZeros(~InvMask);
8839     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8840     unsigned Mask = (1 << Width)-1;
8841     unsigned Mask2 = N11C->getZExtValue();
8842     if ((Mask & (~Mask2)) == 0)
8843       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8844                              N->getOperand(0), N1.getOperand(0),
8845                              N->getOperand(2));
8846   }
8847   return SDValue();
8848 }
8849
8850 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8851 /// ARMISD::VMOVRRD.
8852 static SDValue PerformVMOVRRDCombine(SDNode *N,
8853                                      TargetLowering::DAGCombinerInfo &DCI) {
8854   // vmovrrd(vmovdrr x, y) -> x,y
8855   SDValue InDouble = N->getOperand(0);
8856   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8857     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8858
8859   // vmovrrd(load f64) -> (load i32), (load i32)
8860   SDNode *InNode = InDouble.getNode();
8861   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8862       InNode->getValueType(0) == MVT::f64 &&
8863       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8864       !cast<LoadSDNode>(InNode)->isVolatile()) {
8865     // TODO: Should this be done for non-FrameIndex operands?
8866     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8867
8868     SelectionDAG &DAG = DCI.DAG;
8869     SDLoc DL(LD);
8870     SDValue BasePtr = LD->getBasePtr();
8871     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8872                                  LD->getPointerInfo(), LD->isVolatile(),
8873                                  LD->isNonTemporal(), LD->isInvariant(),
8874                                  LD->getAlignment());
8875
8876     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8877                                     DAG.getConstant(4, MVT::i32));
8878     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8879                                  LD->getPointerInfo(), LD->isVolatile(),
8880                                  LD->isNonTemporal(), LD->isInvariant(),
8881                                  std::min(4U, LD->getAlignment() / 2));
8882
8883     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8884     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8885     DCI.RemoveFromWorklist(LD);
8886     DAG.DeleteNode(LD);
8887     return Result;
8888   }
8889
8890   return SDValue();
8891 }
8892
8893 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8894 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8895 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8896   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8897   SDValue Op0 = N->getOperand(0);
8898   SDValue Op1 = N->getOperand(1);
8899   if (Op0.getOpcode() == ISD::BITCAST)
8900     Op0 = Op0.getOperand(0);
8901   if (Op1.getOpcode() == ISD::BITCAST)
8902     Op1 = Op1.getOperand(0);
8903   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8904       Op0.getNode() == Op1.getNode() &&
8905       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8906     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8907                        N->getValueType(0), Op0.getOperand(0));
8908   return SDValue();
8909 }
8910
8911 /// PerformSTORECombine - Target-specific dag combine xforms for
8912 /// ISD::STORE.
8913 static SDValue PerformSTORECombine(SDNode *N,
8914                                    TargetLowering::DAGCombinerInfo &DCI) {
8915   StoreSDNode *St = cast<StoreSDNode>(N);
8916   if (St->isVolatile())
8917     return SDValue();
8918
8919   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8920   // pack all of the elements in one place.  Next, store to memory in fewer
8921   // chunks.
8922   SDValue StVal = St->getValue();
8923   EVT VT = StVal.getValueType();
8924   if (St->isTruncatingStore() && VT.isVector()) {
8925     SelectionDAG &DAG = DCI.DAG;
8926     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8927     EVT StVT = St->getMemoryVT();
8928     unsigned NumElems = VT.getVectorNumElements();
8929     assert(StVT != VT && "Cannot truncate to the same type");
8930     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8931     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8932
8933     // From, To sizes and ElemCount must be pow of two
8934     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8935
8936     // We are going to use the original vector elt for storing.
8937     // Accumulated smaller vector elements must be a multiple of the store size.
8938     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8939
8940     unsigned SizeRatio  = FromEltSz / ToEltSz;
8941     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8942
8943     // Create a type on which we perform the shuffle.
8944     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8945                                      NumElems*SizeRatio);
8946     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8947
8948     SDLoc DL(St);
8949     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8950     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8951     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8952
8953     // Can't shuffle using an illegal type.
8954     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8955
8956     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8957                                 DAG.getUNDEF(WideVec.getValueType()),
8958                                 ShuffleVec.data());
8959     // At this point all of the data is stored at the bottom of the
8960     // register. We now need to save it to mem.
8961
8962     // Find the largest store unit
8963     MVT StoreType = MVT::i8;
8964     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8965          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8966       MVT Tp = (MVT::SimpleValueType)tp;
8967       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8968         StoreType = Tp;
8969     }
8970     // Didn't find a legal store type.
8971     if (!TLI.isTypeLegal(StoreType))
8972       return SDValue();
8973
8974     // Bitcast the original vector into a vector of store-size units
8975     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8976             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8977     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8978     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8979     SmallVector<SDValue, 8> Chains;
8980     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8981                                         TLI.getPointerTy());
8982     SDValue BasePtr = St->getBasePtr();
8983
8984     // Perform one or more big stores into memory.
8985     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8986     for (unsigned I = 0; I < E; I++) {
8987       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8988                                    StoreType, ShuffWide,
8989                                    DAG.getIntPtrConstant(I));
8990       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8991                                 St->getPointerInfo(), St->isVolatile(),
8992                                 St->isNonTemporal(), St->getAlignment());
8993       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8994                             Increment);
8995       Chains.push_back(Ch);
8996     }
8997     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8998                        Chains.size());
8999   }
9000
9001   if (!ISD::isNormalStore(St))
9002     return SDValue();
9003
9004   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9005   // ARM stores of arguments in the same cache line.
9006   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9007       StVal.getNode()->hasOneUse()) {
9008     SelectionDAG  &DAG = DCI.DAG;
9009     SDLoc DL(St);
9010     SDValue BasePtr = St->getBasePtr();
9011     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9012                                   StVal.getNode()->getOperand(0), BasePtr,
9013                                   St->getPointerInfo(), St->isVolatile(),
9014                                   St->isNonTemporal(), St->getAlignment());
9015
9016     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9017                                     DAG.getConstant(4, MVT::i32));
9018     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9019                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9020                         St->isNonTemporal(),
9021                         std::min(4U, St->getAlignment() / 2));
9022   }
9023
9024   if (StVal.getValueType() != MVT::i64 ||
9025       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9026     return SDValue();
9027
9028   // Bitcast an i64 store extracted from a vector to f64.
9029   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9030   SelectionDAG &DAG = DCI.DAG;
9031   SDLoc dl(StVal);
9032   SDValue IntVec = StVal.getOperand(0);
9033   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9034                                  IntVec.getValueType().getVectorNumElements());
9035   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9036   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9037                                Vec, StVal.getOperand(1));
9038   dl = SDLoc(N);
9039   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9040   // Make the DAGCombiner fold the bitcasts.
9041   DCI.AddToWorklist(Vec.getNode());
9042   DCI.AddToWorklist(ExtElt.getNode());
9043   DCI.AddToWorklist(V.getNode());
9044   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9045                       St->getPointerInfo(), St->isVolatile(),
9046                       St->isNonTemporal(), St->getAlignment(),
9047                       St->getTBAAInfo());
9048 }
9049
9050 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9051 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9052 /// i64 vector to have f64 elements, since the value can then be loaded
9053 /// directly into a VFP register.
9054 static bool hasNormalLoadOperand(SDNode *N) {
9055   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9056   for (unsigned i = 0; i < NumElts; ++i) {
9057     SDNode *Elt = N->getOperand(i).getNode();
9058     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9059       return true;
9060   }
9061   return false;
9062 }
9063
9064 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9065 /// ISD::BUILD_VECTOR.
9066 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9067                                           TargetLowering::DAGCombinerInfo &DCI){
9068   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9069   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9070   // into a pair of GPRs, which is fine when the value is used as a scalar,
9071   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9072   SelectionDAG &DAG = DCI.DAG;
9073   if (N->getNumOperands() == 2) {
9074     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9075     if (RV.getNode())
9076       return RV;
9077   }
9078
9079   // Load i64 elements as f64 values so that type legalization does not split
9080   // them up into i32 values.
9081   EVT VT = N->getValueType(0);
9082   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9083     return SDValue();
9084   SDLoc dl(N);
9085   SmallVector<SDValue, 8> Ops;
9086   unsigned NumElts = VT.getVectorNumElements();
9087   for (unsigned i = 0; i < NumElts; ++i) {
9088     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9089     Ops.push_back(V);
9090     // Make the DAGCombiner fold the bitcast.
9091     DCI.AddToWorklist(V.getNode());
9092   }
9093   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9094   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9095   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9096 }
9097
9098 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9099 static SDValue
9100 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9101   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9102   // At that time, we may have inserted bitcasts from integer to float.
9103   // If these bitcasts have survived DAGCombine, change the lowering of this
9104   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9105   // force to use floating point types.
9106
9107   // Make sure we can change the type of the vector.
9108   // This is possible iff:
9109   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9110   //    1.1. Vector is used only once.
9111   //    1.2. Use is a bit convert to an integer type.
9112   // 2. The size of its operands are 32-bits (64-bits are not legal).
9113   EVT VT = N->getValueType(0);
9114   EVT EltVT = VT.getVectorElementType();
9115
9116   // Check 1.1. and 2.
9117   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9118     return SDValue();
9119
9120   // By construction, the input type must be float.
9121   assert(EltVT == MVT::f32 && "Unexpected type!");
9122
9123   // Check 1.2.
9124   SDNode *Use = *N->use_begin();
9125   if (Use->getOpcode() != ISD::BITCAST ||
9126       Use->getValueType(0).isFloatingPoint())
9127     return SDValue();
9128
9129   // Check profitability.
9130   // Model is, if more than half of the relevant operands are bitcast from
9131   // i32, turn the build_vector into a sequence of insert_vector_elt.
9132   // Relevant operands are everything that is not statically
9133   // (i.e., at compile time) bitcasted.
9134   unsigned NumOfBitCastedElts = 0;
9135   unsigned NumElts = VT.getVectorNumElements();
9136   unsigned NumOfRelevantElts = NumElts;
9137   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9138     SDValue Elt = N->getOperand(Idx);
9139     if (Elt->getOpcode() == ISD::BITCAST) {
9140       // Assume only bit cast to i32 will go away.
9141       if (Elt->getOperand(0).getValueType() == MVT::i32)
9142         ++NumOfBitCastedElts;
9143     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9144       // Constants are statically casted, thus do not count them as
9145       // relevant operands.
9146       --NumOfRelevantElts;
9147   }
9148
9149   // Check if more than half of the elements require a non-free bitcast.
9150   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9151     return SDValue();
9152
9153   SelectionDAG &DAG = DCI.DAG;
9154   // Create the new vector type.
9155   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9156   // Check if the type is legal.
9157   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9158   if (!TLI.isTypeLegal(VecVT))
9159     return SDValue();
9160
9161   // Combine:
9162   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9163   // => BITCAST INSERT_VECTOR_ELT
9164   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9165   //                      (BITCAST EN), N.
9166   SDValue Vec = DAG.getUNDEF(VecVT);
9167   SDLoc dl(N);
9168   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9169     SDValue V = N->getOperand(Idx);
9170     if (V.getOpcode() == ISD::UNDEF)
9171       continue;
9172     if (V.getOpcode() == ISD::BITCAST &&
9173         V->getOperand(0).getValueType() == MVT::i32)
9174       // Fold obvious case.
9175       V = V.getOperand(0);
9176     else {
9177       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9178       // Make the DAGCombiner fold the bitcasts.
9179       DCI.AddToWorklist(V.getNode());
9180     }
9181     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9182     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9183   }
9184   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9185   // Make the DAGCombiner fold the bitcasts.
9186   DCI.AddToWorklist(Vec.getNode());
9187   return Vec;
9188 }
9189
9190 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9191 /// ISD::INSERT_VECTOR_ELT.
9192 static SDValue PerformInsertEltCombine(SDNode *N,
9193                                        TargetLowering::DAGCombinerInfo &DCI) {
9194   // Bitcast an i64 load inserted into a vector to f64.
9195   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9196   EVT VT = N->getValueType(0);
9197   SDNode *Elt = N->getOperand(1).getNode();
9198   if (VT.getVectorElementType() != MVT::i64 ||
9199       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9200     return SDValue();
9201
9202   SelectionDAG &DAG = DCI.DAG;
9203   SDLoc dl(N);
9204   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9205                                  VT.getVectorNumElements());
9206   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9207   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9208   // Make the DAGCombiner fold the bitcasts.
9209   DCI.AddToWorklist(Vec.getNode());
9210   DCI.AddToWorklist(V.getNode());
9211   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9212                                Vec, V, N->getOperand(2));
9213   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9214 }
9215
9216 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9217 /// ISD::VECTOR_SHUFFLE.
9218 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9219   // The LLVM shufflevector instruction does not require the shuffle mask
9220   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9221   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9222   // operands do not match the mask length, they are extended by concatenating
9223   // them with undef vectors.  That is probably the right thing for other
9224   // targets, but for NEON it is better to concatenate two double-register
9225   // size vector operands into a single quad-register size vector.  Do that
9226   // transformation here:
9227   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9228   //   shuffle(concat(v1, v2), undef)
9229   SDValue Op0 = N->getOperand(0);
9230   SDValue Op1 = N->getOperand(1);
9231   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9232       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9233       Op0.getNumOperands() != 2 ||
9234       Op1.getNumOperands() != 2)
9235     return SDValue();
9236   SDValue Concat0Op1 = Op0.getOperand(1);
9237   SDValue Concat1Op1 = Op1.getOperand(1);
9238   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9239       Concat1Op1.getOpcode() != ISD::UNDEF)
9240     return SDValue();
9241   // Skip the transformation if any of the types are illegal.
9242   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9243   EVT VT = N->getValueType(0);
9244   if (!TLI.isTypeLegal(VT) ||
9245       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9246       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9247     return SDValue();
9248
9249   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9250                                   Op0.getOperand(0), Op1.getOperand(0));
9251   // Translate the shuffle mask.
9252   SmallVector<int, 16> NewMask;
9253   unsigned NumElts = VT.getVectorNumElements();
9254   unsigned HalfElts = NumElts/2;
9255   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9256   for (unsigned n = 0; n < NumElts; ++n) {
9257     int MaskElt = SVN->getMaskElt(n);
9258     int NewElt = -1;
9259     if (MaskElt < (int)HalfElts)
9260       NewElt = MaskElt;
9261     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9262       NewElt = HalfElts + MaskElt - NumElts;
9263     NewMask.push_back(NewElt);
9264   }
9265   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9266                               DAG.getUNDEF(VT), NewMask.data());
9267 }
9268
9269 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9270 /// NEON load/store intrinsics to merge base address updates.
9271 static SDValue CombineBaseUpdate(SDNode *N,
9272                                  TargetLowering::DAGCombinerInfo &DCI) {
9273   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9274     return SDValue();
9275
9276   SelectionDAG &DAG = DCI.DAG;
9277   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9278                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9279   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9280   SDValue Addr = N->getOperand(AddrOpIdx);
9281
9282   // Search for a use of the address operand that is an increment.
9283   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9284          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9285     SDNode *User = *UI;
9286     if (User->getOpcode() != ISD::ADD ||
9287         UI.getUse().getResNo() != Addr.getResNo())
9288       continue;
9289
9290     // Check that the add is independent of the load/store.  Otherwise, folding
9291     // it would create a cycle.
9292     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9293       continue;
9294
9295     // Find the new opcode for the updating load/store.
9296     bool isLoad = true;
9297     bool isLaneOp = false;
9298     unsigned NewOpc = 0;
9299     unsigned NumVecs = 0;
9300     if (isIntrinsic) {
9301       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9302       switch (IntNo) {
9303       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9304       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9305         NumVecs = 1; break;
9306       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9307         NumVecs = 2; break;
9308       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9309         NumVecs = 3; break;
9310       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9311         NumVecs = 4; break;
9312       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9313         NumVecs = 2; isLaneOp = true; break;
9314       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9315         NumVecs = 3; isLaneOp = true; break;
9316       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9317         NumVecs = 4; isLaneOp = true; break;
9318       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9319         NumVecs = 1; isLoad = false; break;
9320       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9321         NumVecs = 2; isLoad = false; break;
9322       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9323         NumVecs = 3; isLoad = false; break;
9324       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9325         NumVecs = 4; isLoad = false; break;
9326       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9327         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9328       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9329         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9330       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9331         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9332       }
9333     } else {
9334       isLaneOp = true;
9335       switch (N->getOpcode()) {
9336       default: llvm_unreachable("unexpected opcode for Neon base update");
9337       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9338       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9339       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9340       }
9341     }
9342
9343     // Find the size of memory referenced by the load/store.
9344     EVT VecTy;
9345     if (isLoad)
9346       VecTy = N->getValueType(0);
9347     else
9348       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9349     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9350     if (isLaneOp)
9351       NumBytes /= VecTy.getVectorNumElements();
9352
9353     // If the increment is a constant, it must match the memory ref size.
9354     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9355     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9356       uint64_t IncVal = CInc->getZExtValue();
9357       if (IncVal != NumBytes)
9358         continue;
9359     } else if (NumBytes >= 3 * 16) {
9360       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9361       // separate instructions that make it harder to use a non-constant update.
9362       continue;
9363     }
9364
9365     // Create the new updating load/store node.
9366     EVT Tys[6];
9367     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9368     unsigned n;
9369     for (n = 0; n < NumResultVecs; ++n)
9370       Tys[n] = VecTy;
9371     Tys[n++] = MVT::i32;
9372     Tys[n] = MVT::Other;
9373     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9374     SmallVector<SDValue, 8> Ops;
9375     Ops.push_back(N->getOperand(0)); // incoming chain
9376     Ops.push_back(N->getOperand(AddrOpIdx));
9377     Ops.push_back(Inc);
9378     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9379       Ops.push_back(N->getOperand(i));
9380     }
9381     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9382     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9383                                            Ops.data(), Ops.size(),
9384                                            MemInt->getMemoryVT(),
9385                                            MemInt->getMemOperand());
9386
9387     // Update the uses.
9388     std::vector<SDValue> NewResults;
9389     for (unsigned i = 0; i < NumResultVecs; ++i) {
9390       NewResults.push_back(SDValue(UpdN.getNode(), i));
9391     }
9392     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9393     DCI.CombineTo(N, NewResults);
9394     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9395
9396     break;
9397   }
9398   return SDValue();
9399 }
9400
9401 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9402 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9403 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9404 /// return true.
9405 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9406   SelectionDAG &DAG = DCI.DAG;
9407   EVT VT = N->getValueType(0);
9408   // vldN-dup instructions only support 64-bit vectors for N > 1.
9409   if (!VT.is64BitVector())
9410     return false;
9411
9412   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9413   SDNode *VLD = N->getOperand(0).getNode();
9414   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9415     return false;
9416   unsigned NumVecs = 0;
9417   unsigned NewOpc = 0;
9418   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9419   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9420     NumVecs = 2;
9421     NewOpc = ARMISD::VLD2DUP;
9422   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9423     NumVecs = 3;
9424     NewOpc = ARMISD::VLD3DUP;
9425   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9426     NumVecs = 4;
9427     NewOpc = ARMISD::VLD4DUP;
9428   } else {
9429     return false;
9430   }
9431
9432   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9433   // numbers match the load.
9434   unsigned VLDLaneNo =
9435     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9436   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9437        UI != UE; ++UI) {
9438     // Ignore uses of the chain result.
9439     if (UI.getUse().getResNo() == NumVecs)
9440       continue;
9441     SDNode *User = *UI;
9442     if (User->getOpcode() != ARMISD::VDUPLANE ||
9443         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9444       return false;
9445   }
9446
9447   // Create the vldN-dup node.
9448   EVT Tys[5];
9449   unsigned n;
9450   for (n = 0; n < NumVecs; ++n)
9451     Tys[n] = VT;
9452   Tys[n] = MVT::Other;
9453   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9454   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9455   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9456   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9457                                            Ops, 2, VLDMemInt->getMemoryVT(),
9458                                            VLDMemInt->getMemOperand());
9459
9460   // Update the uses.
9461   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9462        UI != UE; ++UI) {
9463     unsigned ResNo = UI.getUse().getResNo();
9464     // Ignore uses of the chain result.
9465     if (ResNo == NumVecs)
9466       continue;
9467     SDNode *User = *UI;
9468     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9469   }
9470
9471   // Now the vldN-lane intrinsic is dead except for its chain result.
9472   // Update uses of the chain.
9473   std::vector<SDValue> VLDDupResults;
9474   for (unsigned n = 0; n < NumVecs; ++n)
9475     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9476   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9477   DCI.CombineTo(VLD, VLDDupResults);
9478
9479   return true;
9480 }
9481
9482 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9483 /// ARMISD::VDUPLANE.
9484 static SDValue PerformVDUPLANECombine(SDNode *N,
9485                                       TargetLowering::DAGCombinerInfo &DCI) {
9486   SDValue Op = N->getOperand(0);
9487
9488   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9489   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9490   if (CombineVLDDUP(N, DCI))
9491     return SDValue(N, 0);
9492
9493   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9494   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9495   while (Op.getOpcode() == ISD::BITCAST)
9496     Op = Op.getOperand(0);
9497   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9498     return SDValue();
9499
9500   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9501   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9502   // The canonical VMOV for a zero vector uses a 32-bit element size.
9503   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9504   unsigned EltBits;
9505   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9506     EltSize = 8;
9507   EVT VT = N->getValueType(0);
9508   if (EltSize > VT.getVectorElementType().getSizeInBits())
9509     return SDValue();
9510
9511   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9512 }
9513
9514 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9515 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9516 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9517 {
9518   integerPart cN;
9519   integerPart c0 = 0;
9520   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9521        I != E; I++) {
9522     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9523     if (!C)
9524       return false;
9525
9526     bool isExact;
9527     APFloat APF = C->getValueAPF();
9528     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9529         != APFloat::opOK || !isExact)
9530       return false;
9531
9532     c0 = (I == 0) ? cN : c0;
9533     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9534       return false;
9535   }
9536   C = c0;
9537   return true;
9538 }
9539
9540 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9541 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9542 /// when the VMUL has a constant operand that is a power of 2.
9543 ///
9544 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9545 ///  vmul.f32        d16, d17, d16
9546 ///  vcvt.s32.f32    d16, d16
9547 /// becomes:
9548 ///  vcvt.s32.f32    d16, d16, #3
9549 static SDValue PerformVCVTCombine(SDNode *N,
9550                                   TargetLowering::DAGCombinerInfo &DCI,
9551                                   const ARMSubtarget *Subtarget) {
9552   SelectionDAG &DAG = DCI.DAG;
9553   SDValue Op = N->getOperand(0);
9554
9555   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9556       Op.getOpcode() != ISD::FMUL)
9557     return SDValue();
9558
9559   uint64_t C;
9560   SDValue N0 = Op->getOperand(0);
9561   SDValue ConstVec = Op->getOperand(1);
9562   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9563
9564   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9565       !isConstVecPow2(ConstVec, isSigned, C))
9566     return SDValue();
9567
9568   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9569   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9570   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9571     // These instructions only exist converting from f32 to i32. We can handle
9572     // smaller integers by generating an extra truncate, but larger ones would
9573     // be lossy.
9574     return SDValue();
9575   }
9576
9577   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9578     Intrinsic::arm_neon_vcvtfp2fxu;
9579   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9580   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9581                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9582                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9583                                  DAG.getConstant(Log2_64(C), MVT::i32));
9584
9585   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9586     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9587
9588   return FixConv;
9589 }
9590
9591 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9592 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9593 /// when the VDIV has a constant operand that is a power of 2.
9594 ///
9595 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9596 ///  vcvt.f32.s32    d16, d16
9597 ///  vdiv.f32        d16, d17, d16
9598 /// becomes:
9599 ///  vcvt.f32.s32    d16, d16, #3
9600 static SDValue PerformVDIVCombine(SDNode *N,
9601                                   TargetLowering::DAGCombinerInfo &DCI,
9602                                   const ARMSubtarget *Subtarget) {
9603   SelectionDAG &DAG = DCI.DAG;
9604   SDValue Op = N->getOperand(0);
9605   unsigned OpOpcode = Op.getNode()->getOpcode();
9606
9607   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9608       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9609     return SDValue();
9610
9611   uint64_t C;
9612   SDValue ConstVec = N->getOperand(1);
9613   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9614
9615   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9616       !isConstVecPow2(ConstVec, isSigned, C))
9617     return SDValue();
9618
9619   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9620   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9621   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9622     // These instructions only exist converting from i32 to f32. We can handle
9623     // smaller integers by generating an extra extend, but larger ones would
9624     // be lossy.
9625     return SDValue();
9626   }
9627
9628   SDValue ConvInput = Op.getOperand(0);
9629   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9630   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9631     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9632                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9633                             ConvInput);
9634
9635   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9636     Intrinsic::arm_neon_vcvtfxu2fp;
9637   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9638                      Op.getValueType(),
9639                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9640                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9641 }
9642
9643 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9644 /// operand of a vector shift operation, where all the elements of the
9645 /// build_vector must have the same constant integer value.
9646 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9647   // Ignore bit_converts.
9648   while (Op.getOpcode() == ISD::BITCAST)
9649     Op = Op.getOperand(0);
9650   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9651   APInt SplatBits, SplatUndef;
9652   unsigned SplatBitSize;
9653   bool HasAnyUndefs;
9654   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9655                                       HasAnyUndefs, ElementBits) ||
9656       SplatBitSize > ElementBits)
9657     return false;
9658   Cnt = SplatBits.getSExtValue();
9659   return true;
9660 }
9661
9662 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9663 /// operand of a vector shift left operation.  That value must be in the range:
9664 ///   0 <= Value < ElementBits for a left shift; or
9665 ///   0 <= Value <= ElementBits for a long left shift.
9666 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9667   assert(VT.isVector() && "vector shift count is not a vector type");
9668   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9669   if (! getVShiftImm(Op, ElementBits, Cnt))
9670     return false;
9671   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9672 }
9673
9674 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9675 /// operand of a vector shift right operation.  For a shift opcode, the value
9676 /// is positive, but for an intrinsic the value count must be negative. The
9677 /// absolute value must be in the range:
9678 ///   1 <= |Value| <= ElementBits for a right shift; or
9679 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9680 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9681                          int64_t &Cnt) {
9682   assert(VT.isVector() && "vector shift count is not a vector type");
9683   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9684   if (! getVShiftImm(Op, ElementBits, Cnt))
9685     return false;
9686   if (isIntrinsic)
9687     Cnt = -Cnt;
9688   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9689 }
9690
9691 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9692 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9693   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9694   switch (IntNo) {
9695   default:
9696     // Don't do anything for most intrinsics.
9697     break;
9698
9699   // Vector shifts: check for immediate versions and lower them.
9700   // Note: This is done during DAG combining instead of DAG legalizing because
9701   // the build_vectors for 64-bit vector element shift counts are generally
9702   // not legal, and it is hard to see their values after they get legalized to
9703   // loads from a constant pool.
9704   case Intrinsic::arm_neon_vshifts:
9705   case Intrinsic::arm_neon_vshiftu:
9706   case Intrinsic::arm_neon_vrshifts:
9707   case Intrinsic::arm_neon_vrshiftu:
9708   case Intrinsic::arm_neon_vrshiftn:
9709   case Intrinsic::arm_neon_vqshifts:
9710   case Intrinsic::arm_neon_vqshiftu:
9711   case Intrinsic::arm_neon_vqshiftsu:
9712   case Intrinsic::arm_neon_vqshiftns:
9713   case Intrinsic::arm_neon_vqshiftnu:
9714   case Intrinsic::arm_neon_vqshiftnsu:
9715   case Intrinsic::arm_neon_vqrshiftns:
9716   case Intrinsic::arm_neon_vqrshiftnu:
9717   case Intrinsic::arm_neon_vqrshiftnsu: {
9718     EVT VT = N->getOperand(1).getValueType();
9719     int64_t Cnt;
9720     unsigned VShiftOpc = 0;
9721
9722     switch (IntNo) {
9723     case Intrinsic::arm_neon_vshifts:
9724     case Intrinsic::arm_neon_vshiftu:
9725       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9726         VShiftOpc = ARMISD::VSHL;
9727         break;
9728       }
9729       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9730         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9731                      ARMISD::VSHRs : ARMISD::VSHRu);
9732         break;
9733       }
9734       return SDValue();
9735
9736     case Intrinsic::arm_neon_vrshifts:
9737     case Intrinsic::arm_neon_vrshiftu:
9738       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9739         break;
9740       return SDValue();
9741
9742     case Intrinsic::arm_neon_vqshifts:
9743     case Intrinsic::arm_neon_vqshiftu:
9744       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9745         break;
9746       return SDValue();
9747
9748     case Intrinsic::arm_neon_vqshiftsu:
9749       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9750         break;
9751       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9752
9753     case Intrinsic::arm_neon_vrshiftn:
9754     case Intrinsic::arm_neon_vqshiftns:
9755     case Intrinsic::arm_neon_vqshiftnu:
9756     case Intrinsic::arm_neon_vqshiftnsu:
9757     case Intrinsic::arm_neon_vqrshiftns:
9758     case Intrinsic::arm_neon_vqrshiftnu:
9759     case Intrinsic::arm_neon_vqrshiftnsu:
9760       // Narrowing shifts require an immediate right shift.
9761       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9762         break;
9763       llvm_unreachable("invalid shift count for narrowing vector shift "
9764                        "intrinsic");
9765
9766     default:
9767       llvm_unreachable("unhandled vector shift");
9768     }
9769
9770     switch (IntNo) {
9771     case Intrinsic::arm_neon_vshifts:
9772     case Intrinsic::arm_neon_vshiftu:
9773       // Opcode already set above.
9774       break;
9775     case Intrinsic::arm_neon_vrshifts:
9776       VShiftOpc = ARMISD::VRSHRs; break;
9777     case Intrinsic::arm_neon_vrshiftu:
9778       VShiftOpc = ARMISD::VRSHRu; break;
9779     case Intrinsic::arm_neon_vrshiftn:
9780       VShiftOpc = ARMISD::VRSHRN; break;
9781     case Intrinsic::arm_neon_vqshifts:
9782       VShiftOpc = ARMISD::VQSHLs; break;
9783     case Intrinsic::arm_neon_vqshiftu:
9784       VShiftOpc = ARMISD::VQSHLu; break;
9785     case Intrinsic::arm_neon_vqshiftsu:
9786       VShiftOpc = ARMISD::VQSHLsu; break;
9787     case Intrinsic::arm_neon_vqshiftns:
9788       VShiftOpc = ARMISD::VQSHRNs; break;
9789     case Intrinsic::arm_neon_vqshiftnu:
9790       VShiftOpc = ARMISD::VQSHRNu; break;
9791     case Intrinsic::arm_neon_vqshiftnsu:
9792       VShiftOpc = ARMISD::VQSHRNsu; break;
9793     case Intrinsic::arm_neon_vqrshiftns:
9794       VShiftOpc = ARMISD::VQRSHRNs; break;
9795     case Intrinsic::arm_neon_vqrshiftnu:
9796       VShiftOpc = ARMISD::VQRSHRNu; break;
9797     case Intrinsic::arm_neon_vqrshiftnsu:
9798       VShiftOpc = ARMISD::VQRSHRNsu; break;
9799     }
9800
9801     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9802                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9803   }
9804
9805   case Intrinsic::arm_neon_vshiftins: {
9806     EVT VT = N->getOperand(1).getValueType();
9807     int64_t Cnt;
9808     unsigned VShiftOpc = 0;
9809
9810     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9811       VShiftOpc = ARMISD::VSLI;
9812     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9813       VShiftOpc = ARMISD::VSRI;
9814     else {
9815       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9816     }
9817
9818     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9819                        N->getOperand(1), N->getOperand(2),
9820                        DAG.getConstant(Cnt, MVT::i32));
9821   }
9822
9823   case Intrinsic::arm_neon_vqrshifts:
9824   case Intrinsic::arm_neon_vqrshiftu:
9825     // No immediate versions of these to check for.
9826     break;
9827   }
9828
9829   return SDValue();
9830 }
9831
9832 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9833 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9834 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9835 /// vector element shift counts are generally not legal, and it is hard to see
9836 /// their values after they get legalized to loads from a constant pool.
9837 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9838                                    const ARMSubtarget *ST) {
9839   EVT VT = N->getValueType(0);
9840   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9841     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9842     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9843     SDValue N1 = N->getOperand(1);
9844     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9845       SDValue N0 = N->getOperand(0);
9846       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9847           DAG.MaskedValueIsZero(N0.getOperand(0),
9848                                 APInt::getHighBitsSet(32, 16)))
9849         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9850     }
9851   }
9852
9853   // Nothing to be done for scalar shifts.
9854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9855   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9856     return SDValue();
9857
9858   assert(ST->hasNEON() && "unexpected vector shift");
9859   int64_t Cnt;
9860
9861   switch (N->getOpcode()) {
9862   default: llvm_unreachable("unexpected shift opcode");
9863
9864   case ISD::SHL:
9865     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9866       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9867                          DAG.getConstant(Cnt, MVT::i32));
9868     break;
9869
9870   case ISD::SRA:
9871   case ISD::SRL:
9872     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9873       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9874                             ARMISD::VSHRs : ARMISD::VSHRu);
9875       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9876                          DAG.getConstant(Cnt, MVT::i32));
9877     }
9878   }
9879   return SDValue();
9880 }
9881
9882 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9883 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9884 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9885                                     const ARMSubtarget *ST) {
9886   SDValue N0 = N->getOperand(0);
9887
9888   // Check for sign- and zero-extensions of vector extract operations of 8-
9889   // and 16-bit vector elements.  NEON supports these directly.  They are
9890   // handled during DAG combining because type legalization will promote them
9891   // to 32-bit types and it is messy to recognize the operations after that.
9892   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9893     SDValue Vec = N0.getOperand(0);
9894     SDValue Lane = N0.getOperand(1);
9895     EVT VT = N->getValueType(0);
9896     EVT EltVT = N0.getValueType();
9897     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9898
9899     if (VT == MVT::i32 &&
9900         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9901         TLI.isTypeLegal(Vec.getValueType()) &&
9902         isa<ConstantSDNode>(Lane)) {
9903
9904       unsigned Opc = 0;
9905       switch (N->getOpcode()) {
9906       default: llvm_unreachable("unexpected opcode");
9907       case ISD::SIGN_EXTEND:
9908         Opc = ARMISD::VGETLANEs;
9909         break;
9910       case ISD::ZERO_EXTEND:
9911       case ISD::ANY_EXTEND:
9912         Opc = ARMISD::VGETLANEu;
9913         break;
9914       }
9915       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9916     }
9917   }
9918
9919   return SDValue();
9920 }
9921
9922 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9923 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9924 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9925                                        const ARMSubtarget *ST) {
9926   // If the target supports NEON, try to use vmax/vmin instructions for f32
9927   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9928   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9929   // a NaN; only do the transformation when it matches that behavior.
9930
9931   // For now only do this when using NEON for FP operations; if using VFP, it
9932   // is not obvious that the benefit outweighs the cost of switching to the
9933   // NEON pipeline.
9934   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9935       N->getValueType(0) != MVT::f32)
9936     return SDValue();
9937
9938   SDValue CondLHS = N->getOperand(0);
9939   SDValue CondRHS = N->getOperand(1);
9940   SDValue LHS = N->getOperand(2);
9941   SDValue RHS = N->getOperand(3);
9942   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9943
9944   unsigned Opcode = 0;
9945   bool IsReversed;
9946   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9947     IsReversed = false; // x CC y ? x : y
9948   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9949     IsReversed = true ; // x CC y ? y : x
9950   } else {
9951     return SDValue();
9952   }
9953
9954   bool IsUnordered;
9955   switch (CC) {
9956   default: break;
9957   case ISD::SETOLT:
9958   case ISD::SETOLE:
9959   case ISD::SETLT:
9960   case ISD::SETLE:
9961   case ISD::SETULT:
9962   case ISD::SETULE:
9963     // If LHS is NaN, an ordered comparison will be false and the result will
9964     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9965     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9966     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9967     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9968       break;
9969     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9970     // will return -0, so vmin can only be used for unsafe math or if one of
9971     // the operands is known to be nonzero.
9972     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9973         !DAG.getTarget().Options.UnsafeFPMath &&
9974         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9975       break;
9976     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9977     break;
9978
9979   case ISD::SETOGT:
9980   case ISD::SETOGE:
9981   case ISD::SETGT:
9982   case ISD::SETGE:
9983   case ISD::SETUGT:
9984   case ISD::SETUGE:
9985     // If LHS is NaN, an ordered comparison will be false and the result will
9986     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9987     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9988     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9989     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9990       break;
9991     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9992     // will return +0, so vmax can only be used for unsafe math or if one of
9993     // the operands is known to be nonzero.
9994     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9995         !DAG.getTarget().Options.UnsafeFPMath &&
9996         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9997       break;
9998     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9999     break;
10000   }
10001
10002   if (!Opcode)
10003     return SDValue();
10004   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10005 }
10006
10007 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10008 SDValue
10009 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10010   SDValue Cmp = N->getOperand(4);
10011   if (Cmp.getOpcode() != ARMISD::CMPZ)
10012     // Only looking at EQ and NE cases.
10013     return SDValue();
10014
10015   EVT VT = N->getValueType(0);
10016   SDLoc dl(N);
10017   SDValue LHS = Cmp.getOperand(0);
10018   SDValue RHS = Cmp.getOperand(1);
10019   SDValue FalseVal = N->getOperand(0);
10020   SDValue TrueVal = N->getOperand(1);
10021   SDValue ARMcc = N->getOperand(2);
10022   ARMCC::CondCodes CC =
10023     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10024
10025   // Simplify
10026   //   mov     r1, r0
10027   //   cmp     r1, x
10028   //   mov     r0, y
10029   //   moveq   r0, x
10030   // to
10031   //   cmp     r0, x
10032   //   movne   r0, y
10033   //
10034   //   mov     r1, r0
10035   //   cmp     r1, x
10036   //   mov     r0, x
10037   //   movne   r0, y
10038   // to
10039   //   cmp     r0, x
10040   //   movne   r0, y
10041   /// FIXME: Turn this into a target neutral optimization?
10042   SDValue Res;
10043   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10044     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10045                       N->getOperand(3), Cmp);
10046   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10047     SDValue ARMcc;
10048     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10049     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10050                       N->getOperand(3), NewCmp);
10051   }
10052
10053   if (Res.getNode()) {
10054     APInt KnownZero, KnownOne;
10055     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10056     // Capture demanded bits information that would be otherwise lost.
10057     if (KnownZero == 0xfffffffe)
10058       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10059                         DAG.getValueType(MVT::i1));
10060     else if (KnownZero == 0xffffff00)
10061       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10062                         DAG.getValueType(MVT::i8));
10063     else if (KnownZero == 0xffff0000)
10064       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10065                         DAG.getValueType(MVT::i16));
10066   }
10067
10068   return Res;
10069 }
10070
10071 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10072                                              DAGCombinerInfo &DCI) const {
10073   switch (N->getOpcode()) {
10074   default: break;
10075   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10076   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10077   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10078   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10079   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10080   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10081   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10082   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10083   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10084   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10085   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10086   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10087   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10088   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10089   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10090   case ISD::FP_TO_SINT:
10091   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10092   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10093   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10094   case ISD::SHL:
10095   case ISD::SRA:
10096   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10097   case ISD::SIGN_EXTEND:
10098   case ISD::ZERO_EXTEND:
10099   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10100   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10101   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10102   case ARMISD::VLD2DUP:
10103   case ARMISD::VLD3DUP:
10104   case ARMISD::VLD4DUP:
10105     return CombineBaseUpdate(N, DCI);
10106   case ARMISD::BUILD_VECTOR:
10107     return PerformARMBUILD_VECTORCombine(N, DCI);
10108   case ISD::INTRINSIC_VOID:
10109   case ISD::INTRINSIC_W_CHAIN:
10110     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10111     case Intrinsic::arm_neon_vld1:
10112     case Intrinsic::arm_neon_vld2:
10113     case Intrinsic::arm_neon_vld3:
10114     case Intrinsic::arm_neon_vld4:
10115     case Intrinsic::arm_neon_vld2lane:
10116     case Intrinsic::arm_neon_vld3lane:
10117     case Intrinsic::arm_neon_vld4lane:
10118     case Intrinsic::arm_neon_vst1:
10119     case Intrinsic::arm_neon_vst2:
10120     case Intrinsic::arm_neon_vst3:
10121     case Intrinsic::arm_neon_vst4:
10122     case Intrinsic::arm_neon_vst2lane:
10123     case Intrinsic::arm_neon_vst3lane:
10124     case Intrinsic::arm_neon_vst4lane:
10125       return CombineBaseUpdate(N, DCI);
10126     default: break;
10127     }
10128     break;
10129   }
10130   return SDValue();
10131 }
10132
10133 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10134                                                           EVT VT) const {
10135   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10136 }
10137
10138 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10139                                                       bool *Fast) const {
10140   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10141   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10142
10143   switch (VT.getSimpleVT().SimpleTy) {
10144   default:
10145     return false;
10146   case MVT::i8:
10147   case MVT::i16:
10148   case MVT::i32: {
10149     // Unaligned access can use (for example) LRDB, LRDH, LDR
10150     if (AllowsUnaligned) {
10151       if (Fast)
10152         *Fast = Subtarget->hasV7Ops();
10153       return true;
10154     }
10155     return false;
10156   }
10157   case MVT::f64:
10158   case MVT::v2f64: {
10159     // For any little-endian targets with neon, we can support unaligned ld/st
10160     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10161     // A big-endian target may also explicitly support unaligned accesses
10162     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10163       if (Fast)
10164         *Fast = true;
10165       return true;
10166     }
10167     return false;
10168   }
10169   }
10170 }
10171
10172 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10173                        unsigned AlignCheck) {
10174   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10175           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10176 }
10177
10178 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10179                                            unsigned DstAlign, unsigned SrcAlign,
10180                                            bool IsMemset, bool ZeroMemset,
10181                                            bool MemcpyStrSrc,
10182                                            MachineFunction &MF) const {
10183   const Function *F = MF.getFunction();
10184
10185   // See if we can use NEON instructions for this...
10186   if ((!IsMemset || ZeroMemset) &&
10187       Subtarget->hasNEON() &&
10188       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10189                                        Attribute::NoImplicitFloat)) {
10190     bool Fast;
10191     if (Size >= 16 &&
10192         (memOpAlign(SrcAlign, DstAlign, 16) ||
10193          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10194       return MVT::v2f64;
10195     } else if (Size >= 8 &&
10196                (memOpAlign(SrcAlign, DstAlign, 8) ||
10197                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10198       return MVT::f64;
10199     }
10200   }
10201
10202   // Lowering to i32/i16 if the size permits.
10203   if (Size >= 4)
10204     return MVT::i32;
10205   else if (Size >= 2)
10206     return MVT::i16;
10207
10208   // Let the target-independent logic figure it out.
10209   return MVT::Other;
10210 }
10211
10212 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10213   if (Val.getOpcode() != ISD::LOAD)
10214     return false;
10215
10216   EVT VT1 = Val.getValueType();
10217   if (!VT1.isSimple() || !VT1.isInteger() ||
10218       !VT2.isSimple() || !VT2.isInteger())
10219     return false;
10220
10221   switch (VT1.getSimpleVT().SimpleTy) {
10222   default: break;
10223   case MVT::i1:
10224   case MVT::i8:
10225   case MVT::i16:
10226     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10227     return true;
10228   }
10229
10230   return false;
10231 }
10232
10233 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10234   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10235     return false;
10236
10237   if (!isTypeLegal(EVT::getEVT(Ty1)))
10238     return false;
10239
10240   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10241
10242   // Assuming the caller doesn't have a zeroext or signext return parameter,
10243   // truncation all the way down to i1 is valid.
10244   return true;
10245 }
10246
10247
10248 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10249   if (V < 0)
10250     return false;
10251
10252   unsigned Scale = 1;
10253   switch (VT.getSimpleVT().SimpleTy) {
10254   default: return false;
10255   case MVT::i1:
10256   case MVT::i8:
10257     // Scale == 1;
10258     break;
10259   case MVT::i16:
10260     // Scale == 2;
10261     Scale = 2;
10262     break;
10263   case MVT::i32:
10264     // Scale == 4;
10265     Scale = 4;
10266     break;
10267   }
10268
10269   if ((V & (Scale - 1)) != 0)
10270     return false;
10271   V /= Scale;
10272   return V == (V & ((1LL << 5) - 1));
10273 }
10274
10275 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10276                                       const ARMSubtarget *Subtarget) {
10277   bool isNeg = false;
10278   if (V < 0) {
10279     isNeg = true;
10280     V = - V;
10281   }
10282
10283   switch (VT.getSimpleVT().SimpleTy) {
10284   default: return false;
10285   case MVT::i1:
10286   case MVT::i8:
10287   case MVT::i16:
10288   case MVT::i32:
10289     // + imm12 or - imm8
10290     if (isNeg)
10291       return V == (V & ((1LL << 8) - 1));
10292     return V == (V & ((1LL << 12) - 1));
10293   case MVT::f32:
10294   case MVT::f64:
10295     // Same as ARM mode. FIXME: NEON?
10296     if (!Subtarget->hasVFP2())
10297       return false;
10298     if ((V & 3) != 0)
10299       return false;
10300     V >>= 2;
10301     return V == (V & ((1LL << 8) - 1));
10302   }
10303 }
10304
10305 /// isLegalAddressImmediate - Return true if the integer value can be used
10306 /// as the offset of the target addressing mode for load / store of the
10307 /// given type.
10308 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10309                                     const ARMSubtarget *Subtarget) {
10310   if (V == 0)
10311     return true;
10312
10313   if (!VT.isSimple())
10314     return false;
10315
10316   if (Subtarget->isThumb1Only())
10317     return isLegalT1AddressImmediate(V, VT);
10318   else if (Subtarget->isThumb2())
10319     return isLegalT2AddressImmediate(V, VT, Subtarget);
10320
10321   // ARM mode.
10322   if (V < 0)
10323     V = - V;
10324   switch (VT.getSimpleVT().SimpleTy) {
10325   default: return false;
10326   case MVT::i1:
10327   case MVT::i8:
10328   case MVT::i32:
10329     // +- imm12
10330     return V == (V & ((1LL << 12) - 1));
10331   case MVT::i16:
10332     // +- imm8
10333     return V == (V & ((1LL << 8) - 1));
10334   case MVT::f32:
10335   case MVT::f64:
10336     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10337       return false;
10338     if ((V & 3) != 0)
10339       return false;
10340     V >>= 2;
10341     return V == (V & ((1LL << 8) - 1));
10342   }
10343 }
10344
10345 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10346                                                       EVT VT) const {
10347   int Scale = AM.Scale;
10348   if (Scale < 0)
10349     return false;
10350
10351   switch (VT.getSimpleVT().SimpleTy) {
10352   default: return false;
10353   case MVT::i1:
10354   case MVT::i8:
10355   case MVT::i16:
10356   case MVT::i32:
10357     if (Scale == 1)
10358       return true;
10359     // r + r << imm
10360     Scale = Scale & ~1;
10361     return Scale == 2 || Scale == 4 || Scale == 8;
10362   case MVT::i64:
10363     // r + r
10364     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10365       return true;
10366     return false;
10367   case MVT::isVoid:
10368     // Note, we allow "void" uses (basically, uses that aren't loads or
10369     // stores), because arm allows folding a scale into many arithmetic
10370     // operations.  This should be made more precise and revisited later.
10371
10372     // Allow r << imm, but the imm has to be a multiple of two.
10373     if (Scale & 1) return false;
10374     return isPowerOf2_32(Scale);
10375   }
10376 }
10377
10378 /// isLegalAddressingMode - Return true if the addressing mode represented
10379 /// by AM is legal for this target, for a load/store of the specified type.
10380 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10381                                               Type *Ty) const {
10382   EVT VT = getValueType(Ty, true);
10383   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10384     return false;
10385
10386   // Can never fold addr of global into load/store.
10387   if (AM.BaseGV)
10388     return false;
10389
10390   switch (AM.Scale) {
10391   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10392     break;
10393   case 1:
10394     if (Subtarget->isThumb1Only())
10395       return false;
10396     // FALL THROUGH.
10397   default:
10398     // ARM doesn't support any R+R*scale+imm addr modes.
10399     if (AM.BaseOffs)
10400       return false;
10401
10402     if (!VT.isSimple())
10403       return false;
10404
10405     if (Subtarget->isThumb2())
10406       return isLegalT2ScaledAddressingMode(AM, VT);
10407
10408     int Scale = AM.Scale;
10409     switch (VT.getSimpleVT().SimpleTy) {
10410     default: return false;
10411     case MVT::i1:
10412     case MVT::i8:
10413     case MVT::i32:
10414       if (Scale < 0) Scale = -Scale;
10415       if (Scale == 1)
10416         return true;
10417       // r + r << imm
10418       return isPowerOf2_32(Scale & ~1);
10419     case MVT::i16:
10420     case MVT::i64:
10421       // r + r
10422       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10423         return true;
10424       return false;
10425
10426     case MVT::isVoid:
10427       // Note, we allow "void" uses (basically, uses that aren't loads or
10428       // stores), because arm allows folding a scale into many arithmetic
10429       // operations.  This should be made more precise and revisited later.
10430
10431       // Allow r << imm, but the imm has to be a multiple of two.
10432       if (Scale & 1) return false;
10433       return isPowerOf2_32(Scale);
10434     }
10435   }
10436   return true;
10437 }
10438
10439 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10440 /// icmp immediate, that is the target has icmp instructions which can compare
10441 /// a register against the immediate without having to materialize the
10442 /// immediate into a register.
10443 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10444   // Thumb2 and ARM modes can use cmn for negative immediates.
10445   if (!Subtarget->isThumb())
10446     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10447   if (Subtarget->isThumb2())
10448     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10449   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10450   return Imm >= 0 && Imm <= 255;
10451 }
10452
10453 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10454 /// *or sub* immediate, that is the target has add or sub instructions which can
10455 /// add a register with the immediate without having to materialize the
10456 /// immediate into a register.
10457 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10458   // Same encoding for add/sub, just flip the sign.
10459   int64_t AbsImm = llvm::abs64(Imm);
10460   if (!Subtarget->isThumb())
10461     return ARM_AM::getSOImmVal(AbsImm) != -1;
10462   if (Subtarget->isThumb2())
10463     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10464   // Thumb1 only has 8-bit unsigned immediate.
10465   return AbsImm >= 0 && AbsImm <= 255;
10466 }
10467
10468 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10469                                       bool isSEXTLoad, SDValue &Base,
10470                                       SDValue &Offset, bool &isInc,
10471                                       SelectionDAG &DAG) {
10472   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10473     return false;
10474
10475   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10476     // AddressingMode 3
10477     Base = Ptr->getOperand(0);
10478     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10479       int RHSC = (int)RHS->getZExtValue();
10480       if (RHSC < 0 && RHSC > -256) {
10481         assert(Ptr->getOpcode() == ISD::ADD);
10482         isInc = false;
10483         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10484         return true;
10485       }
10486     }
10487     isInc = (Ptr->getOpcode() == ISD::ADD);
10488     Offset = Ptr->getOperand(1);
10489     return true;
10490   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10491     // AddressingMode 2
10492     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10493       int RHSC = (int)RHS->getZExtValue();
10494       if (RHSC < 0 && RHSC > -0x1000) {
10495         assert(Ptr->getOpcode() == ISD::ADD);
10496         isInc = false;
10497         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10498         Base = Ptr->getOperand(0);
10499         return true;
10500       }
10501     }
10502
10503     if (Ptr->getOpcode() == ISD::ADD) {
10504       isInc = true;
10505       ARM_AM::ShiftOpc ShOpcVal=
10506         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10507       if (ShOpcVal != ARM_AM::no_shift) {
10508         Base = Ptr->getOperand(1);
10509         Offset = Ptr->getOperand(0);
10510       } else {
10511         Base = Ptr->getOperand(0);
10512         Offset = Ptr->getOperand(1);
10513       }
10514       return true;
10515     }
10516
10517     isInc = (Ptr->getOpcode() == ISD::ADD);
10518     Base = Ptr->getOperand(0);
10519     Offset = Ptr->getOperand(1);
10520     return true;
10521   }
10522
10523   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10524   return false;
10525 }
10526
10527 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10528                                      bool isSEXTLoad, SDValue &Base,
10529                                      SDValue &Offset, bool &isInc,
10530                                      SelectionDAG &DAG) {
10531   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10532     return false;
10533
10534   Base = Ptr->getOperand(0);
10535   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10536     int RHSC = (int)RHS->getZExtValue();
10537     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10538       assert(Ptr->getOpcode() == ISD::ADD);
10539       isInc = false;
10540       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10541       return true;
10542     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10543       isInc = Ptr->getOpcode() == ISD::ADD;
10544       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10545       return true;
10546     }
10547   }
10548
10549   return false;
10550 }
10551
10552 /// getPreIndexedAddressParts - returns true by value, base pointer and
10553 /// offset pointer and addressing mode by reference if the node's address
10554 /// can be legally represented as pre-indexed load / store address.
10555 bool
10556 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10557                                              SDValue &Offset,
10558                                              ISD::MemIndexedMode &AM,
10559                                              SelectionDAG &DAG) const {
10560   if (Subtarget->isThumb1Only())
10561     return false;
10562
10563   EVT VT;
10564   SDValue Ptr;
10565   bool isSEXTLoad = false;
10566   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10567     Ptr = LD->getBasePtr();
10568     VT  = LD->getMemoryVT();
10569     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10570   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10571     Ptr = ST->getBasePtr();
10572     VT  = ST->getMemoryVT();
10573   } else
10574     return false;
10575
10576   bool isInc;
10577   bool isLegal = false;
10578   if (Subtarget->isThumb2())
10579     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10580                                        Offset, isInc, DAG);
10581   else
10582     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10583                                         Offset, isInc, DAG);
10584   if (!isLegal)
10585     return false;
10586
10587   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10588   return true;
10589 }
10590
10591 /// getPostIndexedAddressParts - returns true by value, base pointer and
10592 /// offset pointer and addressing mode by reference if this node can be
10593 /// combined with a load / store to form a post-indexed load / store.
10594 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10595                                                    SDValue &Base,
10596                                                    SDValue &Offset,
10597                                                    ISD::MemIndexedMode &AM,
10598                                                    SelectionDAG &DAG) const {
10599   if (Subtarget->isThumb1Only())
10600     return false;
10601
10602   EVT VT;
10603   SDValue Ptr;
10604   bool isSEXTLoad = false;
10605   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10606     VT  = LD->getMemoryVT();
10607     Ptr = LD->getBasePtr();
10608     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10609   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10610     VT  = ST->getMemoryVT();
10611     Ptr = ST->getBasePtr();
10612   } else
10613     return false;
10614
10615   bool isInc;
10616   bool isLegal = false;
10617   if (Subtarget->isThumb2())
10618     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10619                                        isInc, DAG);
10620   else
10621     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10622                                         isInc, DAG);
10623   if (!isLegal)
10624     return false;
10625
10626   if (Ptr != Base) {
10627     // Swap base ptr and offset to catch more post-index load / store when
10628     // it's legal. In Thumb2 mode, offset must be an immediate.
10629     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10630         !Subtarget->isThumb2())
10631       std::swap(Base, Offset);
10632
10633     // Post-indexed load / store update the base pointer.
10634     if (Ptr != Base)
10635       return false;
10636   }
10637
10638   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10639   return true;
10640 }
10641
10642 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10643                                                        APInt &KnownZero,
10644                                                        APInt &KnownOne,
10645                                                        const SelectionDAG &DAG,
10646                                                        unsigned Depth) const {
10647   unsigned BitWidth = KnownOne.getBitWidth();
10648   KnownZero = KnownOne = APInt(BitWidth, 0);
10649   switch (Op.getOpcode()) {
10650   default: break;
10651   case ARMISD::ADDC:
10652   case ARMISD::ADDE:
10653   case ARMISD::SUBC:
10654   case ARMISD::SUBE:
10655     // These nodes' second result is a boolean
10656     if (Op.getResNo() == 0)
10657       break;
10658     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10659     break;
10660   case ARMISD::CMOV: {
10661     // Bits are known zero/one if known on the LHS and RHS.
10662     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10663     if (KnownZero == 0 && KnownOne == 0) return;
10664
10665     APInt KnownZeroRHS, KnownOneRHS;
10666     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10667     KnownZero &= KnownZeroRHS;
10668     KnownOne  &= KnownOneRHS;
10669     return;
10670   }
10671   }
10672 }
10673
10674 //===----------------------------------------------------------------------===//
10675 //                           ARM Inline Assembly Support
10676 //===----------------------------------------------------------------------===//
10677
10678 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10679   // Looking for "rev" which is V6+.
10680   if (!Subtarget->hasV6Ops())
10681     return false;
10682
10683   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10684   std::string AsmStr = IA->getAsmString();
10685   SmallVector<StringRef, 4> AsmPieces;
10686   SplitString(AsmStr, AsmPieces, ";\n");
10687
10688   switch (AsmPieces.size()) {
10689   default: return false;
10690   case 1:
10691     AsmStr = AsmPieces[0];
10692     AsmPieces.clear();
10693     SplitString(AsmStr, AsmPieces, " \t,");
10694
10695     // rev $0, $1
10696     if (AsmPieces.size() == 3 &&
10697         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10698         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10699       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10700       if (Ty && Ty->getBitWidth() == 32)
10701         return IntrinsicLowering::LowerToByteSwap(CI);
10702     }
10703     break;
10704   }
10705
10706   return false;
10707 }
10708
10709 /// getConstraintType - Given a constraint letter, return the type of
10710 /// constraint it is for this target.
10711 ARMTargetLowering::ConstraintType
10712 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10713   if (Constraint.size() == 1) {
10714     switch (Constraint[0]) {
10715     default:  break;
10716     case 'l': return C_RegisterClass;
10717     case 'w': return C_RegisterClass;
10718     case 'h': return C_RegisterClass;
10719     case 'x': return C_RegisterClass;
10720     case 't': return C_RegisterClass;
10721     case 'j': return C_Other; // Constant for movw.
10722       // An address with a single base register. Due to the way we
10723       // currently handle addresses it is the same as an 'r' memory constraint.
10724     case 'Q': return C_Memory;
10725     }
10726   } else if (Constraint.size() == 2) {
10727     switch (Constraint[0]) {
10728     default: break;
10729     // All 'U+' constraints are addresses.
10730     case 'U': return C_Memory;
10731     }
10732   }
10733   return TargetLowering::getConstraintType(Constraint);
10734 }
10735
10736 /// Examine constraint type and operand type and determine a weight value.
10737 /// This object must already have been set up with the operand type
10738 /// and the current alternative constraint selected.
10739 TargetLowering::ConstraintWeight
10740 ARMTargetLowering::getSingleConstraintMatchWeight(
10741     AsmOperandInfo &info, const char *constraint) const {
10742   ConstraintWeight weight = CW_Invalid;
10743   Value *CallOperandVal = info.CallOperandVal;
10744     // If we don't have a value, we can't do a match,
10745     // but allow it at the lowest weight.
10746   if (CallOperandVal == NULL)
10747     return CW_Default;
10748   Type *type = CallOperandVal->getType();
10749   // Look at the constraint type.
10750   switch (*constraint) {
10751   default:
10752     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10753     break;
10754   case 'l':
10755     if (type->isIntegerTy()) {
10756       if (Subtarget->isThumb())
10757         weight = CW_SpecificReg;
10758       else
10759         weight = CW_Register;
10760     }
10761     break;
10762   case 'w':
10763     if (type->isFloatingPointTy())
10764       weight = CW_Register;
10765     break;
10766   }
10767   return weight;
10768 }
10769
10770 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10771 RCPair
10772 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10773                                                 MVT VT) const {
10774   if (Constraint.size() == 1) {
10775     // GCC ARM Constraint Letters
10776     switch (Constraint[0]) {
10777     case 'l': // Low regs or general regs.
10778       if (Subtarget->isThumb())
10779         return RCPair(0U, &ARM::tGPRRegClass);
10780       return RCPair(0U, &ARM::GPRRegClass);
10781     case 'h': // High regs or no regs.
10782       if (Subtarget->isThumb())
10783         return RCPair(0U, &ARM::hGPRRegClass);
10784       break;
10785     case 'r':
10786       return RCPair(0U, &ARM::GPRRegClass);
10787     case 'w':
10788       if (VT == MVT::Other)
10789         break;
10790       if (VT == MVT::f32)
10791         return RCPair(0U, &ARM::SPRRegClass);
10792       if (VT.getSizeInBits() == 64)
10793         return RCPair(0U, &ARM::DPRRegClass);
10794       if (VT.getSizeInBits() == 128)
10795         return RCPair(0U, &ARM::QPRRegClass);
10796       break;
10797     case 'x':
10798       if (VT == MVT::Other)
10799         break;
10800       if (VT == MVT::f32)
10801         return RCPair(0U, &ARM::SPR_8RegClass);
10802       if (VT.getSizeInBits() == 64)
10803         return RCPair(0U, &ARM::DPR_8RegClass);
10804       if (VT.getSizeInBits() == 128)
10805         return RCPair(0U, &ARM::QPR_8RegClass);
10806       break;
10807     case 't':
10808       if (VT == MVT::f32)
10809         return RCPair(0U, &ARM::SPRRegClass);
10810       break;
10811     }
10812   }
10813   if (StringRef("{cc}").equals_lower(Constraint))
10814     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10815
10816   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10817 }
10818
10819 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10820 /// vector.  If it is invalid, don't add anything to Ops.
10821 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10822                                                      std::string &Constraint,
10823                                                      std::vector<SDValue>&Ops,
10824                                                      SelectionDAG &DAG) const {
10825   SDValue Result(0, 0);
10826
10827   // Currently only support length 1 constraints.
10828   if (Constraint.length() != 1) return;
10829
10830   char ConstraintLetter = Constraint[0];
10831   switch (ConstraintLetter) {
10832   default: break;
10833   case 'j':
10834   case 'I': case 'J': case 'K': case 'L':
10835   case 'M': case 'N': case 'O':
10836     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10837     if (!C)
10838       return;
10839
10840     int64_t CVal64 = C->getSExtValue();
10841     int CVal = (int) CVal64;
10842     // None of these constraints allow values larger than 32 bits.  Check
10843     // that the value fits in an int.
10844     if (CVal != CVal64)
10845       return;
10846
10847     switch (ConstraintLetter) {
10848       case 'j':
10849         // Constant suitable for movw, must be between 0 and
10850         // 65535.
10851         if (Subtarget->hasV6T2Ops())
10852           if (CVal >= 0 && CVal <= 65535)
10853             break;
10854         return;
10855       case 'I':
10856         if (Subtarget->isThumb1Only()) {
10857           // This must be a constant between 0 and 255, for ADD
10858           // immediates.
10859           if (CVal >= 0 && CVal <= 255)
10860             break;
10861         } else if (Subtarget->isThumb2()) {
10862           // A constant that can be used as an immediate value in a
10863           // data-processing instruction.
10864           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10865             break;
10866         } else {
10867           // A constant that can be used as an immediate value in a
10868           // data-processing instruction.
10869           if (ARM_AM::getSOImmVal(CVal) != -1)
10870             break;
10871         }
10872         return;
10873
10874       case 'J':
10875         if (Subtarget->isThumb()) {  // FIXME thumb2
10876           // This must be a constant between -255 and -1, for negated ADD
10877           // immediates. This can be used in GCC with an "n" modifier that
10878           // prints the negated value, for use with SUB instructions. It is
10879           // not useful otherwise but is implemented for compatibility.
10880           if (CVal >= -255 && CVal <= -1)
10881             break;
10882         } else {
10883           // This must be a constant between -4095 and 4095. It is not clear
10884           // what this constraint is intended for. Implemented for
10885           // compatibility with GCC.
10886           if (CVal >= -4095 && CVal <= 4095)
10887             break;
10888         }
10889         return;
10890
10891       case 'K':
10892         if (Subtarget->isThumb1Only()) {
10893           // A 32-bit value where only one byte has a nonzero value. Exclude
10894           // zero to match GCC. This constraint is used by GCC internally for
10895           // constants that can be loaded with a move/shift combination.
10896           // It is not useful otherwise but is implemented for compatibility.
10897           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10898             break;
10899         } else if (Subtarget->isThumb2()) {
10900           // A constant whose bitwise inverse can be used as an immediate
10901           // value in a data-processing instruction. This can be used in GCC
10902           // with a "B" modifier that prints the inverted value, for use with
10903           // BIC and MVN instructions. It is not useful otherwise but is
10904           // implemented for compatibility.
10905           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10906             break;
10907         } else {
10908           // A constant whose bitwise inverse can be used as an immediate
10909           // value in a data-processing instruction. This can be used in GCC
10910           // with a "B" modifier that prints the inverted value, for use with
10911           // BIC and MVN instructions. It is not useful otherwise but is
10912           // implemented for compatibility.
10913           if (ARM_AM::getSOImmVal(~CVal) != -1)
10914             break;
10915         }
10916         return;
10917
10918       case 'L':
10919         if (Subtarget->isThumb1Only()) {
10920           // This must be a constant between -7 and 7,
10921           // for 3-operand ADD/SUB immediate instructions.
10922           if (CVal >= -7 && CVal < 7)
10923             break;
10924         } else if (Subtarget->isThumb2()) {
10925           // A constant whose negation can be used as an immediate value in a
10926           // data-processing instruction. This can be used in GCC with an "n"
10927           // modifier that prints the negated value, for use with SUB
10928           // instructions. It is not useful otherwise but is implemented for
10929           // compatibility.
10930           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10931             break;
10932         } else {
10933           // A constant whose negation can be used as an immediate value in a
10934           // data-processing instruction. This can be used in GCC with an "n"
10935           // modifier that prints the negated value, for use with SUB
10936           // instructions. It is not useful otherwise but is implemented for
10937           // compatibility.
10938           if (ARM_AM::getSOImmVal(-CVal) != -1)
10939             break;
10940         }
10941         return;
10942
10943       case 'M':
10944         if (Subtarget->isThumb()) { // FIXME thumb2
10945           // This must be a multiple of 4 between 0 and 1020, for
10946           // ADD sp + immediate.
10947           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10948             break;
10949         } else {
10950           // A power of two or a constant between 0 and 32.  This is used in
10951           // GCC for the shift amount on shifted register operands, but it is
10952           // useful in general for any shift amounts.
10953           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10954             break;
10955         }
10956         return;
10957
10958       case 'N':
10959         if (Subtarget->isThumb()) {  // FIXME thumb2
10960           // This must be a constant between 0 and 31, for shift amounts.
10961           if (CVal >= 0 && CVal <= 31)
10962             break;
10963         }
10964         return;
10965
10966       case 'O':
10967         if (Subtarget->isThumb()) {  // FIXME thumb2
10968           // This must be a multiple of 4 between -508 and 508, for
10969           // ADD/SUB sp = sp + immediate.
10970           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10971             break;
10972         }
10973         return;
10974     }
10975     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10976     break;
10977   }
10978
10979   if (Result.getNode()) {
10980     Ops.push_back(Result);
10981     return;
10982   }
10983   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10984 }
10985
10986 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10987   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10988   unsigned Opcode = Op->getOpcode();
10989   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10990       "Invalid opcode for Div/Rem lowering");
10991   bool isSigned = (Opcode == ISD::SDIVREM);
10992   EVT VT = Op->getValueType(0);
10993   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10994
10995   RTLIB::Libcall LC;
10996   switch (VT.getSimpleVT().SimpleTy) {
10997   default: llvm_unreachable("Unexpected request for libcall!");
10998   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10999   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11000   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11001   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11002   }
11003
11004   SDValue InChain = DAG.getEntryNode();
11005
11006   TargetLowering::ArgListTy Args;
11007   TargetLowering::ArgListEntry Entry;
11008   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11009     EVT ArgVT = Op->getOperand(i).getValueType();
11010     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11011     Entry.Node = Op->getOperand(i);
11012     Entry.Ty = ArgTy;
11013     Entry.isSExt = isSigned;
11014     Entry.isZExt = !isSigned;
11015     Args.push_back(Entry);
11016   }
11017
11018   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11019                                          getPointerTy());
11020
11021   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11022
11023   SDLoc dl(Op);
11024   TargetLowering::
11025   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11026                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11027                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11028                     Callee, Args, DAG, dl);
11029   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11030
11031   return CallInfo.first;
11032 }
11033
11034 bool
11035 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11036   // The ARM target isn't yet aware of offsets.
11037   return false;
11038 }
11039
11040 bool ARM::isBitFieldInvertedMask(unsigned v) {
11041   if (v == 0xffffffff)
11042     return false;
11043
11044   // there can be 1's on either or both "outsides", all the "inside"
11045   // bits must be 0's
11046   unsigned TO = CountTrailingOnes_32(v);
11047   unsigned LO = CountLeadingOnes_32(v);
11048   v = (v >> TO) << TO;
11049   v = (v << LO) >> LO;
11050   return v == 0;
11051 }
11052
11053 /// isFPImmLegal - Returns true if the target can instruction select the
11054 /// specified FP immediate natively. If false, the legalizer will
11055 /// materialize the FP immediate as a load from a constant pool.
11056 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11057   if (!Subtarget->hasVFP3())
11058     return false;
11059   if (VT == MVT::f32)
11060     return ARM_AM::getFP32Imm(Imm) != -1;
11061   if (VT == MVT::f64)
11062     return ARM_AM::getFP64Imm(Imm) != -1;
11063   return false;
11064 }
11065
11066 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11067 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11068 /// specified in the intrinsic calls.
11069 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11070                                            const CallInst &I,
11071                                            unsigned Intrinsic) const {
11072   switch (Intrinsic) {
11073   case Intrinsic::arm_neon_vld1:
11074   case Intrinsic::arm_neon_vld2:
11075   case Intrinsic::arm_neon_vld3:
11076   case Intrinsic::arm_neon_vld4:
11077   case Intrinsic::arm_neon_vld2lane:
11078   case Intrinsic::arm_neon_vld3lane:
11079   case Intrinsic::arm_neon_vld4lane: {
11080     Info.opc = ISD::INTRINSIC_W_CHAIN;
11081     // Conservatively set memVT to the entire set of vectors loaded.
11082     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11083     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11084     Info.ptrVal = I.getArgOperand(0);
11085     Info.offset = 0;
11086     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11087     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11088     Info.vol = false; // volatile loads with NEON intrinsics not supported
11089     Info.readMem = true;
11090     Info.writeMem = false;
11091     return true;
11092   }
11093   case Intrinsic::arm_neon_vst1:
11094   case Intrinsic::arm_neon_vst2:
11095   case Intrinsic::arm_neon_vst3:
11096   case Intrinsic::arm_neon_vst4:
11097   case Intrinsic::arm_neon_vst2lane:
11098   case Intrinsic::arm_neon_vst3lane:
11099   case Intrinsic::arm_neon_vst4lane: {
11100     Info.opc = ISD::INTRINSIC_VOID;
11101     // Conservatively set memVT to the entire set of vectors stored.
11102     unsigned NumElts = 0;
11103     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11104       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11105       if (!ArgTy->isVectorTy())
11106         break;
11107       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11108     }
11109     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11110     Info.ptrVal = I.getArgOperand(0);
11111     Info.offset = 0;
11112     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11113     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11114     Info.vol = false; // volatile stores with NEON intrinsics not supported
11115     Info.readMem = false;
11116     Info.writeMem = true;
11117     return true;
11118   }
11119   case Intrinsic::arm_ldrex: {
11120     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11121     Info.opc = ISD::INTRINSIC_W_CHAIN;
11122     Info.memVT = MVT::getVT(PtrTy->getElementType());
11123     Info.ptrVal = I.getArgOperand(0);
11124     Info.offset = 0;
11125     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11126     Info.vol = true;
11127     Info.readMem = true;
11128     Info.writeMem = false;
11129     return true;
11130   }
11131   case Intrinsic::arm_strex: {
11132     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11133     Info.opc = ISD::INTRINSIC_W_CHAIN;
11134     Info.memVT = MVT::getVT(PtrTy->getElementType());
11135     Info.ptrVal = I.getArgOperand(1);
11136     Info.offset = 0;
11137     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11138     Info.vol = true;
11139     Info.readMem = false;
11140     Info.writeMem = true;
11141     return true;
11142   }
11143   case Intrinsic::arm_strexd: {
11144     Info.opc = ISD::INTRINSIC_W_CHAIN;
11145     Info.memVT = MVT::i64;
11146     Info.ptrVal = I.getArgOperand(2);
11147     Info.offset = 0;
11148     Info.align = 8;
11149     Info.vol = true;
11150     Info.readMem = false;
11151     Info.writeMem = true;
11152     return true;
11153   }
11154   case Intrinsic::arm_ldrexd: {
11155     Info.opc = ISD::INTRINSIC_W_CHAIN;
11156     Info.memVT = MVT::i64;
11157     Info.ptrVal = I.getArgOperand(0);
11158     Info.offset = 0;
11159     Info.align = 8;
11160     Info.vol = true;
11161     Info.readMem = true;
11162     Info.writeMem = false;
11163     return true;
11164   }
11165   default:
11166     break;
11167   }
11168
11169   return false;
11170 }
11171
11172 /// \brief Returns true if it is beneficial to convert a load of a constant
11173 /// to just the constant itself.
11174 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11175                                                           Type *Ty) const {
11176   assert(Ty->isIntegerTy());
11177
11178   unsigned Bits = Ty->getPrimitiveSizeInBits();
11179   if (Bits == 0 || Bits > 32)
11180     return false;
11181   return true;
11182 }