ARM: use LLVM IR to represent the vshrn operation
[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::VSHLLs:        return "ARMISD::VSHLLs";
1082   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1083   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1084   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1085   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1086   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1087   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1088   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1089   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1090   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1091   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1092   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1093   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1094   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1095   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1096   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1097   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1098   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1099   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1100   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1101   case ARMISD::VDUP:          return "ARMISD::VDUP";
1102   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1103   case ARMISD::VEXT:          return "ARMISD::VEXT";
1104   case ARMISD::VREV64:        return "ARMISD::VREV64";
1105   case ARMISD::VREV32:        return "ARMISD::VREV32";
1106   case ARMISD::VREV16:        return "ARMISD::VREV16";
1107   case ARMISD::VZIP:          return "ARMISD::VZIP";
1108   case ARMISD::VUZP:          return "ARMISD::VUZP";
1109   case ARMISD::VTRN:          return "ARMISD::VTRN";
1110   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1111   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1112   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1113   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1114   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1115   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1116   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1117   case ARMISD::FMAX:          return "ARMISD::FMAX";
1118   case ARMISD::FMIN:          return "ARMISD::FMIN";
1119   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1120   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1121   case ARMISD::BFI:           return "ARMISD::BFI";
1122   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1123   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1124   case ARMISD::VBSL:          return "ARMISD::VBSL";
1125   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1126   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1127   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1128   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1129   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1130   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1131   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1132   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1133   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1134   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1135   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1136   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1137   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1138   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1139   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1140   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1141   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1142   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1143   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1144   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1145   }
1146 }
1147
1148 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1149   if (!VT.isVector()) return getPointerTy();
1150   return VT.changeVectorElementTypeToInteger();
1151 }
1152
1153 /// getRegClassFor - Return the register class that should be used for the
1154 /// specified value type.
1155 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1156   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1157   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1158   // load / store 4 to 8 consecutive D registers.
1159   if (Subtarget->hasNEON()) {
1160     if (VT == MVT::v4i64)
1161       return &ARM::QQPRRegClass;
1162     if (VT == MVT::v8i64)
1163       return &ARM::QQQQPRRegClass;
1164   }
1165   return TargetLowering::getRegClassFor(VT);
1166 }
1167
1168 // Create a fast isel object.
1169 FastISel *
1170 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1171                                   const TargetLibraryInfo *libInfo) const {
1172   return ARM::createFastISel(funcInfo, libInfo);
1173 }
1174
1175 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1176 /// be used for loads / stores from the global.
1177 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1178   return (Subtarget->isThumb1Only() ? 127 : 4095);
1179 }
1180
1181 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1182   unsigned NumVals = N->getNumValues();
1183   if (!NumVals)
1184     return Sched::RegPressure;
1185
1186   for (unsigned i = 0; i != NumVals; ++i) {
1187     EVT VT = N->getValueType(i);
1188     if (VT == MVT::Glue || VT == MVT::Other)
1189       continue;
1190     if (VT.isFloatingPoint() || VT.isVector())
1191       return Sched::ILP;
1192   }
1193
1194   if (!N->isMachineOpcode())
1195     return Sched::RegPressure;
1196
1197   // Load are scheduled for latency even if there instruction itinerary
1198   // is not available.
1199   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1200   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1201
1202   if (MCID.getNumDefs() == 0)
1203     return Sched::RegPressure;
1204   if (!Itins->isEmpty() &&
1205       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1206     return Sched::ILP;
1207
1208   return Sched::RegPressure;
1209 }
1210
1211 //===----------------------------------------------------------------------===//
1212 // Lowering Code
1213 //===----------------------------------------------------------------------===//
1214
1215 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1216 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1217   switch (CC) {
1218   default: llvm_unreachable("Unknown condition code!");
1219   case ISD::SETNE:  return ARMCC::NE;
1220   case ISD::SETEQ:  return ARMCC::EQ;
1221   case ISD::SETGT:  return ARMCC::GT;
1222   case ISD::SETGE:  return ARMCC::GE;
1223   case ISD::SETLT:  return ARMCC::LT;
1224   case ISD::SETLE:  return ARMCC::LE;
1225   case ISD::SETUGT: return ARMCC::HI;
1226   case ISD::SETUGE: return ARMCC::HS;
1227   case ISD::SETULT: return ARMCC::LO;
1228   case ISD::SETULE: return ARMCC::LS;
1229   }
1230 }
1231
1232 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1233 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1234                         ARMCC::CondCodes &CondCode2) {
1235   CondCode2 = ARMCC::AL;
1236   switch (CC) {
1237   default: llvm_unreachable("Unknown FP condition!");
1238   case ISD::SETEQ:
1239   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1240   case ISD::SETGT:
1241   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1242   case ISD::SETGE:
1243   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1244   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1245   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1246   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1247   case ISD::SETO:   CondCode = ARMCC::VC; break;
1248   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1249   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1250   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1251   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1252   case ISD::SETLT:
1253   case ISD::SETULT: CondCode = ARMCC::LT; break;
1254   case ISD::SETLE:
1255   case ISD::SETULE: CondCode = ARMCC::LE; break;
1256   case ISD::SETNE:
1257   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1258   }
1259 }
1260
1261 //===----------------------------------------------------------------------===//
1262 //                      Calling Convention Implementation
1263 //===----------------------------------------------------------------------===//
1264
1265 #include "ARMGenCallingConv.inc"
1266
1267 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1268 /// given CallingConvention value.
1269 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1270                                                  bool Return,
1271                                                  bool isVarArg) const {
1272   switch (CC) {
1273   default:
1274     llvm_unreachable("Unsupported calling convention");
1275   case CallingConv::Fast:
1276     if (Subtarget->hasVFP2() && !isVarArg) {
1277       if (!Subtarget->isAAPCS_ABI())
1278         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1279       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1280       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1281     }
1282     // Fallthrough
1283   case CallingConv::C: {
1284     // Use target triple & subtarget features to do actual dispatch.
1285     if (!Subtarget->isAAPCS_ABI())
1286       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1287     else if (Subtarget->hasVFP2() &&
1288              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1289              !isVarArg)
1290       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1291     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1292   }
1293   case CallingConv::ARM_AAPCS_VFP:
1294     if (!isVarArg)
1295       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1296     // Fallthrough
1297   case CallingConv::ARM_AAPCS:
1298     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1299   case CallingConv::ARM_APCS:
1300     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1301   case CallingConv::GHC:
1302     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1303   }
1304 }
1305
1306 /// LowerCallResult - Lower the result values of a call into the
1307 /// appropriate copies out of appropriate physical registers.
1308 SDValue
1309 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1310                                    CallingConv::ID CallConv, bool isVarArg,
1311                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1312                                    SDLoc dl, SelectionDAG &DAG,
1313                                    SmallVectorImpl<SDValue> &InVals,
1314                                    bool isThisReturn, SDValue ThisVal) const {
1315
1316   // Assign locations to each value returned by this call.
1317   SmallVector<CCValAssign, 16> RVLocs;
1318   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1319                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1320   CCInfo.AnalyzeCallResult(Ins,
1321                            CCAssignFnForNode(CallConv, /* Return*/ true,
1322                                              isVarArg));
1323
1324   // Copy all of the result registers out of their specified physreg.
1325   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1326     CCValAssign VA = RVLocs[i];
1327
1328     // Pass 'this' value directly from the argument to return value, to avoid
1329     // reg unit interference
1330     if (i == 0 && isThisReturn) {
1331       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1332              "unexpected return calling convention register assignment");
1333       InVals.push_back(ThisVal);
1334       continue;
1335     }
1336
1337     SDValue Val;
1338     if (VA.needsCustom()) {
1339       // Handle f64 or half of a v2f64.
1340       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1341                                       InFlag);
1342       Chain = Lo.getValue(1);
1343       InFlag = Lo.getValue(2);
1344       VA = RVLocs[++i]; // skip ahead to next loc
1345       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1346                                       InFlag);
1347       Chain = Hi.getValue(1);
1348       InFlag = Hi.getValue(2);
1349       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1350
1351       if (VA.getLocVT() == MVT::v2f64) {
1352         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1353         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1354                           DAG.getConstant(0, MVT::i32));
1355
1356         VA = RVLocs[++i]; // skip ahead to next loc
1357         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1358         Chain = Lo.getValue(1);
1359         InFlag = Lo.getValue(2);
1360         VA = RVLocs[++i]; // skip ahead to next loc
1361         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1362         Chain = Hi.getValue(1);
1363         InFlag = Hi.getValue(2);
1364         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1365         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1366                           DAG.getConstant(1, MVT::i32));
1367       }
1368     } else {
1369       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1370                                InFlag);
1371       Chain = Val.getValue(1);
1372       InFlag = Val.getValue(2);
1373     }
1374
1375     switch (VA.getLocInfo()) {
1376     default: llvm_unreachable("Unknown loc info!");
1377     case CCValAssign::Full: break;
1378     case CCValAssign::BCvt:
1379       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1380       break;
1381     }
1382
1383     InVals.push_back(Val);
1384   }
1385
1386   return Chain;
1387 }
1388
1389 /// LowerMemOpCallTo - Store the argument to the stack.
1390 SDValue
1391 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1392                                     SDValue StackPtr, SDValue Arg,
1393                                     SDLoc dl, SelectionDAG &DAG,
1394                                     const CCValAssign &VA,
1395                                     ISD::ArgFlagsTy Flags) const {
1396   unsigned LocMemOffset = VA.getLocMemOffset();
1397   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1398   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1399   return DAG.getStore(Chain, dl, Arg, PtrOff,
1400                       MachinePointerInfo::getStack(LocMemOffset),
1401                       false, false, 0);
1402 }
1403
1404 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1405                                          SDValue Chain, SDValue &Arg,
1406                                          RegsToPassVector &RegsToPass,
1407                                          CCValAssign &VA, CCValAssign &NextVA,
1408                                          SDValue &StackPtr,
1409                                          SmallVectorImpl<SDValue> &MemOpChains,
1410                                          ISD::ArgFlagsTy Flags) const {
1411
1412   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1413                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1414   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1415
1416   if (NextVA.isRegLoc())
1417     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1418   else {
1419     assert(NextVA.isMemLoc());
1420     if (StackPtr.getNode() == 0)
1421       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1422
1423     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1424                                            dl, DAG, NextVA,
1425                                            Flags));
1426   }
1427 }
1428
1429 /// LowerCall - Lowering a call into a callseq_start <-
1430 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1431 /// nodes.
1432 SDValue
1433 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1434                              SmallVectorImpl<SDValue> &InVals) const {
1435   SelectionDAG &DAG                     = CLI.DAG;
1436   SDLoc &dl                          = CLI.DL;
1437   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1438   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1439   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1440   SDValue Chain                         = CLI.Chain;
1441   SDValue Callee                        = CLI.Callee;
1442   bool &isTailCall                      = CLI.IsTailCall;
1443   CallingConv::ID CallConv              = CLI.CallConv;
1444   bool doesNotRet                       = CLI.DoesNotReturn;
1445   bool isVarArg                         = CLI.IsVarArg;
1446
1447   MachineFunction &MF = DAG.getMachineFunction();
1448   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1449   bool isThisReturn   = false;
1450   bool isSibCall      = false;
1451   // Disable tail calls if they're not supported.
1452   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1453     isTailCall = false;
1454   if (isTailCall) {
1455     // Check if it's really possible to do a tail call.
1456     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1457                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1458                                                    Outs, OutVals, Ins, DAG);
1459     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1460     // detected sibcalls.
1461     if (isTailCall) {
1462       ++NumTailCalls;
1463       isSibCall = true;
1464     }
1465   }
1466
1467   // Analyze operands of the call, assigning locations to each operand.
1468   SmallVector<CCValAssign, 16> ArgLocs;
1469   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1470                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1471   CCInfo.AnalyzeCallOperands(Outs,
1472                              CCAssignFnForNode(CallConv, /* Return*/ false,
1473                                                isVarArg));
1474
1475   // Get a count of how many bytes are to be pushed on the stack.
1476   unsigned NumBytes = CCInfo.getNextStackOffset();
1477
1478   // For tail calls, memory operands are available in our caller's stack.
1479   if (isSibCall)
1480     NumBytes = 0;
1481
1482   // Adjust the stack pointer for the new arguments...
1483   // These operations are automatically eliminated by the prolog/epilog pass
1484   if (!isSibCall)
1485     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1486                                  dl);
1487
1488   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1489
1490   RegsToPassVector RegsToPass;
1491   SmallVector<SDValue, 8> MemOpChains;
1492
1493   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1494   // of tail call optimization, arguments are handled later.
1495   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1496        i != e;
1497        ++i, ++realArgIdx) {
1498     CCValAssign &VA = ArgLocs[i];
1499     SDValue Arg = OutVals[realArgIdx];
1500     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1501     bool isByVal = Flags.isByVal();
1502
1503     // Promote the value if needed.
1504     switch (VA.getLocInfo()) {
1505     default: llvm_unreachable("Unknown loc info!");
1506     case CCValAssign::Full: break;
1507     case CCValAssign::SExt:
1508       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1509       break;
1510     case CCValAssign::ZExt:
1511       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1512       break;
1513     case CCValAssign::AExt:
1514       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1515       break;
1516     case CCValAssign::BCvt:
1517       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1518       break;
1519     }
1520
1521     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1522     if (VA.needsCustom()) {
1523       if (VA.getLocVT() == MVT::v2f64) {
1524         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1525                                   DAG.getConstant(0, MVT::i32));
1526         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1527                                   DAG.getConstant(1, MVT::i32));
1528
1529         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1530                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1531
1532         VA = ArgLocs[++i]; // skip ahead to next loc
1533         if (VA.isRegLoc()) {
1534           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1535                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1536         } else {
1537           assert(VA.isMemLoc());
1538
1539           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1540                                                  dl, DAG, VA, Flags));
1541         }
1542       } else {
1543         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1544                          StackPtr, MemOpChains, Flags);
1545       }
1546     } else if (VA.isRegLoc()) {
1547       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1548         assert(VA.getLocVT() == MVT::i32 &&
1549                "unexpected calling convention register assignment");
1550         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1551                "unexpected use of 'returned'");
1552         isThisReturn = true;
1553       }
1554       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1555     } else if (isByVal) {
1556       assert(VA.isMemLoc());
1557       unsigned offset = 0;
1558
1559       // True if this byval aggregate will be split between registers
1560       // and memory.
1561       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1562       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1563
1564       if (CurByValIdx < ByValArgsCount) {
1565
1566         unsigned RegBegin, RegEnd;
1567         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1568
1569         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1570         unsigned int i, j;
1571         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1572           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1573           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1574           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1575                                      MachinePointerInfo(),
1576                                      false, false, false,
1577                                      DAG.InferPtrAlignment(AddArg));
1578           MemOpChains.push_back(Load.getValue(1));
1579           RegsToPass.push_back(std::make_pair(j, Load));
1580         }
1581
1582         // If parameter size outsides register area, "offset" value
1583         // helps us to calculate stack slot for remained part properly.
1584         offset = RegEnd - RegBegin;
1585
1586         CCInfo.nextInRegsParam();
1587       }
1588
1589       if (Flags.getByValSize() > 4*offset) {
1590         unsigned LocMemOffset = VA.getLocMemOffset();
1591         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1592         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1593                                   StkPtrOff);
1594         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1595         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1596         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1597                                            MVT::i32);
1598         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1599
1600         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1601         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1602         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1603                                           Ops, array_lengthof(Ops)));
1604       }
1605     } else if (!isSibCall) {
1606       assert(VA.isMemLoc());
1607
1608       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1609                                              dl, DAG, VA, Flags));
1610     }
1611   }
1612
1613   if (!MemOpChains.empty())
1614     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1615                         &MemOpChains[0], MemOpChains.size());
1616
1617   // Build a sequence of copy-to-reg nodes chained together with token chain
1618   // and flag operands which copy the outgoing args into the appropriate regs.
1619   SDValue InFlag;
1620   // Tail call byval lowering might overwrite argument registers so in case of
1621   // tail call optimization the copies to registers are lowered later.
1622   if (!isTailCall)
1623     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1624       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1625                                RegsToPass[i].second, InFlag);
1626       InFlag = Chain.getValue(1);
1627     }
1628
1629   // For tail calls lower the arguments to the 'real' stack slot.
1630   if (isTailCall) {
1631     // Force all the incoming stack arguments to be loaded from the stack
1632     // before any new outgoing arguments are stored to the stack, because the
1633     // outgoing stack slots may alias the incoming argument stack slots, and
1634     // the alias isn't otherwise explicit. This is slightly more conservative
1635     // than necessary, because it means that each store effectively depends
1636     // on every argument instead of just those arguments it would clobber.
1637
1638     // Do not flag preceding copytoreg stuff together with the following stuff.
1639     InFlag = SDValue();
1640     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1641       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1642                                RegsToPass[i].second, InFlag);
1643       InFlag = Chain.getValue(1);
1644     }
1645     InFlag = SDValue();
1646   }
1647
1648   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1649   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1650   // node so that legalize doesn't hack it.
1651   bool isDirect = false;
1652   bool isARMFunc = false;
1653   bool isLocalARMFunc = false;
1654   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1655
1656   if (EnableARMLongCalls) {
1657     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1658             && "long-calls with non-static relocation model!");
1659     // Handle a global address or an external symbol. If it's not one of
1660     // those, the target's already in a register, so we don't need to do
1661     // anything extra.
1662     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1663       const GlobalValue *GV = G->getGlobal();
1664       // Create a constant pool entry for the callee address
1665       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1666       ARMConstantPoolValue *CPV =
1667         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1668
1669       // Get the address of the callee into a register
1670       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1671       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1672       Callee = DAG.getLoad(getPointerTy(), dl,
1673                            DAG.getEntryNode(), CPAddr,
1674                            MachinePointerInfo::getConstantPool(),
1675                            false, false, false, 0);
1676     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1677       const char *Sym = S->getSymbol();
1678
1679       // Create a constant pool entry for the callee address
1680       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1681       ARMConstantPoolValue *CPV =
1682         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1683                                       ARMPCLabelIndex, 0);
1684       // Get the address of the callee into a register
1685       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1686       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1687       Callee = DAG.getLoad(getPointerTy(), dl,
1688                            DAG.getEntryNode(), CPAddr,
1689                            MachinePointerInfo::getConstantPool(),
1690                            false, false, false, 0);
1691     }
1692   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1693     const GlobalValue *GV = G->getGlobal();
1694     isDirect = true;
1695     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1696     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1697                    getTargetMachine().getRelocationModel() != Reloc::Static;
1698     isARMFunc = !Subtarget->isThumb() || isStub;
1699     // ARM call to a local ARM function is predicable.
1700     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1701     // tBX takes a register source operand.
1702     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1703       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1704       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1705                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1706     } else {
1707       // On ELF targets for PIC code, direct calls should go through the PLT
1708       unsigned OpFlags = 0;
1709       if (Subtarget->isTargetELF() &&
1710           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1711         OpFlags = ARMII::MO_PLT;
1712       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1713     }
1714   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1715     isDirect = true;
1716     bool isStub = Subtarget->isTargetMachO() &&
1717                   getTargetMachine().getRelocationModel() != Reloc::Static;
1718     isARMFunc = !Subtarget->isThumb() || isStub;
1719     // tBX takes a register source operand.
1720     const char *Sym = S->getSymbol();
1721     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1722       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1723       ARMConstantPoolValue *CPV =
1724         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1725                                       ARMPCLabelIndex, 4);
1726       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1727       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1728       Callee = DAG.getLoad(getPointerTy(), dl,
1729                            DAG.getEntryNode(), CPAddr,
1730                            MachinePointerInfo::getConstantPool(),
1731                            false, false, false, 0);
1732       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1733       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1734                            getPointerTy(), Callee, PICLabel);
1735     } else {
1736       unsigned OpFlags = 0;
1737       // On ELF targets for PIC code, direct calls should go through the PLT
1738       if (Subtarget->isTargetELF() &&
1739                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1740         OpFlags = ARMII::MO_PLT;
1741       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1742     }
1743   }
1744
1745   // FIXME: handle tail calls differently.
1746   unsigned CallOpc;
1747   bool HasMinSizeAttr = Subtarget->isMinSize();
1748   if (Subtarget->isThumb()) {
1749     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1750       CallOpc = ARMISD::CALL_NOLINK;
1751     else
1752       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1753   } else {
1754     if (!isDirect && !Subtarget->hasV5TOps())
1755       CallOpc = ARMISD::CALL_NOLINK;
1756     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1757                // Emit regular call when code size is the priority
1758                !HasMinSizeAttr)
1759       // "mov lr, pc; b _foo" to avoid confusing the RSP
1760       CallOpc = ARMISD::CALL_NOLINK;
1761     else
1762       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1763   }
1764
1765   std::vector<SDValue> Ops;
1766   Ops.push_back(Chain);
1767   Ops.push_back(Callee);
1768
1769   // Add argument registers to the end of the list so that they are known live
1770   // into the call.
1771   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1772     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1773                                   RegsToPass[i].second.getValueType()));
1774
1775   // Add a register mask operand representing the call-preserved registers.
1776   if (!isTailCall) {
1777     const uint32_t *Mask;
1778     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1779     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1780     if (isThisReturn) {
1781       // For 'this' returns, use the R0-preserving mask if applicable
1782       Mask = ARI->getThisReturnPreservedMask(CallConv);
1783       if (!Mask) {
1784         // Set isThisReturn to false if the calling convention is not one that
1785         // allows 'returned' to be modeled in this way, so LowerCallResult does
1786         // not try to pass 'this' straight through
1787         isThisReturn = false;
1788         Mask = ARI->getCallPreservedMask(CallConv);
1789       }
1790     } else
1791       Mask = ARI->getCallPreservedMask(CallConv);
1792
1793     assert(Mask && "Missing call preserved mask for calling convention");
1794     Ops.push_back(DAG.getRegisterMask(Mask));
1795   }
1796
1797   if (InFlag.getNode())
1798     Ops.push_back(InFlag);
1799
1800   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1801   if (isTailCall)
1802     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1803
1804   // Returns a chain and a flag for retval copy to use.
1805   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1806   InFlag = Chain.getValue(1);
1807
1808   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1809                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1810   if (!Ins.empty())
1811     InFlag = Chain.getValue(1);
1812
1813   // Handle result values, copying them out of physregs into vregs that we
1814   // return.
1815   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1816                          InVals, isThisReturn,
1817                          isThisReturn ? OutVals[0] : SDValue());
1818 }
1819
1820 /// HandleByVal - Every parameter *after* a byval parameter is passed
1821 /// on the stack.  Remember the next parameter register to allocate,
1822 /// and then confiscate the rest of the parameter registers to insure
1823 /// this.
1824 void
1825 ARMTargetLowering::HandleByVal(
1826     CCState *State, unsigned &size, unsigned Align) const {
1827   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1828   assert((State->getCallOrPrologue() == Prologue ||
1829           State->getCallOrPrologue() == Call) &&
1830          "unhandled ParmContext");
1831
1832   // For in-prologue parameters handling, we also introduce stack offset
1833   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1834   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1835   // NSAA should be evaluted (NSAA means "next stacked argument address").
1836   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1837   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1838   unsigned NSAAOffset = State->getNextStackOffset();
1839   if (State->getCallOrPrologue() != Call) {
1840     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1841       unsigned RB, RE;
1842       State->getInRegsParamInfo(i, RB, RE);
1843       assert(NSAAOffset >= (RE-RB)*4 &&
1844              "Stack offset for byval regs doesn't introduced anymore?");
1845       NSAAOffset -= (RE-RB)*4;
1846     }
1847   }
1848   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1849     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1850       unsigned AlignInRegs = Align / 4;
1851       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1852       for (unsigned i = 0; i < Waste; ++i)
1853         reg = State->AllocateReg(GPRArgRegs, 4);
1854     }
1855     if (reg != 0) {
1856       unsigned excess = 4 * (ARM::R4 - reg);
1857
1858       // Special case when NSAA != SP and parameter size greater than size of
1859       // all remained GPR regs. In that case we can't split parameter, we must
1860       // send it to stack. We also must set NCRN to R4, so waste all
1861       // remained registers.
1862       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1863         while (State->AllocateReg(GPRArgRegs, 4))
1864           ;
1865         return;
1866       }
1867
1868       // First register for byval parameter is the first register that wasn't
1869       // allocated before this method call, so it would be "reg".
1870       // If parameter is small enough to be saved in range [reg, r4), then
1871       // the end (first after last) register would be reg + param-size-in-regs,
1872       // else parameter would be splitted between registers and stack,
1873       // end register would be r4 in this case.
1874       unsigned ByValRegBegin = reg;
1875       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1876       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1877       // Note, first register is allocated in the beginning of function already,
1878       // allocate remained amount of registers we need.
1879       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1880         State->AllocateReg(GPRArgRegs, 4);
1881       // At a call site, a byval parameter that is split between
1882       // registers and memory needs its size truncated here.  In a
1883       // function prologue, such byval parameters are reassembled in
1884       // memory, and are not truncated.
1885       if (State->getCallOrPrologue() == Call) {
1886         // Make remained size equal to 0 in case, when
1887         // the whole structure may be stored into registers.
1888         if (size < excess)
1889           size = 0;
1890         else
1891           size -= excess;
1892       }
1893     }
1894   }
1895 }
1896
1897 /// MatchingStackOffset - Return true if the given stack call argument is
1898 /// already available in the same position (relatively) of the caller's
1899 /// incoming argument stack.
1900 static
1901 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1902                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1903                          const TargetInstrInfo *TII) {
1904   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1905   int FI = INT_MAX;
1906   if (Arg.getOpcode() == ISD::CopyFromReg) {
1907     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1908     if (!TargetRegisterInfo::isVirtualRegister(VR))
1909       return false;
1910     MachineInstr *Def = MRI->getVRegDef(VR);
1911     if (!Def)
1912       return false;
1913     if (!Flags.isByVal()) {
1914       if (!TII->isLoadFromStackSlot(Def, FI))
1915         return false;
1916     } else {
1917       return false;
1918     }
1919   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1920     if (Flags.isByVal())
1921       // ByVal argument is passed in as a pointer but it's now being
1922       // dereferenced. e.g.
1923       // define @foo(%struct.X* %A) {
1924       //   tail call @bar(%struct.X* byval %A)
1925       // }
1926       return false;
1927     SDValue Ptr = Ld->getBasePtr();
1928     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1929     if (!FINode)
1930       return false;
1931     FI = FINode->getIndex();
1932   } else
1933     return false;
1934
1935   assert(FI != INT_MAX);
1936   if (!MFI->isFixedObjectIndex(FI))
1937     return false;
1938   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1939 }
1940
1941 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1942 /// for tail call optimization. Targets which want to do tail call
1943 /// optimization should implement this function.
1944 bool
1945 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1946                                                      CallingConv::ID CalleeCC,
1947                                                      bool isVarArg,
1948                                                      bool isCalleeStructRet,
1949                                                      bool isCallerStructRet,
1950                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1951                                     const SmallVectorImpl<SDValue> &OutVals,
1952                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1953                                                      SelectionDAG& DAG) const {
1954   const Function *CallerF = DAG.getMachineFunction().getFunction();
1955   CallingConv::ID CallerCC = CallerF->getCallingConv();
1956   bool CCMatch = CallerCC == CalleeCC;
1957
1958   // Look for obvious safe cases to perform tail call optimization that do not
1959   // require ABI changes. This is what gcc calls sibcall.
1960
1961   // Do not sibcall optimize vararg calls unless the call site is not passing
1962   // any arguments.
1963   if (isVarArg && !Outs.empty())
1964     return false;
1965
1966   // Exception-handling functions need a special set of instructions to indicate
1967   // a return to the hardware. Tail-calling another function would probably
1968   // break this.
1969   if (CallerF->hasFnAttribute("interrupt"))
1970     return false;
1971
1972   // Also avoid sibcall optimization if either caller or callee uses struct
1973   // return semantics.
1974   if (isCalleeStructRet || isCallerStructRet)
1975     return false;
1976
1977   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1978   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1979   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1980   // support in the assembler and linker to be used. This would need to be
1981   // fixed to fully support tail calls in Thumb1.
1982   //
1983   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1984   // LR.  This means if we need to reload LR, it takes an extra instructions,
1985   // which outweighs the value of the tail call; but here we don't know yet
1986   // whether LR is going to be used.  Probably the right approach is to
1987   // generate the tail call here and turn it back into CALL/RET in
1988   // emitEpilogue if LR is used.
1989
1990   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1991   // but we need to make sure there are enough registers; the only valid
1992   // registers are the 4 used for parameters.  We don't currently do this
1993   // case.
1994   if (Subtarget->isThumb1Only())
1995     return false;
1996
1997   // If the calling conventions do not match, then we'd better make sure the
1998   // results are returned in the same way as what the caller expects.
1999   if (!CCMatch) {
2000     SmallVector<CCValAssign, 16> RVLocs1;
2001     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2002                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2003     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2004
2005     SmallVector<CCValAssign, 16> RVLocs2;
2006     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2007                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2008     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2009
2010     if (RVLocs1.size() != RVLocs2.size())
2011       return false;
2012     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2013       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2014         return false;
2015       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2016         return false;
2017       if (RVLocs1[i].isRegLoc()) {
2018         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2019           return false;
2020       } else {
2021         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2022           return false;
2023       }
2024     }
2025   }
2026
2027   // If Caller's vararg or byval argument has been split between registers and
2028   // stack, do not perform tail call, since part of the argument is in caller's
2029   // local frame.
2030   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2031                                       getInfo<ARMFunctionInfo>();
2032   if (AFI_Caller->getArgRegsSaveSize())
2033     return false;
2034
2035   // If the callee takes no arguments then go on to check the results of the
2036   // call.
2037   if (!Outs.empty()) {
2038     // Check if stack adjustment is needed. For now, do not do this if any
2039     // argument is passed on the stack.
2040     SmallVector<CCValAssign, 16> ArgLocs;
2041     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2042                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2043     CCInfo.AnalyzeCallOperands(Outs,
2044                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2045     if (CCInfo.getNextStackOffset()) {
2046       MachineFunction &MF = DAG.getMachineFunction();
2047
2048       // Check if the arguments are already laid out in the right way as
2049       // the caller's fixed stack objects.
2050       MachineFrameInfo *MFI = MF.getFrameInfo();
2051       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2052       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2053       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2054            i != e;
2055            ++i, ++realArgIdx) {
2056         CCValAssign &VA = ArgLocs[i];
2057         EVT RegVT = VA.getLocVT();
2058         SDValue Arg = OutVals[realArgIdx];
2059         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2060         if (VA.getLocInfo() == CCValAssign::Indirect)
2061           return false;
2062         if (VA.needsCustom()) {
2063           // f64 and vector types are split into multiple registers or
2064           // register/stack-slot combinations.  The types will not match
2065           // the registers; give up on memory f64 refs until we figure
2066           // out what to do about this.
2067           if (!VA.isRegLoc())
2068             return false;
2069           if (!ArgLocs[++i].isRegLoc())
2070             return false;
2071           if (RegVT == MVT::v2f64) {
2072             if (!ArgLocs[++i].isRegLoc())
2073               return false;
2074             if (!ArgLocs[++i].isRegLoc())
2075               return false;
2076           }
2077         } else if (!VA.isRegLoc()) {
2078           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2079                                    MFI, MRI, TII))
2080             return false;
2081         }
2082       }
2083     }
2084   }
2085
2086   return true;
2087 }
2088
2089 bool
2090 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2091                                   MachineFunction &MF, bool isVarArg,
2092                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2093                                   LLVMContext &Context) const {
2094   SmallVector<CCValAssign, 16> RVLocs;
2095   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2096   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2097                                                     isVarArg));
2098 }
2099
2100 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2101                                     SDLoc DL, SelectionDAG &DAG) {
2102   const MachineFunction &MF = DAG.getMachineFunction();
2103   const Function *F = MF.getFunction();
2104
2105   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2106
2107   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2108   // version of the "preferred return address". These offsets affect the return
2109   // instruction if this is a return from PL1 without hypervisor extensions.
2110   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2111   //    SWI:     0      "subs pc, lr, #0"
2112   //    ABORT:   +4     "subs pc, lr, #4"
2113   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2114   // UNDEF varies depending on where the exception came from ARM or Thumb
2115   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2116
2117   int64_t LROffset;
2118   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2119       IntKind == "ABORT")
2120     LROffset = 4;
2121   else if (IntKind == "SWI" || IntKind == "UNDEF")
2122     LROffset = 0;
2123   else
2124     report_fatal_error("Unsupported interrupt attribute. If present, value "
2125                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2126
2127   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2128
2129   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2130                      RetOps.data(), RetOps.size());
2131 }
2132
2133 SDValue
2134 ARMTargetLowering::LowerReturn(SDValue Chain,
2135                                CallingConv::ID CallConv, bool isVarArg,
2136                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2137                                const SmallVectorImpl<SDValue> &OutVals,
2138                                SDLoc dl, SelectionDAG &DAG) const {
2139
2140   // CCValAssign - represent the assignment of the return value to a location.
2141   SmallVector<CCValAssign, 16> RVLocs;
2142
2143   // CCState - Info about the registers and stack slots.
2144   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2145                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2146
2147   // Analyze outgoing return values.
2148   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2149                                                isVarArg));
2150
2151   SDValue Flag;
2152   SmallVector<SDValue, 4> RetOps;
2153   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2154
2155   // Copy the result values into the output registers.
2156   for (unsigned i = 0, realRVLocIdx = 0;
2157        i != RVLocs.size();
2158        ++i, ++realRVLocIdx) {
2159     CCValAssign &VA = RVLocs[i];
2160     assert(VA.isRegLoc() && "Can only return in registers!");
2161
2162     SDValue Arg = OutVals[realRVLocIdx];
2163
2164     switch (VA.getLocInfo()) {
2165     default: llvm_unreachable("Unknown loc info!");
2166     case CCValAssign::Full: break;
2167     case CCValAssign::BCvt:
2168       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2169       break;
2170     }
2171
2172     if (VA.needsCustom()) {
2173       if (VA.getLocVT() == MVT::v2f64) {
2174         // Extract the first half and return it in two registers.
2175         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2176                                    DAG.getConstant(0, MVT::i32));
2177         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2178                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2179
2180         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2181         Flag = Chain.getValue(1);
2182         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2183         VA = RVLocs[++i]; // skip ahead to next loc
2184         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2185                                  HalfGPRs.getValue(1), Flag);
2186         Flag = Chain.getValue(1);
2187         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2188         VA = RVLocs[++i]; // skip ahead to next loc
2189
2190         // Extract the 2nd half and fall through to handle it as an f64 value.
2191         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2192                           DAG.getConstant(1, MVT::i32));
2193       }
2194       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2195       // available.
2196       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2197                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2198       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2199       Flag = Chain.getValue(1);
2200       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2201       VA = RVLocs[++i]; // skip ahead to next loc
2202       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2203                                Flag);
2204     } else
2205       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2206
2207     // Guarantee that all emitted copies are
2208     // stuck together, avoiding something bad.
2209     Flag = Chain.getValue(1);
2210     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2211   }
2212
2213   // Update chain and glue.
2214   RetOps[0] = Chain;
2215   if (Flag.getNode())
2216     RetOps.push_back(Flag);
2217
2218   // CPUs which aren't M-class use a special sequence to return from
2219   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2220   // though we use "subs pc, lr, #N").
2221   //
2222   // M-class CPUs actually use a normal return sequence with a special
2223   // (hardware-provided) value in LR, so the normal code path works.
2224   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2225       !Subtarget->isMClass()) {
2226     if (Subtarget->isThumb1Only())
2227       report_fatal_error("interrupt attribute is not supported in Thumb1");
2228     return LowerInterruptReturn(RetOps, dl, DAG);
2229   }
2230
2231   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2232                      RetOps.data(), RetOps.size());
2233 }
2234
2235 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2236   if (N->getNumValues() != 1)
2237     return false;
2238   if (!N->hasNUsesOfValue(1, 0))
2239     return false;
2240
2241   SDValue TCChain = Chain;
2242   SDNode *Copy = *N->use_begin();
2243   if (Copy->getOpcode() == ISD::CopyToReg) {
2244     // If the copy has a glue operand, we conservatively assume it isn't safe to
2245     // perform a tail call.
2246     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2247       return false;
2248     TCChain = Copy->getOperand(0);
2249   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2250     SDNode *VMov = Copy;
2251     // f64 returned in a pair of GPRs.
2252     SmallPtrSet<SDNode*, 2> Copies;
2253     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2254          UI != UE; ++UI) {
2255       if (UI->getOpcode() != ISD::CopyToReg)
2256         return false;
2257       Copies.insert(*UI);
2258     }
2259     if (Copies.size() > 2)
2260       return false;
2261
2262     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2263          UI != UE; ++UI) {
2264       SDValue UseChain = UI->getOperand(0);
2265       if (Copies.count(UseChain.getNode()))
2266         // Second CopyToReg
2267         Copy = *UI;
2268       else
2269         // First CopyToReg
2270         TCChain = UseChain;
2271     }
2272   } else if (Copy->getOpcode() == ISD::BITCAST) {
2273     // f32 returned in a single GPR.
2274     if (!Copy->hasOneUse())
2275       return false;
2276     Copy = *Copy->use_begin();
2277     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2278       return false;
2279     TCChain = Copy->getOperand(0);
2280   } else {
2281     return false;
2282   }
2283
2284   bool HasRet = false;
2285   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2286        UI != UE; ++UI) {
2287     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2288         UI->getOpcode() != ARMISD::INTRET_FLAG)
2289       return false;
2290     HasRet = true;
2291   }
2292
2293   if (!HasRet)
2294     return false;
2295
2296   Chain = TCChain;
2297   return true;
2298 }
2299
2300 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2301   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2302     return false;
2303
2304   if (!CI->isTailCall())
2305     return false;
2306
2307   return !Subtarget->isThumb1Only();
2308 }
2309
2310 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2311 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2312 // one of the above mentioned nodes. It has to be wrapped because otherwise
2313 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2314 // be used to form addressing mode. These wrapped nodes will be selected
2315 // into MOVi.
2316 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2317   EVT PtrVT = Op.getValueType();
2318   // FIXME there is no actual debug info here
2319   SDLoc dl(Op);
2320   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2321   SDValue Res;
2322   if (CP->isMachineConstantPoolEntry())
2323     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2324                                     CP->getAlignment());
2325   else
2326     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2327                                     CP->getAlignment());
2328   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2329 }
2330
2331 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2332   return MachineJumpTableInfo::EK_Inline;
2333 }
2334
2335 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2336                                              SelectionDAG &DAG) const {
2337   MachineFunction &MF = DAG.getMachineFunction();
2338   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2339   unsigned ARMPCLabelIndex = 0;
2340   SDLoc DL(Op);
2341   EVT PtrVT = getPointerTy();
2342   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2343   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2344   SDValue CPAddr;
2345   if (RelocM == Reloc::Static) {
2346     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2347   } else {
2348     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2349     ARMPCLabelIndex = AFI->createPICLabelUId();
2350     ARMConstantPoolValue *CPV =
2351       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2352                                       ARMCP::CPBlockAddress, PCAdj);
2353     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2354   }
2355   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2356   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2357                                MachinePointerInfo::getConstantPool(),
2358                                false, false, false, 0);
2359   if (RelocM == Reloc::Static)
2360     return Result;
2361   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2362   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2363 }
2364
2365 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2366 SDValue
2367 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2368                                                  SelectionDAG &DAG) const {
2369   SDLoc dl(GA);
2370   EVT PtrVT = getPointerTy();
2371   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2372   MachineFunction &MF = DAG.getMachineFunction();
2373   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2374   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2375   ARMConstantPoolValue *CPV =
2376     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2377                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2378   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2379   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2380   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2381                          MachinePointerInfo::getConstantPool(),
2382                          false, false, false, 0);
2383   SDValue Chain = Argument.getValue(1);
2384
2385   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2386   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2387
2388   // call __tls_get_addr.
2389   ArgListTy Args;
2390   ArgListEntry Entry;
2391   Entry.Node = Argument;
2392   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2393   Args.push_back(Entry);
2394   // FIXME: is there useful debug info available here?
2395   TargetLowering::CallLoweringInfo CLI(Chain,
2396                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2397                 false, false, false, false,
2398                 0, CallingConv::C, /*isTailCall=*/false,
2399                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2400                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2401   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2402   return CallResult.first;
2403 }
2404
2405 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2406 // "local exec" model.
2407 SDValue
2408 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2409                                         SelectionDAG &DAG,
2410                                         TLSModel::Model model) const {
2411   const GlobalValue *GV = GA->getGlobal();
2412   SDLoc dl(GA);
2413   SDValue Offset;
2414   SDValue Chain = DAG.getEntryNode();
2415   EVT PtrVT = getPointerTy();
2416   // Get the Thread Pointer
2417   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2418
2419   if (model == TLSModel::InitialExec) {
2420     MachineFunction &MF = DAG.getMachineFunction();
2421     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2422     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2423     // Initial exec model.
2424     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2425     ARMConstantPoolValue *CPV =
2426       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2427                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2428                                       true);
2429     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2430     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2431     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2432                          MachinePointerInfo::getConstantPool(),
2433                          false, false, false, 0);
2434     Chain = Offset.getValue(1);
2435
2436     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2437     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2438
2439     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2440                          MachinePointerInfo::getConstantPool(),
2441                          false, false, false, 0);
2442   } else {
2443     // local exec model
2444     assert(model == TLSModel::LocalExec);
2445     ARMConstantPoolValue *CPV =
2446       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2447     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2448     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2449     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2450                          MachinePointerInfo::getConstantPool(),
2451                          false, false, false, 0);
2452   }
2453
2454   // The address of the thread local variable is the add of the thread
2455   // pointer with the offset of the variable.
2456   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2457 }
2458
2459 SDValue
2460 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2461   // TODO: implement the "local dynamic" model
2462   assert(Subtarget->isTargetELF() &&
2463          "TLS not implemented for non-ELF targets");
2464   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2465
2466   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2467
2468   switch (model) {
2469     case TLSModel::GeneralDynamic:
2470     case TLSModel::LocalDynamic:
2471       return LowerToTLSGeneralDynamicModel(GA, DAG);
2472     case TLSModel::InitialExec:
2473     case TLSModel::LocalExec:
2474       return LowerToTLSExecModels(GA, DAG, model);
2475   }
2476   llvm_unreachable("bogus TLS model");
2477 }
2478
2479 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2480                                                  SelectionDAG &DAG) const {
2481   EVT PtrVT = getPointerTy();
2482   SDLoc dl(Op);
2483   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2484   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2485     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2486     ARMConstantPoolValue *CPV =
2487       ARMConstantPoolConstant::Create(GV,
2488                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2489     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2490     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2491     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2492                                  CPAddr,
2493                                  MachinePointerInfo::getConstantPool(),
2494                                  false, false, false, 0);
2495     SDValue Chain = Result.getValue(1);
2496     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2497     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2498     if (!UseGOTOFF)
2499       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2500                            MachinePointerInfo::getGOT(),
2501                            false, false, false, 0);
2502     return Result;
2503   }
2504
2505   // If we have T2 ops, we can materialize the address directly via movt/movw
2506   // pair. This is always cheaper.
2507   if (Subtarget->useMovt()) {
2508     ++NumMovwMovt;
2509     // FIXME: Once remat is capable of dealing with instructions with register
2510     // operands, expand this into two nodes.
2511     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2512                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2513   } else {
2514     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2515     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2516     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517                        MachinePointerInfo::getConstantPool(),
2518                        false, false, false, 0);
2519   }
2520 }
2521
2522 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2523                                                     SelectionDAG &DAG) const {
2524   EVT PtrVT = getPointerTy();
2525   SDLoc dl(Op);
2526   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2527   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2528
2529   if (Subtarget->useMovt())
2530     ++NumMovwMovt;
2531
2532   // FIXME: Once remat is capable of dealing with instructions with register
2533   // operands, expand this into multiple nodes
2534   unsigned Wrapper =
2535       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2536
2537   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2538   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2539
2540   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2541     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2542                          MachinePointerInfo::getGOT(), false, false, false, 0);
2543   return Result;
2544 }
2545
2546 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2547                                                     SelectionDAG &DAG) const {
2548   assert(Subtarget->isTargetELF() &&
2549          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2550   MachineFunction &MF = DAG.getMachineFunction();
2551   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2552   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2553   EVT PtrVT = getPointerTy();
2554   SDLoc dl(Op);
2555   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2556   ARMConstantPoolValue *CPV =
2557     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2558                                   ARMPCLabelIndex, PCAdj);
2559   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2560   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2561   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2562                                MachinePointerInfo::getConstantPool(),
2563                                false, false, false, 0);
2564   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2565   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2566 }
2567
2568 SDValue
2569 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2570   SDLoc dl(Op);
2571   SDValue Val = DAG.getConstant(0, MVT::i32);
2572   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2573                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2574                      Op.getOperand(1), Val);
2575 }
2576
2577 SDValue
2578 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2579   SDLoc dl(Op);
2580   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2581                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2582 }
2583
2584 SDValue
2585 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2586                                           const ARMSubtarget *Subtarget) const {
2587   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2588   SDLoc dl(Op);
2589   switch (IntNo) {
2590   default: return SDValue();    // Don't custom lower most intrinsics.
2591   case Intrinsic::arm_thread_pointer: {
2592     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2593     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2594   }
2595   case Intrinsic::eh_sjlj_lsda: {
2596     MachineFunction &MF = DAG.getMachineFunction();
2597     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2598     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2599     EVT PtrVT = getPointerTy();
2600     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2601     SDValue CPAddr;
2602     unsigned PCAdj = (RelocM != Reloc::PIC_)
2603       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2604     ARMConstantPoolValue *CPV =
2605       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2606                                       ARMCP::CPLSDA, PCAdj);
2607     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2608     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2609     SDValue Result =
2610       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2611                   MachinePointerInfo::getConstantPool(),
2612                   false, false, false, 0);
2613
2614     if (RelocM == Reloc::PIC_) {
2615       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2616       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2617     }
2618     return Result;
2619   }
2620   case Intrinsic::arm_neon_vmulls:
2621   case Intrinsic::arm_neon_vmullu: {
2622     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2623       ? ARMISD::VMULLs : ARMISD::VMULLu;
2624     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2625                        Op.getOperand(1), Op.getOperand(2));
2626   }
2627   }
2628 }
2629
2630 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2631                                  const ARMSubtarget *Subtarget) {
2632   // FIXME: handle "fence singlethread" more efficiently.
2633   SDLoc dl(Op);
2634   if (!Subtarget->hasDataBarrier()) {
2635     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2636     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2637     // here.
2638     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2639            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2640     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2641                        DAG.getConstant(0, MVT::i32));
2642   }
2643
2644   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2645   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2646   unsigned Domain = ARM_MB::ISH;
2647   if (Subtarget->isMClass()) {
2648     // Only a full system barrier exists in the M-class architectures.
2649     Domain = ARM_MB::SY;
2650   } else if (Subtarget->isSwift() && Ord == Release) {
2651     // Swift happens to implement ISHST barriers in a way that's compatible with
2652     // Release semantics but weaker than ISH so we'd be fools not to use
2653     // it. Beware: other processors probably don't!
2654     Domain = ARM_MB::ISHST;
2655   }
2656
2657   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2658                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2659                      DAG.getConstant(Domain, MVT::i32));
2660 }
2661
2662 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2663                              const ARMSubtarget *Subtarget) {
2664   // ARM pre v5TE and Thumb1 does not have preload instructions.
2665   if (!(Subtarget->isThumb2() ||
2666         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2667     // Just preserve the chain.
2668     return Op.getOperand(0);
2669
2670   SDLoc dl(Op);
2671   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2672   if (!isRead &&
2673       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2674     // ARMv7 with MP extension has PLDW.
2675     return Op.getOperand(0);
2676
2677   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2678   if (Subtarget->isThumb()) {
2679     // Invert the bits.
2680     isRead = ~isRead & 1;
2681     isData = ~isData & 1;
2682   }
2683
2684   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2685                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2686                      DAG.getConstant(isData, MVT::i32));
2687 }
2688
2689 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2690   MachineFunction &MF = DAG.getMachineFunction();
2691   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2692
2693   // vastart just stores the address of the VarArgsFrameIndex slot into the
2694   // memory location argument.
2695   SDLoc dl(Op);
2696   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2697   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2698   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2699   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2700                       MachinePointerInfo(SV), false, false, 0);
2701 }
2702
2703 SDValue
2704 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2705                                         SDValue &Root, SelectionDAG &DAG,
2706                                         SDLoc dl) const {
2707   MachineFunction &MF = DAG.getMachineFunction();
2708   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2709
2710   const TargetRegisterClass *RC;
2711   if (AFI->isThumb1OnlyFunction())
2712     RC = &ARM::tGPRRegClass;
2713   else
2714     RC = &ARM::GPRRegClass;
2715
2716   // Transform the arguments stored in physical registers into virtual ones.
2717   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2718   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2719
2720   SDValue ArgValue2;
2721   if (NextVA.isMemLoc()) {
2722     MachineFrameInfo *MFI = MF.getFrameInfo();
2723     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2724
2725     // Create load node to retrieve arguments from the stack.
2726     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2727     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2728                             MachinePointerInfo::getFixedStack(FI),
2729                             false, false, false, 0);
2730   } else {
2731     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2732     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2733   }
2734
2735   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2736 }
2737
2738 void
2739 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2740                                   unsigned InRegsParamRecordIdx,
2741                                   unsigned ArgSize,
2742                                   unsigned &ArgRegsSize,
2743                                   unsigned &ArgRegsSaveSize)
2744   const {
2745   unsigned NumGPRs;
2746   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2747     unsigned RBegin, REnd;
2748     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2749     NumGPRs = REnd - RBegin;
2750   } else {
2751     unsigned int firstUnalloced;
2752     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2753                                                 sizeof(GPRArgRegs) /
2754                                                 sizeof(GPRArgRegs[0]));
2755     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2756   }
2757
2758   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2759   ArgRegsSize = NumGPRs * 4;
2760
2761   // If parameter is split between stack and GPRs...
2762   if (NumGPRs && Align == 8 &&
2763       (ArgRegsSize < ArgSize ||
2764         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2765     // Add padding for part of param recovered from GPRs, so
2766     // its last byte must be at address K*8 - 1.
2767     // We need to do it, since remained (stack) part of parameter has
2768     // stack alignment, and we need to "attach" "GPRs head" without gaps
2769     // to it:
2770     // Stack:
2771     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2772     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2773     //
2774     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2775     unsigned Padding =
2776         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2777         (ArgRegsSize + AFI->getArgRegsSaveSize());
2778     ArgRegsSaveSize = ArgRegsSize + Padding;
2779   } else
2780     // We don't need to extend regs save size for byval parameters if they
2781     // are passed via GPRs only.
2782     ArgRegsSaveSize = ArgRegsSize;
2783 }
2784
2785 // The remaining GPRs hold either the beginning of variable-argument
2786 // data, or the beginning of an aggregate passed by value (usually
2787 // byval).  Either way, we allocate stack slots adjacent to the data
2788 // provided by our caller, and store the unallocated registers there.
2789 // If this is a variadic function, the va_list pointer will begin with
2790 // these values; otherwise, this reassembles a (byval) structure that
2791 // was split between registers and memory.
2792 // Return: The frame index registers were stored into.
2793 int
2794 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2795                                   SDLoc dl, SDValue &Chain,
2796                                   const Value *OrigArg,
2797                                   unsigned InRegsParamRecordIdx,
2798                                   unsigned OffsetFromOrigArg,
2799                                   unsigned ArgOffset,
2800                                   unsigned ArgSize,
2801                                   bool ForceMutable) const {
2802
2803   // Currently, two use-cases possible:
2804   // Case #1. Non-var-args function, and we meet first byval parameter.
2805   //          Setup first unallocated register as first byval register;
2806   //          eat all remained registers
2807   //          (these two actions are performed by HandleByVal method).
2808   //          Then, here, we initialize stack frame with
2809   //          "store-reg" instructions.
2810   // Case #2. Var-args function, that doesn't contain byval parameters.
2811   //          The same: eat all remained unallocated registers,
2812   //          initialize stack frame.
2813
2814   MachineFunction &MF = DAG.getMachineFunction();
2815   MachineFrameInfo *MFI = MF.getFrameInfo();
2816   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2817   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2818   unsigned RBegin, REnd;
2819   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2820     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2821     firstRegToSaveIndex = RBegin - ARM::R0;
2822     lastRegToSaveIndex = REnd - ARM::R0;
2823   } else {
2824     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2825       (GPRArgRegs, array_lengthof(GPRArgRegs));
2826     lastRegToSaveIndex = 4;
2827   }
2828
2829   unsigned ArgRegsSize, ArgRegsSaveSize;
2830   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2831                  ArgRegsSize, ArgRegsSaveSize);
2832
2833   // Store any by-val regs to their spots on the stack so that they may be
2834   // loaded by deferencing the result of formal parameter pointer or va_next.
2835   // Note: once stack area for byval/varargs registers
2836   // was initialized, it can't be initialized again.
2837   if (ArgRegsSaveSize) {
2838
2839     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2840
2841     if (Padding) {
2842       assert(AFI->getStoredByValParamsPadding() == 0 &&
2843              "The only parameter may be padded.");
2844       AFI->setStoredByValParamsPadding(Padding);
2845     }
2846
2847     int FrameIndex = MFI->CreateFixedObject(
2848                       ArgRegsSaveSize,
2849                       Padding + ArgOffset,
2850                       false);
2851     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2852
2853     SmallVector<SDValue, 4> MemOps;
2854     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2855          ++firstRegToSaveIndex, ++i) {
2856       const TargetRegisterClass *RC;
2857       if (AFI->isThumb1OnlyFunction())
2858         RC = &ARM::tGPRRegClass;
2859       else
2860         RC = &ARM::GPRRegClass;
2861
2862       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2863       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2864       SDValue Store =
2865         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2866                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2867                      false, false, 0);
2868       MemOps.push_back(Store);
2869       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2870                         DAG.getConstant(4, getPointerTy()));
2871     }
2872
2873     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2874
2875     if (!MemOps.empty())
2876       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2877                           &MemOps[0], MemOps.size());
2878     return FrameIndex;
2879   } else
2880     // This will point to the next argument passed via stack.
2881     return MFI->CreateFixedObject(
2882         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2883 }
2884
2885 // Setup stack frame, the va_list pointer will start from.
2886 void
2887 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2888                                         SDLoc dl, SDValue &Chain,
2889                                         unsigned ArgOffset,
2890                                         bool ForceMutable) const {
2891   MachineFunction &MF = DAG.getMachineFunction();
2892   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2893
2894   // Try to store any remaining integer argument regs
2895   // to their spots on the stack so that they may be loaded by deferencing
2896   // the result of va_next.
2897   // If there is no regs to be stored, just point address after last
2898   // argument passed via stack.
2899   int FrameIndex =
2900     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2901                    0, ArgOffset, 0, ForceMutable);
2902
2903   AFI->setVarArgsFrameIndex(FrameIndex);
2904 }
2905
2906 SDValue
2907 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2908                                         CallingConv::ID CallConv, bool isVarArg,
2909                                         const SmallVectorImpl<ISD::InputArg>
2910                                           &Ins,
2911                                         SDLoc dl, SelectionDAG &DAG,
2912                                         SmallVectorImpl<SDValue> &InVals)
2913                                           const {
2914   MachineFunction &MF = DAG.getMachineFunction();
2915   MachineFrameInfo *MFI = MF.getFrameInfo();
2916
2917   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2918
2919   // Assign locations to all of the incoming arguments.
2920   SmallVector<CCValAssign, 16> ArgLocs;
2921   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2922                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2923   CCInfo.AnalyzeFormalArguments(Ins,
2924                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2925                                                   isVarArg));
2926
2927   SmallVector<SDValue, 16> ArgValues;
2928   int lastInsIndex = -1;
2929   SDValue ArgValue;
2930   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2931   unsigned CurArgIdx = 0;
2932
2933   // Initially ArgRegsSaveSize is zero.
2934   // Then we increase this value each time we meet byval parameter.
2935   // We also increase this value in case of varargs function.
2936   AFI->setArgRegsSaveSize(0);
2937
2938   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2939     CCValAssign &VA = ArgLocs[i];
2940     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2941     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2942     // Arguments stored in registers.
2943     if (VA.isRegLoc()) {
2944       EVT RegVT = VA.getLocVT();
2945
2946       if (VA.needsCustom()) {
2947         // f64 and vector types are split up into multiple registers or
2948         // combinations of registers and stack slots.
2949         if (VA.getLocVT() == MVT::v2f64) {
2950           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2951                                                    Chain, DAG, dl);
2952           VA = ArgLocs[++i]; // skip ahead to next loc
2953           SDValue ArgValue2;
2954           if (VA.isMemLoc()) {
2955             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2956             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2957             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2958                                     MachinePointerInfo::getFixedStack(FI),
2959                                     false, false, false, 0);
2960           } else {
2961             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2962                                              Chain, DAG, dl);
2963           }
2964           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2965           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2966                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2967           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2968                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2969         } else
2970           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2971
2972       } else {
2973         const TargetRegisterClass *RC;
2974
2975         if (RegVT == MVT::f32)
2976           RC = &ARM::SPRRegClass;
2977         else if (RegVT == MVT::f64)
2978           RC = &ARM::DPRRegClass;
2979         else if (RegVT == MVT::v2f64)
2980           RC = &ARM::QPRRegClass;
2981         else if (RegVT == MVT::i32)
2982           RC = AFI->isThumb1OnlyFunction() ?
2983             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2984             (const TargetRegisterClass*)&ARM::GPRRegClass;
2985         else
2986           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2987
2988         // Transform the arguments in physical registers into virtual ones.
2989         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2990         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2991       }
2992
2993       // If this is an 8 or 16-bit value, it is really passed promoted
2994       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2995       // truncate to the right size.
2996       switch (VA.getLocInfo()) {
2997       default: llvm_unreachable("Unknown loc info!");
2998       case CCValAssign::Full: break;
2999       case CCValAssign::BCvt:
3000         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3001         break;
3002       case CCValAssign::SExt:
3003         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3004                                DAG.getValueType(VA.getValVT()));
3005         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3006         break;
3007       case CCValAssign::ZExt:
3008         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3009                                DAG.getValueType(VA.getValVT()));
3010         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3011         break;
3012       }
3013
3014       InVals.push_back(ArgValue);
3015
3016     } else { // VA.isRegLoc()
3017
3018       // sanity check
3019       assert(VA.isMemLoc());
3020       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3021
3022       int index = ArgLocs[i].getValNo();
3023
3024       // Some Ins[] entries become multiple ArgLoc[] entries.
3025       // Process them only once.
3026       if (index != lastInsIndex)
3027         {
3028           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3029           // FIXME: For now, all byval parameter objects are marked mutable.
3030           // This can be changed with more analysis.
3031           // In case of tail call optimization mark all arguments mutable.
3032           // Since they could be overwritten by lowering of arguments in case of
3033           // a tail call.
3034           if (Flags.isByVal()) {
3035             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3036             int FrameIndex = StoreByValRegs(
3037                 CCInfo, DAG, dl, Chain, CurOrigArg,
3038                 CurByValIndex,
3039                 Ins[VA.getValNo()].PartOffset,
3040                 VA.getLocMemOffset(),
3041                 Flags.getByValSize(),
3042                 true /*force mutable frames*/);
3043             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3044             CCInfo.nextInRegsParam();
3045           } else {
3046             unsigned FIOffset = VA.getLocMemOffset() +
3047                                 AFI->getStoredByValParamsPadding();
3048             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3049                                             FIOffset, true);
3050
3051             // Create load nodes to retrieve arguments from the stack.
3052             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3053             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3054                                          MachinePointerInfo::getFixedStack(FI),
3055                                          false, false, false, 0));
3056           }
3057           lastInsIndex = index;
3058         }
3059     }
3060   }
3061
3062   // varargs
3063   if (isVarArg)
3064     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3065                          CCInfo.getNextStackOffset());
3066
3067   return Chain;
3068 }
3069
3070 /// isFloatingPointZero - Return true if this is +0.0.
3071 static bool isFloatingPointZero(SDValue Op) {
3072   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3073     return CFP->getValueAPF().isPosZero();
3074   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3075     // Maybe this has already been legalized into the constant pool?
3076     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3077       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3078       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3079         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3080           return CFP->getValueAPF().isPosZero();
3081     }
3082   }
3083   return false;
3084 }
3085
3086 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3087 /// the given operands.
3088 SDValue
3089 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3090                              SDValue &ARMcc, SelectionDAG &DAG,
3091                              SDLoc dl) const {
3092   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3093     unsigned C = RHSC->getZExtValue();
3094     if (!isLegalICmpImmediate(C)) {
3095       // Constant does not fit, try adjusting it by one?
3096       switch (CC) {
3097       default: break;
3098       case ISD::SETLT:
3099       case ISD::SETGE:
3100         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3101           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3102           RHS = DAG.getConstant(C-1, MVT::i32);
3103         }
3104         break;
3105       case ISD::SETULT:
3106       case ISD::SETUGE:
3107         if (C != 0 && isLegalICmpImmediate(C-1)) {
3108           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3109           RHS = DAG.getConstant(C-1, MVT::i32);
3110         }
3111         break;
3112       case ISD::SETLE:
3113       case ISD::SETGT:
3114         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3115           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3116           RHS = DAG.getConstant(C+1, MVT::i32);
3117         }
3118         break;
3119       case ISD::SETULE:
3120       case ISD::SETUGT:
3121         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3122           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3123           RHS = DAG.getConstant(C+1, MVT::i32);
3124         }
3125         break;
3126       }
3127     }
3128   }
3129
3130   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3131   ARMISD::NodeType CompareType;
3132   switch (CondCode) {
3133   default:
3134     CompareType = ARMISD::CMP;
3135     break;
3136   case ARMCC::EQ:
3137   case ARMCC::NE:
3138     // Uses only Z Flag
3139     CompareType = ARMISD::CMPZ;
3140     break;
3141   }
3142   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3143   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3144 }
3145
3146 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3147 SDValue
3148 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3149                              SDLoc dl) const {
3150   SDValue Cmp;
3151   if (!isFloatingPointZero(RHS))
3152     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3153   else
3154     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3155   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3156 }
3157
3158 /// duplicateCmp - Glue values can have only one use, so this function
3159 /// duplicates a comparison node.
3160 SDValue
3161 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3162   unsigned Opc = Cmp.getOpcode();
3163   SDLoc DL(Cmp);
3164   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3165     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3166
3167   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3168   Cmp = Cmp.getOperand(0);
3169   Opc = Cmp.getOpcode();
3170   if (Opc == ARMISD::CMPFP)
3171     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3172   else {
3173     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3174     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3175   }
3176   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3177 }
3178
3179 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3180   SDValue Cond = Op.getOperand(0);
3181   SDValue SelectTrue = Op.getOperand(1);
3182   SDValue SelectFalse = Op.getOperand(2);
3183   SDLoc dl(Op);
3184
3185   // Convert:
3186   //
3187   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3188   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3189   //
3190   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3191     const ConstantSDNode *CMOVTrue =
3192       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3193     const ConstantSDNode *CMOVFalse =
3194       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3195
3196     if (CMOVTrue && CMOVFalse) {
3197       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3198       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3199
3200       SDValue True;
3201       SDValue False;
3202       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3203         True = SelectTrue;
3204         False = SelectFalse;
3205       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3206         True = SelectFalse;
3207         False = SelectTrue;
3208       }
3209
3210       if (True.getNode() && False.getNode()) {
3211         EVT VT = Op.getValueType();
3212         SDValue ARMcc = Cond.getOperand(2);
3213         SDValue CCR = Cond.getOperand(3);
3214         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3215         assert(True.getValueType() == VT);
3216         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3217       }
3218     }
3219   }
3220
3221   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3222   // undefined bits before doing a full-word comparison with zero.
3223   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3224                      DAG.getConstant(1, Cond.getValueType()));
3225
3226   return DAG.getSelectCC(dl, Cond,
3227                          DAG.getConstant(0, Cond.getValueType()),
3228                          SelectTrue, SelectFalse, ISD::SETNE);
3229 }
3230
3231 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3232   if (CC == ISD::SETNE)
3233     return ISD::SETEQ;
3234   return ISD::getSetCCInverse(CC, true);
3235 }
3236
3237 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3238                                  bool &swpCmpOps, bool &swpVselOps) {
3239   // Start by selecting the GE condition code for opcodes that return true for
3240   // 'equality'
3241   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3242       CC == ISD::SETULE)
3243     CondCode = ARMCC::GE;
3244
3245   // and GT for opcodes that return false for 'equality'.
3246   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3247            CC == ISD::SETULT)
3248     CondCode = ARMCC::GT;
3249
3250   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3251   // to swap the compare operands.
3252   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3253       CC == ISD::SETULT)
3254     swpCmpOps = true;
3255
3256   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3257   // If we have an unordered opcode, we need to swap the operands to the VSEL
3258   // instruction (effectively negating the condition).
3259   //
3260   // This also has the effect of swapping which one of 'less' or 'greater'
3261   // returns true, so we also swap the compare operands. It also switches
3262   // whether we return true for 'equality', so we compensate by picking the
3263   // opposite condition code to our original choice.
3264   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3265       CC == ISD::SETUGT) {
3266     swpCmpOps = !swpCmpOps;
3267     swpVselOps = !swpVselOps;
3268     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3269   }
3270
3271   // 'ordered' is 'anything but unordered', so use the VS condition code and
3272   // swap the VSEL operands.
3273   if (CC == ISD::SETO) {
3274     CondCode = ARMCC::VS;
3275     swpVselOps = true;
3276   }
3277
3278   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3279   // code and swap the VSEL operands.
3280   if (CC == ISD::SETUNE) {
3281     CondCode = ARMCC::EQ;
3282     swpVselOps = true;
3283   }
3284 }
3285
3286 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3287   EVT VT = Op.getValueType();
3288   SDValue LHS = Op.getOperand(0);
3289   SDValue RHS = Op.getOperand(1);
3290   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3291   SDValue TrueVal = Op.getOperand(2);
3292   SDValue FalseVal = Op.getOperand(3);
3293   SDLoc dl(Op);
3294
3295   if (LHS.getValueType() == MVT::i32) {
3296     // Try to generate VSEL on ARMv8.
3297     // The VSEL instruction can't use all the usual ARM condition
3298     // codes: it only has two bits to select the condition code, so it's
3299     // constrained to use only GE, GT, VS and EQ.
3300     //
3301     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3302     // swap the operands of the previous compare instruction (effectively
3303     // inverting the compare condition, swapping 'less' and 'greater') and
3304     // sometimes need to swap the operands to the VSEL (which inverts the
3305     // condition in the sense of firing whenever the previous condition didn't)
3306     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3307                                       TrueVal.getValueType() == MVT::f64)) {
3308       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3309       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3310           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3311         CC = getInverseCCForVSEL(CC);
3312         std::swap(TrueVal, FalseVal);
3313       }
3314     }
3315
3316     SDValue ARMcc;
3317     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3318     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3319     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3320                        Cmp);
3321   }
3322
3323   ARMCC::CondCodes CondCode, CondCode2;
3324   FPCCToARMCC(CC, CondCode, CondCode2);
3325
3326   // Try to generate VSEL on ARMv8.
3327   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3328                                     TrueVal.getValueType() == MVT::f64)) {
3329     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3330     // same operands, as follows:
3331     //   c = fcmp [ogt, olt, ugt, ult] a, b
3332     //   select c, a, b
3333     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3334     // handled differently than the original code sequence.
3335     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3336         RHS == FalseVal) {
3337       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3338         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3339       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3340         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3341     }
3342
3343     bool swpCmpOps = false;
3344     bool swpVselOps = false;
3345     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3346
3347     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3348         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3349       if (swpCmpOps)
3350         std::swap(LHS, RHS);
3351       if (swpVselOps)
3352         std::swap(TrueVal, FalseVal);
3353     }
3354   }
3355
3356   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3357   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3358   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3359   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3360                                ARMcc, CCR, Cmp);
3361   if (CondCode2 != ARMCC::AL) {
3362     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3363     // FIXME: Needs another CMP because flag can have but one use.
3364     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3365     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3366                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3367   }
3368   return Result;
3369 }
3370
3371 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3372 /// to morph to an integer compare sequence.
3373 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3374                            const ARMSubtarget *Subtarget) {
3375   SDNode *N = Op.getNode();
3376   if (!N->hasOneUse())
3377     // Otherwise it requires moving the value from fp to integer registers.
3378     return false;
3379   if (!N->getNumValues())
3380     return false;
3381   EVT VT = Op.getValueType();
3382   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3383     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3384     // vmrs are very slow, e.g. cortex-a8.
3385     return false;
3386
3387   if (isFloatingPointZero(Op)) {
3388     SeenZero = true;
3389     return true;
3390   }
3391   return ISD::isNormalLoad(N);
3392 }
3393
3394 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3395   if (isFloatingPointZero(Op))
3396     return DAG.getConstant(0, MVT::i32);
3397
3398   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3399     return DAG.getLoad(MVT::i32, SDLoc(Op),
3400                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3401                        Ld->isVolatile(), Ld->isNonTemporal(),
3402                        Ld->isInvariant(), Ld->getAlignment());
3403
3404   llvm_unreachable("Unknown VFP cmp argument!");
3405 }
3406
3407 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3408                            SDValue &RetVal1, SDValue &RetVal2) {
3409   if (isFloatingPointZero(Op)) {
3410     RetVal1 = DAG.getConstant(0, MVT::i32);
3411     RetVal2 = DAG.getConstant(0, MVT::i32);
3412     return;
3413   }
3414
3415   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3416     SDValue Ptr = Ld->getBasePtr();
3417     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3418                           Ld->getChain(), Ptr,
3419                           Ld->getPointerInfo(),
3420                           Ld->isVolatile(), Ld->isNonTemporal(),
3421                           Ld->isInvariant(), Ld->getAlignment());
3422
3423     EVT PtrType = Ptr.getValueType();
3424     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3425     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3426                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3427     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3428                           Ld->getChain(), NewPtr,
3429                           Ld->getPointerInfo().getWithOffset(4),
3430                           Ld->isVolatile(), Ld->isNonTemporal(),
3431                           Ld->isInvariant(), NewAlign);
3432     return;
3433   }
3434
3435   llvm_unreachable("Unknown VFP cmp argument!");
3436 }
3437
3438 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3439 /// f32 and even f64 comparisons to integer ones.
3440 SDValue
3441 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3442   SDValue Chain = Op.getOperand(0);
3443   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3444   SDValue LHS = Op.getOperand(2);
3445   SDValue RHS = Op.getOperand(3);
3446   SDValue Dest = Op.getOperand(4);
3447   SDLoc dl(Op);
3448
3449   bool LHSSeenZero = false;
3450   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3451   bool RHSSeenZero = false;
3452   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3453   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3454     // If unsafe fp math optimization is enabled and there are no other uses of
3455     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3456     // to an integer comparison.
3457     if (CC == ISD::SETOEQ)
3458       CC = ISD::SETEQ;
3459     else if (CC == ISD::SETUNE)
3460       CC = ISD::SETNE;
3461
3462     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3463     SDValue ARMcc;
3464     if (LHS.getValueType() == MVT::f32) {
3465       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3466                         bitcastf32Toi32(LHS, DAG), Mask);
3467       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3468                         bitcastf32Toi32(RHS, DAG), Mask);
3469       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3470       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3471       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3472                          Chain, Dest, ARMcc, CCR, Cmp);
3473     }
3474
3475     SDValue LHS1, LHS2;
3476     SDValue RHS1, RHS2;
3477     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3478     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3479     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3480     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3481     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3482     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3483     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3484     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3485     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3486   }
3487
3488   return SDValue();
3489 }
3490
3491 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3492   SDValue Chain = Op.getOperand(0);
3493   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3494   SDValue LHS = Op.getOperand(2);
3495   SDValue RHS = Op.getOperand(3);
3496   SDValue Dest = Op.getOperand(4);
3497   SDLoc dl(Op);
3498
3499   if (LHS.getValueType() == MVT::i32) {
3500     SDValue ARMcc;
3501     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3502     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3503     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3504                        Chain, Dest, ARMcc, CCR, Cmp);
3505   }
3506
3507   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3508
3509   if (getTargetMachine().Options.UnsafeFPMath &&
3510       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3511        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3512     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3513     if (Result.getNode())
3514       return Result;
3515   }
3516
3517   ARMCC::CondCodes CondCode, CondCode2;
3518   FPCCToARMCC(CC, CondCode, CondCode2);
3519
3520   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3521   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3522   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3523   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3524   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3525   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3526   if (CondCode2 != ARMCC::AL) {
3527     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3528     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3529     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3530   }
3531   return Res;
3532 }
3533
3534 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3535   SDValue Chain = Op.getOperand(0);
3536   SDValue Table = Op.getOperand(1);
3537   SDValue Index = Op.getOperand(2);
3538   SDLoc dl(Op);
3539
3540   EVT PTy = getPointerTy();
3541   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3542   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3543   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3544   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3545   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3546   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3547   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3548   if (Subtarget->isThumb2()) {
3549     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3550     // which does another jump to the destination. This also makes it easier
3551     // to translate it to TBB / TBH later.
3552     // FIXME: This might not work if the function is extremely large.
3553     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3554                        Addr, Op.getOperand(2), JTI, UId);
3555   }
3556   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3557     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3558                        MachinePointerInfo::getJumpTable(),
3559                        false, false, false, 0);
3560     Chain = Addr.getValue(1);
3561     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3562     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3563   } else {
3564     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3565                        MachinePointerInfo::getJumpTable(),
3566                        false, false, false, 0);
3567     Chain = Addr.getValue(1);
3568     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3569   }
3570 }
3571
3572 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3573   EVT VT = Op.getValueType();
3574   SDLoc dl(Op);
3575
3576   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3577     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3578       return Op;
3579     return DAG.UnrollVectorOp(Op.getNode());
3580   }
3581
3582   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3583          "Invalid type for custom lowering!");
3584   if (VT != MVT::v4i16)
3585     return DAG.UnrollVectorOp(Op.getNode());
3586
3587   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3588   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3589 }
3590
3591 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3592   EVT VT = Op.getValueType();
3593   if (VT.isVector())
3594     return LowerVectorFP_TO_INT(Op, DAG);
3595
3596   SDLoc dl(Op);
3597   unsigned Opc;
3598
3599   switch (Op.getOpcode()) {
3600   default: llvm_unreachable("Invalid opcode!");
3601   case ISD::FP_TO_SINT:
3602     Opc = ARMISD::FTOSI;
3603     break;
3604   case ISD::FP_TO_UINT:
3605     Opc = ARMISD::FTOUI;
3606     break;
3607   }
3608   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3609   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3610 }
3611
3612 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3613   EVT VT = Op.getValueType();
3614   SDLoc dl(Op);
3615
3616   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3617     if (VT.getVectorElementType() == MVT::f32)
3618       return Op;
3619     return DAG.UnrollVectorOp(Op.getNode());
3620   }
3621
3622   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3623          "Invalid type for custom lowering!");
3624   if (VT != MVT::v4f32)
3625     return DAG.UnrollVectorOp(Op.getNode());
3626
3627   unsigned CastOpc;
3628   unsigned Opc;
3629   switch (Op.getOpcode()) {
3630   default: llvm_unreachable("Invalid opcode!");
3631   case ISD::SINT_TO_FP:
3632     CastOpc = ISD::SIGN_EXTEND;
3633     Opc = ISD::SINT_TO_FP;
3634     break;
3635   case ISD::UINT_TO_FP:
3636     CastOpc = ISD::ZERO_EXTEND;
3637     Opc = ISD::UINT_TO_FP;
3638     break;
3639   }
3640
3641   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3642   return DAG.getNode(Opc, dl, VT, Op);
3643 }
3644
3645 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3646   EVT VT = Op.getValueType();
3647   if (VT.isVector())
3648     return LowerVectorINT_TO_FP(Op, DAG);
3649
3650   SDLoc dl(Op);
3651   unsigned Opc;
3652
3653   switch (Op.getOpcode()) {
3654   default: llvm_unreachable("Invalid opcode!");
3655   case ISD::SINT_TO_FP:
3656     Opc = ARMISD::SITOF;
3657     break;
3658   case ISD::UINT_TO_FP:
3659     Opc = ARMISD::UITOF;
3660     break;
3661   }
3662
3663   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3664   return DAG.getNode(Opc, dl, VT, Op);
3665 }
3666
3667 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3668   // Implement fcopysign with a fabs and a conditional fneg.
3669   SDValue Tmp0 = Op.getOperand(0);
3670   SDValue Tmp1 = Op.getOperand(1);
3671   SDLoc dl(Op);
3672   EVT VT = Op.getValueType();
3673   EVT SrcVT = Tmp1.getValueType();
3674   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3675     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3676   bool UseNEON = !InGPR && Subtarget->hasNEON();
3677
3678   if (UseNEON) {
3679     // Use VBSL to copy the sign bit.
3680     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3681     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3682                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3683     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3684     if (VT == MVT::f64)
3685       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3686                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3687                          DAG.getConstant(32, MVT::i32));
3688     else /*if (VT == MVT::f32)*/
3689       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3690     if (SrcVT == MVT::f32) {
3691       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3692       if (VT == MVT::f64)
3693         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3694                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3695                            DAG.getConstant(32, MVT::i32));
3696     } else if (VT == MVT::f32)
3697       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3698                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3699                          DAG.getConstant(32, MVT::i32));
3700     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3701     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3702
3703     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3704                                             MVT::i32);
3705     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3706     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3707                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3708
3709     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3710                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3711                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3712     if (VT == MVT::f32) {
3713       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3714       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3715                         DAG.getConstant(0, MVT::i32));
3716     } else {
3717       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3718     }
3719
3720     return Res;
3721   }
3722
3723   // Bitcast operand 1 to i32.
3724   if (SrcVT == MVT::f64)
3725     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3726                        &Tmp1, 1).getValue(1);
3727   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3728
3729   // Or in the signbit with integer operations.
3730   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3731   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3732   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3733   if (VT == MVT::f32) {
3734     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3735                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3736     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3737                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3738   }
3739
3740   // f64: Or the high part with signbit and then combine two parts.
3741   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3742                      &Tmp0, 1);
3743   SDValue Lo = Tmp0.getValue(0);
3744   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3745   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3746   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3747 }
3748
3749 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3750   MachineFunction &MF = DAG.getMachineFunction();
3751   MachineFrameInfo *MFI = MF.getFrameInfo();
3752   MFI->setReturnAddressIsTaken(true);
3753
3754   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3755     return SDValue();
3756
3757   EVT VT = Op.getValueType();
3758   SDLoc dl(Op);
3759   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3760   if (Depth) {
3761     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3762     SDValue Offset = DAG.getConstant(4, MVT::i32);
3763     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3764                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3765                        MachinePointerInfo(), false, false, false, 0);
3766   }
3767
3768   // Return LR, which contains the return address. Mark it an implicit live-in.
3769   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3770   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3771 }
3772
3773 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3774   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3775   MFI->setFrameAddressIsTaken(true);
3776
3777   EVT VT = Op.getValueType();
3778   SDLoc dl(Op);  // FIXME probably not meaningful
3779   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3780   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3781     ? ARM::R7 : ARM::R11;
3782   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3783   while (Depth--)
3784     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3785                             MachinePointerInfo(),
3786                             false, false, false, 0);
3787   return FrameAddr;
3788 }
3789
3790 /// ExpandBITCAST - If the target supports VFP, this function is called to
3791 /// expand a bit convert where either the source or destination type is i64 to
3792 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3793 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3794 /// vectors), since the legalizer won't know what to do with that.
3795 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3797   SDLoc dl(N);
3798   SDValue Op = N->getOperand(0);
3799
3800   // This function is only supposed to be called for i64 types, either as the
3801   // source or destination of the bit convert.
3802   EVT SrcVT = Op.getValueType();
3803   EVT DstVT = N->getValueType(0);
3804   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3805          "ExpandBITCAST called for non-i64 type");
3806
3807   // Turn i64->f64 into VMOVDRR.
3808   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3809     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3810                              DAG.getConstant(0, MVT::i32));
3811     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3812                              DAG.getConstant(1, MVT::i32));
3813     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3814                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3815   }
3816
3817   // Turn f64->i64 into VMOVRRD.
3818   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3819     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3820                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3821     // Merge the pieces into a single i64 value.
3822     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3823   }
3824
3825   return SDValue();
3826 }
3827
3828 /// getZeroVector - Returns a vector of specified type with all zero elements.
3829 /// Zero vectors are used to represent vector negation and in those cases
3830 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3831 /// not support i64 elements, so sometimes the zero vectors will need to be
3832 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3833 /// zero vector.
3834 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3835   assert(VT.isVector() && "Expected a vector type");
3836   // The canonical modified immediate encoding of a zero vector is....0!
3837   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3838   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3839   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3840   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3841 }
3842
3843 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3844 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3845 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3846                                                 SelectionDAG &DAG) const {
3847   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3848   EVT VT = Op.getValueType();
3849   unsigned VTBits = VT.getSizeInBits();
3850   SDLoc dl(Op);
3851   SDValue ShOpLo = Op.getOperand(0);
3852   SDValue ShOpHi = Op.getOperand(1);
3853   SDValue ShAmt  = Op.getOperand(2);
3854   SDValue ARMcc;
3855   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3856
3857   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3858
3859   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3860                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3861   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3862   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3863                                    DAG.getConstant(VTBits, MVT::i32));
3864   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3865   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3866   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3867
3868   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3869   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3870                           ARMcc, DAG, dl);
3871   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3872   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3873                            CCR, Cmp);
3874
3875   SDValue Ops[2] = { Lo, Hi };
3876   return DAG.getMergeValues(Ops, 2, dl);
3877 }
3878
3879 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3880 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3881 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3882                                                SelectionDAG &DAG) const {
3883   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3884   EVT VT = Op.getValueType();
3885   unsigned VTBits = VT.getSizeInBits();
3886   SDLoc dl(Op);
3887   SDValue ShOpLo = Op.getOperand(0);
3888   SDValue ShOpHi = Op.getOperand(1);
3889   SDValue ShAmt  = Op.getOperand(2);
3890   SDValue ARMcc;
3891
3892   assert(Op.getOpcode() == ISD::SHL_PARTS);
3893   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3894                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3895   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3896   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3897                                    DAG.getConstant(VTBits, MVT::i32));
3898   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3899   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3900
3901   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3902   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3903   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3904                           ARMcc, DAG, dl);
3905   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3906   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3907                            CCR, Cmp);
3908
3909   SDValue Ops[2] = { Lo, Hi };
3910   return DAG.getMergeValues(Ops, 2, dl);
3911 }
3912
3913 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3914                                             SelectionDAG &DAG) const {
3915   // The rounding mode is in bits 23:22 of the FPSCR.
3916   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3917   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3918   // so that the shift + and get folded into a bitfield extract.
3919   SDLoc dl(Op);
3920   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3921                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3922                                               MVT::i32));
3923   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3924                                   DAG.getConstant(1U << 22, MVT::i32));
3925   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3926                               DAG.getConstant(22, MVT::i32));
3927   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3928                      DAG.getConstant(3, MVT::i32));
3929 }
3930
3931 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3932                          const ARMSubtarget *ST) {
3933   EVT VT = N->getValueType(0);
3934   SDLoc dl(N);
3935
3936   if (!ST->hasV6T2Ops())
3937     return SDValue();
3938
3939   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3940   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3941 }
3942
3943 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3944 /// for each 16-bit element from operand, repeated.  The basic idea is to
3945 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3946 ///
3947 /// Trace for v4i16:
3948 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3949 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3950 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3951 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3952 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3953 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3954 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3955 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3956 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3957   EVT VT = N->getValueType(0);
3958   SDLoc DL(N);
3959
3960   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3961   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3962   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3963   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3964   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3965   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3966 }
3967
3968 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3969 /// bit-count for each 16-bit element from the operand.  We need slightly
3970 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3971 /// 64/128-bit registers.
3972 ///
3973 /// Trace for v4i16:
3974 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3975 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3976 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3977 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3978 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3979   EVT VT = N->getValueType(0);
3980   SDLoc DL(N);
3981
3982   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3983   if (VT.is64BitVector()) {
3984     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3985     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3986                        DAG.getIntPtrConstant(0));
3987   } else {
3988     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3989                                     BitCounts, DAG.getIntPtrConstant(0));
3990     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3991   }
3992 }
3993
3994 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3995 /// bit-count for each 32-bit element from the operand.  The idea here is
3996 /// to split the vector into 16-bit elements, leverage the 16-bit count
3997 /// routine, and then combine the results.
3998 ///
3999 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4000 /// input    = [v0    v1    ] (vi: 32-bit elements)
4001 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4002 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4003 /// vrev: N0 = [k1 k0 k3 k2 ]
4004 ///            [k0 k1 k2 k3 ]
4005 ///       N1 =+[k1 k0 k3 k2 ]
4006 ///            [k0 k2 k1 k3 ]
4007 ///       N2 =+[k1 k3 k0 k2 ]
4008 ///            [k0    k2    k1    k3    ]
4009 /// Extended =+[k1    k3    k0    k2    ]
4010 ///            [k0    k2    ]
4011 /// Extracted=+[k1    k3    ]
4012 ///
4013 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4014   EVT VT = N->getValueType(0);
4015   SDLoc DL(N);
4016
4017   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4018
4019   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4020   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4021   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4022   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4023   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4024
4025   if (VT.is64BitVector()) {
4026     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4027     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4028                        DAG.getIntPtrConstant(0));
4029   } else {
4030     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4031                                     DAG.getIntPtrConstant(0));
4032     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4033   }
4034 }
4035
4036 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4037                           const ARMSubtarget *ST) {
4038   EVT VT = N->getValueType(0);
4039
4040   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4041   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4042           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4043          "Unexpected type for custom ctpop lowering");
4044
4045   if (VT.getVectorElementType() == MVT::i32)
4046     return lowerCTPOP32BitElements(N, DAG);
4047   else
4048     return lowerCTPOP16BitElements(N, DAG);
4049 }
4050
4051 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4052                           const ARMSubtarget *ST) {
4053   EVT VT = N->getValueType(0);
4054   SDLoc dl(N);
4055
4056   if (!VT.isVector())
4057     return SDValue();
4058
4059   // Lower vector shifts on NEON to use VSHL.
4060   assert(ST->hasNEON() && "unexpected vector shift");
4061
4062   // Left shifts translate directly to the vshiftu intrinsic.
4063   if (N->getOpcode() == ISD::SHL)
4064     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4065                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4066                        N->getOperand(0), N->getOperand(1));
4067
4068   assert((N->getOpcode() == ISD::SRA ||
4069           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4070
4071   // NEON uses the same intrinsics for both left and right shifts.  For
4072   // right shifts, the shift amounts are negative, so negate the vector of
4073   // shift amounts.
4074   EVT ShiftVT = N->getOperand(1).getValueType();
4075   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4076                                      getZeroVector(ShiftVT, DAG, dl),
4077                                      N->getOperand(1));
4078   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4079                              Intrinsic::arm_neon_vshifts :
4080                              Intrinsic::arm_neon_vshiftu);
4081   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4082                      DAG.getConstant(vshiftInt, MVT::i32),
4083                      N->getOperand(0), NegatedCount);
4084 }
4085
4086 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4087                                 const ARMSubtarget *ST) {
4088   EVT VT = N->getValueType(0);
4089   SDLoc dl(N);
4090
4091   // We can get here for a node like i32 = ISD::SHL i32, i64
4092   if (VT != MVT::i64)
4093     return SDValue();
4094
4095   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4096          "Unknown shift to lower!");
4097
4098   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4099   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4100       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4101     return SDValue();
4102
4103   // If we are in thumb mode, we don't have RRX.
4104   if (ST->isThumb1Only()) return SDValue();
4105
4106   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4107   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4108                            DAG.getConstant(0, MVT::i32));
4109   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4110                            DAG.getConstant(1, MVT::i32));
4111
4112   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4113   // captures the result into a carry flag.
4114   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4115   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4116
4117   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4118   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4119
4120   // Merge the pieces into a single i64 value.
4121  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4122 }
4123
4124 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4125   SDValue TmpOp0, TmpOp1;
4126   bool Invert = false;
4127   bool Swap = false;
4128   unsigned Opc = 0;
4129
4130   SDValue Op0 = Op.getOperand(0);
4131   SDValue Op1 = Op.getOperand(1);
4132   SDValue CC = Op.getOperand(2);
4133   EVT VT = Op.getValueType();
4134   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4135   SDLoc dl(Op);
4136
4137   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4138     switch (SetCCOpcode) {
4139     default: llvm_unreachable("Illegal FP comparison");
4140     case ISD::SETUNE:
4141     case ISD::SETNE:  Invert = true; // Fallthrough
4142     case ISD::SETOEQ:
4143     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4144     case ISD::SETOLT:
4145     case ISD::SETLT: Swap = true; // Fallthrough
4146     case ISD::SETOGT:
4147     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4148     case ISD::SETOLE:
4149     case ISD::SETLE:  Swap = true; // Fallthrough
4150     case ISD::SETOGE:
4151     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4152     case ISD::SETUGE: Swap = true; // Fallthrough
4153     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4154     case ISD::SETUGT: Swap = true; // Fallthrough
4155     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4156     case ISD::SETUEQ: Invert = true; // Fallthrough
4157     case ISD::SETONE:
4158       // Expand this to (OLT | OGT).
4159       TmpOp0 = Op0;
4160       TmpOp1 = Op1;
4161       Opc = ISD::OR;
4162       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4163       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4164       break;
4165     case ISD::SETUO: Invert = true; // Fallthrough
4166     case ISD::SETO:
4167       // Expand this to (OLT | OGE).
4168       TmpOp0 = Op0;
4169       TmpOp1 = Op1;
4170       Opc = ISD::OR;
4171       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4172       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4173       break;
4174     }
4175   } else {
4176     // Integer comparisons.
4177     switch (SetCCOpcode) {
4178     default: llvm_unreachable("Illegal integer comparison");
4179     case ISD::SETNE:  Invert = true;
4180     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4181     case ISD::SETLT:  Swap = true;
4182     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4183     case ISD::SETLE:  Swap = true;
4184     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4185     case ISD::SETULT: Swap = true;
4186     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4187     case ISD::SETULE: Swap = true;
4188     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4189     }
4190
4191     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4192     if (Opc == ARMISD::VCEQ) {
4193
4194       SDValue AndOp;
4195       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4196         AndOp = Op0;
4197       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4198         AndOp = Op1;
4199
4200       // Ignore bitconvert.
4201       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4202         AndOp = AndOp.getOperand(0);
4203
4204       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4205         Opc = ARMISD::VTST;
4206         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4207         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4208         Invert = !Invert;
4209       }
4210     }
4211   }
4212
4213   if (Swap)
4214     std::swap(Op0, Op1);
4215
4216   // If one of the operands is a constant vector zero, attempt to fold the
4217   // comparison to a specialized compare-against-zero form.
4218   SDValue SingleOp;
4219   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4220     SingleOp = Op0;
4221   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4222     if (Opc == ARMISD::VCGE)
4223       Opc = ARMISD::VCLEZ;
4224     else if (Opc == ARMISD::VCGT)
4225       Opc = ARMISD::VCLTZ;
4226     SingleOp = Op1;
4227   }
4228
4229   SDValue Result;
4230   if (SingleOp.getNode()) {
4231     switch (Opc) {
4232     case ARMISD::VCEQ:
4233       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4234     case ARMISD::VCGE:
4235       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4236     case ARMISD::VCLEZ:
4237       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4238     case ARMISD::VCGT:
4239       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4240     case ARMISD::VCLTZ:
4241       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4242     default:
4243       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4244     }
4245   } else {
4246      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4247   }
4248
4249   if (Invert)
4250     Result = DAG.getNOT(dl, Result, VT);
4251
4252   return Result;
4253 }
4254
4255 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4256 /// valid vector constant for a NEON instruction with a "modified immediate"
4257 /// operand (e.g., VMOV).  If so, return the encoded value.
4258 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4259                                  unsigned SplatBitSize, SelectionDAG &DAG,
4260                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4261   unsigned OpCmode, Imm;
4262
4263   // SplatBitSize is set to the smallest size that splats the vector, so a
4264   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4265   // immediate instructions others than VMOV do not support the 8-bit encoding
4266   // of a zero vector, and the default encoding of zero is supposed to be the
4267   // 32-bit version.
4268   if (SplatBits == 0)
4269     SplatBitSize = 32;
4270
4271   switch (SplatBitSize) {
4272   case 8:
4273     if (type != VMOVModImm)
4274       return SDValue();
4275     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4276     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4277     OpCmode = 0xe;
4278     Imm = SplatBits;
4279     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4280     break;
4281
4282   case 16:
4283     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4284     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4285     if ((SplatBits & ~0xff) == 0) {
4286       // Value = 0x00nn: Op=x, Cmode=100x.
4287       OpCmode = 0x8;
4288       Imm = SplatBits;
4289       break;
4290     }
4291     if ((SplatBits & ~0xff00) == 0) {
4292       // Value = 0xnn00: Op=x, Cmode=101x.
4293       OpCmode = 0xa;
4294       Imm = SplatBits >> 8;
4295       break;
4296     }
4297     return SDValue();
4298
4299   case 32:
4300     // NEON's 32-bit VMOV supports splat values where:
4301     // * only one byte is nonzero, or
4302     // * the least significant byte is 0xff and the second byte is nonzero, or
4303     // * the least significant 2 bytes are 0xff and the third is nonzero.
4304     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4305     if ((SplatBits & ~0xff) == 0) {
4306       // Value = 0x000000nn: Op=x, Cmode=000x.
4307       OpCmode = 0;
4308       Imm = SplatBits;
4309       break;
4310     }
4311     if ((SplatBits & ~0xff00) == 0) {
4312       // Value = 0x0000nn00: Op=x, Cmode=001x.
4313       OpCmode = 0x2;
4314       Imm = SplatBits >> 8;
4315       break;
4316     }
4317     if ((SplatBits & ~0xff0000) == 0) {
4318       // Value = 0x00nn0000: Op=x, Cmode=010x.
4319       OpCmode = 0x4;
4320       Imm = SplatBits >> 16;
4321       break;
4322     }
4323     if ((SplatBits & ~0xff000000) == 0) {
4324       // Value = 0xnn000000: Op=x, Cmode=011x.
4325       OpCmode = 0x6;
4326       Imm = SplatBits >> 24;
4327       break;
4328     }
4329
4330     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4331     if (type == OtherModImm) return SDValue();
4332
4333     if ((SplatBits & ~0xffff) == 0 &&
4334         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4335       // Value = 0x0000nnff: Op=x, Cmode=1100.
4336       OpCmode = 0xc;
4337       Imm = SplatBits >> 8;
4338       SplatBits |= 0xff;
4339       break;
4340     }
4341
4342     if ((SplatBits & ~0xffffff) == 0 &&
4343         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4344       // Value = 0x00nnffff: Op=x, Cmode=1101.
4345       OpCmode = 0xd;
4346       Imm = SplatBits >> 16;
4347       SplatBits |= 0xffff;
4348       break;
4349     }
4350
4351     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4352     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4353     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4354     // and fall through here to test for a valid 64-bit splat.  But, then the
4355     // caller would also need to check and handle the change in size.
4356     return SDValue();
4357
4358   case 64: {
4359     if (type != VMOVModImm)
4360       return SDValue();
4361     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4362     uint64_t BitMask = 0xff;
4363     uint64_t Val = 0;
4364     unsigned ImmMask = 1;
4365     Imm = 0;
4366     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4367       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4368         Val |= BitMask;
4369         Imm |= ImmMask;
4370       } else if ((SplatBits & BitMask) != 0) {
4371         return SDValue();
4372       }
4373       BitMask <<= 8;
4374       ImmMask <<= 1;
4375     }
4376     // Op=1, Cmode=1110.
4377     OpCmode = 0x1e;
4378     SplatBits = Val;
4379     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4380     break;
4381   }
4382
4383   default:
4384     llvm_unreachable("unexpected size for isNEONModifiedImm");
4385   }
4386
4387   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4388   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4389 }
4390
4391 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4392                                            const ARMSubtarget *ST) const {
4393   if (!ST->hasVFP3())
4394     return SDValue();
4395
4396   bool IsDouble = Op.getValueType() == MVT::f64;
4397   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4398
4399   // Try splatting with a VMOV.f32...
4400   APFloat FPVal = CFP->getValueAPF();
4401   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4402
4403   if (ImmVal != -1) {
4404     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4405       // We have code in place to select a valid ConstantFP already, no need to
4406       // do any mangling.
4407       return Op;
4408     }
4409
4410     // It's a float and we are trying to use NEON operations where
4411     // possible. Lower it to a splat followed by an extract.
4412     SDLoc DL(Op);
4413     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4414     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4415                                       NewVal);
4416     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4417                        DAG.getConstant(0, MVT::i32));
4418   }
4419
4420   // The rest of our options are NEON only, make sure that's allowed before
4421   // proceeding..
4422   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4423     return SDValue();
4424
4425   EVT VMovVT;
4426   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4427
4428   // It wouldn't really be worth bothering for doubles except for one very
4429   // important value, which does happen to match: 0.0. So make sure we don't do
4430   // anything stupid.
4431   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4432     return SDValue();
4433
4434   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4435   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4436                                      false, VMOVModImm);
4437   if (NewVal != SDValue()) {
4438     SDLoc DL(Op);
4439     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4440                                       NewVal);
4441     if (IsDouble)
4442       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4443
4444     // It's a float: cast and extract a vector element.
4445     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4446                                        VecConstant);
4447     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4448                        DAG.getConstant(0, MVT::i32));
4449   }
4450
4451   // Finally, try a VMVN.i32
4452   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4453                              false, VMVNModImm);
4454   if (NewVal != SDValue()) {
4455     SDLoc DL(Op);
4456     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4457
4458     if (IsDouble)
4459       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4460
4461     // It's a float: cast and extract a vector element.
4462     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4463                                        VecConstant);
4464     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4465                        DAG.getConstant(0, MVT::i32));
4466   }
4467
4468   return SDValue();
4469 }
4470
4471 // check if an VEXT instruction can handle the shuffle mask when the
4472 // vector sources of the shuffle are the same.
4473 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4474   unsigned NumElts = VT.getVectorNumElements();
4475
4476   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4477   if (M[0] < 0)
4478     return false;
4479
4480   Imm = M[0];
4481
4482   // If this is a VEXT shuffle, the immediate value is the index of the first
4483   // element.  The other shuffle indices must be the successive elements after
4484   // the first one.
4485   unsigned ExpectedElt = Imm;
4486   for (unsigned i = 1; i < NumElts; ++i) {
4487     // Increment the expected index.  If it wraps around, just follow it
4488     // back to index zero and keep going.
4489     ++ExpectedElt;
4490     if (ExpectedElt == NumElts)
4491       ExpectedElt = 0;
4492
4493     if (M[i] < 0) continue; // ignore UNDEF indices
4494     if (ExpectedElt != static_cast<unsigned>(M[i]))
4495       return false;
4496   }
4497
4498   return true;
4499 }
4500
4501
4502 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4503                        bool &ReverseVEXT, unsigned &Imm) {
4504   unsigned NumElts = VT.getVectorNumElements();
4505   ReverseVEXT = false;
4506
4507   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4508   if (M[0] < 0)
4509     return false;
4510
4511   Imm = M[0];
4512
4513   // If this is a VEXT shuffle, the immediate value is the index of the first
4514   // element.  The other shuffle indices must be the successive elements after
4515   // the first one.
4516   unsigned ExpectedElt = Imm;
4517   for (unsigned i = 1; i < NumElts; ++i) {
4518     // Increment the expected index.  If it wraps around, it may still be
4519     // a VEXT but the source vectors must be swapped.
4520     ExpectedElt += 1;
4521     if (ExpectedElt == NumElts * 2) {
4522       ExpectedElt = 0;
4523       ReverseVEXT = true;
4524     }
4525
4526     if (M[i] < 0) continue; // ignore UNDEF indices
4527     if (ExpectedElt != static_cast<unsigned>(M[i]))
4528       return false;
4529   }
4530
4531   // Adjust the index value if the source operands will be swapped.
4532   if (ReverseVEXT)
4533     Imm -= NumElts;
4534
4535   return true;
4536 }
4537
4538 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4539 /// instruction with the specified blocksize.  (The order of the elements
4540 /// within each block of the vector is reversed.)
4541 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4542   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4543          "Only possible block sizes for VREV are: 16, 32, 64");
4544
4545   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4546   if (EltSz == 64)
4547     return false;
4548
4549   unsigned NumElts = VT.getVectorNumElements();
4550   unsigned BlockElts = M[0] + 1;
4551   // If the first shuffle index is UNDEF, be optimistic.
4552   if (M[0] < 0)
4553     BlockElts = BlockSize / EltSz;
4554
4555   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4556     return false;
4557
4558   for (unsigned i = 0; i < NumElts; ++i) {
4559     if (M[i] < 0) continue; // ignore UNDEF indices
4560     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4561       return false;
4562   }
4563
4564   return true;
4565 }
4566
4567 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4568   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4569   // range, then 0 is placed into the resulting vector. So pretty much any mask
4570   // of 8 elements can work here.
4571   return VT == MVT::v8i8 && M.size() == 8;
4572 }
4573
4574 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4575   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4576   if (EltSz == 64)
4577     return false;
4578
4579   unsigned NumElts = VT.getVectorNumElements();
4580   WhichResult = (M[0] == 0 ? 0 : 1);
4581   for (unsigned i = 0; i < NumElts; i += 2) {
4582     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4583         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4584       return false;
4585   }
4586   return true;
4587 }
4588
4589 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4590 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4591 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4592 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4593   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4594   if (EltSz == 64)
4595     return false;
4596
4597   unsigned NumElts = VT.getVectorNumElements();
4598   WhichResult = (M[0] == 0 ? 0 : 1);
4599   for (unsigned i = 0; i < NumElts; i += 2) {
4600     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4601         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4602       return false;
4603   }
4604   return true;
4605 }
4606
4607 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4608   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4609   if (EltSz == 64)
4610     return false;
4611
4612   unsigned NumElts = VT.getVectorNumElements();
4613   WhichResult = (M[0] == 0 ? 0 : 1);
4614   for (unsigned i = 0; i != NumElts; ++i) {
4615     if (M[i] < 0) continue; // ignore UNDEF indices
4616     if ((unsigned) M[i] != 2 * i + WhichResult)
4617       return false;
4618   }
4619
4620   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4621   if (VT.is64BitVector() && EltSz == 32)
4622     return false;
4623
4624   return true;
4625 }
4626
4627 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4628 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4629 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4630 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4631   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4632   if (EltSz == 64)
4633     return false;
4634
4635   unsigned Half = VT.getVectorNumElements() / 2;
4636   WhichResult = (M[0] == 0 ? 0 : 1);
4637   for (unsigned j = 0; j != 2; ++j) {
4638     unsigned Idx = WhichResult;
4639     for (unsigned i = 0; i != Half; ++i) {
4640       int MIdx = M[i + j * Half];
4641       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4642         return false;
4643       Idx += 2;
4644     }
4645   }
4646
4647   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4648   if (VT.is64BitVector() && EltSz == 32)
4649     return false;
4650
4651   return true;
4652 }
4653
4654 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4655   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4656   if (EltSz == 64)
4657     return false;
4658
4659   unsigned NumElts = VT.getVectorNumElements();
4660   WhichResult = (M[0] == 0 ? 0 : 1);
4661   unsigned Idx = WhichResult * NumElts / 2;
4662   for (unsigned i = 0; i != NumElts; i += 2) {
4663     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4664         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4665       return false;
4666     Idx += 1;
4667   }
4668
4669   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4670   if (VT.is64BitVector() && EltSz == 32)
4671     return false;
4672
4673   return true;
4674 }
4675
4676 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4677 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4678 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4679 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4680   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4681   if (EltSz == 64)
4682     return false;
4683
4684   unsigned NumElts = VT.getVectorNumElements();
4685   WhichResult = (M[0] == 0 ? 0 : 1);
4686   unsigned Idx = WhichResult * NumElts / 2;
4687   for (unsigned i = 0; i != NumElts; i += 2) {
4688     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4689         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4690       return false;
4691     Idx += 1;
4692   }
4693
4694   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4695   if (VT.is64BitVector() && EltSz == 32)
4696     return false;
4697
4698   return true;
4699 }
4700
4701 /// \return true if this is a reverse operation on an vector.
4702 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4703   unsigned NumElts = VT.getVectorNumElements();
4704   // Make sure the mask has the right size.
4705   if (NumElts != M.size())
4706       return false;
4707
4708   // Look for <15, ..., 3, -1, 1, 0>.
4709   for (unsigned i = 0; i != NumElts; ++i)
4710     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4711       return false;
4712
4713   return true;
4714 }
4715
4716 // If N is an integer constant that can be moved into a register in one
4717 // instruction, return an SDValue of such a constant (will become a MOV
4718 // instruction).  Otherwise return null.
4719 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4720                                      const ARMSubtarget *ST, SDLoc dl) {
4721   uint64_t Val;
4722   if (!isa<ConstantSDNode>(N))
4723     return SDValue();
4724   Val = cast<ConstantSDNode>(N)->getZExtValue();
4725
4726   if (ST->isThumb1Only()) {
4727     if (Val <= 255 || ~Val <= 255)
4728       return DAG.getConstant(Val, MVT::i32);
4729   } else {
4730     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4731       return DAG.getConstant(Val, MVT::i32);
4732   }
4733   return SDValue();
4734 }
4735
4736 // If this is a case we can't handle, return null and let the default
4737 // expansion code take care of it.
4738 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4739                                              const ARMSubtarget *ST) const {
4740   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4741   SDLoc dl(Op);
4742   EVT VT = Op.getValueType();
4743
4744   APInt SplatBits, SplatUndef;
4745   unsigned SplatBitSize;
4746   bool HasAnyUndefs;
4747   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4748     if (SplatBitSize <= 64) {
4749       // Check if an immediate VMOV works.
4750       EVT VmovVT;
4751       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4752                                       SplatUndef.getZExtValue(), SplatBitSize,
4753                                       DAG, VmovVT, VT.is128BitVector(),
4754                                       VMOVModImm);
4755       if (Val.getNode()) {
4756         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4757         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4758       }
4759
4760       // Try an immediate VMVN.
4761       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4762       Val = isNEONModifiedImm(NegatedImm,
4763                                       SplatUndef.getZExtValue(), SplatBitSize,
4764                                       DAG, VmovVT, VT.is128BitVector(),
4765                                       VMVNModImm);
4766       if (Val.getNode()) {
4767         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4768         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4769       }
4770
4771       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4772       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4773         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4774         if (ImmVal != -1) {
4775           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4776           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4777         }
4778       }
4779     }
4780   }
4781
4782   // Scan through the operands to see if only one value is used.
4783   //
4784   // As an optimisation, even if more than one value is used it may be more
4785   // profitable to splat with one value then change some lanes.
4786   //
4787   // Heuristically we decide to do this if the vector has a "dominant" value,
4788   // defined as splatted to more than half of the lanes.
4789   unsigned NumElts = VT.getVectorNumElements();
4790   bool isOnlyLowElement = true;
4791   bool usesOnlyOneValue = true;
4792   bool hasDominantValue = false;
4793   bool isConstant = true;
4794
4795   // Map of the number of times a particular SDValue appears in the
4796   // element list.
4797   DenseMap<SDValue, unsigned> ValueCounts;
4798   SDValue Value;
4799   for (unsigned i = 0; i < NumElts; ++i) {
4800     SDValue V = Op.getOperand(i);
4801     if (V.getOpcode() == ISD::UNDEF)
4802       continue;
4803     if (i > 0)
4804       isOnlyLowElement = false;
4805     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4806       isConstant = false;
4807
4808     ValueCounts.insert(std::make_pair(V, 0));
4809     unsigned &Count = ValueCounts[V];
4810
4811     // Is this value dominant? (takes up more than half of the lanes)
4812     if (++Count > (NumElts / 2)) {
4813       hasDominantValue = true;
4814       Value = V;
4815     }
4816   }
4817   if (ValueCounts.size() != 1)
4818     usesOnlyOneValue = false;
4819   if (!Value.getNode() && ValueCounts.size() > 0)
4820     Value = ValueCounts.begin()->first;
4821
4822   if (ValueCounts.size() == 0)
4823     return DAG.getUNDEF(VT);
4824
4825   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4826   // Keep going if we are hitting this case.
4827   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4828     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4829
4830   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4831
4832   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4833   // i32 and try again.
4834   if (hasDominantValue && EltSize <= 32) {
4835     if (!isConstant) {
4836       SDValue N;
4837
4838       // If we are VDUPing a value that comes directly from a vector, that will
4839       // cause an unnecessary move to and from a GPR, where instead we could
4840       // just use VDUPLANE. We can only do this if the lane being extracted
4841       // is at a constant index, as the VDUP from lane instructions only have
4842       // constant-index forms.
4843       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4844           isa<ConstantSDNode>(Value->getOperand(1))) {
4845         // We need to create a new undef vector to use for the VDUPLANE if the
4846         // size of the vector from which we get the value is different than the
4847         // size of the vector that we need to create. We will insert the element
4848         // such that the register coalescer will remove unnecessary copies.
4849         if (VT != Value->getOperand(0).getValueType()) {
4850           ConstantSDNode *constIndex;
4851           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4852           assert(constIndex && "The index is not a constant!");
4853           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4854                              VT.getVectorNumElements();
4855           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4856                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4857                         Value, DAG.getConstant(index, MVT::i32)),
4858                            DAG.getConstant(index, MVT::i32));
4859         } else
4860           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4861                         Value->getOperand(0), Value->getOperand(1));
4862       } else
4863         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4864
4865       if (!usesOnlyOneValue) {
4866         // The dominant value was splatted as 'N', but we now have to insert
4867         // all differing elements.
4868         for (unsigned I = 0; I < NumElts; ++I) {
4869           if (Op.getOperand(I) == Value)
4870             continue;
4871           SmallVector<SDValue, 3> Ops;
4872           Ops.push_back(N);
4873           Ops.push_back(Op.getOperand(I));
4874           Ops.push_back(DAG.getConstant(I, MVT::i32));
4875           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4876         }
4877       }
4878       return N;
4879     }
4880     if (VT.getVectorElementType().isFloatingPoint()) {
4881       SmallVector<SDValue, 8> Ops;
4882       for (unsigned i = 0; i < NumElts; ++i)
4883         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4884                                   Op.getOperand(i)));
4885       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4886       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4887       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4888       if (Val.getNode())
4889         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4890     }
4891     if (usesOnlyOneValue) {
4892       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4893       if (isConstant && Val.getNode())
4894         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4895     }
4896   }
4897
4898   // If all elements are constants and the case above didn't get hit, fall back
4899   // to the default expansion, which will generate a load from the constant
4900   // pool.
4901   if (isConstant)
4902     return SDValue();
4903
4904   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4905   if (NumElts >= 4) {
4906     SDValue shuffle = ReconstructShuffle(Op, DAG);
4907     if (shuffle != SDValue())
4908       return shuffle;
4909   }
4910
4911   // Vectors with 32- or 64-bit elements can be built by directly assigning
4912   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4913   // will be legalized.
4914   if (EltSize >= 32) {
4915     // Do the expansion with floating-point types, since that is what the VFP
4916     // registers are defined to use, and since i64 is not legal.
4917     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4918     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4919     SmallVector<SDValue, 8> Ops;
4920     for (unsigned i = 0; i < NumElts; ++i)
4921       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4922     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4923     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4924   }
4925
4926   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4927   // know the default expansion would otherwise fall back on something even
4928   // worse. For a vector with one or two non-undef values, that's
4929   // scalar_to_vector for the elements followed by a shuffle (provided the
4930   // shuffle is valid for the target) and materialization element by element
4931   // on the stack followed by a load for everything else.
4932   if (!isConstant && !usesOnlyOneValue) {
4933     SDValue Vec = DAG.getUNDEF(VT);
4934     for (unsigned i = 0 ; i < NumElts; ++i) {
4935       SDValue V = Op.getOperand(i);
4936       if (V.getOpcode() == ISD::UNDEF)
4937         continue;
4938       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4939       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4940     }
4941     return Vec;
4942   }
4943
4944   return SDValue();
4945 }
4946
4947 // Gather data to see if the operation can be modelled as a
4948 // shuffle in combination with VEXTs.
4949 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4950                                               SelectionDAG &DAG) const {
4951   SDLoc dl(Op);
4952   EVT VT = Op.getValueType();
4953   unsigned NumElts = VT.getVectorNumElements();
4954
4955   SmallVector<SDValue, 2> SourceVecs;
4956   SmallVector<unsigned, 2> MinElts;
4957   SmallVector<unsigned, 2> MaxElts;
4958
4959   for (unsigned i = 0; i < NumElts; ++i) {
4960     SDValue V = Op.getOperand(i);
4961     if (V.getOpcode() == ISD::UNDEF)
4962       continue;
4963     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4964       // A shuffle can only come from building a vector from various
4965       // elements of other vectors.
4966       return SDValue();
4967     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4968                VT.getVectorElementType()) {
4969       // This code doesn't know how to handle shuffles where the vector
4970       // element types do not match (this happens because type legalization
4971       // promotes the return type of EXTRACT_VECTOR_ELT).
4972       // FIXME: It might be appropriate to extend this code to handle
4973       // mismatched types.
4974       return SDValue();
4975     }
4976
4977     // Record this extraction against the appropriate vector if possible...
4978     SDValue SourceVec = V.getOperand(0);
4979     // If the element number isn't a constant, we can't effectively
4980     // analyze what's going on.
4981     if (!isa<ConstantSDNode>(V.getOperand(1)))
4982       return SDValue();
4983     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4984     bool FoundSource = false;
4985     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4986       if (SourceVecs[j] == SourceVec) {
4987         if (MinElts[j] > EltNo)
4988           MinElts[j] = EltNo;
4989         if (MaxElts[j] < EltNo)
4990           MaxElts[j] = EltNo;
4991         FoundSource = true;
4992         break;
4993       }
4994     }
4995
4996     // Or record a new source if not...
4997     if (!FoundSource) {
4998       SourceVecs.push_back(SourceVec);
4999       MinElts.push_back(EltNo);
5000       MaxElts.push_back(EltNo);
5001     }
5002   }
5003
5004   // Currently only do something sane when at most two source vectors
5005   // involved.
5006   if (SourceVecs.size() > 2)
5007     return SDValue();
5008
5009   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5010   int VEXTOffsets[2] = {0, 0};
5011
5012   // This loop extracts the usage patterns of the source vectors
5013   // and prepares appropriate SDValues for a shuffle if possible.
5014   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5015     if (SourceVecs[i].getValueType() == VT) {
5016       // No VEXT necessary
5017       ShuffleSrcs[i] = SourceVecs[i];
5018       VEXTOffsets[i] = 0;
5019       continue;
5020     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5021       // It probably isn't worth padding out a smaller vector just to
5022       // break it down again in a shuffle.
5023       return SDValue();
5024     }
5025
5026     // Since only 64-bit and 128-bit vectors are legal on ARM and
5027     // we've eliminated the other cases...
5028     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5029            "unexpected vector sizes in ReconstructShuffle");
5030
5031     if (MaxElts[i] - MinElts[i] >= NumElts) {
5032       // Span too large for a VEXT to cope
5033       return SDValue();
5034     }
5035
5036     if (MinElts[i] >= NumElts) {
5037       // The extraction can just take the second half
5038       VEXTOffsets[i] = NumElts;
5039       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5040                                    SourceVecs[i],
5041                                    DAG.getIntPtrConstant(NumElts));
5042     } else if (MaxElts[i] < NumElts) {
5043       // The extraction can just take the first half
5044       VEXTOffsets[i] = 0;
5045       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5046                                    SourceVecs[i],
5047                                    DAG.getIntPtrConstant(0));
5048     } else {
5049       // An actual VEXT is needed
5050       VEXTOffsets[i] = MinElts[i];
5051       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5052                                      SourceVecs[i],
5053                                      DAG.getIntPtrConstant(0));
5054       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5055                                      SourceVecs[i],
5056                                      DAG.getIntPtrConstant(NumElts));
5057       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5058                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5059     }
5060   }
5061
5062   SmallVector<int, 8> Mask;
5063
5064   for (unsigned i = 0; i < NumElts; ++i) {
5065     SDValue Entry = Op.getOperand(i);
5066     if (Entry.getOpcode() == ISD::UNDEF) {
5067       Mask.push_back(-1);
5068       continue;
5069     }
5070
5071     SDValue ExtractVec = Entry.getOperand(0);
5072     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5073                                           .getOperand(1))->getSExtValue();
5074     if (ExtractVec == SourceVecs[0]) {
5075       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5076     } else {
5077       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5078     }
5079   }
5080
5081   // Final check before we try to produce nonsense...
5082   if (isShuffleMaskLegal(Mask, VT))
5083     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5084                                 &Mask[0]);
5085
5086   return SDValue();
5087 }
5088
5089 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5090 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5091 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5092 /// are assumed to be legal.
5093 bool
5094 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5095                                       EVT VT) const {
5096   if (VT.getVectorNumElements() == 4 &&
5097       (VT.is128BitVector() || VT.is64BitVector())) {
5098     unsigned PFIndexes[4];
5099     for (unsigned i = 0; i != 4; ++i) {
5100       if (M[i] < 0)
5101         PFIndexes[i] = 8;
5102       else
5103         PFIndexes[i] = M[i];
5104     }
5105
5106     // Compute the index in the perfect shuffle table.
5107     unsigned PFTableIndex =
5108       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5109     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5110     unsigned Cost = (PFEntry >> 30);
5111
5112     if (Cost <= 4)
5113       return true;
5114   }
5115
5116   bool ReverseVEXT;
5117   unsigned Imm, WhichResult;
5118
5119   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5120   return (EltSize >= 32 ||
5121           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5122           isVREVMask(M, VT, 64) ||
5123           isVREVMask(M, VT, 32) ||
5124           isVREVMask(M, VT, 16) ||
5125           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5126           isVTBLMask(M, VT) ||
5127           isVTRNMask(M, VT, WhichResult) ||
5128           isVUZPMask(M, VT, WhichResult) ||
5129           isVZIPMask(M, VT, WhichResult) ||
5130           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5131           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5132           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5133           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5134 }
5135
5136 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5137 /// the specified operations to build the shuffle.
5138 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5139                                       SDValue RHS, SelectionDAG &DAG,
5140                                       SDLoc dl) {
5141   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5142   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5143   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5144
5145   enum {
5146     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5147     OP_VREV,
5148     OP_VDUP0,
5149     OP_VDUP1,
5150     OP_VDUP2,
5151     OP_VDUP3,
5152     OP_VEXT1,
5153     OP_VEXT2,
5154     OP_VEXT3,
5155     OP_VUZPL, // VUZP, left result
5156     OP_VUZPR, // VUZP, right result
5157     OP_VZIPL, // VZIP, left result
5158     OP_VZIPR, // VZIP, right result
5159     OP_VTRNL, // VTRN, left result
5160     OP_VTRNR  // VTRN, right result
5161   };
5162
5163   if (OpNum == OP_COPY) {
5164     if (LHSID == (1*9+2)*9+3) return LHS;
5165     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5166     return RHS;
5167   }
5168
5169   SDValue OpLHS, OpRHS;
5170   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5171   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5172   EVT VT = OpLHS.getValueType();
5173
5174   switch (OpNum) {
5175   default: llvm_unreachable("Unknown shuffle opcode!");
5176   case OP_VREV:
5177     // VREV divides the vector in half and swaps within the half.
5178     if (VT.getVectorElementType() == MVT::i32 ||
5179         VT.getVectorElementType() == MVT::f32)
5180       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5181     // vrev <4 x i16> -> VREV32
5182     if (VT.getVectorElementType() == MVT::i16)
5183       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5184     // vrev <4 x i8> -> VREV16
5185     assert(VT.getVectorElementType() == MVT::i8);
5186     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5187   case OP_VDUP0:
5188   case OP_VDUP1:
5189   case OP_VDUP2:
5190   case OP_VDUP3:
5191     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5192                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5193   case OP_VEXT1:
5194   case OP_VEXT2:
5195   case OP_VEXT3:
5196     return DAG.getNode(ARMISD::VEXT, dl, VT,
5197                        OpLHS, OpRHS,
5198                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5199   case OP_VUZPL:
5200   case OP_VUZPR:
5201     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5202                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5203   case OP_VZIPL:
5204   case OP_VZIPR:
5205     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5206                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5207   case OP_VTRNL:
5208   case OP_VTRNR:
5209     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5210                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5211   }
5212 }
5213
5214 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5215                                        ArrayRef<int> ShuffleMask,
5216                                        SelectionDAG &DAG) {
5217   // Check to see if we can use the VTBL instruction.
5218   SDValue V1 = Op.getOperand(0);
5219   SDValue V2 = Op.getOperand(1);
5220   SDLoc DL(Op);
5221
5222   SmallVector<SDValue, 8> VTBLMask;
5223   for (ArrayRef<int>::iterator
5224          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5225     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5226
5227   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5228     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5229                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5230                                    &VTBLMask[0], 8));
5231
5232   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5233                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5234                                  &VTBLMask[0], 8));
5235 }
5236
5237 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5238                                                       SelectionDAG &DAG) {
5239   SDLoc DL(Op);
5240   SDValue OpLHS = Op.getOperand(0);
5241   EVT VT = OpLHS.getValueType();
5242
5243   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5244          "Expect an v8i16/v16i8 type");
5245   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5246   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5247   // extract the first 8 bytes into the top double word and the last 8 bytes
5248   // into the bottom double word. The v8i16 case is similar.
5249   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5250   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5251                      DAG.getConstant(ExtractNum, MVT::i32));
5252 }
5253
5254 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5255   SDValue V1 = Op.getOperand(0);
5256   SDValue V2 = Op.getOperand(1);
5257   SDLoc dl(Op);
5258   EVT VT = Op.getValueType();
5259   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5260
5261   // Convert shuffles that are directly supported on NEON to target-specific
5262   // DAG nodes, instead of keeping them as shuffles and matching them again
5263   // during code selection.  This is more efficient and avoids the possibility
5264   // of inconsistencies between legalization and selection.
5265   // FIXME: floating-point vectors should be canonicalized to integer vectors
5266   // of the same time so that they get CSEd properly.
5267   ArrayRef<int> ShuffleMask = SVN->getMask();
5268
5269   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5270   if (EltSize <= 32) {
5271     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5272       int Lane = SVN->getSplatIndex();
5273       // If this is undef splat, generate it via "just" vdup, if possible.
5274       if (Lane == -1) Lane = 0;
5275
5276       // Test if V1 is a SCALAR_TO_VECTOR.
5277       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5278         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5279       }
5280       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5281       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5282       // reaches it).
5283       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5284           !isa<ConstantSDNode>(V1.getOperand(0))) {
5285         bool IsScalarToVector = true;
5286         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5287           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5288             IsScalarToVector = false;
5289             break;
5290           }
5291         if (IsScalarToVector)
5292           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5293       }
5294       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5295                          DAG.getConstant(Lane, MVT::i32));
5296     }
5297
5298     bool ReverseVEXT;
5299     unsigned Imm;
5300     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5301       if (ReverseVEXT)
5302         std::swap(V1, V2);
5303       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5304                          DAG.getConstant(Imm, MVT::i32));
5305     }
5306
5307     if (isVREVMask(ShuffleMask, VT, 64))
5308       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5309     if (isVREVMask(ShuffleMask, VT, 32))
5310       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5311     if (isVREVMask(ShuffleMask, VT, 16))
5312       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5313
5314     if (V2->getOpcode() == ISD::UNDEF &&
5315         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5316       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5317                          DAG.getConstant(Imm, MVT::i32));
5318     }
5319
5320     // Check for Neon shuffles that modify both input vectors in place.
5321     // If both results are used, i.e., if there are two shuffles with the same
5322     // source operands and with masks corresponding to both results of one of
5323     // these operations, DAG memoization will ensure that a single node is
5324     // used for both shuffles.
5325     unsigned WhichResult;
5326     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5327       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5328                          V1, V2).getValue(WhichResult);
5329     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5330       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5331                          V1, V2).getValue(WhichResult);
5332     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5333       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5334                          V1, V2).getValue(WhichResult);
5335
5336     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5337       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5338                          V1, V1).getValue(WhichResult);
5339     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5340       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5341                          V1, V1).getValue(WhichResult);
5342     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5343       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5344                          V1, V1).getValue(WhichResult);
5345   }
5346
5347   // If the shuffle is not directly supported and it has 4 elements, use
5348   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5349   unsigned NumElts = VT.getVectorNumElements();
5350   if (NumElts == 4) {
5351     unsigned PFIndexes[4];
5352     for (unsigned i = 0; i != 4; ++i) {
5353       if (ShuffleMask[i] < 0)
5354         PFIndexes[i] = 8;
5355       else
5356         PFIndexes[i] = ShuffleMask[i];
5357     }
5358
5359     // Compute the index in the perfect shuffle table.
5360     unsigned PFTableIndex =
5361       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5362     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5363     unsigned Cost = (PFEntry >> 30);
5364
5365     if (Cost <= 4)
5366       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5367   }
5368
5369   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5370   if (EltSize >= 32) {
5371     // Do the expansion with floating-point types, since that is what the VFP
5372     // registers are defined to use, and since i64 is not legal.
5373     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5374     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5375     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5376     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5377     SmallVector<SDValue, 8> Ops;
5378     for (unsigned i = 0; i < NumElts; ++i) {
5379       if (ShuffleMask[i] < 0)
5380         Ops.push_back(DAG.getUNDEF(EltVT));
5381       else
5382         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5383                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5384                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5385                                                   MVT::i32)));
5386     }
5387     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5388     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5389   }
5390
5391   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5392     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5393
5394   if (VT == MVT::v8i8) {
5395     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5396     if (NewOp.getNode())
5397       return NewOp;
5398   }
5399
5400   return SDValue();
5401 }
5402
5403 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5404   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5405   SDValue Lane = Op.getOperand(2);
5406   if (!isa<ConstantSDNode>(Lane))
5407     return SDValue();
5408
5409   return Op;
5410 }
5411
5412 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5413   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5414   SDValue Lane = Op.getOperand(1);
5415   if (!isa<ConstantSDNode>(Lane))
5416     return SDValue();
5417
5418   SDValue Vec = Op.getOperand(0);
5419   if (Op.getValueType() == MVT::i32 &&
5420       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5421     SDLoc dl(Op);
5422     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5423   }
5424
5425   return Op;
5426 }
5427
5428 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5429   // The only time a CONCAT_VECTORS operation can have legal types is when
5430   // two 64-bit vectors are concatenated to a 128-bit vector.
5431   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5432          "unexpected CONCAT_VECTORS");
5433   SDLoc dl(Op);
5434   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5435   SDValue Op0 = Op.getOperand(0);
5436   SDValue Op1 = Op.getOperand(1);
5437   if (Op0.getOpcode() != ISD::UNDEF)
5438     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5439                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5440                       DAG.getIntPtrConstant(0));
5441   if (Op1.getOpcode() != ISD::UNDEF)
5442     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5443                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5444                       DAG.getIntPtrConstant(1));
5445   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5446 }
5447
5448 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5449 /// element has been zero/sign-extended, depending on the isSigned parameter,
5450 /// from an integer type half its size.
5451 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5452                                    bool isSigned) {
5453   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5454   EVT VT = N->getValueType(0);
5455   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5456     SDNode *BVN = N->getOperand(0).getNode();
5457     if (BVN->getValueType(0) != MVT::v4i32 ||
5458         BVN->getOpcode() != ISD::BUILD_VECTOR)
5459       return false;
5460     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5461     unsigned HiElt = 1 - LoElt;
5462     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5463     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5464     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5465     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5466     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5467       return false;
5468     if (isSigned) {
5469       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5470           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5471         return true;
5472     } else {
5473       if (Hi0->isNullValue() && Hi1->isNullValue())
5474         return true;
5475     }
5476     return false;
5477   }
5478
5479   if (N->getOpcode() != ISD::BUILD_VECTOR)
5480     return false;
5481
5482   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5483     SDNode *Elt = N->getOperand(i).getNode();
5484     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5485       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5486       unsigned HalfSize = EltSize / 2;
5487       if (isSigned) {
5488         if (!isIntN(HalfSize, C->getSExtValue()))
5489           return false;
5490       } else {
5491         if (!isUIntN(HalfSize, C->getZExtValue()))
5492           return false;
5493       }
5494       continue;
5495     }
5496     return false;
5497   }
5498
5499   return true;
5500 }
5501
5502 /// isSignExtended - Check if a node is a vector value that is sign-extended
5503 /// or a constant BUILD_VECTOR with sign-extended elements.
5504 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5505   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5506     return true;
5507   if (isExtendedBUILD_VECTOR(N, DAG, true))
5508     return true;
5509   return false;
5510 }
5511
5512 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5513 /// or a constant BUILD_VECTOR with zero-extended elements.
5514 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5515   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5516     return true;
5517   if (isExtendedBUILD_VECTOR(N, DAG, false))
5518     return true;
5519   return false;
5520 }
5521
5522 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5523   if (OrigVT.getSizeInBits() >= 64)
5524     return OrigVT;
5525
5526   assert(OrigVT.isSimple() && "Expecting a simple value type");
5527
5528   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5529   switch (OrigSimpleTy) {
5530   default: llvm_unreachable("Unexpected Vector Type");
5531   case MVT::v2i8:
5532   case MVT::v2i16:
5533      return MVT::v2i32;
5534   case MVT::v4i8:
5535     return  MVT::v4i16;
5536   }
5537 }
5538
5539 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5540 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5541 /// We insert the required extension here to get the vector to fill a D register.
5542 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5543                                             const EVT &OrigTy,
5544                                             const EVT &ExtTy,
5545                                             unsigned ExtOpcode) {
5546   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5547   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5548   // 64-bits we need to insert a new extension so that it will be 64-bits.
5549   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5550   if (OrigTy.getSizeInBits() >= 64)
5551     return N;
5552
5553   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5554   EVT NewVT = getExtensionTo64Bits(OrigTy);
5555
5556   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5557 }
5558
5559 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5560 /// does not do any sign/zero extension. If the original vector is less
5561 /// than 64 bits, an appropriate extension will be added after the load to
5562 /// reach a total size of 64 bits. We have to add the extension separately
5563 /// because ARM does not have a sign/zero extending load for vectors.
5564 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5565   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5566
5567   // The load already has the right type.
5568   if (ExtendedTy == LD->getMemoryVT())
5569     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5570                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5571                 LD->isNonTemporal(), LD->isInvariant(),
5572                 LD->getAlignment());
5573
5574   // We need to create a zextload/sextload. We cannot just create a load
5575   // followed by a zext/zext node because LowerMUL is also run during normal
5576   // operation legalization where we can't create illegal types.
5577   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5578                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5579                         LD->getMemoryVT(), LD->isVolatile(),
5580                         LD->isNonTemporal(), LD->getAlignment());
5581 }
5582
5583 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5584 /// extending load, or BUILD_VECTOR with extended elements, return the
5585 /// unextended value. The unextended vector should be 64 bits so that it can
5586 /// be used as an operand to a VMULL instruction. If the original vector size
5587 /// before extension is less than 64 bits we add a an extension to resize
5588 /// the vector to 64 bits.
5589 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5590   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5591     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5592                                         N->getOperand(0)->getValueType(0),
5593                                         N->getValueType(0),
5594                                         N->getOpcode());
5595
5596   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5597     return SkipLoadExtensionForVMULL(LD, DAG);
5598
5599   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5600   // have been legalized as a BITCAST from v4i32.
5601   if (N->getOpcode() == ISD::BITCAST) {
5602     SDNode *BVN = N->getOperand(0).getNode();
5603     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5604            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5605     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5606     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5607                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5608   }
5609   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5610   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5611   EVT VT = N->getValueType(0);
5612   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5613   unsigned NumElts = VT.getVectorNumElements();
5614   MVT TruncVT = MVT::getIntegerVT(EltSize);
5615   SmallVector<SDValue, 8> Ops;
5616   for (unsigned i = 0; i != NumElts; ++i) {
5617     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5618     const APInt &CInt = C->getAPIntValue();
5619     // Element types smaller than 32 bits are not legal, so use i32 elements.
5620     // The values are implicitly truncated so sext vs. zext doesn't matter.
5621     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5622   }
5623   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5624                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5625 }
5626
5627 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5628   unsigned Opcode = N->getOpcode();
5629   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5630     SDNode *N0 = N->getOperand(0).getNode();
5631     SDNode *N1 = N->getOperand(1).getNode();
5632     return N0->hasOneUse() && N1->hasOneUse() &&
5633       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5634   }
5635   return false;
5636 }
5637
5638 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5639   unsigned Opcode = N->getOpcode();
5640   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5641     SDNode *N0 = N->getOperand(0).getNode();
5642     SDNode *N1 = N->getOperand(1).getNode();
5643     return N0->hasOneUse() && N1->hasOneUse() &&
5644       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5645   }
5646   return false;
5647 }
5648
5649 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5650   // Multiplications are only custom-lowered for 128-bit vectors so that
5651   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5652   EVT VT = Op.getValueType();
5653   assert(VT.is128BitVector() && VT.isInteger() &&
5654          "unexpected type for custom-lowering ISD::MUL");
5655   SDNode *N0 = Op.getOperand(0).getNode();
5656   SDNode *N1 = Op.getOperand(1).getNode();
5657   unsigned NewOpc = 0;
5658   bool isMLA = false;
5659   bool isN0SExt = isSignExtended(N0, DAG);
5660   bool isN1SExt = isSignExtended(N1, DAG);
5661   if (isN0SExt && isN1SExt)
5662     NewOpc = ARMISD::VMULLs;
5663   else {
5664     bool isN0ZExt = isZeroExtended(N0, DAG);
5665     bool isN1ZExt = isZeroExtended(N1, DAG);
5666     if (isN0ZExt && isN1ZExt)
5667       NewOpc = ARMISD::VMULLu;
5668     else if (isN1SExt || isN1ZExt) {
5669       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5670       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5671       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5672         NewOpc = ARMISD::VMULLs;
5673         isMLA = true;
5674       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5675         NewOpc = ARMISD::VMULLu;
5676         isMLA = true;
5677       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5678         std::swap(N0, N1);
5679         NewOpc = ARMISD::VMULLu;
5680         isMLA = true;
5681       }
5682     }
5683
5684     if (!NewOpc) {
5685       if (VT == MVT::v2i64)
5686         // Fall through to expand this.  It is not legal.
5687         return SDValue();
5688       else
5689         // Other vector multiplications are legal.
5690         return Op;
5691     }
5692   }
5693
5694   // Legalize to a VMULL instruction.
5695   SDLoc DL(Op);
5696   SDValue Op0;
5697   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5698   if (!isMLA) {
5699     Op0 = SkipExtensionForVMULL(N0, DAG);
5700     assert(Op0.getValueType().is64BitVector() &&
5701            Op1.getValueType().is64BitVector() &&
5702            "unexpected types for extended operands to VMULL");
5703     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5704   }
5705
5706   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5707   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5708   //   vmull q0, d4, d6
5709   //   vmlal q0, d5, d6
5710   // is faster than
5711   //   vaddl q0, d4, d5
5712   //   vmovl q1, d6
5713   //   vmul  q0, q0, q1
5714   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5715   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5716   EVT Op1VT = Op1.getValueType();
5717   return DAG.getNode(N0->getOpcode(), DL, VT,
5718                      DAG.getNode(NewOpc, DL, VT,
5719                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5720                      DAG.getNode(NewOpc, DL, VT,
5721                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5722 }
5723
5724 static SDValue
5725 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5726   // Convert to float
5727   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5728   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5729   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5730   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5731   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5732   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5733   // Get reciprocal estimate.
5734   // float4 recip = vrecpeq_f32(yf);
5735   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5736                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5737   // Because char has a smaller range than uchar, we can actually get away
5738   // without any newton steps.  This requires that we use a weird bias
5739   // of 0xb000, however (again, this has been exhaustively tested).
5740   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5741   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5742   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5743   Y = DAG.getConstant(0xb000, MVT::i32);
5744   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5745   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5746   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5747   // Convert back to short.
5748   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5749   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5750   return X;
5751 }
5752
5753 static SDValue
5754 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5755   SDValue N2;
5756   // Convert to float.
5757   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5758   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5759   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5760   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5761   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5762   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5763
5764   // Use reciprocal estimate and one refinement step.
5765   // float4 recip = vrecpeq_f32(yf);
5766   // recip *= vrecpsq_f32(yf, recip);
5767   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5768                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5769   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5770                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5771                    N1, N2);
5772   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5773   // Because short has a smaller range than ushort, we can actually get away
5774   // with only a single newton step.  This requires that we use a weird bias
5775   // of 89, however (again, this has been exhaustively tested).
5776   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5777   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5778   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5779   N1 = DAG.getConstant(0x89, MVT::i32);
5780   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5781   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5782   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5783   // Convert back to integer and return.
5784   // return vmovn_s32(vcvt_s32_f32(result));
5785   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5786   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5787   return N0;
5788 }
5789
5790 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5791   EVT VT = Op.getValueType();
5792   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5793          "unexpected type for custom-lowering ISD::SDIV");
5794
5795   SDLoc dl(Op);
5796   SDValue N0 = Op.getOperand(0);
5797   SDValue N1 = Op.getOperand(1);
5798   SDValue N2, N3;
5799
5800   if (VT == MVT::v8i8) {
5801     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5802     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5803
5804     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5805                      DAG.getIntPtrConstant(4));
5806     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5807                      DAG.getIntPtrConstant(4));
5808     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5809                      DAG.getIntPtrConstant(0));
5810     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5811                      DAG.getIntPtrConstant(0));
5812
5813     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5814     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5815
5816     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5817     N0 = LowerCONCAT_VECTORS(N0, DAG);
5818
5819     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5820     return N0;
5821   }
5822   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5823 }
5824
5825 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5826   EVT VT = Op.getValueType();
5827   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5828          "unexpected type for custom-lowering ISD::UDIV");
5829
5830   SDLoc dl(Op);
5831   SDValue N0 = Op.getOperand(0);
5832   SDValue N1 = Op.getOperand(1);
5833   SDValue N2, N3;
5834
5835   if (VT == MVT::v8i8) {
5836     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5837     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5838
5839     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5840                      DAG.getIntPtrConstant(4));
5841     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5842                      DAG.getIntPtrConstant(4));
5843     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5844                      DAG.getIntPtrConstant(0));
5845     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5846                      DAG.getIntPtrConstant(0));
5847
5848     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5849     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5850
5851     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5852     N0 = LowerCONCAT_VECTORS(N0, DAG);
5853
5854     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5855                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5856                      N0);
5857     return N0;
5858   }
5859
5860   // v4i16 sdiv ... Convert to float.
5861   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5862   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5863   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5864   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5865   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5866   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5867
5868   // Use reciprocal estimate and two refinement steps.
5869   // float4 recip = vrecpeq_f32(yf);
5870   // recip *= vrecpsq_f32(yf, recip);
5871   // recip *= vrecpsq_f32(yf, recip);
5872   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5873                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
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   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5879                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5880                    BN1, N2);
5881   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5882   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5883   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5884   // and that it will never cause us to return an answer too large).
5885   // float4 result = as_float4(as_int4(xf*recip) + 2);
5886   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5887   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5888   N1 = DAG.getConstant(2, MVT::i32);
5889   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5890   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5891   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5892   // Convert back to integer and return.
5893   // return vmovn_u32(vcvt_s32_f32(result));
5894   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5895   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5896   return N0;
5897 }
5898
5899 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5900   EVT VT = Op.getNode()->getValueType(0);
5901   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5902
5903   unsigned Opc;
5904   bool ExtraOp = false;
5905   switch (Op.getOpcode()) {
5906   default: llvm_unreachable("Invalid code");
5907   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5908   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5909   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5910   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5911   }
5912
5913   if (!ExtraOp)
5914     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5915                        Op.getOperand(1));
5916   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5917                      Op.getOperand(1), Op.getOperand(2));
5918 }
5919
5920 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5921   assert(Subtarget->isTargetDarwin());
5922
5923   // For iOS, we want to call an alternative entry point: __sincos_stret,
5924   // return values are passed via sret.
5925   SDLoc dl(Op);
5926   SDValue Arg = Op.getOperand(0);
5927   EVT ArgVT = Arg.getValueType();
5928   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5929
5930   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5931   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5932
5933   // Pair of floats / doubles used to pass the result.
5934   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5935
5936   // Create stack object for sret.
5937   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5938   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5939   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5940   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5941
5942   ArgListTy Args;
5943   ArgListEntry Entry;
5944
5945   Entry.Node = SRet;
5946   Entry.Ty = RetTy->getPointerTo();
5947   Entry.isSExt = false;
5948   Entry.isZExt = false;
5949   Entry.isSRet = true;
5950   Args.push_back(Entry);
5951
5952   Entry.Node = Arg;
5953   Entry.Ty = ArgTy;
5954   Entry.isSExt = false;
5955   Entry.isZExt = false;
5956   Args.push_back(Entry);
5957
5958   const char *LibcallName  = (ArgVT == MVT::f64)
5959   ? "__sincos_stret" : "__sincosf_stret";
5960   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5961
5962   TargetLowering::
5963   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5964                        false, false, false, false, 0,
5965                        CallingConv::C, /*isTaillCall=*/false,
5966                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5967                        Callee, Args, DAG, dl);
5968   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5969
5970   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5971                                 MachinePointerInfo(), false, false, false, 0);
5972
5973   // Address of cos field.
5974   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5975                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5976   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5977                                 MachinePointerInfo(), false, false, false, 0);
5978
5979   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5980   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5981                      LoadSin.getValue(0), LoadCos.getValue(0));
5982 }
5983
5984 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5985   // Monotonic load/store is legal for all targets
5986   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5987     return Op;
5988
5989   // Acquire/Release load/store is not legal for targets without a
5990   // dmb or equivalent available.
5991   return SDValue();
5992 }
5993
5994 static void
5995 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5996                     SelectionDAG &DAG) {
5997   SDLoc dl(Node);
5998   assert (Node->getValueType(0) == MVT::i64 &&
5999           "Only know how to expand i64 atomics");
6000   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6001
6002   SmallVector<SDValue, 6> Ops;
6003   Ops.push_back(Node->getOperand(0)); // Chain
6004   Ops.push_back(Node->getOperand(1)); // Ptr
6005   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6006     // Low part
6007     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6008                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6009     // High part
6010     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6011                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6012   }
6013   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6014   SDValue Result =
6015     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6016                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6017                   AN->getSynchScope());
6018   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6019   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6020   Results.push_back(Result.getValue(2));
6021 }
6022
6023 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6024                                     SmallVectorImpl<SDValue> &Results,
6025                                     SelectionDAG &DAG,
6026                                     const ARMSubtarget *Subtarget) {
6027   SDLoc DL(N);
6028   SDValue Cycles32, OutChain;
6029
6030   if (Subtarget->hasPerfMon()) {
6031     // Under Power Management extensions, the cycle-count is:
6032     //    mrc p15, #0, <Rt>, c9, c13, #0
6033     SDValue Ops[] = { N->getOperand(0), // Chain
6034                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6035                       DAG.getConstant(15, MVT::i32),
6036                       DAG.getConstant(0, MVT::i32),
6037                       DAG.getConstant(9, MVT::i32),
6038                       DAG.getConstant(13, MVT::i32),
6039                       DAG.getConstant(0, MVT::i32)
6040     };
6041
6042     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6043                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6044                            array_lengthof(Ops));
6045     OutChain = Cycles32.getValue(1);
6046   } else {
6047     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6048     // there are older ARM CPUs that have implementation-specific ways of
6049     // obtaining this information (FIXME!).
6050     Cycles32 = DAG.getConstant(0, MVT::i32);
6051     OutChain = DAG.getEntryNode();
6052   }
6053
6054
6055   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6056                                  Cycles32, DAG.getConstant(0, MVT::i32));
6057   Results.push_back(Cycles64);
6058   Results.push_back(OutChain);
6059 }
6060
6061 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6062   switch (Op.getOpcode()) {
6063   default: llvm_unreachable("Don't know how to custom lower this!");
6064   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6065   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6066   case ISD::GlobalAddress:
6067     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6068       LowerGlobalAddressELF(Op, DAG);
6069   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6070   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6071   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6072   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6073   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6074   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6075   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6076   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6077   case ISD::SINT_TO_FP:
6078   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6079   case ISD::FP_TO_SINT:
6080   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6081   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6082   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6083   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6084   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6085   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6086   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6087   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6088                                                                Subtarget);
6089   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6090   case ISD::SHL:
6091   case ISD::SRL:
6092   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6093   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6094   case ISD::SRL_PARTS:
6095   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6096   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6097   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6098   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6099   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6100   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6101   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6102   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6103   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6104   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6105   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6106   case ISD::MUL:           return LowerMUL(Op, DAG);
6107   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6108   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6109   case ISD::ADDC:
6110   case ISD::ADDE:
6111   case ISD::SUBC:
6112   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6113   case ISD::ATOMIC_LOAD:
6114   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6115   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6116   case ISD::SDIVREM:
6117   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6118   }
6119 }
6120
6121 /// ReplaceNodeResults - Replace the results of node with an illegal result
6122 /// type with new values built out of custom code.
6123 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6124                                            SmallVectorImpl<SDValue>&Results,
6125                                            SelectionDAG &DAG) const {
6126   SDValue Res;
6127   switch (N->getOpcode()) {
6128   default:
6129     llvm_unreachable("Don't know how to custom expand this!");
6130   case ISD::BITCAST:
6131     Res = ExpandBITCAST(N, DAG);
6132     break;
6133   case ISD::SRL:
6134   case ISD::SRA:
6135     Res = Expand64BitShift(N, DAG, Subtarget);
6136     break;
6137   case ISD::READCYCLECOUNTER:
6138     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6139     return;
6140   case ISD::ATOMIC_STORE:
6141   case ISD::ATOMIC_LOAD:
6142   case ISD::ATOMIC_LOAD_ADD:
6143   case ISD::ATOMIC_LOAD_AND:
6144   case ISD::ATOMIC_LOAD_NAND:
6145   case ISD::ATOMIC_LOAD_OR:
6146   case ISD::ATOMIC_LOAD_SUB:
6147   case ISD::ATOMIC_LOAD_XOR:
6148   case ISD::ATOMIC_SWAP:
6149   case ISD::ATOMIC_CMP_SWAP:
6150   case ISD::ATOMIC_LOAD_MIN:
6151   case ISD::ATOMIC_LOAD_UMIN:
6152   case ISD::ATOMIC_LOAD_MAX:
6153   case ISD::ATOMIC_LOAD_UMAX:
6154     ReplaceATOMIC_OP_64(N, Results, DAG);
6155     return;
6156   }
6157   if (Res.getNode())
6158     Results.push_back(Res);
6159 }
6160
6161 //===----------------------------------------------------------------------===//
6162 //                           ARM Scheduler Hooks
6163 //===----------------------------------------------------------------------===//
6164
6165 MachineBasicBlock *
6166 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6167                                      MachineBasicBlock *BB,
6168                                      unsigned Size) const {
6169   unsigned dest    = MI->getOperand(0).getReg();
6170   unsigned ptr     = MI->getOperand(1).getReg();
6171   unsigned oldval  = MI->getOperand(2).getReg();
6172   unsigned newval  = MI->getOperand(3).getReg();
6173   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6174   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6175   DebugLoc dl = MI->getDebugLoc();
6176   bool isThumb2 = Subtarget->isThumb2();
6177
6178   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6179   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6180     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6181     (const TargetRegisterClass*)&ARM::GPRRegClass);
6182
6183   if (isThumb2) {
6184     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6185     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6186     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6187   }
6188
6189   unsigned ldrOpc, strOpc;
6190   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6191
6192   MachineFunction *MF = BB->getParent();
6193   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6194   MachineFunction::iterator It = BB;
6195   ++It; // insert the new blocks after the current block
6196
6197   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6198   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6199   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6200   MF->insert(It, loop1MBB);
6201   MF->insert(It, loop2MBB);
6202   MF->insert(It, exitMBB);
6203
6204   // Transfer the remainder of BB and its successor edges to exitMBB.
6205   exitMBB->splice(exitMBB->begin(), BB,
6206                   llvm::next(MachineBasicBlock::iterator(MI)),
6207                   BB->end());
6208   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6209
6210   //  thisMBB:
6211   //   ...
6212   //   fallthrough --> loop1MBB
6213   BB->addSuccessor(loop1MBB);
6214
6215   // loop1MBB:
6216   //   ldrex dest, [ptr]
6217   //   cmp dest, oldval
6218   //   bne exitMBB
6219   BB = loop1MBB;
6220   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6221   if (ldrOpc == ARM::t2LDREX)
6222     MIB.addImm(0);
6223   AddDefaultPred(MIB);
6224   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6225                  .addReg(dest).addReg(oldval));
6226   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6227     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6228   BB->addSuccessor(loop2MBB);
6229   BB->addSuccessor(exitMBB);
6230
6231   // loop2MBB:
6232   //   strex scratch, newval, [ptr]
6233   //   cmp scratch, #0
6234   //   bne loop1MBB
6235   BB = loop2MBB;
6236   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6237   if (strOpc == ARM::t2STREX)
6238     MIB.addImm(0);
6239   AddDefaultPred(MIB);
6240   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6241                  .addReg(scratch).addImm(0));
6242   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6243     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6244   BB->addSuccessor(loop1MBB);
6245   BB->addSuccessor(exitMBB);
6246
6247   //  exitMBB:
6248   //   ...
6249   BB = exitMBB;
6250
6251   MI->eraseFromParent();   // The instruction is gone now.
6252
6253   return BB;
6254 }
6255
6256 MachineBasicBlock *
6257 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6258                                     unsigned Size, unsigned BinOpcode) const {
6259   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6260   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6261
6262   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6263   MachineFunction *MF = BB->getParent();
6264   MachineFunction::iterator It = BB;
6265   ++It;
6266
6267   unsigned dest = MI->getOperand(0).getReg();
6268   unsigned ptr = MI->getOperand(1).getReg();
6269   unsigned incr = MI->getOperand(2).getReg();
6270   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6271   DebugLoc dl = MI->getDebugLoc();
6272   bool isThumb2 = Subtarget->isThumb2();
6273
6274   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6275   if (isThumb2) {
6276     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6277     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6278     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6279   }
6280
6281   unsigned ldrOpc, strOpc;
6282   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6283
6284   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6285   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6286   MF->insert(It, loopMBB);
6287   MF->insert(It, exitMBB);
6288
6289   // Transfer the remainder of BB and its successor edges to exitMBB.
6290   exitMBB->splice(exitMBB->begin(), BB,
6291                   llvm::next(MachineBasicBlock::iterator(MI)),
6292                   BB->end());
6293   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6294
6295   const TargetRegisterClass *TRC = isThumb2 ?
6296     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6297     (const TargetRegisterClass*)&ARM::GPRRegClass;
6298   unsigned scratch = MRI.createVirtualRegister(TRC);
6299   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6300
6301   //  thisMBB:
6302   //   ...
6303   //   fallthrough --> loopMBB
6304   BB->addSuccessor(loopMBB);
6305
6306   //  loopMBB:
6307   //   ldrex dest, ptr
6308   //   <binop> scratch2, dest, incr
6309   //   strex scratch, scratch2, ptr
6310   //   cmp scratch, #0
6311   //   bne- loopMBB
6312   //   fallthrough --> exitMBB
6313   BB = loopMBB;
6314   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6315   if (ldrOpc == ARM::t2LDREX)
6316     MIB.addImm(0);
6317   AddDefaultPred(MIB);
6318   if (BinOpcode) {
6319     // operand order needs to go the other way for NAND
6320     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6321       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6322                      addReg(incr).addReg(dest)).addReg(0);
6323     else
6324       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6325                      addReg(dest).addReg(incr)).addReg(0);
6326   }
6327
6328   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6329   if (strOpc == ARM::t2STREX)
6330     MIB.addImm(0);
6331   AddDefaultPred(MIB);
6332   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6333                  .addReg(scratch).addImm(0));
6334   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6335     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6336
6337   BB->addSuccessor(loopMBB);
6338   BB->addSuccessor(exitMBB);
6339
6340   //  exitMBB:
6341   //   ...
6342   BB = exitMBB;
6343
6344   MI->eraseFromParent();   // The instruction is gone now.
6345
6346   return BB;
6347 }
6348
6349 MachineBasicBlock *
6350 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6351                                           MachineBasicBlock *BB,
6352                                           unsigned Size,
6353                                           bool signExtend,
6354                                           ARMCC::CondCodes Cond) const {
6355   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6356
6357   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6358   MachineFunction *MF = BB->getParent();
6359   MachineFunction::iterator It = BB;
6360   ++It;
6361
6362   unsigned dest = MI->getOperand(0).getReg();
6363   unsigned ptr = MI->getOperand(1).getReg();
6364   unsigned incr = MI->getOperand(2).getReg();
6365   unsigned oldval = dest;
6366   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6367   DebugLoc dl = MI->getDebugLoc();
6368   bool isThumb2 = Subtarget->isThumb2();
6369
6370   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6371   if (isThumb2) {
6372     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6373     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6374     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6375   }
6376
6377   unsigned ldrOpc, strOpc, extendOpc;
6378   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6379   switch (Size) {
6380   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6381   case 1:
6382     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6383     break;
6384   case 2:
6385     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6386     break;
6387   case 4:
6388     extendOpc = 0;
6389     break;
6390   }
6391
6392   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6393   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6394   MF->insert(It, loopMBB);
6395   MF->insert(It, exitMBB);
6396
6397   // Transfer the remainder of BB and its successor edges to exitMBB.
6398   exitMBB->splice(exitMBB->begin(), BB,
6399                   llvm::next(MachineBasicBlock::iterator(MI)),
6400                   BB->end());
6401   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6402
6403   const TargetRegisterClass *TRC = isThumb2 ?
6404     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6405     (const TargetRegisterClass*)&ARM::GPRRegClass;
6406   unsigned scratch = MRI.createVirtualRegister(TRC);
6407   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6408
6409   //  thisMBB:
6410   //   ...
6411   //   fallthrough --> loopMBB
6412   BB->addSuccessor(loopMBB);
6413
6414   //  loopMBB:
6415   //   ldrex dest, ptr
6416   //   (sign extend dest, if required)
6417   //   cmp dest, incr
6418   //   cmov.cond scratch2, incr, dest
6419   //   strex scratch, scratch2, ptr
6420   //   cmp scratch, #0
6421   //   bne- loopMBB
6422   //   fallthrough --> exitMBB
6423   BB = loopMBB;
6424   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6425   if (ldrOpc == ARM::t2LDREX)
6426     MIB.addImm(0);
6427   AddDefaultPred(MIB);
6428
6429   // Sign extend the value, if necessary.
6430   if (signExtend && extendOpc) {
6431     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6432                                                 : &ARM::GPRnopcRegClass);
6433     if (!isThumb2)
6434       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6435     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6436                      .addReg(dest)
6437                      .addImm(0));
6438   }
6439
6440   // Build compare and cmov instructions.
6441   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6442                  .addReg(oldval).addReg(incr));
6443   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6444          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6445
6446   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6447   if (strOpc == ARM::t2STREX)
6448     MIB.addImm(0);
6449   AddDefaultPred(MIB);
6450   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6451                  .addReg(scratch).addImm(0));
6452   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6453     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6454
6455   BB->addSuccessor(loopMBB);
6456   BB->addSuccessor(exitMBB);
6457
6458   //  exitMBB:
6459   //   ...
6460   BB = exitMBB;
6461
6462   MI->eraseFromParent();   // The instruction is gone now.
6463
6464   return BB;
6465 }
6466
6467 MachineBasicBlock *
6468 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6469                                       unsigned Op1, unsigned Op2,
6470                                       bool NeedsCarry, bool IsCmpxchg,
6471                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6472   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6473   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6474
6475   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6476   MachineFunction *MF = BB->getParent();
6477   MachineFunction::iterator It = BB;
6478   ++It;
6479
6480   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6481   unsigned offset = (isStore ? -2 : 0);
6482   unsigned destlo = MI->getOperand(0).getReg();
6483   unsigned desthi = MI->getOperand(1).getReg();
6484   unsigned ptr = MI->getOperand(offset+2).getReg();
6485   unsigned vallo = MI->getOperand(offset+3).getReg();
6486   unsigned valhi = MI->getOperand(offset+4).getReg();
6487   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6488   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6489   DebugLoc dl = MI->getDebugLoc();
6490   bool isThumb2 = Subtarget->isThumb2();
6491
6492   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6493   if (isThumb2) {
6494     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6495     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6496     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6497     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6498     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6499   }
6500
6501   unsigned ldrOpc, strOpc;
6502   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6503
6504   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6505   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6506   if (IsCmpxchg || IsMinMax)
6507     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6508   if (IsCmpxchg)
6509     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6510   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6511
6512   MF->insert(It, loopMBB);
6513   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6514   if (IsCmpxchg) MF->insert(It, cont2BB);
6515   MF->insert(It, exitMBB);
6516
6517   // Transfer the remainder of BB and its successor edges to exitMBB.
6518   exitMBB->splice(exitMBB->begin(), BB,
6519                   llvm::next(MachineBasicBlock::iterator(MI)),
6520                   BB->end());
6521   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6522
6523   const TargetRegisterClass *TRC = isThumb2 ?
6524     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6525     (const TargetRegisterClass*)&ARM::GPRRegClass;
6526   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6527
6528   //  thisMBB:
6529   //   ...
6530   //   fallthrough --> loopMBB
6531   BB->addSuccessor(loopMBB);
6532
6533   //  loopMBB:
6534   //   ldrexd r2, r3, ptr
6535   //   <binopa> r0, r2, incr
6536   //   <binopb> r1, r3, incr
6537   //   strexd storesuccess, r0, r1, ptr
6538   //   cmp storesuccess, #0
6539   //   bne- loopMBB
6540   //   fallthrough --> exitMBB
6541   BB = loopMBB;
6542
6543   if (!isStore) {
6544     // Load
6545     if (isThumb2) {
6546       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6547                      .addReg(destlo, RegState::Define)
6548                      .addReg(desthi, RegState::Define)
6549                      .addReg(ptr));
6550     } else {
6551       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6552       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6553                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6554       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6555       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6556         .addReg(GPRPair0, 0, ARM::gsub_0);
6557       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6558         .addReg(GPRPair0, 0, ARM::gsub_1);
6559     }
6560   }
6561
6562   unsigned StoreLo, StoreHi;
6563   if (IsCmpxchg) {
6564     // Add early exit
6565     for (unsigned i = 0; i < 2; i++) {
6566       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6567                                                          ARM::CMPrr))
6568                      .addReg(i == 0 ? destlo : desthi)
6569                      .addReg(i == 0 ? vallo : valhi));
6570       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6571         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6572       BB->addSuccessor(exitMBB);
6573       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6574       BB = (i == 0 ? contBB : cont2BB);
6575     }
6576
6577     // Copy to physregs for strexd
6578     StoreLo = MI->getOperand(5).getReg();
6579     StoreHi = MI->getOperand(6).getReg();
6580   } else if (Op1) {
6581     // Perform binary operation
6582     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6583     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6584                    .addReg(destlo).addReg(vallo))
6585         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6586     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6587     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6588                    .addReg(desthi).addReg(valhi))
6589         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6590
6591     StoreLo = tmpRegLo;
6592     StoreHi = tmpRegHi;
6593   } else {
6594     // Copy to physregs for strexd
6595     StoreLo = vallo;
6596     StoreHi = valhi;
6597   }
6598   if (IsMinMax) {
6599     // Compare and branch to exit block.
6600     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6601       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6602     BB->addSuccessor(exitMBB);
6603     BB->addSuccessor(contBB);
6604     BB = contBB;
6605     StoreLo = vallo;
6606     StoreHi = valhi;
6607   }
6608
6609   // Store
6610   if (isThumb2) {
6611     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6612     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6613     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6614                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6615   } else {
6616     // Marshal a pair...
6617     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6618     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6619     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6620     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6621     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6622       .addReg(UndefPair)
6623       .addReg(StoreLo)
6624       .addImm(ARM::gsub_0);
6625     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6626       .addReg(r1)
6627       .addReg(StoreHi)
6628       .addImm(ARM::gsub_1);
6629
6630     // ...and store it
6631     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6632                    .addReg(StorePair).addReg(ptr));
6633   }
6634   // Cmp+jump
6635   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6636                  .addReg(storesuccess).addImm(0));
6637   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6638     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6639
6640   BB->addSuccessor(loopMBB);
6641   BB->addSuccessor(exitMBB);
6642
6643   //  exitMBB:
6644   //   ...
6645   BB = exitMBB;
6646
6647   MI->eraseFromParent();   // The instruction is gone now.
6648
6649   return BB;
6650 }
6651
6652 MachineBasicBlock *
6653 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6654
6655   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6656
6657   unsigned destlo = MI->getOperand(0).getReg();
6658   unsigned desthi = MI->getOperand(1).getReg();
6659   unsigned ptr = MI->getOperand(2).getReg();
6660   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6661   DebugLoc dl = MI->getDebugLoc();
6662   bool isThumb2 = Subtarget->isThumb2();
6663
6664   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6665   if (isThumb2) {
6666     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6667     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6668     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6669   }
6670   unsigned ldrOpc, strOpc;
6671   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6672
6673   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6674
6675   if (isThumb2) {
6676     MIB.addReg(destlo, RegState::Define)
6677        .addReg(desthi, RegState::Define)
6678        .addReg(ptr);
6679
6680   } else {
6681     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6682     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6683
6684     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6685     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6686       .addReg(GPRPair0, 0, ARM::gsub_0);
6687     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6688       .addReg(GPRPair0, 0, ARM::gsub_1);
6689   }
6690   AddDefaultPred(MIB);
6691
6692   MI->eraseFromParent();   // The instruction is gone now.
6693
6694   return BB;
6695 }
6696
6697 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6698 /// registers the function context.
6699 void ARMTargetLowering::
6700 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6701                        MachineBasicBlock *DispatchBB, int FI) const {
6702   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6703   DebugLoc dl = MI->getDebugLoc();
6704   MachineFunction *MF = MBB->getParent();
6705   MachineRegisterInfo *MRI = &MF->getRegInfo();
6706   MachineConstantPool *MCP = MF->getConstantPool();
6707   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6708   const Function *F = MF->getFunction();
6709
6710   bool isThumb = Subtarget->isThumb();
6711   bool isThumb2 = Subtarget->isThumb2();
6712
6713   unsigned PCLabelId = AFI->createPICLabelUId();
6714   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6715   ARMConstantPoolValue *CPV =
6716     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6717   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6718
6719   const TargetRegisterClass *TRC = isThumb ?
6720     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6721     (const TargetRegisterClass*)&ARM::GPRRegClass;
6722
6723   // Grab constant pool and fixed stack memory operands.
6724   MachineMemOperand *CPMMO =
6725     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6726                              MachineMemOperand::MOLoad, 4, 4);
6727
6728   MachineMemOperand *FIMMOSt =
6729     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6730                              MachineMemOperand::MOStore, 4, 4);
6731
6732   // Load the address of the dispatch MBB into the jump buffer.
6733   if (isThumb2) {
6734     // Incoming value: jbuf
6735     //   ldr.n  r5, LCPI1_1
6736     //   orr    r5, r5, #1
6737     //   add    r5, pc
6738     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6739     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6740     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6741                    .addConstantPoolIndex(CPI)
6742                    .addMemOperand(CPMMO));
6743     // Set the low bit because of thumb mode.
6744     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6745     AddDefaultCC(
6746       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6747                      .addReg(NewVReg1, RegState::Kill)
6748                      .addImm(0x01)));
6749     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6750     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6751       .addReg(NewVReg2, RegState::Kill)
6752       .addImm(PCLabelId);
6753     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6754                    .addReg(NewVReg3, RegState::Kill)
6755                    .addFrameIndex(FI)
6756                    .addImm(36)  // &jbuf[1] :: pc
6757                    .addMemOperand(FIMMOSt));
6758   } else if (isThumb) {
6759     // Incoming value: jbuf
6760     //   ldr.n  r1, LCPI1_4
6761     //   add    r1, pc
6762     //   mov    r2, #1
6763     //   orrs   r1, r2
6764     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6765     //   str    r1, [r2]
6766     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6767     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6768                    .addConstantPoolIndex(CPI)
6769                    .addMemOperand(CPMMO));
6770     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6771     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6772       .addReg(NewVReg1, RegState::Kill)
6773       .addImm(PCLabelId);
6774     // Set the low bit because of thumb mode.
6775     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6776     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6777                    .addReg(ARM::CPSR, RegState::Define)
6778                    .addImm(1));
6779     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6780     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6781                    .addReg(ARM::CPSR, RegState::Define)
6782                    .addReg(NewVReg2, RegState::Kill)
6783                    .addReg(NewVReg3, RegState::Kill));
6784     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6785     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6786                    .addFrameIndex(FI)
6787                    .addImm(36)); // &jbuf[1] :: pc
6788     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6789                    .addReg(NewVReg4, RegState::Kill)
6790                    .addReg(NewVReg5, RegState::Kill)
6791                    .addImm(0)
6792                    .addMemOperand(FIMMOSt));
6793   } else {
6794     // Incoming value: jbuf
6795     //   ldr  r1, LCPI1_1
6796     //   add  r1, pc, r1
6797     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6798     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6799     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6800                    .addConstantPoolIndex(CPI)
6801                    .addImm(0)
6802                    .addMemOperand(CPMMO));
6803     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6804     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6805                    .addReg(NewVReg1, RegState::Kill)
6806                    .addImm(PCLabelId));
6807     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6808                    .addReg(NewVReg2, RegState::Kill)
6809                    .addFrameIndex(FI)
6810                    .addImm(36)  // &jbuf[1] :: pc
6811                    .addMemOperand(FIMMOSt));
6812   }
6813 }
6814
6815 MachineBasicBlock *ARMTargetLowering::
6816 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6817   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6818   DebugLoc dl = MI->getDebugLoc();
6819   MachineFunction *MF = MBB->getParent();
6820   MachineRegisterInfo *MRI = &MF->getRegInfo();
6821   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6822   MachineFrameInfo *MFI = MF->getFrameInfo();
6823   int FI = MFI->getFunctionContextIndex();
6824
6825   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6826     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6827     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6828
6829   // Get a mapping of the call site numbers to all of the landing pads they're
6830   // associated with.
6831   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6832   unsigned MaxCSNum = 0;
6833   MachineModuleInfo &MMI = MF->getMMI();
6834   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6835        ++BB) {
6836     if (!BB->isLandingPad()) continue;
6837
6838     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6839     // pad.
6840     for (MachineBasicBlock::iterator
6841            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6842       if (!II->isEHLabel()) continue;
6843
6844       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6845       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6846
6847       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6848       for (SmallVectorImpl<unsigned>::iterator
6849              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6850            CSI != CSE; ++CSI) {
6851         CallSiteNumToLPad[*CSI].push_back(BB);
6852         MaxCSNum = std::max(MaxCSNum, *CSI);
6853       }
6854       break;
6855     }
6856   }
6857
6858   // Get an ordered list of the machine basic blocks for the jump table.
6859   std::vector<MachineBasicBlock*> LPadList;
6860   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6861   LPadList.reserve(CallSiteNumToLPad.size());
6862   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6863     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6864     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6865            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6866       LPadList.push_back(*II);
6867       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6868     }
6869   }
6870
6871   assert(!LPadList.empty() &&
6872          "No landing pad destinations for the dispatch jump table!");
6873
6874   // Create the jump table and associated information.
6875   MachineJumpTableInfo *JTI =
6876     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6877   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6878   unsigned UId = AFI->createJumpTableUId();
6879   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6880
6881   // Create the MBBs for the dispatch code.
6882
6883   // Shove the dispatch's address into the return slot in the function context.
6884   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6885   DispatchBB->setIsLandingPad();
6886
6887   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6888   unsigned trap_opcode;
6889   if (Subtarget->isThumb())
6890     trap_opcode = ARM::tTRAP;
6891   else
6892     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6893
6894   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6895   DispatchBB->addSuccessor(TrapBB);
6896
6897   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6898   DispatchBB->addSuccessor(DispContBB);
6899
6900   // Insert and MBBs.
6901   MF->insert(MF->end(), DispatchBB);
6902   MF->insert(MF->end(), DispContBB);
6903   MF->insert(MF->end(), TrapBB);
6904
6905   // Insert code into the entry block that creates and registers the function
6906   // context.
6907   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6908
6909   MachineMemOperand *FIMMOLd =
6910     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6911                              MachineMemOperand::MOLoad |
6912                              MachineMemOperand::MOVolatile, 4, 4);
6913
6914   MachineInstrBuilder MIB;
6915   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6916
6917   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6918   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6919
6920   // Add a register mask with no preserved registers.  This results in all
6921   // registers being marked as clobbered.
6922   MIB.addRegMask(RI.getNoPreservedMask());
6923
6924   unsigned NumLPads = LPadList.size();
6925   if (Subtarget->isThumb2()) {
6926     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6927     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6928                    .addFrameIndex(FI)
6929                    .addImm(4)
6930                    .addMemOperand(FIMMOLd));
6931
6932     if (NumLPads < 256) {
6933       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6934                      .addReg(NewVReg1)
6935                      .addImm(LPadList.size()));
6936     } else {
6937       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6938       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6939                      .addImm(NumLPads & 0xFFFF));
6940
6941       unsigned VReg2 = VReg1;
6942       if ((NumLPads & 0xFFFF0000) != 0) {
6943         VReg2 = MRI->createVirtualRegister(TRC);
6944         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6945                        .addReg(VReg1)
6946                        .addImm(NumLPads >> 16));
6947       }
6948
6949       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6950                      .addReg(NewVReg1)
6951                      .addReg(VReg2));
6952     }
6953
6954     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6955       .addMBB(TrapBB)
6956       .addImm(ARMCC::HI)
6957       .addReg(ARM::CPSR);
6958
6959     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6960     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6961                    .addJumpTableIndex(MJTI)
6962                    .addImm(UId));
6963
6964     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6965     AddDefaultCC(
6966       AddDefaultPred(
6967         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6968         .addReg(NewVReg3, RegState::Kill)
6969         .addReg(NewVReg1)
6970         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6971
6972     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6973       .addReg(NewVReg4, RegState::Kill)
6974       .addReg(NewVReg1)
6975       .addJumpTableIndex(MJTI)
6976       .addImm(UId);
6977   } else if (Subtarget->isThumb()) {
6978     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6979     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6980                    .addFrameIndex(FI)
6981                    .addImm(1)
6982                    .addMemOperand(FIMMOLd));
6983
6984     if (NumLPads < 256) {
6985       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6986                      .addReg(NewVReg1)
6987                      .addImm(NumLPads));
6988     } else {
6989       MachineConstantPool *ConstantPool = MF->getConstantPool();
6990       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6991       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6992
6993       // MachineConstantPool wants an explicit alignment.
6994       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6995       if (Align == 0)
6996         Align = getDataLayout()->getTypeAllocSize(C->getType());
6997       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6998
6999       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7000       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7001                      .addReg(VReg1, RegState::Define)
7002                      .addConstantPoolIndex(Idx));
7003       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7004                      .addReg(NewVReg1)
7005                      .addReg(VReg1));
7006     }
7007
7008     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7009       .addMBB(TrapBB)
7010       .addImm(ARMCC::HI)
7011       .addReg(ARM::CPSR);
7012
7013     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7014     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7015                    .addReg(ARM::CPSR, RegState::Define)
7016                    .addReg(NewVReg1)
7017                    .addImm(2));
7018
7019     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7020     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7021                    .addJumpTableIndex(MJTI)
7022                    .addImm(UId));
7023
7024     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7025     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7026                    .addReg(ARM::CPSR, RegState::Define)
7027                    .addReg(NewVReg2, RegState::Kill)
7028                    .addReg(NewVReg3));
7029
7030     MachineMemOperand *JTMMOLd =
7031       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7032                                MachineMemOperand::MOLoad, 4, 4);
7033
7034     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7035     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7036                    .addReg(NewVReg4, RegState::Kill)
7037                    .addImm(0)
7038                    .addMemOperand(JTMMOLd));
7039
7040     unsigned NewVReg6 = NewVReg5;
7041     if (RelocM == Reloc::PIC_) {
7042       NewVReg6 = MRI->createVirtualRegister(TRC);
7043       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7044                      .addReg(ARM::CPSR, RegState::Define)
7045                      .addReg(NewVReg5, RegState::Kill)
7046                      .addReg(NewVReg3));
7047     }
7048
7049     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7050       .addReg(NewVReg6, RegState::Kill)
7051       .addJumpTableIndex(MJTI)
7052       .addImm(UId);
7053   } else {
7054     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7055     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7056                    .addFrameIndex(FI)
7057                    .addImm(4)
7058                    .addMemOperand(FIMMOLd));
7059
7060     if (NumLPads < 256) {
7061       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7062                      .addReg(NewVReg1)
7063                      .addImm(NumLPads));
7064     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7065       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7066       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7067                      .addImm(NumLPads & 0xFFFF));
7068
7069       unsigned VReg2 = VReg1;
7070       if ((NumLPads & 0xFFFF0000) != 0) {
7071         VReg2 = MRI->createVirtualRegister(TRC);
7072         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7073                        .addReg(VReg1)
7074                        .addImm(NumLPads >> 16));
7075       }
7076
7077       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7078                      .addReg(NewVReg1)
7079                      .addReg(VReg2));
7080     } else {
7081       MachineConstantPool *ConstantPool = MF->getConstantPool();
7082       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7083       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7084
7085       // MachineConstantPool wants an explicit alignment.
7086       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7087       if (Align == 0)
7088         Align = getDataLayout()->getTypeAllocSize(C->getType());
7089       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7090
7091       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7092       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7093                      .addReg(VReg1, RegState::Define)
7094                      .addConstantPoolIndex(Idx)
7095                      .addImm(0));
7096       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7097                      .addReg(NewVReg1)
7098                      .addReg(VReg1, RegState::Kill));
7099     }
7100
7101     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7102       .addMBB(TrapBB)
7103       .addImm(ARMCC::HI)
7104       .addReg(ARM::CPSR);
7105
7106     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7107     AddDefaultCC(
7108       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7109                      .addReg(NewVReg1)
7110                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7111     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7112     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7113                    .addJumpTableIndex(MJTI)
7114                    .addImm(UId));
7115
7116     MachineMemOperand *JTMMOLd =
7117       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7118                                MachineMemOperand::MOLoad, 4, 4);
7119     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7120     AddDefaultPred(
7121       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7122       .addReg(NewVReg3, RegState::Kill)
7123       .addReg(NewVReg4)
7124       .addImm(0)
7125       .addMemOperand(JTMMOLd));
7126
7127     if (RelocM == Reloc::PIC_) {
7128       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7129         .addReg(NewVReg5, RegState::Kill)
7130         .addReg(NewVReg4)
7131         .addJumpTableIndex(MJTI)
7132         .addImm(UId);
7133     } else {
7134       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7135         .addReg(NewVReg5, RegState::Kill)
7136         .addJumpTableIndex(MJTI)
7137         .addImm(UId);
7138     }
7139   }
7140
7141   // Add the jump table entries as successors to the MBB.
7142   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7143   for (std::vector<MachineBasicBlock*>::iterator
7144          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7145     MachineBasicBlock *CurMBB = *I;
7146     if (SeenMBBs.insert(CurMBB))
7147       DispContBB->addSuccessor(CurMBB);
7148   }
7149
7150   // N.B. the order the invoke BBs are processed in doesn't matter here.
7151   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7152   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7153   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7154          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7155     MachineBasicBlock *BB = *I;
7156
7157     // Remove the landing pad successor from the invoke block and replace it
7158     // with the new dispatch block.
7159     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7160                                                   BB->succ_end());
7161     while (!Successors.empty()) {
7162       MachineBasicBlock *SMBB = Successors.pop_back_val();
7163       if (SMBB->isLandingPad()) {
7164         BB->removeSuccessor(SMBB);
7165         MBBLPads.push_back(SMBB);
7166       }
7167     }
7168
7169     BB->addSuccessor(DispatchBB);
7170
7171     // Find the invoke call and mark all of the callee-saved registers as
7172     // 'implicit defined' so that they're spilled. This prevents code from
7173     // moving instructions to before the EH block, where they will never be
7174     // executed.
7175     for (MachineBasicBlock::reverse_iterator
7176            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7177       if (!II->isCall()) continue;
7178
7179       DenseMap<unsigned, bool> DefRegs;
7180       for (MachineInstr::mop_iterator
7181              OI = II->operands_begin(), OE = II->operands_end();
7182            OI != OE; ++OI) {
7183         if (!OI->isReg()) continue;
7184         DefRegs[OI->getReg()] = true;
7185       }
7186
7187       MachineInstrBuilder MIB(*MF, &*II);
7188
7189       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7190         unsigned Reg = SavedRegs[i];
7191         if (Subtarget->isThumb2() &&
7192             !ARM::tGPRRegClass.contains(Reg) &&
7193             !ARM::hGPRRegClass.contains(Reg))
7194           continue;
7195         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7196           continue;
7197         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7198           continue;
7199         if (!DefRegs[Reg])
7200           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7201       }
7202
7203       break;
7204     }
7205   }
7206
7207   // Mark all former landing pads as non-landing pads. The dispatch is the only
7208   // landing pad now.
7209   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7210          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7211     (*I)->setIsLandingPad(false);
7212
7213   // The instruction is gone now.
7214   MI->eraseFromParent();
7215
7216   return MBB;
7217 }
7218
7219 static
7220 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7221   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7222        E = MBB->succ_end(); I != E; ++I)
7223     if (*I != Succ)
7224       return *I;
7225   llvm_unreachable("Expecting a BB with two successors!");
7226 }
7227
7228 /// Return the load opcode for a given load size. If load size >= 8,
7229 /// neon opcode will be returned.
7230 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7231   if (LdSize >= 8)
7232     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7233                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7234   if (IsThumb1)
7235     return LdSize == 4 ? ARM::tLDRi
7236                        : LdSize == 2 ? ARM::tLDRHi
7237                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7238   if (IsThumb2)
7239     return LdSize == 4 ? ARM::t2LDR_POST
7240                        : LdSize == 2 ? ARM::t2LDRH_POST
7241                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7242   return LdSize == 4 ? ARM::LDR_POST_IMM
7243                      : LdSize == 2 ? ARM::LDRH_POST
7244                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7245 }
7246
7247 /// Return the store opcode for a given store size. If store size >= 8,
7248 /// neon opcode will be returned.
7249 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7250   if (StSize >= 8)
7251     return StSize == 16 ? ARM::VST1q32wb_fixed
7252                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7253   if (IsThumb1)
7254     return StSize == 4 ? ARM::tSTRi
7255                        : StSize == 2 ? ARM::tSTRHi
7256                                      : StSize == 1 ? ARM::tSTRBi : 0;
7257   if (IsThumb2)
7258     return StSize == 4 ? ARM::t2STR_POST
7259                        : StSize == 2 ? ARM::t2STRH_POST
7260                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7261   return StSize == 4 ? ARM::STR_POST_IMM
7262                      : StSize == 2 ? ARM::STRH_POST
7263                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7264 }
7265
7266 /// Emit a post-increment load operation with given size. The instructions
7267 /// will be added to BB at Pos.
7268 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7269                        const TargetInstrInfo *TII, DebugLoc dl,
7270                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7271                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7272   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7273   assert(LdOpc != 0 && "Should have a load opcode");
7274   if (LdSize >= 8) {
7275     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7276                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7277                        .addImm(0));
7278   } else if (IsThumb1) {
7279     // load + update AddrIn
7280     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7281                        .addReg(AddrIn).addImm(0));
7282     MachineInstrBuilder MIB =
7283         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7284     MIB = AddDefaultT1CC(MIB);
7285     MIB.addReg(AddrIn).addImm(LdSize);
7286     AddDefaultPred(MIB);
7287   } else if (IsThumb2) {
7288     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7289                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7290                        .addImm(LdSize));
7291   } else { // arm
7292     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7293                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7294                        .addReg(0).addImm(LdSize));
7295   }
7296 }
7297
7298 /// Emit a post-increment store operation with given size. The instructions
7299 /// will be added to BB at Pos.
7300 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7301                        const TargetInstrInfo *TII, DebugLoc dl,
7302                        unsigned StSize, unsigned Data, unsigned AddrIn,
7303                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7304   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7305   assert(StOpc != 0 && "Should have a store opcode");
7306   if (StSize >= 8) {
7307     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7308                        .addReg(AddrIn).addImm(0).addReg(Data));
7309   } else if (IsThumb1) {
7310     // store + update AddrIn
7311     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7312                        .addReg(AddrIn).addImm(0));
7313     MachineInstrBuilder MIB =
7314         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7315     MIB = AddDefaultT1CC(MIB);
7316     MIB.addReg(AddrIn).addImm(StSize);
7317     AddDefaultPred(MIB);
7318   } else if (IsThumb2) {
7319     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7320                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7321   } else { // arm
7322     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7323                        .addReg(Data).addReg(AddrIn).addReg(0)
7324                        .addImm(StSize));
7325   }
7326 }
7327
7328 MachineBasicBlock *
7329 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7330                                    MachineBasicBlock *BB) const {
7331   // This pseudo instruction has 3 operands: dst, src, size
7332   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7333   // Otherwise, we will generate unrolled scalar copies.
7334   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7335   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7336   MachineFunction::iterator It = BB;
7337   ++It;
7338
7339   unsigned dest = MI->getOperand(0).getReg();
7340   unsigned src = MI->getOperand(1).getReg();
7341   unsigned SizeVal = MI->getOperand(2).getImm();
7342   unsigned Align = MI->getOperand(3).getImm();
7343   DebugLoc dl = MI->getDebugLoc();
7344
7345   MachineFunction *MF = BB->getParent();
7346   MachineRegisterInfo &MRI = MF->getRegInfo();
7347   unsigned UnitSize = 0;
7348   const TargetRegisterClass *TRC = 0;
7349   const TargetRegisterClass *VecTRC = 0;
7350
7351   bool IsThumb1 = Subtarget->isThumb1Only();
7352   bool IsThumb2 = Subtarget->isThumb2();
7353
7354   if (Align & 1) {
7355     UnitSize = 1;
7356   } else if (Align & 2) {
7357     UnitSize = 2;
7358   } else {
7359     // Check whether we can use NEON instructions.
7360     if (!MF->getFunction()->getAttributes().
7361           hasAttribute(AttributeSet::FunctionIndex,
7362                        Attribute::NoImplicitFloat) &&
7363         Subtarget->hasNEON()) {
7364       if ((Align % 16 == 0) && SizeVal >= 16)
7365         UnitSize = 16;
7366       else if ((Align % 8 == 0) && SizeVal >= 8)
7367         UnitSize = 8;
7368     }
7369     // Can't use NEON instructions.
7370     if (UnitSize == 0)
7371       UnitSize = 4;
7372   }
7373
7374   // Select the correct opcode and register class for unit size load/store
7375   bool IsNeon = UnitSize >= 8;
7376   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7377                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7378   if (IsNeon)
7379     VecTRC = UnitSize == 16
7380                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7381                  : UnitSize == 8
7382                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7383                        : 0;
7384
7385   unsigned BytesLeft = SizeVal % UnitSize;
7386   unsigned LoopSize = SizeVal - BytesLeft;
7387
7388   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7389     // Use LDR and STR to copy.
7390     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7391     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7392     unsigned srcIn = src;
7393     unsigned destIn = dest;
7394     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7395       unsigned srcOut = MRI.createVirtualRegister(TRC);
7396       unsigned destOut = MRI.createVirtualRegister(TRC);
7397       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7398       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7399                  IsThumb1, IsThumb2);
7400       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7401                  IsThumb1, IsThumb2);
7402       srcIn = srcOut;
7403       destIn = destOut;
7404     }
7405
7406     // Handle the leftover bytes with LDRB and STRB.
7407     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7408     // [destOut] = STRB_POST(scratch, destIn, 1)
7409     for (unsigned i = 0; i < BytesLeft; i++) {
7410       unsigned srcOut = MRI.createVirtualRegister(TRC);
7411       unsigned destOut = MRI.createVirtualRegister(TRC);
7412       unsigned scratch = MRI.createVirtualRegister(TRC);
7413       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7414                  IsThumb1, IsThumb2);
7415       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7416                  IsThumb1, IsThumb2);
7417       srcIn = srcOut;
7418       destIn = destOut;
7419     }
7420     MI->eraseFromParent();   // The instruction is gone now.
7421     return BB;
7422   }
7423
7424   // Expand the pseudo op to a loop.
7425   // thisMBB:
7426   //   ...
7427   //   movw varEnd, # --> with thumb2
7428   //   movt varEnd, #
7429   //   ldrcp varEnd, idx --> without thumb2
7430   //   fallthrough --> loopMBB
7431   // loopMBB:
7432   //   PHI varPhi, varEnd, varLoop
7433   //   PHI srcPhi, src, srcLoop
7434   //   PHI destPhi, dst, destLoop
7435   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7436   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7437   //   subs varLoop, varPhi, #UnitSize
7438   //   bne loopMBB
7439   //   fallthrough --> exitMBB
7440   // exitMBB:
7441   //   epilogue to handle left-over bytes
7442   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7443   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7444   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7445   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7446   MF->insert(It, loopMBB);
7447   MF->insert(It, exitMBB);
7448
7449   // Transfer the remainder of BB and its successor edges to exitMBB.
7450   exitMBB->splice(exitMBB->begin(), BB,
7451                   llvm::next(MachineBasicBlock::iterator(MI)),
7452                   BB->end());
7453   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7454
7455   // Load an immediate to varEnd.
7456   unsigned varEnd = MRI.createVirtualRegister(TRC);
7457   if (IsThumb2) {
7458     unsigned Vtmp = varEnd;
7459     if ((LoopSize & 0xFFFF0000) != 0)
7460       Vtmp = MRI.createVirtualRegister(TRC);
7461     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7462                        .addImm(LoopSize & 0xFFFF));
7463
7464     if ((LoopSize & 0xFFFF0000) != 0)
7465       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7466                          .addReg(Vtmp).addImm(LoopSize >> 16));
7467   } else {
7468     MachineConstantPool *ConstantPool = MF->getConstantPool();
7469     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7470     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7471
7472     // MachineConstantPool wants an explicit alignment.
7473     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7474     if (Align == 0)
7475       Align = getDataLayout()->getTypeAllocSize(C->getType());
7476     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7477
7478     if (IsThumb1)
7479       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7480           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7481     else
7482       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7483           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7484   }
7485   BB->addSuccessor(loopMBB);
7486
7487   // Generate the loop body:
7488   //   varPhi = PHI(varLoop, varEnd)
7489   //   srcPhi = PHI(srcLoop, src)
7490   //   destPhi = PHI(destLoop, dst)
7491   MachineBasicBlock *entryBB = BB;
7492   BB = loopMBB;
7493   unsigned varLoop = MRI.createVirtualRegister(TRC);
7494   unsigned varPhi = MRI.createVirtualRegister(TRC);
7495   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7496   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7497   unsigned destLoop = MRI.createVirtualRegister(TRC);
7498   unsigned destPhi = MRI.createVirtualRegister(TRC);
7499
7500   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7501     .addReg(varLoop).addMBB(loopMBB)
7502     .addReg(varEnd).addMBB(entryBB);
7503   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7504     .addReg(srcLoop).addMBB(loopMBB)
7505     .addReg(src).addMBB(entryBB);
7506   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7507     .addReg(destLoop).addMBB(loopMBB)
7508     .addReg(dest).addMBB(entryBB);
7509
7510   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7511   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7512   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7513   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7514              IsThumb1, IsThumb2);
7515   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7516              IsThumb1, IsThumb2);
7517
7518   // Decrement loop variable by UnitSize.
7519   if (IsThumb1) {
7520     MachineInstrBuilder MIB =
7521         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7522     MIB = AddDefaultT1CC(MIB);
7523     MIB.addReg(varPhi).addImm(UnitSize);
7524     AddDefaultPred(MIB);
7525   } else {
7526     MachineInstrBuilder MIB =
7527         BuildMI(*BB, BB->end(), dl,
7528                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7529     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7530     MIB->getOperand(5).setReg(ARM::CPSR);
7531     MIB->getOperand(5).setIsDef(true);
7532   }
7533   BuildMI(*BB, BB->end(), dl,
7534           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7535       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7536
7537   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7538   BB->addSuccessor(loopMBB);
7539   BB->addSuccessor(exitMBB);
7540
7541   // Add epilogue to handle BytesLeft.
7542   BB = exitMBB;
7543   MachineInstr *StartOfExit = exitMBB->begin();
7544
7545   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7546   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7547   unsigned srcIn = srcLoop;
7548   unsigned destIn = destLoop;
7549   for (unsigned i = 0; i < BytesLeft; i++) {
7550     unsigned srcOut = MRI.createVirtualRegister(TRC);
7551     unsigned destOut = MRI.createVirtualRegister(TRC);
7552     unsigned scratch = MRI.createVirtualRegister(TRC);
7553     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7554                IsThumb1, IsThumb2);
7555     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7556                IsThumb1, IsThumb2);
7557     srcIn = srcOut;
7558     destIn = destOut;
7559   }
7560
7561   MI->eraseFromParent();   // The instruction is gone now.
7562   return BB;
7563 }
7564
7565 MachineBasicBlock *
7566 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7567                                                MachineBasicBlock *BB) const {
7568   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7569   DebugLoc dl = MI->getDebugLoc();
7570   bool isThumb2 = Subtarget->isThumb2();
7571   switch (MI->getOpcode()) {
7572   default: {
7573     MI->dump();
7574     llvm_unreachable("Unexpected instr type to insert");
7575   }
7576   // The Thumb2 pre-indexed stores have the same MI operands, they just
7577   // define them differently in the .td files from the isel patterns, so
7578   // they need pseudos.
7579   case ARM::t2STR_preidx:
7580     MI->setDesc(TII->get(ARM::t2STR_PRE));
7581     return BB;
7582   case ARM::t2STRB_preidx:
7583     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7584     return BB;
7585   case ARM::t2STRH_preidx:
7586     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7587     return BB;
7588
7589   case ARM::STRi_preidx:
7590   case ARM::STRBi_preidx: {
7591     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7592       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7593     // Decode the offset.
7594     unsigned Offset = MI->getOperand(4).getImm();
7595     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7596     Offset = ARM_AM::getAM2Offset(Offset);
7597     if (isSub)
7598       Offset = -Offset;
7599
7600     MachineMemOperand *MMO = *MI->memoperands_begin();
7601     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7602       .addOperand(MI->getOperand(0))  // Rn_wb
7603       .addOperand(MI->getOperand(1))  // Rt
7604       .addOperand(MI->getOperand(2))  // Rn
7605       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7606       .addOperand(MI->getOperand(5))  // pred
7607       .addOperand(MI->getOperand(6))
7608       .addMemOperand(MMO);
7609     MI->eraseFromParent();
7610     return BB;
7611   }
7612   case ARM::STRr_preidx:
7613   case ARM::STRBr_preidx:
7614   case ARM::STRH_preidx: {
7615     unsigned NewOpc;
7616     switch (MI->getOpcode()) {
7617     default: llvm_unreachable("unexpected opcode!");
7618     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7619     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7620     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7621     }
7622     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7623     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7624       MIB.addOperand(MI->getOperand(i));
7625     MI->eraseFromParent();
7626     return BB;
7627   }
7628   case ARM::ATOMIC_LOAD_ADD_I8:
7629      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7630   case ARM::ATOMIC_LOAD_ADD_I16:
7631      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7632   case ARM::ATOMIC_LOAD_ADD_I32:
7633      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7634
7635   case ARM::ATOMIC_LOAD_AND_I8:
7636      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7637   case ARM::ATOMIC_LOAD_AND_I16:
7638      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7639   case ARM::ATOMIC_LOAD_AND_I32:
7640      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7641
7642   case ARM::ATOMIC_LOAD_OR_I8:
7643      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7644   case ARM::ATOMIC_LOAD_OR_I16:
7645      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7646   case ARM::ATOMIC_LOAD_OR_I32:
7647      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7648
7649   case ARM::ATOMIC_LOAD_XOR_I8:
7650      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7651   case ARM::ATOMIC_LOAD_XOR_I16:
7652      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7653   case ARM::ATOMIC_LOAD_XOR_I32:
7654      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7655
7656   case ARM::ATOMIC_LOAD_NAND_I8:
7657      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7658   case ARM::ATOMIC_LOAD_NAND_I16:
7659      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7660   case ARM::ATOMIC_LOAD_NAND_I32:
7661      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7662
7663   case ARM::ATOMIC_LOAD_SUB_I8:
7664      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7665   case ARM::ATOMIC_LOAD_SUB_I16:
7666      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7667   case ARM::ATOMIC_LOAD_SUB_I32:
7668      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7669
7670   case ARM::ATOMIC_LOAD_MIN_I8:
7671      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7672   case ARM::ATOMIC_LOAD_MIN_I16:
7673      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7674   case ARM::ATOMIC_LOAD_MIN_I32:
7675      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7676
7677   case ARM::ATOMIC_LOAD_MAX_I8:
7678      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7679   case ARM::ATOMIC_LOAD_MAX_I16:
7680      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7681   case ARM::ATOMIC_LOAD_MAX_I32:
7682      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7683
7684   case ARM::ATOMIC_LOAD_UMIN_I8:
7685      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7686   case ARM::ATOMIC_LOAD_UMIN_I16:
7687      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7688   case ARM::ATOMIC_LOAD_UMIN_I32:
7689      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7690
7691   case ARM::ATOMIC_LOAD_UMAX_I8:
7692      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7693   case ARM::ATOMIC_LOAD_UMAX_I16:
7694      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7695   case ARM::ATOMIC_LOAD_UMAX_I32:
7696      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7697
7698   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7699   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7700   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7701
7702   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7703   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7704   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7705
7706   case ARM::ATOMIC_LOAD_I64:
7707     return EmitAtomicLoad64(MI, BB);
7708
7709   case ARM::ATOMIC_LOAD_ADD_I64:
7710     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7711                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7712                               /*NeedsCarry*/ true);
7713   case ARM::ATOMIC_LOAD_SUB_I64:
7714     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7715                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7716                               /*NeedsCarry*/ true);
7717   case ARM::ATOMIC_LOAD_OR_I64:
7718     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7719                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7720   case ARM::ATOMIC_LOAD_XOR_I64:
7721     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7722                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7723   case ARM::ATOMIC_LOAD_AND_I64:
7724     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7725                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7726   case ARM::ATOMIC_STORE_I64:
7727   case ARM::ATOMIC_SWAP_I64:
7728     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7729   case ARM::ATOMIC_CMP_SWAP_I64:
7730     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7731                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7732                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7733   case ARM::ATOMIC_LOAD_MIN_I64:
7734     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7735                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7736                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7737                               /*IsMinMax*/ true, ARMCC::LT);
7738   case ARM::ATOMIC_LOAD_MAX_I64:
7739     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7740                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7741                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7742                               /*IsMinMax*/ true, ARMCC::GE);
7743   case ARM::ATOMIC_LOAD_UMIN_I64:
7744     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7745                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7746                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7747                               /*IsMinMax*/ true, ARMCC::LO);
7748   case ARM::ATOMIC_LOAD_UMAX_I64:
7749     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7750                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7751                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7752                               /*IsMinMax*/ true, ARMCC::HS);
7753
7754   case ARM::tMOVCCr_pseudo: {
7755     // To "insert" a SELECT_CC instruction, we actually have to insert the
7756     // diamond control-flow pattern.  The incoming instruction knows the
7757     // destination vreg to set, the condition code register to branch on, the
7758     // true/false values to select between, and a branch opcode to use.
7759     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7760     MachineFunction::iterator It = BB;
7761     ++It;
7762
7763     //  thisMBB:
7764     //  ...
7765     //   TrueVal = ...
7766     //   cmpTY ccX, r1, r2
7767     //   bCC copy1MBB
7768     //   fallthrough --> copy0MBB
7769     MachineBasicBlock *thisMBB  = BB;
7770     MachineFunction *F = BB->getParent();
7771     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7772     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7773     F->insert(It, copy0MBB);
7774     F->insert(It, sinkMBB);
7775
7776     // Transfer the remainder of BB and its successor edges to sinkMBB.
7777     sinkMBB->splice(sinkMBB->begin(), BB,
7778                     llvm::next(MachineBasicBlock::iterator(MI)),
7779                     BB->end());
7780     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7781
7782     BB->addSuccessor(copy0MBB);
7783     BB->addSuccessor(sinkMBB);
7784
7785     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7786       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7787
7788     //  copy0MBB:
7789     //   %FalseValue = ...
7790     //   # fallthrough to sinkMBB
7791     BB = copy0MBB;
7792
7793     // Update machine-CFG edges
7794     BB->addSuccessor(sinkMBB);
7795
7796     //  sinkMBB:
7797     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7798     //  ...
7799     BB = sinkMBB;
7800     BuildMI(*BB, BB->begin(), dl,
7801             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7802       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7803       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7804
7805     MI->eraseFromParent();   // The pseudo instruction is gone now.
7806     return BB;
7807   }
7808
7809   case ARM::BCCi64:
7810   case ARM::BCCZi64: {
7811     // If there is an unconditional branch to the other successor, remove it.
7812     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7813
7814     // Compare both parts that make up the double comparison separately for
7815     // equality.
7816     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7817
7818     unsigned LHS1 = MI->getOperand(1).getReg();
7819     unsigned LHS2 = MI->getOperand(2).getReg();
7820     if (RHSisZero) {
7821       AddDefaultPred(BuildMI(BB, dl,
7822                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7823                      .addReg(LHS1).addImm(0));
7824       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7825         .addReg(LHS2).addImm(0)
7826         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7827     } else {
7828       unsigned RHS1 = MI->getOperand(3).getReg();
7829       unsigned RHS2 = MI->getOperand(4).getReg();
7830       AddDefaultPred(BuildMI(BB, dl,
7831                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7832                      .addReg(LHS1).addReg(RHS1));
7833       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7834         .addReg(LHS2).addReg(RHS2)
7835         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7836     }
7837
7838     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7839     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7840     if (MI->getOperand(0).getImm() == ARMCC::NE)
7841       std::swap(destMBB, exitMBB);
7842
7843     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7844       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7845     if (isThumb2)
7846       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7847     else
7848       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7849
7850     MI->eraseFromParent();   // The pseudo instruction is gone now.
7851     return BB;
7852   }
7853
7854   case ARM::Int_eh_sjlj_setjmp:
7855   case ARM::Int_eh_sjlj_setjmp_nofp:
7856   case ARM::tInt_eh_sjlj_setjmp:
7857   case ARM::t2Int_eh_sjlj_setjmp:
7858   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7859     EmitSjLjDispatchBlock(MI, BB);
7860     return BB;
7861
7862   case ARM::ABS:
7863   case ARM::t2ABS: {
7864     // To insert an ABS instruction, we have to insert the
7865     // diamond control-flow pattern.  The incoming instruction knows the
7866     // source vreg to test against 0, the destination vreg to set,
7867     // the condition code register to branch on, the
7868     // true/false values to select between, and a branch opcode to use.
7869     // It transforms
7870     //     V1 = ABS V0
7871     // into
7872     //     V2 = MOVS V0
7873     //     BCC                      (branch to SinkBB if V0 >= 0)
7874     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7875     //     SinkBB: V1 = PHI(V2, V3)
7876     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7877     MachineFunction::iterator BBI = BB;
7878     ++BBI;
7879     MachineFunction *Fn = BB->getParent();
7880     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7881     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7882     Fn->insert(BBI, RSBBB);
7883     Fn->insert(BBI, SinkBB);
7884
7885     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7886     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7887     bool isThumb2 = Subtarget->isThumb2();
7888     MachineRegisterInfo &MRI = Fn->getRegInfo();
7889     // In Thumb mode S must not be specified if source register is the SP or
7890     // PC and if destination register is the SP, so restrict register class
7891     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7892       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7893       (const TargetRegisterClass*)&ARM::GPRRegClass);
7894
7895     // Transfer the remainder of BB and its successor edges to sinkMBB.
7896     SinkBB->splice(SinkBB->begin(), BB,
7897       llvm::next(MachineBasicBlock::iterator(MI)),
7898       BB->end());
7899     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7900
7901     BB->addSuccessor(RSBBB);
7902     BB->addSuccessor(SinkBB);
7903
7904     // fall through to SinkMBB
7905     RSBBB->addSuccessor(SinkBB);
7906
7907     // insert a cmp at the end of BB
7908     AddDefaultPred(BuildMI(BB, dl,
7909                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7910                    .addReg(ABSSrcReg).addImm(0));
7911
7912     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7913     BuildMI(BB, dl,
7914       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7915       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7916
7917     // insert rsbri in RSBBB
7918     // Note: BCC and rsbri will be converted into predicated rsbmi
7919     // by if-conversion pass
7920     BuildMI(*RSBBB, RSBBB->begin(), dl,
7921       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7922       .addReg(ABSSrcReg, RegState::Kill)
7923       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7924
7925     // insert PHI in SinkBB,
7926     // reuse ABSDstReg to not change uses of ABS instruction
7927     BuildMI(*SinkBB, SinkBB->begin(), dl,
7928       TII->get(ARM::PHI), ABSDstReg)
7929       .addReg(NewRsbDstReg).addMBB(RSBBB)
7930       .addReg(ABSSrcReg).addMBB(BB);
7931
7932     // remove ABS instruction
7933     MI->eraseFromParent();
7934
7935     // return last added BB
7936     return SinkBB;
7937   }
7938   case ARM::COPY_STRUCT_BYVAL_I32:
7939     ++NumLoopByVals;
7940     return EmitStructByval(MI, BB);
7941   }
7942 }
7943
7944 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7945                                                       SDNode *Node) const {
7946   if (!MI->hasPostISelHook()) {
7947     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7948            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7949     return;
7950   }
7951
7952   const MCInstrDesc *MCID = &MI->getDesc();
7953   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7954   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7955   // operand is still set to noreg. If needed, set the optional operand's
7956   // register to CPSR, and remove the redundant implicit def.
7957   //
7958   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7959
7960   // Rename pseudo opcodes.
7961   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7962   if (NewOpc) {
7963     const ARMBaseInstrInfo *TII =
7964       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7965     MCID = &TII->get(NewOpc);
7966
7967     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7968            "converted opcode should be the same except for cc_out");
7969
7970     MI->setDesc(*MCID);
7971
7972     // Add the optional cc_out operand
7973     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7974   }
7975   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7976
7977   // Any ARM instruction that sets the 's' bit should specify an optional
7978   // "cc_out" operand in the last operand position.
7979   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7980     assert(!NewOpc && "Optional cc_out operand required");
7981     return;
7982   }
7983   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7984   // since we already have an optional CPSR def.
7985   bool definesCPSR = false;
7986   bool deadCPSR = false;
7987   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7988        i != e; ++i) {
7989     const MachineOperand &MO = MI->getOperand(i);
7990     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7991       definesCPSR = true;
7992       if (MO.isDead())
7993         deadCPSR = true;
7994       MI->RemoveOperand(i);
7995       break;
7996     }
7997   }
7998   if (!definesCPSR) {
7999     assert(!NewOpc && "Optional cc_out operand required");
8000     return;
8001   }
8002   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8003   if (deadCPSR) {
8004     assert(!MI->getOperand(ccOutIdx).getReg() &&
8005            "expect uninitialized optional cc_out operand");
8006     return;
8007   }
8008
8009   // If this instruction was defined with an optional CPSR def and its dag node
8010   // had a live implicit CPSR def, then activate the optional CPSR def.
8011   MachineOperand &MO = MI->getOperand(ccOutIdx);
8012   MO.setReg(ARM::CPSR);
8013   MO.setIsDef(true);
8014 }
8015
8016 //===----------------------------------------------------------------------===//
8017 //                           ARM Optimization Hooks
8018 //===----------------------------------------------------------------------===//
8019
8020 // Helper function that checks if N is a null or all ones constant.
8021 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8022   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8023   if (!C)
8024     return false;
8025   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8026 }
8027
8028 // Return true if N is conditionally 0 or all ones.
8029 // Detects these expressions where cc is an i1 value:
8030 //
8031 //   (select cc 0, y)   [AllOnes=0]
8032 //   (select cc y, 0)   [AllOnes=0]
8033 //   (zext cc)          [AllOnes=0]
8034 //   (sext cc)          [AllOnes=0/1]
8035 //   (select cc -1, y)  [AllOnes=1]
8036 //   (select cc y, -1)  [AllOnes=1]
8037 //
8038 // Invert is set when N is the null/all ones constant when CC is false.
8039 // OtherOp is set to the alternative value of N.
8040 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8041                                        SDValue &CC, bool &Invert,
8042                                        SDValue &OtherOp,
8043                                        SelectionDAG &DAG) {
8044   switch (N->getOpcode()) {
8045   default: return false;
8046   case ISD::SELECT: {
8047     CC = N->getOperand(0);
8048     SDValue N1 = N->getOperand(1);
8049     SDValue N2 = N->getOperand(2);
8050     if (isZeroOrAllOnes(N1, AllOnes)) {
8051       Invert = false;
8052       OtherOp = N2;
8053       return true;
8054     }
8055     if (isZeroOrAllOnes(N2, AllOnes)) {
8056       Invert = true;
8057       OtherOp = N1;
8058       return true;
8059     }
8060     return false;
8061   }
8062   case ISD::ZERO_EXTEND:
8063     // (zext cc) can never be the all ones value.
8064     if (AllOnes)
8065       return false;
8066     // Fall through.
8067   case ISD::SIGN_EXTEND: {
8068     EVT VT = N->getValueType(0);
8069     CC = N->getOperand(0);
8070     if (CC.getValueType() != MVT::i1)
8071       return false;
8072     Invert = !AllOnes;
8073     if (AllOnes)
8074       // When looking for an AllOnes constant, N is an sext, and the 'other'
8075       // value is 0.
8076       OtherOp = DAG.getConstant(0, VT);
8077     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8078       // When looking for a 0 constant, N can be zext or sext.
8079       OtherOp = DAG.getConstant(1, VT);
8080     else
8081       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8082     return true;
8083   }
8084   }
8085 }
8086
8087 // Combine a constant select operand into its use:
8088 //
8089 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8090 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8091 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8092 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8093 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8094 //
8095 // The transform is rejected if the select doesn't have a constant operand that
8096 // is null, or all ones when AllOnes is set.
8097 //
8098 // Also recognize sext/zext from i1:
8099 //
8100 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8101 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8102 //
8103 // These transformations eventually create predicated instructions.
8104 //
8105 // @param N       The node to transform.
8106 // @param Slct    The N operand that is a select.
8107 // @param OtherOp The other N operand (x above).
8108 // @param DCI     Context.
8109 // @param AllOnes Require the select constant to be all ones instead of null.
8110 // @returns The new node, or SDValue() on failure.
8111 static
8112 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8113                             TargetLowering::DAGCombinerInfo &DCI,
8114                             bool AllOnes = false) {
8115   SelectionDAG &DAG = DCI.DAG;
8116   EVT VT = N->getValueType(0);
8117   SDValue NonConstantVal;
8118   SDValue CCOp;
8119   bool SwapSelectOps;
8120   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8121                                   NonConstantVal, DAG))
8122     return SDValue();
8123
8124   // Slct is now know to be the desired identity constant when CC is true.
8125   SDValue TrueVal = OtherOp;
8126   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8127                                  OtherOp, NonConstantVal);
8128   // Unless SwapSelectOps says CC should be false.
8129   if (SwapSelectOps)
8130     std::swap(TrueVal, FalseVal);
8131
8132   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8133                      CCOp, TrueVal, FalseVal);
8134 }
8135
8136 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8137 static
8138 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8139                                        TargetLowering::DAGCombinerInfo &DCI) {
8140   SDValue N0 = N->getOperand(0);
8141   SDValue N1 = N->getOperand(1);
8142   if (N0.getNode()->hasOneUse()) {
8143     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8144     if (Result.getNode())
8145       return Result;
8146   }
8147   if (N1.getNode()->hasOneUse()) {
8148     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8149     if (Result.getNode())
8150       return Result;
8151   }
8152   return SDValue();
8153 }
8154
8155 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8156 // (only after legalization).
8157 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8158                                  TargetLowering::DAGCombinerInfo &DCI,
8159                                  const ARMSubtarget *Subtarget) {
8160
8161   // Only perform optimization if after legalize, and if NEON is available. We
8162   // also expected both operands to be BUILD_VECTORs.
8163   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8164       || N0.getOpcode() != ISD::BUILD_VECTOR
8165       || N1.getOpcode() != ISD::BUILD_VECTOR)
8166     return SDValue();
8167
8168   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8169   EVT VT = N->getValueType(0);
8170   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8171     return SDValue();
8172
8173   // Check that the vector operands are of the right form.
8174   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8175   // operands, where N is the size of the formed vector.
8176   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8177   // index such that we have a pair wise add pattern.
8178
8179   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8180   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8181     return SDValue();
8182   SDValue Vec = N0->getOperand(0)->getOperand(0);
8183   SDNode *V = Vec.getNode();
8184   unsigned nextIndex = 0;
8185
8186   // For each operands to the ADD which are BUILD_VECTORs,
8187   // check to see if each of their operands are an EXTRACT_VECTOR with
8188   // the same vector and appropriate index.
8189   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8190     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8191         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8192
8193       SDValue ExtVec0 = N0->getOperand(i);
8194       SDValue ExtVec1 = N1->getOperand(i);
8195
8196       // First operand is the vector, verify its the same.
8197       if (V != ExtVec0->getOperand(0).getNode() ||
8198           V != ExtVec1->getOperand(0).getNode())
8199         return SDValue();
8200
8201       // Second is the constant, verify its correct.
8202       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8203       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8204
8205       // For the constant, we want to see all the even or all the odd.
8206       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8207           || C1->getZExtValue() != nextIndex+1)
8208         return SDValue();
8209
8210       // Increment index.
8211       nextIndex+=2;
8212     } else
8213       return SDValue();
8214   }
8215
8216   // Create VPADDL node.
8217   SelectionDAG &DAG = DCI.DAG;
8218   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8219
8220   // Build operand list.
8221   SmallVector<SDValue, 8> Ops;
8222   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8223                                 TLI.getPointerTy()));
8224
8225   // Input is the vector.
8226   Ops.push_back(Vec);
8227
8228   // Get widened type and narrowed type.
8229   MVT widenType;
8230   unsigned numElem = VT.getVectorNumElements();
8231   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8232     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8233     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8234     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8235     default:
8236       llvm_unreachable("Invalid vector element type for padd optimization.");
8237   }
8238
8239   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8240                             widenType, &Ops[0], Ops.size());
8241   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8242 }
8243
8244 static SDValue findMUL_LOHI(SDValue V) {
8245   if (V->getOpcode() == ISD::UMUL_LOHI ||
8246       V->getOpcode() == ISD::SMUL_LOHI)
8247     return V;
8248   return SDValue();
8249 }
8250
8251 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8252                                      TargetLowering::DAGCombinerInfo &DCI,
8253                                      const ARMSubtarget *Subtarget) {
8254
8255   if (Subtarget->isThumb1Only()) return SDValue();
8256
8257   // Only perform the checks after legalize when the pattern is available.
8258   if (DCI.isBeforeLegalize()) return SDValue();
8259
8260   // Look for multiply add opportunities.
8261   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8262   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8263   // a glue link from the first add to the second add.
8264   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8265   // a S/UMLAL instruction.
8266   //          loAdd   UMUL_LOHI
8267   //            \    / :lo    \ :hi
8268   //             \  /          \          [no multiline comment]
8269   //              ADDC         |  hiAdd
8270   //                 \ :glue  /  /
8271   //                  \      /  /
8272   //                    ADDE
8273   //
8274   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8275   SDValue AddcOp0 = AddcNode->getOperand(0);
8276   SDValue AddcOp1 = AddcNode->getOperand(1);
8277
8278   // Check if the two operands are from the same mul_lohi node.
8279   if (AddcOp0.getNode() == AddcOp1.getNode())
8280     return SDValue();
8281
8282   assert(AddcNode->getNumValues() == 2 &&
8283          AddcNode->getValueType(0) == MVT::i32 &&
8284          "Expect ADDC with two result values. First: i32");
8285
8286   // Check that we have a glued ADDC node.
8287   if (AddcNode->getValueType(1) != MVT::Glue)
8288     return SDValue();
8289
8290   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8291   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8292       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8293       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8294       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8295     return SDValue();
8296
8297   // Look for the glued ADDE.
8298   SDNode* AddeNode = AddcNode->getGluedUser();
8299   if (AddeNode == NULL)
8300     return SDValue();
8301
8302   // Make sure it is really an ADDE.
8303   if (AddeNode->getOpcode() != ISD::ADDE)
8304     return SDValue();
8305
8306   assert(AddeNode->getNumOperands() == 3 &&
8307          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8308          "ADDE node has the wrong inputs");
8309
8310   // Check for the triangle shape.
8311   SDValue AddeOp0 = AddeNode->getOperand(0);
8312   SDValue AddeOp1 = AddeNode->getOperand(1);
8313
8314   // Make sure that the ADDE operands are not coming from the same node.
8315   if (AddeOp0.getNode() == AddeOp1.getNode())
8316     return SDValue();
8317
8318   // Find the MUL_LOHI node walking up ADDE's operands.
8319   bool IsLeftOperandMUL = false;
8320   SDValue MULOp = findMUL_LOHI(AddeOp0);
8321   if (MULOp == SDValue())
8322    MULOp = findMUL_LOHI(AddeOp1);
8323   else
8324     IsLeftOperandMUL = true;
8325   if (MULOp == SDValue())
8326      return SDValue();
8327
8328   // Figure out the right opcode.
8329   unsigned Opc = MULOp->getOpcode();
8330   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8331
8332   // Figure out the high and low input values to the MLAL node.
8333   SDValue* HiMul = &MULOp;
8334   SDValue* HiAdd = NULL;
8335   SDValue* LoMul = NULL;
8336   SDValue* LowAdd = NULL;
8337
8338   if (IsLeftOperandMUL)
8339     HiAdd = &AddeOp1;
8340   else
8341     HiAdd = &AddeOp0;
8342
8343
8344   if (AddcOp0->getOpcode() == Opc) {
8345     LoMul = &AddcOp0;
8346     LowAdd = &AddcOp1;
8347   }
8348   if (AddcOp1->getOpcode() == Opc) {
8349     LoMul = &AddcOp1;
8350     LowAdd = &AddcOp0;
8351   }
8352
8353   if (LoMul == NULL)
8354     return SDValue();
8355
8356   if (LoMul->getNode() != HiMul->getNode())
8357     return SDValue();
8358
8359   // Create the merged node.
8360   SelectionDAG &DAG = DCI.DAG;
8361
8362   // Build operand list.
8363   SmallVector<SDValue, 8> Ops;
8364   Ops.push_back(LoMul->getOperand(0));
8365   Ops.push_back(LoMul->getOperand(1));
8366   Ops.push_back(*LowAdd);
8367   Ops.push_back(*HiAdd);
8368
8369   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8370                                  DAG.getVTList(MVT::i32, MVT::i32),
8371                                  &Ops[0], Ops.size());
8372
8373   // Replace the ADDs' nodes uses by the MLA node's values.
8374   SDValue HiMLALResult(MLALNode.getNode(), 1);
8375   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8376
8377   SDValue LoMLALResult(MLALNode.getNode(), 0);
8378   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8379
8380   // Return original node to notify the driver to stop replacing.
8381   SDValue resNode(AddcNode, 0);
8382   return resNode;
8383 }
8384
8385 /// PerformADDCCombine - Target-specific dag combine transform from
8386 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8387 static SDValue PerformADDCCombine(SDNode *N,
8388                                  TargetLowering::DAGCombinerInfo &DCI,
8389                                  const ARMSubtarget *Subtarget) {
8390
8391   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8392
8393 }
8394
8395 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8396 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8397 /// called with the default operands, and if that fails, with commuted
8398 /// operands.
8399 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8400                                           TargetLowering::DAGCombinerInfo &DCI,
8401                                           const ARMSubtarget *Subtarget){
8402
8403   // Attempt to create vpaddl for this add.
8404   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8405   if (Result.getNode())
8406     return Result;
8407
8408   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8409   if (N0.getNode()->hasOneUse()) {
8410     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8411     if (Result.getNode()) return Result;
8412   }
8413   return SDValue();
8414 }
8415
8416 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8417 ///
8418 static SDValue PerformADDCombine(SDNode *N,
8419                                  TargetLowering::DAGCombinerInfo &DCI,
8420                                  const ARMSubtarget *Subtarget) {
8421   SDValue N0 = N->getOperand(0);
8422   SDValue N1 = N->getOperand(1);
8423
8424   // First try with the default operand order.
8425   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8426   if (Result.getNode())
8427     return Result;
8428
8429   // If that didn't work, try again with the operands commuted.
8430   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8431 }
8432
8433 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8434 ///
8435 static SDValue PerformSUBCombine(SDNode *N,
8436                                  TargetLowering::DAGCombinerInfo &DCI) {
8437   SDValue N0 = N->getOperand(0);
8438   SDValue N1 = N->getOperand(1);
8439
8440   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8441   if (N1.getNode()->hasOneUse()) {
8442     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8443     if (Result.getNode()) return Result;
8444   }
8445
8446   return SDValue();
8447 }
8448
8449 /// PerformVMULCombine
8450 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8451 /// special multiplier accumulator forwarding.
8452 ///   vmul d3, d0, d2
8453 ///   vmla d3, d1, d2
8454 /// is faster than
8455 ///   vadd d3, d0, d1
8456 ///   vmul d3, d3, d2
8457 //  However, for (A + B) * (A + B),
8458 //    vadd d2, d0, d1
8459 //    vmul d3, d0, d2
8460 //    vmla d3, d1, d2
8461 //  is slower than
8462 //    vadd d2, d0, d1
8463 //    vmul d3, d2, d2
8464 static SDValue PerformVMULCombine(SDNode *N,
8465                                   TargetLowering::DAGCombinerInfo &DCI,
8466                                   const ARMSubtarget *Subtarget) {
8467   if (!Subtarget->hasVMLxForwarding())
8468     return SDValue();
8469
8470   SelectionDAG &DAG = DCI.DAG;
8471   SDValue N0 = N->getOperand(0);
8472   SDValue N1 = N->getOperand(1);
8473   unsigned Opcode = N0.getOpcode();
8474   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8475       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8476     Opcode = N1.getOpcode();
8477     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8478         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8479       return SDValue();
8480     std::swap(N0, N1);
8481   }
8482
8483   if (N0 == N1)
8484     return SDValue();
8485
8486   EVT VT = N->getValueType(0);
8487   SDLoc DL(N);
8488   SDValue N00 = N0->getOperand(0);
8489   SDValue N01 = N0->getOperand(1);
8490   return DAG.getNode(Opcode, DL, VT,
8491                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8492                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8493 }
8494
8495 static SDValue PerformMULCombine(SDNode *N,
8496                                  TargetLowering::DAGCombinerInfo &DCI,
8497                                  const ARMSubtarget *Subtarget) {
8498   SelectionDAG &DAG = DCI.DAG;
8499
8500   if (Subtarget->isThumb1Only())
8501     return SDValue();
8502
8503   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8504     return SDValue();
8505
8506   EVT VT = N->getValueType(0);
8507   if (VT.is64BitVector() || VT.is128BitVector())
8508     return PerformVMULCombine(N, DCI, Subtarget);
8509   if (VT != MVT::i32)
8510     return SDValue();
8511
8512   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8513   if (!C)
8514     return SDValue();
8515
8516   int64_t MulAmt = C->getSExtValue();
8517   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8518
8519   ShiftAmt = ShiftAmt & (32 - 1);
8520   SDValue V = N->getOperand(0);
8521   SDLoc DL(N);
8522
8523   SDValue Res;
8524   MulAmt >>= ShiftAmt;
8525
8526   if (MulAmt >= 0) {
8527     if (isPowerOf2_32(MulAmt - 1)) {
8528       // (mul x, 2^N + 1) => (add (shl x, N), x)
8529       Res = DAG.getNode(ISD::ADD, DL, VT,
8530                         V,
8531                         DAG.getNode(ISD::SHL, DL, VT,
8532                                     V,
8533                                     DAG.getConstant(Log2_32(MulAmt - 1),
8534                                                     MVT::i32)));
8535     } else if (isPowerOf2_32(MulAmt + 1)) {
8536       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8537       Res = DAG.getNode(ISD::SUB, DL, VT,
8538                         DAG.getNode(ISD::SHL, DL, VT,
8539                                     V,
8540                                     DAG.getConstant(Log2_32(MulAmt + 1),
8541                                                     MVT::i32)),
8542                         V);
8543     } else
8544       return SDValue();
8545   } else {
8546     uint64_t MulAmtAbs = -MulAmt;
8547     if (isPowerOf2_32(MulAmtAbs + 1)) {
8548       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8549       Res = DAG.getNode(ISD::SUB, DL, VT,
8550                         V,
8551                         DAG.getNode(ISD::SHL, DL, VT,
8552                                     V,
8553                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8554                                                     MVT::i32)));
8555     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8556       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8557       Res = DAG.getNode(ISD::ADD, DL, VT,
8558                         V,
8559                         DAG.getNode(ISD::SHL, DL, VT,
8560                                     V,
8561                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8562                                                     MVT::i32)));
8563       Res = DAG.getNode(ISD::SUB, DL, VT,
8564                         DAG.getConstant(0, MVT::i32),Res);
8565
8566     } else
8567       return SDValue();
8568   }
8569
8570   if (ShiftAmt != 0)
8571     Res = DAG.getNode(ISD::SHL, DL, VT,
8572                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8573
8574   // Do not add new nodes to DAG combiner worklist.
8575   DCI.CombineTo(N, Res, false);
8576   return SDValue();
8577 }
8578
8579 static SDValue PerformANDCombine(SDNode *N,
8580                                  TargetLowering::DAGCombinerInfo &DCI,
8581                                  const ARMSubtarget *Subtarget) {
8582
8583   // Attempt to use immediate-form VBIC
8584   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8585   SDLoc dl(N);
8586   EVT VT = N->getValueType(0);
8587   SelectionDAG &DAG = DCI.DAG;
8588
8589   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8590     return SDValue();
8591
8592   APInt SplatBits, SplatUndef;
8593   unsigned SplatBitSize;
8594   bool HasAnyUndefs;
8595   if (BVN &&
8596       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8597     if (SplatBitSize <= 64) {
8598       EVT VbicVT;
8599       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8600                                       SplatUndef.getZExtValue(), SplatBitSize,
8601                                       DAG, VbicVT, VT.is128BitVector(),
8602                                       OtherModImm);
8603       if (Val.getNode()) {
8604         SDValue Input =
8605           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8606         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8607         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8608       }
8609     }
8610   }
8611
8612   if (!Subtarget->isThumb1Only()) {
8613     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8614     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8615     if (Result.getNode())
8616       return Result;
8617   }
8618
8619   return SDValue();
8620 }
8621
8622 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8623 static SDValue PerformORCombine(SDNode *N,
8624                                 TargetLowering::DAGCombinerInfo &DCI,
8625                                 const ARMSubtarget *Subtarget) {
8626   // Attempt to use immediate-form VORR
8627   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8628   SDLoc dl(N);
8629   EVT VT = N->getValueType(0);
8630   SelectionDAG &DAG = DCI.DAG;
8631
8632   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8633     return SDValue();
8634
8635   APInt SplatBits, SplatUndef;
8636   unsigned SplatBitSize;
8637   bool HasAnyUndefs;
8638   if (BVN && Subtarget->hasNEON() &&
8639       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8640     if (SplatBitSize <= 64) {
8641       EVT VorrVT;
8642       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8643                                       SplatUndef.getZExtValue(), SplatBitSize,
8644                                       DAG, VorrVT, VT.is128BitVector(),
8645                                       OtherModImm);
8646       if (Val.getNode()) {
8647         SDValue Input =
8648           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8649         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8650         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8651       }
8652     }
8653   }
8654
8655   if (!Subtarget->isThumb1Only()) {
8656     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8657     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8658     if (Result.getNode())
8659       return Result;
8660   }
8661
8662   // The code below optimizes (or (and X, Y), Z).
8663   // The AND operand needs to have a single user to make these optimizations
8664   // profitable.
8665   SDValue N0 = N->getOperand(0);
8666   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8667     return SDValue();
8668   SDValue N1 = N->getOperand(1);
8669
8670   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8671   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8672       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8673     APInt SplatUndef;
8674     unsigned SplatBitSize;
8675     bool HasAnyUndefs;
8676
8677     APInt SplatBits0, SplatBits1;
8678     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8679     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8680     // Ensure that the second operand of both ands are constants
8681     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8682                                       HasAnyUndefs) && !HasAnyUndefs) {
8683         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8684                                           HasAnyUndefs) && !HasAnyUndefs) {
8685             // Ensure that the bit width of the constants are the same and that
8686             // the splat arguments are logical inverses as per the pattern we
8687             // are trying to simplify.
8688             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8689                 SplatBits0 == ~SplatBits1) {
8690                 // Canonicalize the vector type to make instruction selection
8691                 // simpler.
8692                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8693                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8694                                              N0->getOperand(1),
8695                                              N0->getOperand(0),
8696                                              N1->getOperand(0));
8697                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8698             }
8699         }
8700     }
8701   }
8702
8703   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8704   // reasonable.
8705
8706   // BFI is only available on V6T2+
8707   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8708     return SDValue();
8709
8710   SDLoc DL(N);
8711   // 1) or (and A, mask), val => ARMbfi A, val, mask
8712   //      iff (val & mask) == val
8713   //
8714   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8715   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8716   //          && mask == ~mask2
8717   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8718   //          && ~mask == mask2
8719   //  (i.e., copy a bitfield value into another bitfield of the same width)
8720
8721   if (VT != MVT::i32)
8722     return SDValue();
8723
8724   SDValue N00 = N0.getOperand(0);
8725
8726   // The value and the mask need to be constants so we can verify this is
8727   // actually a bitfield set. If the mask is 0xffff, we can do better
8728   // via a movt instruction, so don't use BFI in that case.
8729   SDValue MaskOp = N0.getOperand(1);
8730   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8731   if (!MaskC)
8732     return SDValue();
8733   unsigned Mask = MaskC->getZExtValue();
8734   if (Mask == 0xffff)
8735     return SDValue();
8736   SDValue Res;
8737   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8738   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8739   if (N1C) {
8740     unsigned Val = N1C->getZExtValue();
8741     if ((Val & ~Mask) != Val)
8742       return SDValue();
8743
8744     if (ARM::isBitFieldInvertedMask(Mask)) {
8745       Val >>= countTrailingZeros(~Mask);
8746
8747       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8748                         DAG.getConstant(Val, MVT::i32),
8749                         DAG.getConstant(Mask, MVT::i32));
8750
8751       // Do not add new nodes to DAG combiner worklist.
8752       DCI.CombineTo(N, Res, false);
8753       return SDValue();
8754     }
8755   } else if (N1.getOpcode() == ISD::AND) {
8756     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8757     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8758     if (!N11C)
8759       return SDValue();
8760     unsigned Mask2 = N11C->getZExtValue();
8761
8762     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8763     // as is to match.
8764     if (ARM::isBitFieldInvertedMask(Mask) &&
8765         (Mask == ~Mask2)) {
8766       // The pack halfword instruction works better for masks that fit it,
8767       // so use that when it's available.
8768       if (Subtarget->hasT2ExtractPack() &&
8769           (Mask == 0xffff || Mask == 0xffff0000))
8770         return SDValue();
8771       // 2a
8772       unsigned amt = countTrailingZeros(Mask2);
8773       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8774                         DAG.getConstant(amt, MVT::i32));
8775       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8776                         DAG.getConstant(Mask, MVT::i32));
8777       // Do not add new nodes to DAG combiner worklist.
8778       DCI.CombineTo(N, Res, false);
8779       return SDValue();
8780     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8781                (~Mask == Mask2)) {
8782       // The pack halfword instruction works better for masks that fit it,
8783       // so use that when it's available.
8784       if (Subtarget->hasT2ExtractPack() &&
8785           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8786         return SDValue();
8787       // 2b
8788       unsigned lsb = countTrailingZeros(Mask);
8789       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8790                         DAG.getConstant(lsb, MVT::i32));
8791       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8792                         DAG.getConstant(Mask2, MVT::i32));
8793       // Do not add new nodes to DAG combiner worklist.
8794       DCI.CombineTo(N, Res, false);
8795       return SDValue();
8796     }
8797   }
8798
8799   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8800       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8801       ARM::isBitFieldInvertedMask(~Mask)) {
8802     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8803     // where lsb(mask) == #shamt and masked bits of B are known zero.
8804     SDValue ShAmt = N00.getOperand(1);
8805     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8806     unsigned LSB = countTrailingZeros(Mask);
8807     if (ShAmtC != LSB)
8808       return SDValue();
8809
8810     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8811                       DAG.getConstant(~Mask, MVT::i32));
8812
8813     // Do not add new nodes to DAG combiner worklist.
8814     DCI.CombineTo(N, Res, false);
8815   }
8816
8817   return SDValue();
8818 }
8819
8820 static SDValue PerformXORCombine(SDNode *N,
8821                                  TargetLowering::DAGCombinerInfo &DCI,
8822                                  const ARMSubtarget *Subtarget) {
8823   EVT VT = N->getValueType(0);
8824   SelectionDAG &DAG = DCI.DAG;
8825
8826   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8827     return SDValue();
8828
8829   if (!Subtarget->isThumb1Only()) {
8830     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8831     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8832     if (Result.getNode())
8833       return Result;
8834   }
8835
8836   return SDValue();
8837 }
8838
8839 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8840 /// the bits being cleared by the AND are not demanded by the BFI.
8841 static SDValue PerformBFICombine(SDNode *N,
8842                                  TargetLowering::DAGCombinerInfo &DCI) {
8843   SDValue N1 = N->getOperand(1);
8844   if (N1.getOpcode() == ISD::AND) {
8845     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8846     if (!N11C)
8847       return SDValue();
8848     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8849     unsigned LSB = countTrailingZeros(~InvMask);
8850     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8851     unsigned Mask = (1 << Width)-1;
8852     unsigned Mask2 = N11C->getZExtValue();
8853     if ((Mask & (~Mask2)) == 0)
8854       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8855                              N->getOperand(0), N1.getOperand(0),
8856                              N->getOperand(2));
8857   }
8858   return SDValue();
8859 }
8860
8861 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8862 /// ARMISD::VMOVRRD.
8863 static SDValue PerformVMOVRRDCombine(SDNode *N,
8864                                      TargetLowering::DAGCombinerInfo &DCI) {
8865   // vmovrrd(vmovdrr x, y) -> x,y
8866   SDValue InDouble = N->getOperand(0);
8867   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8868     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8869
8870   // vmovrrd(load f64) -> (load i32), (load i32)
8871   SDNode *InNode = InDouble.getNode();
8872   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8873       InNode->getValueType(0) == MVT::f64 &&
8874       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8875       !cast<LoadSDNode>(InNode)->isVolatile()) {
8876     // TODO: Should this be done for non-FrameIndex operands?
8877     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8878
8879     SelectionDAG &DAG = DCI.DAG;
8880     SDLoc DL(LD);
8881     SDValue BasePtr = LD->getBasePtr();
8882     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8883                                  LD->getPointerInfo(), LD->isVolatile(),
8884                                  LD->isNonTemporal(), LD->isInvariant(),
8885                                  LD->getAlignment());
8886
8887     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8888                                     DAG.getConstant(4, MVT::i32));
8889     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8890                                  LD->getPointerInfo(), LD->isVolatile(),
8891                                  LD->isNonTemporal(), LD->isInvariant(),
8892                                  std::min(4U, LD->getAlignment() / 2));
8893
8894     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8895     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8896     DCI.RemoveFromWorklist(LD);
8897     DAG.DeleteNode(LD);
8898     return Result;
8899   }
8900
8901   return SDValue();
8902 }
8903
8904 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8905 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8906 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8907   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8908   SDValue Op0 = N->getOperand(0);
8909   SDValue Op1 = N->getOperand(1);
8910   if (Op0.getOpcode() == ISD::BITCAST)
8911     Op0 = Op0.getOperand(0);
8912   if (Op1.getOpcode() == ISD::BITCAST)
8913     Op1 = Op1.getOperand(0);
8914   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8915       Op0.getNode() == Op1.getNode() &&
8916       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8917     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8918                        N->getValueType(0), Op0.getOperand(0));
8919   return SDValue();
8920 }
8921
8922 /// PerformSTORECombine - Target-specific dag combine xforms for
8923 /// ISD::STORE.
8924 static SDValue PerformSTORECombine(SDNode *N,
8925                                    TargetLowering::DAGCombinerInfo &DCI) {
8926   StoreSDNode *St = cast<StoreSDNode>(N);
8927   if (St->isVolatile())
8928     return SDValue();
8929
8930   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8931   // pack all of the elements in one place.  Next, store to memory in fewer
8932   // chunks.
8933   SDValue StVal = St->getValue();
8934   EVT VT = StVal.getValueType();
8935   if (St->isTruncatingStore() && VT.isVector()) {
8936     SelectionDAG &DAG = DCI.DAG;
8937     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8938     EVT StVT = St->getMemoryVT();
8939     unsigned NumElems = VT.getVectorNumElements();
8940     assert(StVT != VT && "Cannot truncate to the same type");
8941     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8942     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8943
8944     // From, To sizes and ElemCount must be pow of two
8945     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8946
8947     // We are going to use the original vector elt for storing.
8948     // Accumulated smaller vector elements must be a multiple of the store size.
8949     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8950
8951     unsigned SizeRatio  = FromEltSz / ToEltSz;
8952     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8953
8954     // Create a type on which we perform the shuffle.
8955     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8956                                      NumElems*SizeRatio);
8957     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8958
8959     SDLoc DL(St);
8960     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8961     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8962     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8963
8964     // Can't shuffle using an illegal type.
8965     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8966
8967     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8968                                 DAG.getUNDEF(WideVec.getValueType()),
8969                                 ShuffleVec.data());
8970     // At this point all of the data is stored at the bottom of the
8971     // register. We now need to save it to mem.
8972
8973     // Find the largest store unit
8974     MVT StoreType = MVT::i8;
8975     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8976          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8977       MVT Tp = (MVT::SimpleValueType)tp;
8978       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8979         StoreType = Tp;
8980     }
8981     // Didn't find a legal store type.
8982     if (!TLI.isTypeLegal(StoreType))
8983       return SDValue();
8984
8985     // Bitcast the original vector into a vector of store-size units
8986     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8987             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8988     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8989     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8990     SmallVector<SDValue, 8> Chains;
8991     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8992                                         TLI.getPointerTy());
8993     SDValue BasePtr = St->getBasePtr();
8994
8995     // Perform one or more big stores into memory.
8996     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8997     for (unsigned I = 0; I < E; I++) {
8998       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8999                                    StoreType, ShuffWide,
9000                                    DAG.getIntPtrConstant(I));
9001       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9002                                 St->getPointerInfo(), St->isVolatile(),
9003                                 St->isNonTemporal(), St->getAlignment());
9004       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9005                             Increment);
9006       Chains.push_back(Ch);
9007     }
9008     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9009                        Chains.size());
9010   }
9011
9012   if (!ISD::isNormalStore(St))
9013     return SDValue();
9014
9015   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9016   // ARM stores of arguments in the same cache line.
9017   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9018       StVal.getNode()->hasOneUse()) {
9019     SelectionDAG  &DAG = DCI.DAG;
9020     SDLoc DL(St);
9021     SDValue BasePtr = St->getBasePtr();
9022     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9023                                   StVal.getNode()->getOperand(0), BasePtr,
9024                                   St->getPointerInfo(), St->isVolatile(),
9025                                   St->isNonTemporal(), St->getAlignment());
9026
9027     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9028                                     DAG.getConstant(4, MVT::i32));
9029     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9030                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9031                         St->isNonTemporal(),
9032                         std::min(4U, St->getAlignment() / 2));
9033   }
9034
9035   if (StVal.getValueType() != MVT::i64 ||
9036       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9037     return SDValue();
9038
9039   // Bitcast an i64 store extracted from a vector to f64.
9040   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9041   SelectionDAG &DAG = DCI.DAG;
9042   SDLoc dl(StVal);
9043   SDValue IntVec = StVal.getOperand(0);
9044   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9045                                  IntVec.getValueType().getVectorNumElements());
9046   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9047   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9048                                Vec, StVal.getOperand(1));
9049   dl = SDLoc(N);
9050   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9051   // Make the DAGCombiner fold the bitcasts.
9052   DCI.AddToWorklist(Vec.getNode());
9053   DCI.AddToWorklist(ExtElt.getNode());
9054   DCI.AddToWorklist(V.getNode());
9055   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9056                       St->getPointerInfo(), St->isVolatile(),
9057                       St->isNonTemporal(), St->getAlignment(),
9058                       St->getTBAAInfo());
9059 }
9060
9061 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9062 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9063 /// i64 vector to have f64 elements, since the value can then be loaded
9064 /// directly into a VFP register.
9065 static bool hasNormalLoadOperand(SDNode *N) {
9066   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9067   for (unsigned i = 0; i < NumElts; ++i) {
9068     SDNode *Elt = N->getOperand(i).getNode();
9069     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9070       return true;
9071   }
9072   return false;
9073 }
9074
9075 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9076 /// ISD::BUILD_VECTOR.
9077 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9078                                           TargetLowering::DAGCombinerInfo &DCI){
9079   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9080   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9081   // into a pair of GPRs, which is fine when the value is used as a scalar,
9082   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9083   SelectionDAG &DAG = DCI.DAG;
9084   if (N->getNumOperands() == 2) {
9085     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9086     if (RV.getNode())
9087       return RV;
9088   }
9089
9090   // Load i64 elements as f64 values so that type legalization does not split
9091   // them up into i32 values.
9092   EVT VT = N->getValueType(0);
9093   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9094     return SDValue();
9095   SDLoc dl(N);
9096   SmallVector<SDValue, 8> Ops;
9097   unsigned NumElts = VT.getVectorNumElements();
9098   for (unsigned i = 0; i < NumElts; ++i) {
9099     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9100     Ops.push_back(V);
9101     // Make the DAGCombiner fold the bitcast.
9102     DCI.AddToWorklist(V.getNode());
9103   }
9104   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9105   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9106   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9107 }
9108
9109 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9110 static SDValue
9111 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9112   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9113   // At that time, we may have inserted bitcasts from integer to float.
9114   // If these bitcasts have survived DAGCombine, change the lowering of this
9115   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9116   // force to use floating point types.
9117
9118   // Make sure we can change the type of the vector.
9119   // This is possible iff:
9120   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9121   //    1.1. Vector is used only once.
9122   //    1.2. Use is a bit convert to an integer type.
9123   // 2. The size of its operands are 32-bits (64-bits are not legal).
9124   EVT VT = N->getValueType(0);
9125   EVT EltVT = VT.getVectorElementType();
9126
9127   // Check 1.1. and 2.
9128   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9129     return SDValue();
9130
9131   // By construction, the input type must be float.
9132   assert(EltVT == MVT::f32 && "Unexpected type!");
9133
9134   // Check 1.2.
9135   SDNode *Use = *N->use_begin();
9136   if (Use->getOpcode() != ISD::BITCAST ||
9137       Use->getValueType(0).isFloatingPoint())
9138     return SDValue();
9139
9140   // Check profitability.
9141   // Model is, if more than half of the relevant operands are bitcast from
9142   // i32, turn the build_vector into a sequence of insert_vector_elt.
9143   // Relevant operands are everything that is not statically
9144   // (i.e., at compile time) bitcasted.
9145   unsigned NumOfBitCastedElts = 0;
9146   unsigned NumElts = VT.getVectorNumElements();
9147   unsigned NumOfRelevantElts = NumElts;
9148   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9149     SDValue Elt = N->getOperand(Idx);
9150     if (Elt->getOpcode() == ISD::BITCAST) {
9151       // Assume only bit cast to i32 will go away.
9152       if (Elt->getOperand(0).getValueType() == MVT::i32)
9153         ++NumOfBitCastedElts;
9154     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9155       // Constants are statically casted, thus do not count them as
9156       // relevant operands.
9157       --NumOfRelevantElts;
9158   }
9159
9160   // Check if more than half of the elements require a non-free bitcast.
9161   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9162     return SDValue();
9163
9164   SelectionDAG &DAG = DCI.DAG;
9165   // Create the new vector type.
9166   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9167   // Check if the type is legal.
9168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9169   if (!TLI.isTypeLegal(VecVT))
9170     return SDValue();
9171
9172   // Combine:
9173   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9174   // => BITCAST INSERT_VECTOR_ELT
9175   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9176   //                      (BITCAST EN), N.
9177   SDValue Vec = DAG.getUNDEF(VecVT);
9178   SDLoc dl(N);
9179   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9180     SDValue V = N->getOperand(Idx);
9181     if (V.getOpcode() == ISD::UNDEF)
9182       continue;
9183     if (V.getOpcode() == ISD::BITCAST &&
9184         V->getOperand(0).getValueType() == MVT::i32)
9185       // Fold obvious case.
9186       V = V.getOperand(0);
9187     else {
9188       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9189       // Make the DAGCombiner fold the bitcasts.
9190       DCI.AddToWorklist(V.getNode());
9191     }
9192     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9193     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9194   }
9195   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9196   // Make the DAGCombiner fold the bitcasts.
9197   DCI.AddToWorklist(Vec.getNode());
9198   return Vec;
9199 }
9200
9201 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9202 /// ISD::INSERT_VECTOR_ELT.
9203 static SDValue PerformInsertEltCombine(SDNode *N,
9204                                        TargetLowering::DAGCombinerInfo &DCI) {
9205   // Bitcast an i64 load inserted into a vector to f64.
9206   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9207   EVT VT = N->getValueType(0);
9208   SDNode *Elt = N->getOperand(1).getNode();
9209   if (VT.getVectorElementType() != MVT::i64 ||
9210       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9211     return SDValue();
9212
9213   SelectionDAG &DAG = DCI.DAG;
9214   SDLoc dl(N);
9215   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9216                                  VT.getVectorNumElements());
9217   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9218   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9219   // Make the DAGCombiner fold the bitcasts.
9220   DCI.AddToWorklist(Vec.getNode());
9221   DCI.AddToWorklist(V.getNode());
9222   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9223                                Vec, V, N->getOperand(2));
9224   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9225 }
9226
9227 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9228 /// ISD::VECTOR_SHUFFLE.
9229 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9230   // The LLVM shufflevector instruction does not require the shuffle mask
9231   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9232   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9233   // operands do not match the mask length, they are extended by concatenating
9234   // them with undef vectors.  That is probably the right thing for other
9235   // targets, but for NEON it is better to concatenate two double-register
9236   // size vector operands into a single quad-register size vector.  Do that
9237   // transformation here:
9238   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9239   //   shuffle(concat(v1, v2), undef)
9240   SDValue Op0 = N->getOperand(0);
9241   SDValue Op1 = N->getOperand(1);
9242   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9243       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9244       Op0.getNumOperands() != 2 ||
9245       Op1.getNumOperands() != 2)
9246     return SDValue();
9247   SDValue Concat0Op1 = Op0.getOperand(1);
9248   SDValue Concat1Op1 = Op1.getOperand(1);
9249   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9250       Concat1Op1.getOpcode() != ISD::UNDEF)
9251     return SDValue();
9252   // Skip the transformation if any of the types are illegal.
9253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9254   EVT VT = N->getValueType(0);
9255   if (!TLI.isTypeLegal(VT) ||
9256       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9257       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9258     return SDValue();
9259
9260   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9261                                   Op0.getOperand(0), Op1.getOperand(0));
9262   // Translate the shuffle mask.
9263   SmallVector<int, 16> NewMask;
9264   unsigned NumElts = VT.getVectorNumElements();
9265   unsigned HalfElts = NumElts/2;
9266   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9267   for (unsigned n = 0; n < NumElts; ++n) {
9268     int MaskElt = SVN->getMaskElt(n);
9269     int NewElt = -1;
9270     if (MaskElt < (int)HalfElts)
9271       NewElt = MaskElt;
9272     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9273       NewElt = HalfElts + MaskElt - NumElts;
9274     NewMask.push_back(NewElt);
9275   }
9276   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9277                               DAG.getUNDEF(VT), NewMask.data());
9278 }
9279
9280 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9281 /// NEON load/store intrinsics to merge base address updates.
9282 static SDValue CombineBaseUpdate(SDNode *N,
9283                                  TargetLowering::DAGCombinerInfo &DCI) {
9284   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9285     return SDValue();
9286
9287   SelectionDAG &DAG = DCI.DAG;
9288   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9289                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9290   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9291   SDValue Addr = N->getOperand(AddrOpIdx);
9292
9293   // Search for a use of the address operand that is an increment.
9294   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9295          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9296     SDNode *User = *UI;
9297     if (User->getOpcode() != ISD::ADD ||
9298         UI.getUse().getResNo() != Addr.getResNo())
9299       continue;
9300
9301     // Check that the add is independent of the load/store.  Otherwise, folding
9302     // it would create a cycle.
9303     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9304       continue;
9305
9306     // Find the new opcode for the updating load/store.
9307     bool isLoad = true;
9308     bool isLaneOp = false;
9309     unsigned NewOpc = 0;
9310     unsigned NumVecs = 0;
9311     if (isIntrinsic) {
9312       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9313       switch (IntNo) {
9314       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9315       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9316         NumVecs = 1; break;
9317       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9318         NumVecs = 2; break;
9319       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9320         NumVecs = 3; break;
9321       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9322         NumVecs = 4; break;
9323       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9324         NumVecs = 2; isLaneOp = true; break;
9325       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9326         NumVecs = 3; isLaneOp = true; break;
9327       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9328         NumVecs = 4; isLaneOp = true; break;
9329       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9330         NumVecs = 1; isLoad = false; break;
9331       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9332         NumVecs = 2; isLoad = false; break;
9333       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9334         NumVecs = 3; isLoad = false; break;
9335       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9336         NumVecs = 4; isLoad = false; break;
9337       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9338         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9339       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9340         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9341       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9342         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9343       }
9344     } else {
9345       isLaneOp = true;
9346       switch (N->getOpcode()) {
9347       default: llvm_unreachable("unexpected opcode for Neon base update");
9348       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9349       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9350       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9351       }
9352     }
9353
9354     // Find the size of memory referenced by the load/store.
9355     EVT VecTy;
9356     if (isLoad)
9357       VecTy = N->getValueType(0);
9358     else
9359       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9360     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9361     if (isLaneOp)
9362       NumBytes /= VecTy.getVectorNumElements();
9363
9364     // If the increment is a constant, it must match the memory ref size.
9365     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9366     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9367       uint64_t IncVal = CInc->getZExtValue();
9368       if (IncVal != NumBytes)
9369         continue;
9370     } else if (NumBytes >= 3 * 16) {
9371       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9372       // separate instructions that make it harder to use a non-constant update.
9373       continue;
9374     }
9375
9376     // Create the new updating load/store node.
9377     EVT Tys[6];
9378     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9379     unsigned n;
9380     for (n = 0; n < NumResultVecs; ++n)
9381       Tys[n] = VecTy;
9382     Tys[n++] = MVT::i32;
9383     Tys[n] = MVT::Other;
9384     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9385     SmallVector<SDValue, 8> Ops;
9386     Ops.push_back(N->getOperand(0)); // incoming chain
9387     Ops.push_back(N->getOperand(AddrOpIdx));
9388     Ops.push_back(Inc);
9389     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9390       Ops.push_back(N->getOperand(i));
9391     }
9392     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9393     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9394                                            Ops.data(), Ops.size(),
9395                                            MemInt->getMemoryVT(),
9396                                            MemInt->getMemOperand());
9397
9398     // Update the uses.
9399     std::vector<SDValue> NewResults;
9400     for (unsigned i = 0; i < NumResultVecs; ++i) {
9401       NewResults.push_back(SDValue(UpdN.getNode(), i));
9402     }
9403     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9404     DCI.CombineTo(N, NewResults);
9405     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9406
9407     break;
9408   }
9409   return SDValue();
9410 }
9411
9412 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9413 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9414 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9415 /// return true.
9416 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9417   SelectionDAG &DAG = DCI.DAG;
9418   EVT VT = N->getValueType(0);
9419   // vldN-dup instructions only support 64-bit vectors for N > 1.
9420   if (!VT.is64BitVector())
9421     return false;
9422
9423   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9424   SDNode *VLD = N->getOperand(0).getNode();
9425   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9426     return false;
9427   unsigned NumVecs = 0;
9428   unsigned NewOpc = 0;
9429   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9430   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9431     NumVecs = 2;
9432     NewOpc = ARMISD::VLD2DUP;
9433   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9434     NumVecs = 3;
9435     NewOpc = ARMISD::VLD3DUP;
9436   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9437     NumVecs = 4;
9438     NewOpc = ARMISD::VLD4DUP;
9439   } else {
9440     return false;
9441   }
9442
9443   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9444   // numbers match the load.
9445   unsigned VLDLaneNo =
9446     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9447   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9448        UI != UE; ++UI) {
9449     // Ignore uses of the chain result.
9450     if (UI.getUse().getResNo() == NumVecs)
9451       continue;
9452     SDNode *User = *UI;
9453     if (User->getOpcode() != ARMISD::VDUPLANE ||
9454         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9455       return false;
9456   }
9457
9458   // Create the vldN-dup node.
9459   EVT Tys[5];
9460   unsigned n;
9461   for (n = 0; n < NumVecs; ++n)
9462     Tys[n] = VT;
9463   Tys[n] = MVT::Other;
9464   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9465   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9466   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9467   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9468                                            Ops, 2, VLDMemInt->getMemoryVT(),
9469                                            VLDMemInt->getMemOperand());
9470
9471   // Update the uses.
9472   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9473        UI != UE; ++UI) {
9474     unsigned ResNo = UI.getUse().getResNo();
9475     // Ignore uses of the chain result.
9476     if (ResNo == NumVecs)
9477       continue;
9478     SDNode *User = *UI;
9479     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9480   }
9481
9482   // Now the vldN-lane intrinsic is dead except for its chain result.
9483   // Update uses of the chain.
9484   std::vector<SDValue> VLDDupResults;
9485   for (unsigned n = 0; n < NumVecs; ++n)
9486     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9487   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9488   DCI.CombineTo(VLD, VLDDupResults);
9489
9490   return true;
9491 }
9492
9493 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9494 /// ARMISD::VDUPLANE.
9495 static SDValue PerformVDUPLANECombine(SDNode *N,
9496                                       TargetLowering::DAGCombinerInfo &DCI) {
9497   SDValue Op = N->getOperand(0);
9498
9499   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9500   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9501   if (CombineVLDDUP(N, DCI))
9502     return SDValue(N, 0);
9503
9504   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9505   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9506   while (Op.getOpcode() == ISD::BITCAST)
9507     Op = Op.getOperand(0);
9508   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9509     return SDValue();
9510
9511   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9512   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9513   // The canonical VMOV for a zero vector uses a 32-bit element size.
9514   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9515   unsigned EltBits;
9516   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9517     EltSize = 8;
9518   EVT VT = N->getValueType(0);
9519   if (EltSize > VT.getVectorElementType().getSizeInBits())
9520     return SDValue();
9521
9522   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9523 }
9524
9525 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9526 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9527 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9528 {
9529   integerPart cN;
9530   integerPart c0 = 0;
9531   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9532        I != E; I++) {
9533     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9534     if (!C)
9535       return false;
9536
9537     bool isExact;
9538     APFloat APF = C->getValueAPF();
9539     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9540         != APFloat::opOK || !isExact)
9541       return false;
9542
9543     c0 = (I == 0) ? cN : c0;
9544     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9545       return false;
9546   }
9547   C = c0;
9548   return true;
9549 }
9550
9551 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9552 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9553 /// when the VMUL has a constant operand that is a power of 2.
9554 ///
9555 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9556 ///  vmul.f32        d16, d17, d16
9557 ///  vcvt.s32.f32    d16, d16
9558 /// becomes:
9559 ///  vcvt.s32.f32    d16, d16, #3
9560 static SDValue PerformVCVTCombine(SDNode *N,
9561                                   TargetLowering::DAGCombinerInfo &DCI,
9562                                   const ARMSubtarget *Subtarget) {
9563   SelectionDAG &DAG = DCI.DAG;
9564   SDValue Op = N->getOperand(0);
9565
9566   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9567       Op.getOpcode() != ISD::FMUL)
9568     return SDValue();
9569
9570   uint64_t C;
9571   SDValue N0 = Op->getOperand(0);
9572   SDValue ConstVec = Op->getOperand(1);
9573   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9574
9575   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9576       !isConstVecPow2(ConstVec, isSigned, C))
9577     return SDValue();
9578
9579   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9580   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9581   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9582     // These instructions only exist converting from f32 to i32. We can handle
9583     // smaller integers by generating an extra truncate, but larger ones would
9584     // be lossy.
9585     return SDValue();
9586   }
9587
9588   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9589     Intrinsic::arm_neon_vcvtfp2fxu;
9590   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9591   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9592                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9593                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9594                                  DAG.getConstant(Log2_64(C), MVT::i32));
9595
9596   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9597     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9598
9599   return FixConv;
9600 }
9601
9602 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9603 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9604 /// when the VDIV has a constant operand that is a power of 2.
9605 ///
9606 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9607 ///  vcvt.f32.s32    d16, d16
9608 ///  vdiv.f32        d16, d17, d16
9609 /// becomes:
9610 ///  vcvt.f32.s32    d16, d16, #3
9611 static SDValue PerformVDIVCombine(SDNode *N,
9612                                   TargetLowering::DAGCombinerInfo &DCI,
9613                                   const ARMSubtarget *Subtarget) {
9614   SelectionDAG &DAG = DCI.DAG;
9615   SDValue Op = N->getOperand(0);
9616   unsigned OpOpcode = Op.getNode()->getOpcode();
9617
9618   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9619       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9620     return SDValue();
9621
9622   uint64_t C;
9623   SDValue ConstVec = N->getOperand(1);
9624   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9625
9626   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9627       !isConstVecPow2(ConstVec, isSigned, C))
9628     return SDValue();
9629
9630   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9631   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9632   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9633     // These instructions only exist converting from i32 to f32. We can handle
9634     // smaller integers by generating an extra extend, but larger ones would
9635     // be lossy.
9636     return SDValue();
9637   }
9638
9639   SDValue ConvInput = Op.getOperand(0);
9640   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9641   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9642     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9643                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9644                             ConvInput);
9645
9646   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9647     Intrinsic::arm_neon_vcvtfxu2fp;
9648   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9649                      Op.getValueType(),
9650                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9651                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9652 }
9653
9654 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9655 /// operand of a vector shift operation, where all the elements of the
9656 /// build_vector must have the same constant integer value.
9657 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9658   // Ignore bit_converts.
9659   while (Op.getOpcode() == ISD::BITCAST)
9660     Op = Op.getOperand(0);
9661   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9662   APInt SplatBits, SplatUndef;
9663   unsigned SplatBitSize;
9664   bool HasAnyUndefs;
9665   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9666                                       HasAnyUndefs, ElementBits) ||
9667       SplatBitSize > ElementBits)
9668     return false;
9669   Cnt = SplatBits.getSExtValue();
9670   return true;
9671 }
9672
9673 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9674 /// operand of a vector shift left operation.  That value must be in the range:
9675 ///   0 <= Value < ElementBits for a left shift; or
9676 ///   0 <= Value <= ElementBits for a long left shift.
9677 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9678   assert(VT.isVector() && "vector shift count is not a vector type");
9679   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9680   if (! getVShiftImm(Op, ElementBits, Cnt))
9681     return false;
9682   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9683 }
9684
9685 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9686 /// operand of a vector shift right operation.  For a shift opcode, the value
9687 /// is positive, but for an intrinsic the value count must be negative. The
9688 /// absolute value must be in the range:
9689 ///   1 <= |Value| <= ElementBits for a right shift; or
9690 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9691 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9692                          int64_t &Cnt) {
9693   assert(VT.isVector() && "vector shift count is not a vector type");
9694   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9695   if (! getVShiftImm(Op, ElementBits, Cnt))
9696     return false;
9697   if (isIntrinsic)
9698     Cnt = -Cnt;
9699   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9700 }
9701
9702 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9703 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9704   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9705   switch (IntNo) {
9706   default:
9707     // Don't do anything for most intrinsics.
9708     break;
9709
9710   // Vector shifts: check for immediate versions and lower them.
9711   // Note: This is done during DAG combining instead of DAG legalizing because
9712   // the build_vectors for 64-bit vector element shift counts are generally
9713   // not legal, and it is hard to see their values after they get legalized to
9714   // loads from a constant pool.
9715   case Intrinsic::arm_neon_vshifts:
9716   case Intrinsic::arm_neon_vshiftu:
9717   case Intrinsic::arm_neon_vshiftls:
9718   case Intrinsic::arm_neon_vshiftlu:
9719   case Intrinsic::arm_neon_vrshifts:
9720   case Intrinsic::arm_neon_vrshiftu:
9721   case Intrinsic::arm_neon_vrshiftn:
9722   case Intrinsic::arm_neon_vqshifts:
9723   case Intrinsic::arm_neon_vqshiftu:
9724   case Intrinsic::arm_neon_vqshiftsu:
9725   case Intrinsic::arm_neon_vqshiftns:
9726   case Intrinsic::arm_neon_vqshiftnu:
9727   case Intrinsic::arm_neon_vqshiftnsu:
9728   case Intrinsic::arm_neon_vqrshiftns:
9729   case Intrinsic::arm_neon_vqrshiftnu:
9730   case Intrinsic::arm_neon_vqrshiftnsu: {
9731     EVT VT = N->getOperand(1).getValueType();
9732     int64_t Cnt;
9733     unsigned VShiftOpc = 0;
9734
9735     switch (IntNo) {
9736     case Intrinsic::arm_neon_vshifts:
9737     case Intrinsic::arm_neon_vshiftu:
9738       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9739         VShiftOpc = ARMISD::VSHL;
9740         break;
9741       }
9742       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9743         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9744                      ARMISD::VSHRs : ARMISD::VSHRu);
9745         break;
9746       }
9747       return SDValue();
9748
9749     case Intrinsic::arm_neon_vshiftls:
9750     case Intrinsic::arm_neon_vshiftlu:
9751       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9752         break;
9753       llvm_unreachable("invalid shift count for vshll intrinsic");
9754
9755     case Intrinsic::arm_neon_vrshifts:
9756     case Intrinsic::arm_neon_vrshiftu:
9757       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9758         break;
9759       return SDValue();
9760
9761     case Intrinsic::arm_neon_vqshifts:
9762     case Intrinsic::arm_neon_vqshiftu:
9763       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9764         break;
9765       return SDValue();
9766
9767     case Intrinsic::arm_neon_vqshiftsu:
9768       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9769         break;
9770       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9771
9772     case Intrinsic::arm_neon_vrshiftn:
9773     case Intrinsic::arm_neon_vqshiftns:
9774     case Intrinsic::arm_neon_vqshiftnu:
9775     case Intrinsic::arm_neon_vqshiftnsu:
9776     case Intrinsic::arm_neon_vqrshiftns:
9777     case Intrinsic::arm_neon_vqrshiftnu:
9778     case Intrinsic::arm_neon_vqrshiftnsu:
9779       // Narrowing shifts require an immediate right shift.
9780       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9781         break;
9782       llvm_unreachable("invalid shift count for narrowing vector shift "
9783                        "intrinsic");
9784
9785     default:
9786       llvm_unreachable("unhandled vector shift");
9787     }
9788
9789     switch (IntNo) {
9790     case Intrinsic::arm_neon_vshifts:
9791     case Intrinsic::arm_neon_vshiftu:
9792       // Opcode already set above.
9793       break;
9794     case Intrinsic::arm_neon_vshiftls:
9795     case Intrinsic::arm_neon_vshiftlu:
9796       if (Cnt == VT.getVectorElementType().getSizeInBits())
9797         VShiftOpc = ARMISD::VSHLLi;
9798       else
9799         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9800                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9801       break;
9802     case Intrinsic::arm_neon_vrshifts:
9803       VShiftOpc = ARMISD::VRSHRs; break;
9804     case Intrinsic::arm_neon_vrshiftu:
9805       VShiftOpc = ARMISD::VRSHRu; break;
9806     case Intrinsic::arm_neon_vrshiftn:
9807       VShiftOpc = ARMISD::VRSHRN; break;
9808     case Intrinsic::arm_neon_vqshifts:
9809       VShiftOpc = ARMISD::VQSHLs; break;
9810     case Intrinsic::arm_neon_vqshiftu:
9811       VShiftOpc = ARMISD::VQSHLu; break;
9812     case Intrinsic::arm_neon_vqshiftsu:
9813       VShiftOpc = ARMISD::VQSHLsu; break;
9814     case Intrinsic::arm_neon_vqshiftns:
9815       VShiftOpc = ARMISD::VQSHRNs; break;
9816     case Intrinsic::arm_neon_vqshiftnu:
9817       VShiftOpc = ARMISD::VQSHRNu; break;
9818     case Intrinsic::arm_neon_vqshiftnsu:
9819       VShiftOpc = ARMISD::VQSHRNsu; break;
9820     case Intrinsic::arm_neon_vqrshiftns:
9821       VShiftOpc = ARMISD::VQRSHRNs; break;
9822     case Intrinsic::arm_neon_vqrshiftnu:
9823       VShiftOpc = ARMISD::VQRSHRNu; break;
9824     case Intrinsic::arm_neon_vqrshiftnsu:
9825       VShiftOpc = ARMISD::VQRSHRNsu; break;
9826     }
9827
9828     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9829                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9830   }
9831
9832   case Intrinsic::arm_neon_vshiftins: {
9833     EVT VT = N->getOperand(1).getValueType();
9834     int64_t Cnt;
9835     unsigned VShiftOpc = 0;
9836
9837     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9838       VShiftOpc = ARMISD::VSLI;
9839     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9840       VShiftOpc = ARMISD::VSRI;
9841     else {
9842       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9843     }
9844
9845     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9846                        N->getOperand(1), N->getOperand(2),
9847                        DAG.getConstant(Cnt, MVT::i32));
9848   }
9849
9850   case Intrinsic::arm_neon_vqrshifts:
9851   case Intrinsic::arm_neon_vqrshiftu:
9852     // No immediate versions of these to check for.
9853     break;
9854   }
9855
9856   return SDValue();
9857 }
9858
9859 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9860 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9861 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9862 /// vector element shift counts are generally not legal, and it is hard to see
9863 /// their values after they get legalized to loads from a constant pool.
9864 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9865                                    const ARMSubtarget *ST) {
9866   EVT VT = N->getValueType(0);
9867   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9868     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9869     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9870     SDValue N1 = N->getOperand(1);
9871     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9872       SDValue N0 = N->getOperand(0);
9873       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9874           DAG.MaskedValueIsZero(N0.getOperand(0),
9875                                 APInt::getHighBitsSet(32, 16)))
9876         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9877     }
9878   }
9879
9880   // Nothing to be done for scalar shifts.
9881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9882   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9883     return SDValue();
9884
9885   assert(ST->hasNEON() && "unexpected vector shift");
9886   int64_t Cnt;
9887
9888   switch (N->getOpcode()) {
9889   default: llvm_unreachable("unexpected shift opcode");
9890
9891   case ISD::SHL:
9892     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9893       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9894                          DAG.getConstant(Cnt, MVT::i32));
9895     break;
9896
9897   case ISD::SRA:
9898   case ISD::SRL:
9899     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9900       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9901                             ARMISD::VSHRs : ARMISD::VSHRu);
9902       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9903                          DAG.getConstant(Cnt, MVT::i32));
9904     }
9905   }
9906   return SDValue();
9907 }
9908
9909 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9910 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9911 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9912                                     const ARMSubtarget *ST) {
9913   SDValue N0 = N->getOperand(0);
9914
9915   // Check for sign- and zero-extensions of vector extract operations of 8-
9916   // and 16-bit vector elements.  NEON supports these directly.  They are
9917   // handled during DAG combining because type legalization will promote them
9918   // to 32-bit types and it is messy to recognize the operations after that.
9919   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9920     SDValue Vec = N0.getOperand(0);
9921     SDValue Lane = N0.getOperand(1);
9922     EVT VT = N->getValueType(0);
9923     EVT EltVT = N0.getValueType();
9924     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9925
9926     if (VT == MVT::i32 &&
9927         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9928         TLI.isTypeLegal(Vec.getValueType()) &&
9929         isa<ConstantSDNode>(Lane)) {
9930
9931       unsigned Opc = 0;
9932       switch (N->getOpcode()) {
9933       default: llvm_unreachable("unexpected opcode");
9934       case ISD::SIGN_EXTEND:
9935         Opc = ARMISD::VGETLANEs;
9936         break;
9937       case ISD::ZERO_EXTEND:
9938       case ISD::ANY_EXTEND:
9939         Opc = ARMISD::VGETLANEu;
9940         break;
9941       }
9942       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9943     }
9944   }
9945
9946   return SDValue();
9947 }
9948
9949 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9950 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9951 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9952                                        const ARMSubtarget *ST) {
9953   // If the target supports NEON, try to use vmax/vmin instructions for f32
9954   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9955   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9956   // a NaN; only do the transformation when it matches that behavior.
9957
9958   // For now only do this when using NEON for FP operations; if using VFP, it
9959   // is not obvious that the benefit outweighs the cost of switching to the
9960   // NEON pipeline.
9961   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9962       N->getValueType(0) != MVT::f32)
9963     return SDValue();
9964
9965   SDValue CondLHS = N->getOperand(0);
9966   SDValue CondRHS = N->getOperand(1);
9967   SDValue LHS = N->getOperand(2);
9968   SDValue RHS = N->getOperand(3);
9969   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9970
9971   unsigned Opcode = 0;
9972   bool IsReversed;
9973   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9974     IsReversed = false; // x CC y ? x : y
9975   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9976     IsReversed = true ; // x CC y ? y : x
9977   } else {
9978     return SDValue();
9979   }
9980
9981   bool IsUnordered;
9982   switch (CC) {
9983   default: break;
9984   case ISD::SETOLT:
9985   case ISD::SETOLE:
9986   case ISD::SETLT:
9987   case ISD::SETLE:
9988   case ISD::SETULT:
9989   case ISD::SETULE:
9990     // If LHS is NaN, an ordered comparison will be false and the result will
9991     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9992     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9993     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9994     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9995       break;
9996     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9997     // will return -0, so vmin can only be used for unsafe math or if one of
9998     // the operands is known to be nonzero.
9999     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10000         !DAG.getTarget().Options.UnsafeFPMath &&
10001         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10002       break;
10003     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10004     break;
10005
10006   case ISD::SETOGT:
10007   case ISD::SETOGE:
10008   case ISD::SETGT:
10009   case ISD::SETGE:
10010   case ISD::SETUGT:
10011   case ISD::SETUGE:
10012     // If LHS is NaN, an ordered comparison will be false and the result will
10013     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10014     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10015     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10016     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10017       break;
10018     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10019     // will return +0, so vmax can only be used for unsafe math or if one of
10020     // the operands is known to be nonzero.
10021     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10022         !DAG.getTarget().Options.UnsafeFPMath &&
10023         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10024       break;
10025     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10026     break;
10027   }
10028
10029   if (!Opcode)
10030     return SDValue();
10031   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10032 }
10033
10034 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10035 SDValue
10036 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10037   SDValue Cmp = N->getOperand(4);
10038   if (Cmp.getOpcode() != ARMISD::CMPZ)
10039     // Only looking at EQ and NE cases.
10040     return SDValue();
10041
10042   EVT VT = N->getValueType(0);
10043   SDLoc dl(N);
10044   SDValue LHS = Cmp.getOperand(0);
10045   SDValue RHS = Cmp.getOperand(1);
10046   SDValue FalseVal = N->getOperand(0);
10047   SDValue TrueVal = N->getOperand(1);
10048   SDValue ARMcc = N->getOperand(2);
10049   ARMCC::CondCodes CC =
10050     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10051
10052   // Simplify
10053   //   mov     r1, r0
10054   //   cmp     r1, x
10055   //   mov     r0, y
10056   //   moveq   r0, x
10057   // to
10058   //   cmp     r0, x
10059   //   movne   r0, y
10060   //
10061   //   mov     r1, r0
10062   //   cmp     r1, x
10063   //   mov     r0, x
10064   //   movne   r0, y
10065   // to
10066   //   cmp     r0, x
10067   //   movne   r0, y
10068   /// FIXME: Turn this into a target neutral optimization?
10069   SDValue Res;
10070   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10071     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10072                       N->getOperand(3), Cmp);
10073   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10074     SDValue ARMcc;
10075     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10076     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10077                       N->getOperand(3), NewCmp);
10078   }
10079
10080   if (Res.getNode()) {
10081     APInt KnownZero, KnownOne;
10082     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10083     // Capture demanded bits information that would be otherwise lost.
10084     if (KnownZero == 0xfffffffe)
10085       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10086                         DAG.getValueType(MVT::i1));
10087     else if (KnownZero == 0xffffff00)
10088       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10089                         DAG.getValueType(MVT::i8));
10090     else if (KnownZero == 0xffff0000)
10091       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10092                         DAG.getValueType(MVT::i16));
10093   }
10094
10095   return Res;
10096 }
10097
10098 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10099                                              DAGCombinerInfo &DCI) const {
10100   switch (N->getOpcode()) {
10101   default: break;
10102   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10103   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10104   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10105   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10106   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10107   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10108   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10109   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10110   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10111   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10112   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10113   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10114   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10115   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10116   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10117   case ISD::FP_TO_SINT:
10118   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10119   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10120   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10121   case ISD::SHL:
10122   case ISD::SRA:
10123   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10124   case ISD::SIGN_EXTEND:
10125   case ISD::ZERO_EXTEND:
10126   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10127   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10128   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10129   case ARMISD::VLD2DUP:
10130   case ARMISD::VLD3DUP:
10131   case ARMISD::VLD4DUP:
10132     return CombineBaseUpdate(N, DCI);
10133   case ARMISD::BUILD_VECTOR:
10134     return PerformARMBUILD_VECTORCombine(N, DCI);
10135   case ISD::INTRINSIC_VOID:
10136   case ISD::INTRINSIC_W_CHAIN:
10137     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10138     case Intrinsic::arm_neon_vld1:
10139     case Intrinsic::arm_neon_vld2:
10140     case Intrinsic::arm_neon_vld3:
10141     case Intrinsic::arm_neon_vld4:
10142     case Intrinsic::arm_neon_vld2lane:
10143     case Intrinsic::arm_neon_vld3lane:
10144     case Intrinsic::arm_neon_vld4lane:
10145     case Intrinsic::arm_neon_vst1:
10146     case Intrinsic::arm_neon_vst2:
10147     case Intrinsic::arm_neon_vst3:
10148     case Intrinsic::arm_neon_vst4:
10149     case Intrinsic::arm_neon_vst2lane:
10150     case Intrinsic::arm_neon_vst3lane:
10151     case Intrinsic::arm_neon_vst4lane:
10152       return CombineBaseUpdate(N, DCI);
10153     default: break;
10154     }
10155     break;
10156   }
10157   return SDValue();
10158 }
10159
10160 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10161                                                           EVT VT) const {
10162   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10163 }
10164
10165 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10166                                                       bool *Fast) const {
10167   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10168   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10169
10170   switch (VT.getSimpleVT().SimpleTy) {
10171   default:
10172     return false;
10173   case MVT::i8:
10174   case MVT::i16:
10175   case MVT::i32: {
10176     // Unaligned access can use (for example) LRDB, LRDH, LDR
10177     if (AllowsUnaligned) {
10178       if (Fast)
10179         *Fast = Subtarget->hasV7Ops();
10180       return true;
10181     }
10182     return false;
10183   }
10184   case MVT::f64:
10185   case MVT::v2f64: {
10186     // For any little-endian targets with neon, we can support unaligned ld/st
10187     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10188     // A big-endian target may also explicitly support unaligned accesses
10189     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10190       if (Fast)
10191         *Fast = true;
10192       return true;
10193     }
10194     return false;
10195   }
10196   }
10197 }
10198
10199 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10200                        unsigned AlignCheck) {
10201   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10202           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10203 }
10204
10205 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10206                                            unsigned DstAlign, unsigned SrcAlign,
10207                                            bool IsMemset, bool ZeroMemset,
10208                                            bool MemcpyStrSrc,
10209                                            MachineFunction &MF) const {
10210   const Function *F = MF.getFunction();
10211
10212   // See if we can use NEON instructions for this...
10213   if ((!IsMemset || ZeroMemset) &&
10214       Subtarget->hasNEON() &&
10215       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10216                                        Attribute::NoImplicitFloat)) {
10217     bool Fast;
10218     if (Size >= 16 &&
10219         (memOpAlign(SrcAlign, DstAlign, 16) ||
10220          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10221       return MVT::v2f64;
10222     } else if (Size >= 8 &&
10223                (memOpAlign(SrcAlign, DstAlign, 8) ||
10224                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10225       return MVT::f64;
10226     }
10227   }
10228
10229   // Lowering to i32/i16 if the size permits.
10230   if (Size >= 4)
10231     return MVT::i32;
10232   else if (Size >= 2)
10233     return MVT::i16;
10234
10235   // Let the target-independent logic figure it out.
10236   return MVT::Other;
10237 }
10238
10239 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10240   if (Val.getOpcode() != ISD::LOAD)
10241     return false;
10242
10243   EVT VT1 = Val.getValueType();
10244   if (!VT1.isSimple() || !VT1.isInteger() ||
10245       !VT2.isSimple() || !VT2.isInteger())
10246     return false;
10247
10248   switch (VT1.getSimpleVT().SimpleTy) {
10249   default: break;
10250   case MVT::i1:
10251   case MVT::i8:
10252   case MVT::i16:
10253     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10254     return true;
10255   }
10256
10257   return false;
10258 }
10259
10260 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10261   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10262     return false;
10263
10264   if (!isTypeLegal(EVT::getEVT(Ty1)))
10265     return false;
10266
10267   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10268
10269   // Assuming the caller doesn't have a zeroext or signext return parameter,
10270   // truncation all the way down to i1 is valid.
10271   return true;
10272 }
10273
10274
10275 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10276   if (V < 0)
10277     return false;
10278
10279   unsigned Scale = 1;
10280   switch (VT.getSimpleVT().SimpleTy) {
10281   default: return false;
10282   case MVT::i1:
10283   case MVT::i8:
10284     // Scale == 1;
10285     break;
10286   case MVT::i16:
10287     // Scale == 2;
10288     Scale = 2;
10289     break;
10290   case MVT::i32:
10291     // Scale == 4;
10292     Scale = 4;
10293     break;
10294   }
10295
10296   if ((V & (Scale - 1)) != 0)
10297     return false;
10298   V /= Scale;
10299   return V == (V & ((1LL << 5) - 1));
10300 }
10301
10302 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10303                                       const ARMSubtarget *Subtarget) {
10304   bool isNeg = false;
10305   if (V < 0) {
10306     isNeg = true;
10307     V = - V;
10308   }
10309
10310   switch (VT.getSimpleVT().SimpleTy) {
10311   default: return false;
10312   case MVT::i1:
10313   case MVT::i8:
10314   case MVT::i16:
10315   case MVT::i32:
10316     // + imm12 or - imm8
10317     if (isNeg)
10318       return V == (V & ((1LL << 8) - 1));
10319     return V == (V & ((1LL << 12) - 1));
10320   case MVT::f32:
10321   case MVT::f64:
10322     // Same as ARM mode. FIXME: NEON?
10323     if (!Subtarget->hasVFP2())
10324       return false;
10325     if ((V & 3) != 0)
10326       return false;
10327     V >>= 2;
10328     return V == (V & ((1LL << 8) - 1));
10329   }
10330 }
10331
10332 /// isLegalAddressImmediate - Return true if the integer value can be used
10333 /// as the offset of the target addressing mode for load / store of the
10334 /// given type.
10335 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10336                                     const ARMSubtarget *Subtarget) {
10337   if (V == 0)
10338     return true;
10339
10340   if (!VT.isSimple())
10341     return false;
10342
10343   if (Subtarget->isThumb1Only())
10344     return isLegalT1AddressImmediate(V, VT);
10345   else if (Subtarget->isThumb2())
10346     return isLegalT2AddressImmediate(V, VT, Subtarget);
10347
10348   // ARM mode.
10349   if (V < 0)
10350     V = - V;
10351   switch (VT.getSimpleVT().SimpleTy) {
10352   default: return false;
10353   case MVT::i1:
10354   case MVT::i8:
10355   case MVT::i32:
10356     // +- imm12
10357     return V == (V & ((1LL << 12) - 1));
10358   case MVT::i16:
10359     // +- imm8
10360     return V == (V & ((1LL << 8) - 1));
10361   case MVT::f32:
10362   case MVT::f64:
10363     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10364       return false;
10365     if ((V & 3) != 0)
10366       return false;
10367     V >>= 2;
10368     return V == (V & ((1LL << 8) - 1));
10369   }
10370 }
10371
10372 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10373                                                       EVT VT) const {
10374   int Scale = AM.Scale;
10375   if (Scale < 0)
10376     return false;
10377
10378   switch (VT.getSimpleVT().SimpleTy) {
10379   default: return false;
10380   case MVT::i1:
10381   case MVT::i8:
10382   case MVT::i16:
10383   case MVT::i32:
10384     if (Scale == 1)
10385       return true;
10386     // r + r << imm
10387     Scale = Scale & ~1;
10388     return Scale == 2 || Scale == 4 || Scale == 8;
10389   case MVT::i64:
10390     // r + r
10391     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10392       return true;
10393     return false;
10394   case MVT::isVoid:
10395     // Note, we allow "void" uses (basically, uses that aren't loads or
10396     // stores), because arm allows folding a scale into many arithmetic
10397     // operations.  This should be made more precise and revisited later.
10398
10399     // Allow r << imm, but the imm has to be a multiple of two.
10400     if (Scale & 1) return false;
10401     return isPowerOf2_32(Scale);
10402   }
10403 }
10404
10405 /// isLegalAddressingMode - Return true if the addressing mode represented
10406 /// by AM is legal for this target, for a load/store of the specified type.
10407 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10408                                               Type *Ty) const {
10409   EVT VT = getValueType(Ty, true);
10410   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10411     return false;
10412
10413   // Can never fold addr of global into load/store.
10414   if (AM.BaseGV)
10415     return false;
10416
10417   switch (AM.Scale) {
10418   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10419     break;
10420   case 1:
10421     if (Subtarget->isThumb1Only())
10422       return false;
10423     // FALL THROUGH.
10424   default:
10425     // ARM doesn't support any R+R*scale+imm addr modes.
10426     if (AM.BaseOffs)
10427       return false;
10428
10429     if (!VT.isSimple())
10430       return false;
10431
10432     if (Subtarget->isThumb2())
10433       return isLegalT2ScaledAddressingMode(AM, VT);
10434
10435     int Scale = AM.Scale;
10436     switch (VT.getSimpleVT().SimpleTy) {
10437     default: return false;
10438     case MVT::i1:
10439     case MVT::i8:
10440     case MVT::i32:
10441       if (Scale < 0) Scale = -Scale;
10442       if (Scale == 1)
10443         return true;
10444       // r + r << imm
10445       return isPowerOf2_32(Scale & ~1);
10446     case MVT::i16:
10447     case MVT::i64:
10448       // r + r
10449       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10450         return true;
10451       return false;
10452
10453     case MVT::isVoid:
10454       // Note, we allow "void" uses (basically, uses that aren't loads or
10455       // stores), because arm allows folding a scale into many arithmetic
10456       // operations.  This should be made more precise and revisited later.
10457
10458       // Allow r << imm, but the imm has to be a multiple of two.
10459       if (Scale & 1) return false;
10460       return isPowerOf2_32(Scale);
10461     }
10462   }
10463   return true;
10464 }
10465
10466 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10467 /// icmp immediate, that is the target has icmp instructions which can compare
10468 /// a register against the immediate without having to materialize the
10469 /// immediate into a register.
10470 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10471   // Thumb2 and ARM modes can use cmn for negative immediates.
10472   if (!Subtarget->isThumb())
10473     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10474   if (Subtarget->isThumb2())
10475     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10476   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10477   return Imm >= 0 && Imm <= 255;
10478 }
10479
10480 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10481 /// *or sub* immediate, that is the target has add or sub instructions which can
10482 /// add a register with the immediate without having to materialize the
10483 /// immediate into a register.
10484 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10485   // Same encoding for add/sub, just flip the sign.
10486   int64_t AbsImm = llvm::abs64(Imm);
10487   if (!Subtarget->isThumb())
10488     return ARM_AM::getSOImmVal(AbsImm) != -1;
10489   if (Subtarget->isThumb2())
10490     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10491   // Thumb1 only has 8-bit unsigned immediate.
10492   return AbsImm >= 0 && AbsImm <= 255;
10493 }
10494
10495 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10496                                       bool isSEXTLoad, SDValue &Base,
10497                                       SDValue &Offset, bool &isInc,
10498                                       SelectionDAG &DAG) {
10499   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10500     return false;
10501
10502   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10503     // AddressingMode 3
10504     Base = Ptr->getOperand(0);
10505     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10506       int RHSC = (int)RHS->getZExtValue();
10507       if (RHSC < 0 && RHSC > -256) {
10508         assert(Ptr->getOpcode() == ISD::ADD);
10509         isInc = false;
10510         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10511         return true;
10512       }
10513     }
10514     isInc = (Ptr->getOpcode() == ISD::ADD);
10515     Offset = Ptr->getOperand(1);
10516     return true;
10517   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10518     // AddressingMode 2
10519     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10520       int RHSC = (int)RHS->getZExtValue();
10521       if (RHSC < 0 && RHSC > -0x1000) {
10522         assert(Ptr->getOpcode() == ISD::ADD);
10523         isInc = false;
10524         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10525         Base = Ptr->getOperand(0);
10526         return true;
10527       }
10528     }
10529
10530     if (Ptr->getOpcode() == ISD::ADD) {
10531       isInc = true;
10532       ARM_AM::ShiftOpc ShOpcVal=
10533         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10534       if (ShOpcVal != ARM_AM::no_shift) {
10535         Base = Ptr->getOperand(1);
10536         Offset = Ptr->getOperand(0);
10537       } else {
10538         Base = Ptr->getOperand(0);
10539         Offset = Ptr->getOperand(1);
10540       }
10541       return true;
10542     }
10543
10544     isInc = (Ptr->getOpcode() == ISD::ADD);
10545     Base = Ptr->getOperand(0);
10546     Offset = Ptr->getOperand(1);
10547     return true;
10548   }
10549
10550   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10551   return false;
10552 }
10553
10554 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10555                                      bool isSEXTLoad, SDValue &Base,
10556                                      SDValue &Offset, bool &isInc,
10557                                      SelectionDAG &DAG) {
10558   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10559     return false;
10560
10561   Base = Ptr->getOperand(0);
10562   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10563     int RHSC = (int)RHS->getZExtValue();
10564     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10565       assert(Ptr->getOpcode() == ISD::ADD);
10566       isInc = false;
10567       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10568       return true;
10569     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10570       isInc = Ptr->getOpcode() == ISD::ADD;
10571       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10572       return true;
10573     }
10574   }
10575
10576   return false;
10577 }
10578
10579 /// getPreIndexedAddressParts - returns true by value, base pointer and
10580 /// offset pointer and addressing mode by reference if the node's address
10581 /// can be legally represented as pre-indexed load / store address.
10582 bool
10583 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10584                                              SDValue &Offset,
10585                                              ISD::MemIndexedMode &AM,
10586                                              SelectionDAG &DAG) const {
10587   if (Subtarget->isThumb1Only())
10588     return false;
10589
10590   EVT VT;
10591   SDValue Ptr;
10592   bool isSEXTLoad = false;
10593   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10594     Ptr = LD->getBasePtr();
10595     VT  = LD->getMemoryVT();
10596     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10597   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10598     Ptr = ST->getBasePtr();
10599     VT  = ST->getMemoryVT();
10600   } else
10601     return false;
10602
10603   bool isInc;
10604   bool isLegal = false;
10605   if (Subtarget->isThumb2())
10606     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10607                                        Offset, isInc, DAG);
10608   else
10609     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10610                                         Offset, isInc, DAG);
10611   if (!isLegal)
10612     return false;
10613
10614   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10615   return true;
10616 }
10617
10618 /// getPostIndexedAddressParts - returns true by value, base pointer and
10619 /// offset pointer and addressing mode by reference if this node can be
10620 /// combined with a load / store to form a post-indexed load / store.
10621 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10622                                                    SDValue &Base,
10623                                                    SDValue &Offset,
10624                                                    ISD::MemIndexedMode &AM,
10625                                                    SelectionDAG &DAG) const {
10626   if (Subtarget->isThumb1Only())
10627     return false;
10628
10629   EVT VT;
10630   SDValue Ptr;
10631   bool isSEXTLoad = false;
10632   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10633     VT  = LD->getMemoryVT();
10634     Ptr = LD->getBasePtr();
10635     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10636   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10637     VT  = ST->getMemoryVT();
10638     Ptr = ST->getBasePtr();
10639   } else
10640     return false;
10641
10642   bool isInc;
10643   bool isLegal = false;
10644   if (Subtarget->isThumb2())
10645     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10646                                        isInc, DAG);
10647   else
10648     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10649                                         isInc, DAG);
10650   if (!isLegal)
10651     return false;
10652
10653   if (Ptr != Base) {
10654     // Swap base ptr and offset to catch more post-index load / store when
10655     // it's legal. In Thumb2 mode, offset must be an immediate.
10656     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10657         !Subtarget->isThumb2())
10658       std::swap(Base, Offset);
10659
10660     // Post-indexed load / store update the base pointer.
10661     if (Ptr != Base)
10662       return false;
10663   }
10664
10665   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10666   return true;
10667 }
10668
10669 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10670                                                        APInt &KnownZero,
10671                                                        APInt &KnownOne,
10672                                                        const SelectionDAG &DAG,
10673                                                        unsigned Depth) const {
10674   unsigned BitWidth = KnownOne.getBitWidth();
10675   KnownZero = KnownOne = APInt(BitWidth, 0);
10676   switch (Op.getOpcode()) {
10677   default: break;
10678   case ARMISD::ADDC:
10679   case ARMISD::ADDE:
10680   case ARMISD::SUBC:
10681   case ARMISD::SUBE:
10682     // These nodes' second result is a boolean
10683     if (Op.getResNo() == 0)
10684       break;
10685     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10686     break;
10687   case ARMISD::CMOV: {
10688     // Bits are known zero/one if known on the LHS and RHS.
10689     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10690     if (KnownZero == 0 && KnownOne == 0) return;
10691
10692     APInt KnownZeroRHS, KnownOneRHS;
10693     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10694     KnownZero &= KnownZeroRHS;
10695     KnownOne  &= KnownOneRHS;
10696     return;
10697   }
10698   }
10699 }
10700
10701 //===----------------------------------------------------------------------===//
10702 //                           ARM Inline Assembly Support
10703 //===----------------------------------------------------------------------===//
10704
10705 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10706   // Looking for "rev" which is V6+.
10707   if (!Subtarget->hasV6Ops())
10708     return false;
10709
10710   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10711   std::string AsmStr = IA->getAsmString();
10712   SmallVector<StringRef, 4> AsmPieces;
10713   SplitString(AsmStr, AsmPieces, ";\n");
10714
10715   switch (AsmPieces.size()) {
10716   default: return false;
10717   case 1:
10718     AsmStr = AsmPieces[0];
10719     AsmPieces.clear();
10720     SplitString(AsmStr, AsmPieces, " \t,");
10721
10722     // rev $0, $1
10723     if (AsmPieces.size() == 3 &&
10724         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10725         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10726       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10727       if (Ty && Ty->getBitWidth() == 32)
10728         return IntrinsicLowering::LowerToByteSwap(CI);
10729     }
10730     break;
10731   }
10732
10733   return false;
10734 }
10735
10736 /// getConstraintType - Given a constraint letter, return the type of
10737 /// constraint it is for this target.
10738 ARMTargetLowering::ConstraintType
10739 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10740   if (Constraint.size() == 1) {
10741     switch (Constraint[0]) {
10742     default:  break;
10743     case 'l': return C_RegisterClass;
10744     case 'w': return C_RegisterClass;
10745     case 'h': return C_RegisterClass;
10746     case 'x': return C_RegisterClass;
10747     case 't': return C_RegisterClass;
10748     case 'j': return C_Other; // Constant for movw.
10749       // An address with a single base register. Due to the way we
10750       // currently handle addresses it is the same as an 'r' memory constraint.
10751     case 'Q': return C_Memory;
10752     }
10753   } else if (Constraint.size() == 2) {
10754     switch (Constraint[0]) {
10755     default: break;
10756     // All 'U+' constraints are addresses.
10757     case 'U': return C_Memory;
10758     }
10759   }
10760   return TargetLowering::getConstraintType(Constraint);
10761 }
10762
10763 /// Examine constraint type and operand type and determine a weight value.
10764 /// This object must already have been set up with the operand type
10765 /// and the current alternative constraint selected.
10766 TargetLowering::ConstraintWeight
10767 ARMTargetLowering::getSingleConstraintMatchWeight(
10768     AsmOperandInfo &info, const char *constraint) const {
10769   ConstraintWeight weight = CW_Invalid;
10770   Value *CallOperandVal = info.CallOperandVal;
10771     // If we don't have a value, we can't do a match,
10772     // but allow it at the lowest weight.
10773   if (CallOperandVal == NULL)
10774     return CW_Default;
10775   Type *type = CallOperandVal->getType();
10776   // Look at the constraint type.
10777   switch (*constraint) {
10778   default:
10779     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10780     break;
10781   case 'l':
10782     if (type->isIntegerTy()) {
10783       if (Subtarget->isThumb())
10784         weight = CW_SpecificReg;
10785       else
10786         weight = CW_Register;
10787     }
10788     break;
10789   case 'w':
10790     if (type->isFloatingPointTy())
10791       weight = CW_Register;
10792     break;
10793   }
10794   return weight;
10795 }
10796
10797 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10798 RCPair
10799 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10800                                                 MVT VT) const {
10801   if (Constraint.size() == 1) {
10802     // GCC ARM Constraint Letters
10803     switch (Constraint[0]) {
10804     case 'l': // Low regs or general regs.
10805       if (Subtarget->isThumb())
10806         return RCPair(0U, &ARM::tGPRRegClass);
10807       return RCPair(0U, &ARM::GPRRegClass);
10808     case 'h': // High regs or no regs.
10809       if (Subtarget->isThumb())
10810         return RCPair(0U, &ARM::hGPRRegClass);
10811       break;
10812     case 'r':
10813       return RCPair(0U, &ARM::GPRRegClass);
10814     case 'w':
10815       if (VT == MVT::Other)
10816         break;
10817       if (VT == MVT::f32)
10818         return RCPair(0U, &ARM::SPRRegClass);
10819       if (VT.getSizeInBits() == 64)
10820         return RCPair(0U, &ARM::DPRRegClass);
10821       if (VT.getSizeInBits() == 128)
10822         return RCPair(0U, &ARM::QPRRegClass);
10823       break;
10824     case 'x':
10825       if (VT == MVT::Other)
10826         break;
10827       if (VT == MVT::f32)
10828         return RCPair(0U, &ARM::SPR_8RegClass);
10829       if (VT.getSizeInBits() == 64)
10830         return RCPair(0U, &ARM::DPR_8RegClass);
10831       if (VT.getSizeInBits() == 128)
10832         return RCPair(0U, &ARM::QPR_8RegClass);
10833       break;
10834     case 't':
10835       if (VT == MVT::f32)
10836         return RCPair(0U, &ARM::SPRRegClass);
10837       break;
10838     }
10839   }
10840   if (StringRef("{cc}").equals_lower(Constraint))
10841     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10842
10843   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10844 }
10845
10846 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10847 /// vector.  If it is invalid, don't add anything to Ops.
10848 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10849                                                      std::string &Constraint,
10850                                                      std::vector<SDValue>&Ops,
10851                                                      SelectionDAG &DAG) const {
10852   SDValue Result(0, 0);
10853
10854   // Currently only support length 1 constraints.
10855   if (Constraint.length() != 1) return;
10856
10857   char ConstraintLetter = Constraint[0];
10858   switch (ConstraintLetter) {
10859   default: break;
10860   case 'j':
10861   case 'I': case 'J': case 'K': case 'L':
10862   case 'M': case 'N': case 'O':
10863     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10864     if (!C)
10865       return;
10866
10867     int64_t CVal64 = C->getSExtValue();
10868     int CVal = (int) CVal64;
10869     // None of these constraints allow values larger than 32 bits.  Check
10870     // that the value fits in an int.
10871     if (CVal != CVal64)
10872       return;
10873
10874     switch (ConstraintLetter) {
10875       case 'j':
10876         // Constant suitable for movw, must be between 0 and
10877         // 65535.
10878         if (Subtarget->hasV6T2Ops())
10879           if (CVal >= 0 && CVal <= 65535)
10880             break;
10881         return;
10882       case 'I':
10883         if (Subtarget->isThumb1Only()) {
10884           // This must be a constant between 0 and 255, for ADD
10885           // immediates.
10886           if (CVal >= 0 && CVal <= 255)
10887             break;
10888         } else if (Subtarget->isThumb2()) {
10889           // A constant that can be used as an immediate value in a
10890           // data-processing instruction.
10891           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10892             break;
10893         } else {
10894           // A constant that can be used as an immediate value in a
10895           // data-processing instruction.
10896           if (ARM_AM::getSOImmVal(CVal) != -1)
10897             break;
10898         }
10899         return;
10900
10901       case 'J':
10902         if (Subtarget->isThumb()) {  // FIXME thumb2
10903           // This must be a constant between -255 and -1, for negated ADD
10904           // immediates. This can be used in GCC with an "n" modifier that
10905           // prints the negated value, for use with SUB instructions. It is
10906           // not useful otherwise but is implemented for compatibility.
10907           if (CVal >= -255 && CVal <= -1)
10908             break;
10909         } else {
10910           // This must be a constant between -4095 and 4095. It is not clear
10911           // what this constraint is intended for. Implemented for
10912           // compatibility with GCC.
10913           if (CVal >= -4095 && CVal <= 4095)
10914             break;
10915         }
10916         return;
10917
10918       case 'K':
10919         if (Subtarget->isThumb1Only()) {
10920           // A 32-bit value where only one byte has a nonzero value. Exclude
10921           // zero to match GCC. This constraint is used by GCC internally for
10922           // constants that can be loaded with a move/shift combination.
10923           // It is not useful otherwise but is implemented for compatibility.
10924           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10925             break;
10926         } else if (Subtarget->isThumb2()) {
10927           // A constant whose bitwise inverse can be used as an immediate
10928           // value in a data-processing instruction. This can be used in GCC
10929           // with a "B" modifier that prints the inverted value, for use with
10930           // BIC and MVN instructions. It is not useful otherwise but is
10931           // implemented for compatibility.
10932           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10933             break;
10934         } else {
10935           // A constant whose bitwise inverse can be used as an immediate
10936           // value in a data-processing instruction. This can be used in GCC
10937           // with a "B" modifier that prints the inverted value, for use with
10938           // BIC and MVN instructions. It is not useful otherwise but is
10939           // implemented for compatibility.
10940           if (ARM_AM::getSOImmVal(~CVal) != -1)
10941             break;
10942         }
10943         return;
10944
10945       case 'L':
10946         if (Subtarget->isThumb1Only()) {
10947           // This must be a constant between -7 and 7,
10948           // for 3-operand ADD/SUB immediate instructions.
10949           if (CVal >= -7 && CVal < 7)
10950             break;
10951         } else if (Subtarget->isThumb2()) {
10952           // A constant whose negation can be used as an immediate value in a
10953           // data-processing instruction. This can be used in GCC with an "n"
10954           // modifier that prints the negated value, for use with SUB
10955           // instructions. It is not useful otherwise but is implemented for
10956           // compatibility.
10957           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10958             break;
10959         } else {
10960           // A constant whose negation can be used as an immediate value in a
10961           // data-processing instruction. This can be used in GCC with an "n"
10962           // modifier that prints the negated value, for use with SUB
10963           // instructions. It is not useful otherwise but is implemented for
10964           // compatibility.
10965           if (ARM_AM::getSOImmVal(-CVal) != -1)
10966             break;
10967         }
10968         return;
10969
10970       case 'M':
10971         if (Subtarget->isThumb()) { // FIXME thumb2
10972           // This must be a multiple of 4 between 0 and 1020, for
10973           // ADD sp + immediate.
10974           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10975             break;
10976         } else {
10977           // A power of two or a constant between 0 and 32.  This is used in
10978           // GCC for the shift amount on shifted register operands, but it is
10979           // useful in general for any shift amounts.
10980           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10981             break;
10982         }
10983         return;
10984
10985       case 'N':
10986         if (Subtarget->isThumb()) {  // FIXME thumb2
10987           // This must be a constant between 0 and 31, for shift amounts.
10988           if (CVal >= 0 && CVal <= 31)
10989             break;
10990         }
10991         return;
10992
10993       case 'O':
10994         if (Subtarget->isThumb()) {  // FIXME thumb2
10995           // This must be a multiple of 4 between -508 and 508, for
10996           // ADD/SUB sp = sp + immediate.
10997           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10998             break;
10999         }
11000         return;
11001     }
11002     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11003     break;
11004   }
11005
11006   if (Result.getNode()) {
11007     Ops.push_back(Result);
11008     return;
11009   }
11010   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11011 }
11012
11013 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11014   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11015   unsigned Opcode = Op->getOpcode();
11016   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11017       "Invalid opcode for Div/Rem lowering");
11018   bool isSigned = (Opcode == ISD::SDIVREM);
11019   EVT VT = Op->getValueType(0);
11020   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11021
11022   RTLIB::Libcall LC;
11023   switch (VT.getSimpleVT().SimpleTy) {
11024   default: llvm_unreachable("Unexpected request for libcall!");
11025   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11026   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11027   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11028   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11029   }
11030
11031   SDValue InChain = DAG.getEntryNode();
11032
11033   TargetLowering::ArgListTy Args;
11034   TargetLowering::ArgListEntry Entry;
11035   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11036     EVT ArgVT = Op->getOperand(i).getValueType();
11037     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11038     Entry.Node = Op->getOperand(i);
11039     Entry.Ty = ArgTy;
11040     Entry.isSExt = isSigned;
11041     Entry.isZExt = !isSigned;
11042     Args.push_back(Entry);
11043   }
11044
11045   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11046                                          getPointerTy());
11047
11048   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11049
11050   SDLoc dl(Op);
11051   TargetLowering::
11052   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11053                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11054                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11055                     Callee, Args, DAG, dl);
11056   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11057
11058   return CallInfo.first;
11059 }
11060
11061 bool
11062 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11063   // The ARM target isn't yet aware of offsets.
11064   return false;
11065 }
11066
11067 bool ARM::isBitFieldInvertedMask(unsigned v) {
11068   if (v == 0xffffffff)
11069     return false;
11070
11071   // there can be 1's on either or both "outsides", all the "inside"
11072   // bits must be 0's
11073   unsigned TO = CountTrailingOnes_32(v);
11074   unsigned LO = CountLeadingOnes_32(v);
11075   v = (v >> TO) << TO;
11076   v = (v << LO) >> LO;
11077   return v == 0;
11078 }
11079
11080 /// isFPImmLegal - Returns true if the target can instruction select the
11081 /// specified FP immediate natively. If false, the legalizer will
11082 /// materialize the FP immediate as a load from a constant pool.
11083 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11084   if (!Subtarget->hasVFP3())
11085     return false;
11086   if (VT == MVT::f32)
11087     return ARM_AM::getFP32Imm(Imm) != -1;
11088   if (VT == MVT::f64)
11089     return ARM_AM::getFP64Imm(Imm) != -1;
11090   return false;
11091 }
11092
11093 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11094 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11095 /// specified in the intrinsic calls.
11096 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11097                                            const CallInst &I,
11098                                            unsigned Intrinsic) const {
11099   switch (Intrinsic) {
11100   case Intrinsic::arm_neon_vld1:
11101   case Intrinsic::arm_neon_vld2:
11102   case Intrinsic::arm_neon_vld3:
11103   case Intrinsic::arm_neon_vld4:
11104   case Intrinsic::arm_neon_vld2lane:
11105   case Intrinsic::arm_neon_vld3lane:
11106   case Intrinsic::arm_neon_vld4lane: {
11107     Info.opc = ISD::INTRINSIC_W_CHAIN;
11108     // Conservatively set memVT to the entire set of vectors loaded.
11109     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11110     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11111     Info.ptrVal = I.getArgOperand(0);
11112     Info.offset = 0;
11113     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11114     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11115     Info.vol = false; // volatile loads with NEON intrinsics not supported
11116     Info.readMem = true;
11117     Info.writeMem = false;
11118     return true;
11119   }
11120   case Intrinsic::arm_neon_vst1:
11121   case Intrinsic::arm_neon_vst2:
11122   case Intrinsic::arm_neon_vst3:
11123   case Intrinsic::arm_neon_vst4:
11124   case Intrinsic::arm_neon_vst2lane:
11125   case Intrinsic::arm_neon_vst3lane:
11126   case Intrinsic::arm_neon_vst4lane: {
11127     Info.opc = ISD::INTRINSIC_VOID;
11128     // Conservatively set memVT to the entire set of vectors stored.
11129     unsigned NumElts = 0;
11130     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11131       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11132       if (!ArgTy->isVectorTy())
11133         break;
11134       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11135     }
11136     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11137     Info.ptrVal = I.getArgOperand(0);
11138     Info.offset = 0;
11139     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11140     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11141     Info.vol = false; // volatile stores with NEON intrinsics not supported
11142     Info.readMem = false;
11143     Info.writeMem = true;
11144     return true;
11145   }
11146   case Intrinsic::arm_ldrex: {
11147     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11148     Info.opc = ISD::INTRINSIC_W_CHAIN;
11149     Info.memVT = MVT::getVT(PtrTy->getElementType());
11150     Info.ptrVal = I.getArgOperand(0);
11151     Info.offset = 0;
11152     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11153     Info.vol = true;
11154     Info.readMem = true;
11155     Info.writeMem = false;
11156     return true;
11157   }
11158   case Intrinsic::arm_strex: {
11159     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11160     Info.opc = ISD::INTRINSIC_W_CHAIN;
11161     Info.memVT = MVT::getVT(PtrTy->getElementType());
11162     Info.ptrVal = I.getArgOperand(1);
11163     Info.offset = 0;
11164     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11165     Info.vol = true;
11166     Info.readMem = false;
11167     Info.writeMem = true;
11168     return true;
11169   }
11170   case Intrinsic::arm_strexd: {
11171     Info.opc = ISD::INTRINSIC_W_CHAIN;
11172     Info.memVT = MVT::i64;
11173     Info.ptrVal = I.getArgOperand(2);
11174     Info.offset = 0;
11175     Info.align = 8;
11176     Info.vol = true;
11177     Info.readMem = false;
11178     Info.writeMem = true;
11179     return true;
11180   }
11181   case Intrinsic::arm_ldrexd: {
11182     Info.opc = ISD::INTRINSIC_W_CHAIN;
11183     Info.memVT = MVT::i64;
11184     Info.ptrVal = I.getArgOperand(0);
11185     Info.offset = 0;
11186     Info.align = 8;
11187     Info.vol = true;
11188     Info.readMem = true;
11189     Info.writeMem = false;
11190     return true;
11191   }
11192   default:
11193     break;
11194   }
11195
11196   return false;
11197 }
11198
11199 /// \brief Returns true if it is beneficial to convert a load of a constant
11200 /// to just the constant itself.
11201 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11202                                                           Type *Ty) const {
11203   assert(Ty->isIntegerTy());
11204
11205   unsigned Bits = Ty->getPrimitiveSizeInBits();
11206   if (Bits == 0 || Bits > 32)
11207     return false;
11208   return true;
11209 }